nimpretty.nim 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Standard tool for pretty printing.
  10. when not defined(nimpretty):
  11. {.error: "This needs to be compiled with --define:nimPretty".}
  12. import ../compiler / [idents, msgs, ast, syntaxes, renderer, options,
  13. pathutils, layouter]
  14. import parseopt, strutils, os
  15. const
  16. Version = "0.1"
  17. Usage = "nimpretty - Nim Pretty Printer Version " & Version & """
  18. (c) 2017 Andreas Rumpf
  19. Usage:
  20. nimpretty [options] file.nim
  21. Options:
  22. --backup:on|off create a backup file before overwritting (default: ON)
  23. --output:file set the output file (default: overwrite the .nim file)
  24. --indent:N set the number of spaces that is used for indentation
  25. --version show the version
  26. --help show this help
  27. """
  28. proc writeHelp() =
  29. stdout.write(Usage)
  30. stdout.flushFile()
  31. quit(0)
  32. proc writeVersion() =
  33. stdout.write(Version & "\n")
  34. stdout.flushFile()
  35. quit(0)
  36. type
  37. PrettyOptions = object
  38. indWidth: int
  39. proc prettyPrint(infile, outfile: string, opt: PrettyOptions) =
  40. var conf = newConfigRef()
  41. let fileIdx = fileInfoIdx(conf, AbsoluteFile infile)
  42. conf.outFile = AbsoluteFile outfile
  43. when defined(nimpretty2):
  44. var p: TParsers
  45. p.parser.em.indWidth = opt.indWidth
  46. if setupParsers(p, fileIdx, newIdentCache(), conf):
  47. discard parseAll(p)
  48. closeParsers(p)
  49. else:
  50. let tree = parseFile(fileIdx, newIdentCache(), conf)
  51. renderModule(tree, infile, outfile, {}, fileIdx, conf)
  52. proc main =
  53. var infile, outfile: string
  54. var backup = true
  55. var opt: PrettyOptions
  56. for kind, key, val in getopt():
  57. case kind
  58. of cmdArgument:
  59. infile = key.addFileExt(".nim")
  60. of cmdLongoption, cmdShortOption:
  61. case normalize(key)
  62. of "help", "h": writeHelp()
  63. of "version", "v": writeVersion()
  64. of "backup": backup = parseBool(val)
  65. of "output", "o": outfile = val
  66. of "indent": opt.indWidth = parseInt(val)
  67. else: writeHelp()
  68. of cmdEnd: assert(false) # cannot happen
  69. if infile.len == 0:
  70. quit "[Error] no input file."
  71. if backup:
  72. os.copyFile(source=infile, dest=changeFileExt(infile, ".nim.backup"))
  73. if outfile.len == 0: outfile = infile
  74. prettyPrint(infile, outfile, opt)
  75. main()