gorgeimpl.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. ## Module that implements ``gorge`` for the compiler.
  10. import msgs, options, lineinfos, pathutils
  11. import std/[os, osproc, streams]
  12. when defined(nimPreviewSlimSystem):
  13. import std/syncio
  14. import ../dist/checksums/src/checksums/sha1
  15. proc readOutput(p: Process): (string, int) =
  16. result[0] = ""
  17. var output = p.outputStream
  18. while not output.atEnd:
  19. result[0].add(output.readLine)
  20. result[0].add("\n")
  21. if result[0].len > 0:
  22. result[0].setLen(result[0].len - "\n".len)
  23. result[1] = p.waitForExit
  24. proc opGorge*(cmd, input, cache: string, info: TLineInfo; conf: ConfigRef): (string, int) =
  25. let workingDir = parentDir(toFullPath(conf, info))
  26. result = ("", 0)
  27. if cache.len > 0:
  28. let h = secureHash(cmd & "\t" & input & "\t" & cache)
  29. let filename = toGeneratedFile(conf, AbsoluteFile("gorge_" & $h), "txt").string
  30. var f: File = default(File)
  31. if optForceFullMake notin conf.globalOptions and open(f, filename):
  32. result = (f.readAll, 0)
  33. f.close
  34. return
  35. var readSuccessful = false
  36. try:
  37. var p = startProcess(cmd, workingDir,
  38. options={poEvalCommand, poStdErrToStdOut})
  39. if input.len != 0:
  40. p.inputStream.write(input)
  41. p.inputStream.close()
  42. result = p.readOutput
  43. p.close()
  44. readSuccessful = true
  45. # only cache successful runs:
  46. if result[1] == 0:
  47. writeFile(filename, result[0])
  48. except IOError, OSError:
  49. if not readSuccessful:
  50. when defined(nimLegacyGorgeErrors):
  51. result = ("", -1)
  52. else:
  53. result = ("Error running startProcess: " & getCurrentExceptionMsg(), -1)
  54. else:
  55. try:
  56. var p = startProcess(cmd, workingDir,
  57. options={poEvalCommand, poStdErrToStdOut})
  58. if input.len != 0:
  59. p.inputStream.write(input)
  60. p.inputStream.close()
  61. result = p.readOutput
  62. p.close()
  63. except IOError, OSError:
  64. when defined(nimLegacyGorgeErrors):
  65. result = ("", -1)
  66. else:
  67. result = ("Error running startProcess: " & getCurrentExceptionMsg(), -1)