@@ -16,6 +16,8 @@ import ../compiler / [idents, llstream, ast, msgs, syntaxes, options, pathutils,
1616
1717import parseopt, strutils, os, sequtils
1818
19+ import std/ tempfiles
20+
1921const
2022 Version = " 0.2"
2123 Usage = " nimpretty - Nim Pretty Printer Version " & Version & """
2628Options:
2729 --out:file set the output file (default: overwrite the input file)
2830 --outDir:dir set the output dir (default: overwrite the input files)
31+ --stdin read input from stdin and write output to stdout
2932 --indent:N[=0] set the number of spaces that is used for indentation
3033 --indent:0 means autodetection (default behaviour)
3134 --maxLineLen:N set the desired maximum line length (default: 80)
@@ -84,7 +87,7 @@ proc finalCheck(content: string; origAst: PNode): bool {.nimcall.} =
8487 closeParser (parser)
8588 result = conf.errorCounter == oldErrors # and goodEnough(newAst, origAst)
8689
87- proc prettyPrint * (infile, outfile: string , opt: PrettyOptions ) =
90+ proc prettyPrint * (infile, outfile: string ; opt: PrettyOptions ) =
8891 var conf = newConfigRef ()
8992 let fileIdx = fileInfoIdx (conf, AbsoluteFile infile)
9093 let f = splitFile (outfile.expandTilde)
@@ -99,20 +102,35 @@ proc prettyPrint*(infile, outfile: string, opt: PrettyOptions) =
99102 when defined (nimpretty):
100103 closeEmitter (parser.em, fullAst, finalCheck)
101104
105+ proc handleStdinInput (opt: PrettyOptions ) =
106+ var content = readAll (stdin)
107+
108+ var (cfile, path) = createTempFile (" nimpretty_" , " .nim" )
109+
110+ writeFile (path, content)
111+
112+ prettyPrint (path, path, opt)
113+
114+ echo (readAll (cfile))
115+
116+ close (cfile)
117+ removeFile (path)
118+
102119proc main =
103120 var outfile, outdir: string
104121
105122 var infiles = newSeq [string ]()
106123 var outfiles = newSeq [string ]()
107124
125+ var isStdin = false
126+
108127 var backup = false
109128 # when `on`, create a backup file of input in case
110129 # `prettyPrint` could overwrite it (note that the backup may happen even
111130 # if input is not actually overwritten, when nimpretty is a noop).
112131 # --backup was un-documented (rely on git instead).
113132 var opt = PrettyOptions (indWidth: 0 , maxLineLen: 80 )
114133
115-
116134 for kind, key, val in getopt ():
117135 case kind
118136 of cmdArgument:
@@ -132,8 +150,15 @@ proc main =
132150 of " outDir" , " outdir" : outdir = val
133151 of " indent" : opt.indWidth = parseInt (val)
134152 of " maxlinelen" : opt.maxLineLen = parseInt (val)
153+ # "" is equal to '-' as input
154+ of " stdin" , " " : isStdin = true
135155 else : writeHelp ()
136156 of cmdEnd: assert (false ) # cannot happen
157+
158+ if isStdin:
159+ handleStdinInput (opt)
160+ return
161+
137162 if infiles.len == 0 :
138163 quit " [Error] no input file."
139164
0 commit comments