summary refs log tree commit diff stats
path: root/tools/nimpretty.nim
blob: 36d1382cff872eba830b18e42463d500d3e40546 (plain) (blame)
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
#
#
#           The Nim Compiler
#        (c) Copyright 2017 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## Standard tool for pretty printing.

when not defined(nimpretty):
  {.error: "This needs to be compiled with --define:nimPretty".}

import ../compiler / [idents, msgs, ast, syntaxes, renderer]

import parseopt, strutils, os

const
  Version = "0.1"
  Usage = "nimpretty - Nim Pretty Printer Version " & Version & """

  (c) 2017 Andreas Rumpf
Usage:
  nimpretty [options] file.nim
Options:
  --backup:ON|OFF     create a backup file before overwritting (default: ON)
  --version           show the version
  --help              show this help
"""

proc writeHelp() =
  stdout.write(Usage)
  stdout.flushFile()
  quit(0)

proc writeVersion() =
  stdout.write(Version & "\n")
  stdout.flushFile()
  quit(0)

proc prettyPrint(infile: string) =
  let fileIdx = fileInfoIdx(infile)
  let tree = parseFile(fileIdx, newIdentCache())
  let outfile = changeFileExt(infile, ".pretty.nim")
  renderModule(tree, infile, outfile, {})

proc main =
  var infile: string
  var backup = true
  for kind, key, val in getopt():
    case kind
    of cmdArgument:
      infile = key.addFileExt(".nim")
    of cmdLongoption, cmdShortOption:
      case normalize(key)
      of "help", "h": writeHelp()
      of "version", "v": writeVersion()
      of "backup": backup = parseBool(val)
      else: writeHelp()
    of cmdEnd: assert(false) # cannot happen
  if infile.len == 0:
    quit "[Error] no input file."
  if backup:
    os.copyFile(source=infile, dest=changeFileExt(infile, ".nim.backup"))
  prettyPrint(infile)

main()