gitutils.nim 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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, osproc, strutils]
  6. const commitHead* = "HEAD"
  7. template retryCall*(maxRetry = 3, backoffDuration = 1.0, call: untyped): bool =
  8. ## Retry `call` up to `maxRetry` times with exponential backoff and initial
  9. ## duraton of `backoffDuration` seconds.
  10. ## This is in particular useful for network commands that can fail.
  11. runnableExamples:
  12. doAssert not retryCall(maxRetry = 2, backoffDuration = 0.1, false)
  13. var i = 0
  14. doAssert: retryCall(maxRetry = 3, backoffDuration = 0.1, (i.inc; i >= 3))
  15. doAssert retryCall(call = true)
  16. var result = false
  17. var t = backoffDuration
  18. for i in 0..<maxRetry:
  19. if call:
  20. result = true
  21. break
  22. if i == maxRetry - 1: break
  23. sleep(int(t * 1000))
  24. t = t * 2 # exponential backoff
  25. result
  26. proc isGitRepo*(dir: string): bool =
  27. ## This command is used to get the relative path to the root of the repository.
  28. ## Using this, we can verify whether a folder is a git repository by checking
  29. ## whether the command success and if the output is empty.
  30. let (output, status) = execCmdEx("git rev-parse --show-cdup", workingDir = dir)
  31. # On Windows there will be a trailing newline on success, remove it.
  32. # The value of a successful call typically won't have a whitespace (it's
  33. # usually a series of ../), so we know that it's safe to unconditionally
  34. # remove trailing whitespaces from the result.
  35. result = status == 0 and output.strip() == ""