Skip to content

Commit

Permalink
Make Nimib logging to stdout optional (-d:nimibQuiet) (#242)
Browse files Browse the repository at this point in the history
* add optional logging (`-d:nimibNoLog`)

* update readme to document nimib's define flags

* change flag name to `nimibQuiet`
  • Loading branch information
neroist authored Jun 20, 2024
1 parent 02b5253 commit 6daf489
Show file tree
Hide file tree
Showing 9 changed files with 83 additions and 47 deletions.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,13 @@ Nimib options:
The value of options are available in `nb.options` field which also
tracks further options in `nb.options.other: seq[tuple[kind: CmdLineKind; name, value: string]]`.

### define flags

nimib's behavior can be further turned via Nim's define flags:

* `-d:nimibQuiet`: Completely disables nimib's logging to stdout
* `-d:nimibCodeFromAst`: Makes nimib capture block code from AST of body (as opposed to from file source; see next section). Available since version 0.3

### Code capture

The code capture of a block like `nbCode` (or other custom blocks)
Expand All @@ -268,7 +275,6 @@ can happen in two different ways:
is rendered from AST of body. This means that only documentation comments
are shown (since normal comments are not part of the AST) and that the source show
might be different from original source.
Since version 0.3 this is available through compile time switch `nimibCodeFromAst`.

## 🐝 API <!-- Api means bees in Italian -->

Expand Down
8 changes: 7 additions & 1 deletion docsrc/index.nim
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,13 @@ nbText: hlMdF"""
The value of options are available in `nb.options` field which also
tracks further options in `nb.options.other: seq[tuple[kind: CmdLineKind; name, value: string]]`.
### define flags
nimib's behavior can be further turned via Nim's define flags:
* `-d:nimibQuiet`: Completely disables nimib's logging to stdout
* `-d:nimibCodeFromAst`: Makes nimib capture block code from AST of body (as opposed to from file source; see next section). Available since version 0.3
### Code capture
The code capture of a block like `nbCode` (or other custom blocks)
Expand All @@ -231,7 +238,6 @@ can happen in two different ways:
is rendered from AST of body. This means that only documentation comments
are shown (since normal comments are not part of the AST) and that the source show
might be different from original source.
Since version 0.3 this is available through compile time switch `nimibCodeFromAst`.
## :honeybee: API <!-- Api means bees in Italian -->
Expand Down
12 changes: 6 additions & 6 deletions src/nimib.nim
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import std/[os, strutils, sugar, strformat, macros, macrocache, sequtils, jsonutils]
export jsonutils
import nimib / [types, blocks, docs, boost, config, options, capture, jsutils]
import nimib / [types, blocks, docs, boost, config, options, capture, jsutils, logging]
export types, blocks, docs, boost, sugar, jsutils
# types exports mustache, tables, paths

Expand All @@ -26,25 +26,25 @@ template nbInit*(theme = themes.useDefault, backend = renders.useHtmlBackend, th
nb.thisFile = instantiationInfo(-1, true).filename.AbsoluteFile
else:
nb.thisFile = nb.srcDir / thisFileRel.RelativeFile
echo "[nimib] thisFile: ", nb.thisFile
log "thisFile: " & $nb.thisFile

try:
nb.source = read(nb.thisFile)
except IOError:
echo "[nimib] cannot read source"
log "cannot read source"

if nb.options.filename == "":
nb.filename = nb.thisFile.string.splitFile.name & ".html"
else:
nb.filename = nb.options.filename

if nb.cfg.srcDir != "":
echo "[nimib] srcDir: ", nb.srcDir
log "srcDir: " & $nb.srcDir
nb.filename = (nb.thisDir.relativeTo nb.srcDir).string / nb.filename
echo "[nimib] filename: ", nb.filename
log "filename: " & nb.filename

if nb.cfg.homeDir != "":
echo "[nimib] setting current directory to nb.homeDir: ", nb.homeDir
log "setting current directory to nb.homeDir: " & $nb.homeDir
setCurrentDir nb.homeDir

# can be overriden by theme, but it is better to initialize this anyway
Expand Down
8 changes: 4 additions & 4 deletions src/nimib/blocks.nim
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import std / [macros, strutils, sugar]
import types, sources
import types, sources, logging

macro toStr*(body: untyped): string =
(body.toStrLit)
Expand All @@ -17,17 +17,17 @@ func nbNormalize*(text: string): string =
# note that: '\c' == '\r' and '\l' == '\n'

template newNbBlock*(cmd: string, readCode: static[bool], nbDoc, nbBlock, body, blockImpl: untyped) =
stdout.write "[nimib] ", nbDoc.blocks.len, " ", cmd, ": "
nbBlock = NbBlock(command: cmd, context: newContext(searchDirs = @[], partials = nbDoc.partials))
when readCode:
nbBlock.code = nbNormalize:
when defined(nimibCodeFromAst):
toStr(body)
else:
getCodeAsInSource(nbDoc.source, cmd, body)
echo peekFirstLineOf(nbBlock.code)
log "$1 $2: $3" % [$nbDoc.blocks.len, cmd, peekFirstLineOf(nbBlock.code)]
blockImpl
if len(nbBlock.output) > 0: echo " -> ", peekFirstLineOf(nbBlock.output)
if nimibLog and len(nbBlock.output) > 0:
echo " -> ", peekFirstLineOf(nbBlock.output)
nbBlock.context["code"] = nbBlock.code
nbBlock.context["output"] = nbBlock.output.dup(removeSuffix)
nbDoc.blocks.add nbBlock
Expand Down
51 changes: 27 additions & 24 deletions src/nimib/capture.nim
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,30 @@ import fusion/ioutils
import std/tempfiles

template captureStdout*(ident: untyped, body: untyped) =
## redirect stdout to a temporary file and captures output of body in ident
# Duplicate stdout
let stdoutFileno: FileHandle = stdout.getFileHandle()
let stdoutDupFd: FileHandle = stdoutFileno.duplicate()

# Create a new temporary file or attempt to open it
let (tmpFile, _) = createTempFile("tmp", "")
let tmpFileFd: FileHandle = tmpFile.getFileHandle()

# writing to stdoutFileno now writes to tmpFile
tmpFileFd.duplicateTo(stdoutFileno)

# Execute body code
body

# Flush stdout and tmpFile, read tmpFile from start to ident and then close tmpFile
stdout.flushFile()
tmpFile.flushFile()
tmpFile.setFilePos(0)
ident = tmpFile.readAll()
tmpFile.close()

# Restore stdout
stdoutDupFd.duplicateTo(stdoutFileno)
## redirect stdout to a temporary file and captures output of body in ident
# Duplicate stdout
let stdoutFileno: FileHandle = stdout.getFileHandle()
let stdoutDupFd: FileHandle = stdoutFileno.duplicate()

# Create a new temporary file or attempt to open it
let (tmpFile, _) = createTempFile("tmp", "")
let tmpFileFd: FileHandle = tmpFile.getFileHandle()

# needs to be present when stdout isn't being written to by `newNbBlock` (-d:nimibQuiet)
stdout.flushFile()

# writing to stdoutFileno now writes to tmpFile
tmpFileFd.duplicateTo(stdoutFileno)

# Execute body code
body

# Flush stdout and tmpFile, read tmpFile from start to ident and then close tmpFile
stdout.flushFile()
tmpFile.flushFile()
tmpFile.setFilePos(0)
ident = tmpFile.readAll()
tmpFile.close()

# Restore stdout
stdoutDupFd.duplicateTo(stdoutFileno)
6 changes: 3 additions & 3 deletions src/nimib/config.nim
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import types, parsetoml, jsony, std / [json, os, osproc, math, sequtils]
import types, logging, parsetoml, jsony, std / [json, os, osproc, math, sequtils]

proc getNimibVersion*(): string =
var dir = currentSourcePath().parentDir().parentDir()
Expand Down Expand Up @@ -85,7 +85,7 @@ proc loadNimibCfg*(cfgName: string): tuple[found: bool, dir: AbsoluteDir, raw: s
for dir in parentDirs(getCurrentDir()):
if fileExists(dir / cfgName):
result.dir = dir.AbsoluteDir
echo "[nimib] config file found: ", dir / cfgName
log "config file found: " & dir / cfgName
result.found = true
break
if result.found:
Expand All @@ -99,7 +99,7 @@ proc loadCfg*(doc: var NbDoc) =
doc.rawCfg = cfg.raw
doc.cfg = cfg.nb
if not doc.hasCfg:
echo "[nimib] using default config"
log "using default config"
doc.useDefaultCfg
doc.optOverride

Expand Down
9 changes: 4 additions & 5 deletions src/nimib/docs.nim
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import std/os
import browsers
import types
import nimib / renders
import types, logging, renders

proc write*(doc: var NbDoc) =
echo "[nimib] current directory: ", getCurrentDir()
log "current directory: " & getCurrentDir()
let dir = doc.filename.splitFile().dir
if not dir.dirExists:
echo "[nimib] creating directory: ", dir
log "creating directory: " & dir
createDir(dir)
echo "[nimib] saving file: ", doc.filename
log "saving file: " & doc.filename
writeFile(doc.filename, render(doc))

proc open*(doc: NbDoc) =
Expand Down
22 changes: 22 additions & 0 deletions src/nimib/logging.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import std/strformat

const nimibLog* = not defined(nimibQuiet)

proc log*(label: string, message: string) =
when nimibLog:
if label.len > 0:
echo fmt"[nimib.{label}] {message}"
else:
echo fmt"[nimib] {message}"

proc log*(message: string) =
log("", message)

proc info*(message: string) =
log("info", message)

proc error*(message: string) =
log("error", message)

proc warning*(message: string) =
log("warning", message)
6 changes: 3 additions & 3 deletions src/nimib/renders.nim
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import std / [strutils, tables, sugar, os, strformat, sequtils]
import ./types, ./jsutils, markdown, mustache
import ./types, ./jsutils, ./logging, markdown, mustache

import highlight
import mustachepkg/values
Expand Down Expand Up @@ -109,12 +109,12 @@ proc useMdBackend*(doc: var NbDoc) =

template debugRender(message: string) =
when defined(nimibDebugRender):
echo "[nimib.debugRender] ", message
log "debugRender", message

proc render*(nb: var NbDoc, blk: var NbBlock): string =
debugRender "rendering block " & blk.command
if blk.command not_in nb.partials:
echo "[nimib.warning] no partial found for block ", blk.command
warning "no partial found for block " & blk.command
return
else:
if blk.command in nb.renderPlans:
Expand Down

0 comments on commit 6daf489

Please sign in to comment.