nimpretty.nim 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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, pathutils]
  13. import parseopt, strutils, os
  14. const
  15. Version = "0.1"
  16. Usage = "nimpretty - Nim Pretty Printer Version " & Version & """
  17. (c) 2017 Andreas Rumpf
  18. Usage:
  19. nimpretty [options] file.nim
  20. Options:
  21. --backup:on|off create a backup file before overwritting (default: ON)
  22. --output:file set the output file (default: overwrite the .nim file)
  23. --version show the version
  24. --help show this help
  25. """
  26. proc writeHelp() =
  27. stdout.write(Usage)
  28. stdout.flushFile()
  29. quit(0)
  30. proc writeVersion() =
  31. stdout.write(Version & "\n")
  32. stdout.flushFile()
  33. quit(0)
  34. proc prettyPrint(infile, outfile: string) =
  35. var conf = newConfigRef()
  36. let fileIdx = fileInfoIdx(conf, AbsoluteFile infile)
  37. conf.outFile = AbsoluteFile outfile
  38. when defined(nimpretty2):
  39. discard parseFile(fileIdx, newIdentCache(), conf)
  40. else:
  41. let tree = parseFile(fileIdx, newIdentCache(), conf)
  42. renderModule(tree, infile, outfile, {}, fileIdx, conf)
  43. proc main =
  44. var infile, outfile: string
  45. var backup = true
  46. for kind, key, val in getopt():
  47. case kind
  48. of cmdArgument:
  49. infile = key.addFileExt(".nim")
  50. of cmdLongoption, cmdShortOption:
  51. case normalize(key)
  52. of "help", "h": writeHelp()
  53. of "version", "v": writeVersion()
  54. of "backup": backup = parseBool(val)
  55. of "output", "o": outfile = val
  56. else: writeHelp()
  57. of cmdEnd: assert(false) # cannot happen
  58. if infile.len == 0:
  59. quit "[Error] no input file."
  60. if backup:
  61. os.copyFile(source=infile, dest=changeFileExt(infile, ".nim.backup"))
  62. if outfile.len == 0: outfile = infile
  63. prettyPrint(infile, outfile)
  64. main()