repo.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package git
  2. import (
  3. "bytes"
  4. "container/list"
  5. "errors"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strings"
  10. "time"
  11. "github.com/Unknwon/com"
  12. )
  13. // Repository represents a Git repository.
  14. type Repository struct {
  15. Path string
  16. commitCache *objectCache
  17. tagCache *objectCache
  18. }
  19. const _PRETTY_LOG_FORMAT = `--pretty=format:%H`
  20. func (repo *Repository) parsePrettyFormatLogToList(logs []byte) (*list.List, error) {
  21. l := list.New()
  22. if len(logs) == 0 {
  23. return l, nil
  24. }
  25. parts := bytes.Split(logs, []byte{'\n'})
  26. for _, commitId := range parts {
  27. commit, err := repo.GetCommit(string(commitId))
  28. if err != nil {
  29. return nil, err
  30. }
  31. l.PushBack(commit)
  32. }
  33. return l, nil
  34. }
  35. type NetworkOptions struct {
  36. URL string
  37. Timeout time.Duration
  38. }
  39. // IsRepoURLAccessible checks if given repository URL is accessible.
  40. func IsRepoURLAccessible(opts NetworkOptions) bool {
  41. cmd := NewCommand("ls-remote", "-q", "-h", opts.URL, "HEAD")
  42. if opts.Timeout <= 0 {
  43. opts.Timeout = -1
  44. }
  45. _, err := cmd.RunTimeout(opts.Timeout)
  46. if err != nil {
  47. return false
  48. }
  49. return true
  50. }
  51. // InitRepository initializes a new Git repository.
  52. func InitRepository(repoPath string, bare bool) error {
  53. os.MkdirAll(repoPath, os.ModePerm)
  54. cmd := NewCommand("init")
  55. if bare {
  56. cmd.AddArguments("--bare")
  57. }
  58. _, err := cmd.RunInDir(repoPath)
  59. return err
  60. }
  61. // OpenRepository opens the repository at the given path.
  62. func OpenRepository(repoPath string) (*Repository, error) {
  63. repoPath, err := filepath.Abs(repoPath)
  64. if err != nil {
  65. return nil, err
  66. } else if !isDir(repoPath) {
  67. return nil, errors.New("no such file or directory")
  68. }
  69. return &Repository{
  70. Path: repoPath,
  71. commitCache: newObjectCache(),
  72. tagCache: newObjectCache(),
  73. }, nil
  74. }
  75. type CloneRepoOptions struct {
  76. Mirror bool
  77. Bare bool
  78. Quiet bool
  79. Branch string
  80. Timeout time.Duration
  81. }
  82. // Clone clones original repository to target path.
  83. func Clone(from, to string, opts CloneRepoOptions) (err error) {
  84. toDir := path.Dir(to)
  85. if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
  86. return err
  87. }
  88. cmd := NewCommand("clone")
  89. if opts.Mirror {
  90. cmd.AddArguments("--mirror")
  91. }
  92. if opts.Bare {
  93. cmd.AddArguments("--bare")
  94. }
  95. if opts.Quiet {
  96. cmd.AddArguments("--quiet")
  97. }
  98. if len(opts.Branch) > 0 {
  99. cmd.AddArguments("-b", opts.Branch)
  100. }
  101. cmd.AddArguments(from, to)
  102. if opts.Timeout <= 0 {
  103. opts.Timeout = -1
  104. }
  105. _, err = cmd.RunTimeout(opts.Timeout)
  106. return err
  107. }
  108. type FetchRemoteOptions struct {
  109. Prune bool
  110. Timeout time.Duration
  111. }
  112. // Fetch fetches changes from remotes without merging.
  113. func Fetch(repoPath string, opts FetchRemoteOptions) error {
  114. cmd := NewCommand("fetch")
  115. if opts.Prune {
  116. cmd.AddArguments("--prune")
  117. }
  118. if opts.Timeout <= 0 {
  119. opts.Timeout = -1
  120. }
  121. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  122. return err
  123. }
  124. type PullRemoteOptions struct {
  125. All bool
  126. Rebase bool
  127. Remote string
  128. Branch string
  129. Timeout time.Duration
  130. }
  131. // Pull pulls changes from remotes.
  132. func Pull(repoPath string, opts PullRemoteOptions) error {
  133. cmd := NewCommand("pull")
  134. if opts.Rebase {
  135. cmd.AddArguments("--rebase")
  136. }
  137. if opts.All {
  138. cmd.AddArguments("--all")
  139. } else {
  140. cmd.AddArguments(opts.Remote)
  141. cmd.AddArguments(opts.Branch)
  142. }
  143. if opts.Timeout <= 0 {
  144. opts.Timeout = -1
  145. }
  146. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  147. return err
  148. }
  149. // PushWithEnvs pushs local commits to given remote branch with given environment variables.
  150. func PushWithEnvs(repoPath, remote, branch string, envs []string) error {
  151. _, err := NewCommand("push", remote, branch).AddEnvs(envs...).RunInDir(repoPath)
  152. return err
  153. }
  154. // Push pushs local commits to given remote branch.
  155. func Push(repoPath, remote, branch string) error {
  156. return PushWithEnvs(repoPath, remote, branch, nil)
  157. }
  158. type CheckoutOptions struct {
  159. Branch string
  160. OldBranch string
  161. Timeout time.Duration
  162. }
  163. // Checkout checkouts a branch
  164. func Checkout(repoPath string, opts CheckoutOptions) error {
  165. cmd := NewCommand("checkout")
  166. if len(opts.OldBranch) > 0 {
  167. cmd.AddArguments("-b")
  168. }
  169. cmd.AddArguments(opts.Branch)
  170. if len(opts.OldBranch) > 0 {
  171. cmd.AddArguments(opts.OldBranch)
  172. }
  173. if opts.Timeout <= 0 {
  174. opts.Timeout = -1
  175. }
  176. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  177. return err
  178. }
  179. // ResetHEAD resets HEAD to given revision or head of branch.
  180. func ResetHEAD(repoPath string, hard bool, revision string) error {
  181. cmd := NewCommand("reset")
  182. if hard {
  183. cmd.AddArguments("--hard")
  184. }
  185. _, err := cmd.AddArguments(revision).RunInDir(repoPath)
  186. return err
  187. }
  188. // MoveFile moves a file to another file or directory.
  189. func MoveFile(repoPath, oldTreeName, newTreeName string) error {
  190. _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath)
  191. return err
  192. }
  193. // CountObject represents disk usage report of Git repository.
  194. type CountObject struct {
  195. Count int64
  196. Size int64
  197. InPack int64
  198. Packs int64
  199. SizePack int64
  200. PrunePackable int64
  201. Garbage int64
  202. SizeGarbage int64
  203. }
  204. const (
  205. _STAT_COUNT = "count: "
  206. _STAT_SIZE = "size: "
  207. _STAT_IN_PACK = "in-pack: "
  208. _STAT_PACKS = "packs: "
  209. _STAT_SIZE_PACK = "size-pack: "
  210. _STAT_PRUNE_PACKABLE = "prune-packable: "
  211. _STAT_GARBAGE = "garbage: "
  212. _STAT_SIZE_GARBAGE = "size-garbage: "
  213. )
  214. // GetRepoSize returns disk usage report of repository in given path.
  215. func GetRepoSize(repoPath string) (*CountObject, error) {
  216. cmd := NewCommand("count-objects", "-v")
  217. stdout, err := cmd.RunInDir(repoPath)
  218. if err != nil {
  219. return nil, err
  220. }
  221. countObject := new(CountObject)
  222. for _, line := range strings.Split(stdout, "\n") {
  223. switch {
  224. case strings.HasPrefix(line, _STAT_COUNT):
  225. countObject.Count = com.StrTo(line[7:]).MustInt64()
  226. case strings.HasPrefix(line, _STAT_SIZE):
  227. countObject.Size = com.StrTo(line[6:]).MustInt64() * 1024
  228. case strings.HasPrefix(line, _STAT_IN_PACK):
  229. countObject.InPack = com.StrTo(line[9:]).MustInt64()
  230. case strings.HasPrefix(line, _STAT_PACKS):
  231. countObject.Packs = com.StrTo(line[7:]).MustInt64()
  232. case strings.HasPrefix(line, _STAT_SIZE_PACK):
  233. countObject.SizePack = com.StrTo(line[11:]).MustInt64() * 1024
  234. case strings.HasPrefix(line, _STAT_PRUNE_PACKABLE):
  235. countObject.PrunePackable = com.StrTo(line[16:]).MustInt64()
  236. case strings.HasPrefix(line, _STAT_GARBAGE):
  237. countObject.Garbage = com.StrTo(line[9:]).MustInt64()
  238. case strings.HasPrefix(line, _STAT_SIZE_GARBAGE):
  239. countObject.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024
  240. }
  241. }
  242. return countObject, nil
  243. }