feat(nimpretty): support formatting code from stdin (#24676)

This pr adds support for running `nimpretty` on stdin as described in
#24622.

I tested `:%!nimpretty -` and `:%!nimpretty --stdin` in neovim and both
seems to work without issues.
This commit is contained in:
Mads Hougesen
2025-02-10 11:12:41 +01:00
committed by GitHub
parent e6f6c369ff
commit 1a7bc6d878

View File

@@ -16,6 +16,8 @@ import ../compiler / [idents, llstream, ast, msgs, syntaxes, options, pathutils,
import parseopt, strutils, os, sequtils
import std/tempfiles
const
Version = "0.2"
Usage = "nimpretty - Nim Pretty Printer Version " & Version & """
@@ -26,6 +28,7 @@ Usage:
Options:
--out:file set the output file (default: overwrite the input file)
--outDir:dir set the output dir (default: overwrite the input files)
--stdin read input from stdin and write output to stdout
--indent:N[=0] set the number of spaces that is used for indentation
--indent:0 means autodetection (default behaviour)
--maxLineLen:N set the desired maximum line length (default: 80)
@@ -84,7 +87,7 @@ proc finalCheck(content: string; origAst: PNode): bool {.nimcall.} =
closeParser(parser)
result = conf.errorCounter == oldErrors # and goodEnough(newAst, origAst)
proc prettyPrint*(infile, outfile: string, opt: PrettyOptions) =
proc prettyPrint*(infile, outfile: string; opt: PrettyOptions) =
var conf = newConfigRef()
let fileIdx = fileInfoIdx(conf, AbsoluteFile infile)
let f = splitFile(outfile.expandTilde)
@@ -99,12 +102,28 @@ proc prettyPrint*(infile, outfile: string, opt: PrettyOptions) =
when defined(nimpretty):
closeEmitter(parser.em, fullAst, finalCheck)
proc handleStdinInput(opt: PrettyOptions) =
var content = readAll(stdin)
var (cfile, path) = createTempFile("nimpretty_", ".nim")
writeFile(path, content)
prettyPrint(path, path, opt)
echo(readAll(cfile))
close(cfile)
removeFile(path)
proc main =
var outfile, outdir: string
var infiles = newSeq[string]()
var outfiles = newSeq[string]()
var isStdin = false
var backup = false
# when `on`, create a backup file of input in case
# `prettyPrint` could overwrite it (note that the backup may happen even
@@ -112,7 +131,6 @@ proc main =
# --backup was un-documented (rely on git instead).
var opt = PrettyOptions(indWidth: 0, maxLineLen: 80)
for kind, key, val in getopt():
case kind
of cmdArgument:
@@ -132,8 +150,15 @@ proc main =
of "outDir", "outdir": outdir = val
of "indent": opt.indWidth = parseInt(val)
of "maxlinelen": opt.maxLineLen = parseInt(val)
# "" is equal to '-' as input
of "stdin", "": isStdin = true
else: writeHelp()
of cmdEnd: assert(false) # cannot happen
if isStdin:
handleStdinInput(opt)
return
if infiles.len == 0:
quit "[Error] no input file."