gitutils.nim 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. ##[
  2. internal API for now, API subject to change
  3. ]##
  4. # xxx move other git utilities here; candidate for stdlib.
  5. import std/[os, paths, osproc, strutils, tempfiles]
  6. when defined(nimPreviewSlimSystem):
  7. import std/[assertions, syncio]
  8. const commitHead* = "HEAD"
  9. template retryCall*(maxRetry = 3, backoffDuration = 1.0, call: untyped): bool =
  10. ## Retry `call` up to `maxRetry` times with exponential backoff and initial
  11. ## duraton of `backoffDuration` seconds.
  12. ## This is in particular useful for network commands that can fail.
  13. runnableExamples:
  14. doAssert not retryCall(maxRetry = 2, backoffDuration = 0.1, false)
  15. var i = 0
  16. doAssert: retryCall(maxRetry = 3, backoffDuration = 0.1, (i.inc; i >= 3))
  17. doAssert retryCall(call = true)
  18. var result = false
  19. var t = backoffDuration
  20. for i in 0..<maxRetry:
  21. if call:
  22. result = true
  23. break
  24. if i == maxRetry - 1: break
  25. sleep(int(t * 1000))
  26. t = t * 2 # exponential backoff
  27. result
  28. proc isGitRepo*(dir: string): bool =
  29. ## Avoid calling git since it depends on /bin/sh existing and fails in Nix.
  30. return fileExists(dir/".git/HEAD")
  31. proc diffFiles*(path1, path2: string): tuple[output: string, same: bool] =
  32. ## Returns a human readable diff of files `path1`, `path2`, the exact form of
  33. ## which is implementation defined.
  34. # This could be customized, e.g. non-git diff with `diff -uNdr`, or with
  35. # git diff options (e.g. --color-moved, --word-diff).
  36. # in general, `git diff` has more options than `diff`.
  37. var status = 0
  38. (result.output, status) = execCmdEx("git diff --no-index $1 $2" % [path1.quoteShell, path2.quoteShell])
  39. doAssert (status == 0) or (status == 1)
  40. result.same = status == 0
  41. proc diffStrings*(a, b: string): tuple[output: string, same: bool] =
  42. ## Returns a human readable diff of `a`, `b`, the exact form of which is
  43. ## implementation defined.
  44. ## See also `experimental.diff`.
  45. runnableExamples:
  46. let a = "ok1\nok2\nok3\n"
  47. let b = "ok1\nok2 alt\nok3\nok4\n"
  48. let (c, same) = diffStrings(a, b)
  49. doAssert not same
  50. let (c2, same2) = diffStrings(a, a)
  51. doAssert same2
  52. runnableExamples("-r:off"):
  53. let a = "ok1\nok2\nok3\n"
  54. let b = "ok1\nok2 alt\nok3\nok4\n"
  55. echo diffStrings(a, b).output
  56. template tmpFileImpl(prefix, str): auto =
  57. let path = genTempPath(prefix, "")
  58. writeFile(path, str)
  59. path
  60. let patha = tmpFileImpl("diffStrings_a_", a)
  61. let pathb = tmpFileImpl("diffStrings_b_", b)
  62. defer:
  63. removeFile(patha)
  64. removeFile(pathb)
  65. result = diffFiles(patha, pathb)