repo_editor.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "mime/multipart"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "strings"
  15. "time"
  16. "github.com/Unknwon/com"
  17. gouuid "github.com/satori/go.uuid"
  18. "github.com/gogs/git-module"
  19. "github.com/G-Node/gogs/pkg/process"
  20. "github.com/G-Node/gogs/pkg/setting"
  21. "github.com/G-Node/go-annex"
  22. "encoding/json"
  23. "bytes"
  24. "net/http"
  25. )
  26. const (
  27. ENV_AUTH_USER_ID = "GOGS_AUTH_USER_ID"
  28. ENV_AUTH_USER_NAME = "GOGS_AUTH_USER_NAME"
  29. ENV_AUTH_USER_EMAIL = "GOGS_AUTH_USER_EMAIL"
  30. ENV_REPO_OWNER_NAME = "GOGS_REPO_OWNER_NAME"
  31. ENV_REPO_OWNER_SALT_MD5 = "GOGS_REPO_OWNER_SALT_MD5"
  32. ENV_REPO_ID = "GOGS_REPO_ID"
  33. ENV_REPO_NAME = "GOGS_REPO_NAME"
  34. ENV_REPO_CUSTOM_HOOKS_PATH = "GOGS_REPO_CUSTOM_HOOKS_PATH"
  35. )
  36. type ComposeHookEnvsOptions struct {
  37. AuthUser *User
  38. OwnerName string
  39. OwnerSalt string
  40. RepoID int64
  41. RepoName string
  42. RepoPath string
  43. }
  44. func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
  45. envs := []string{
  46. "SSH_ORIGINAL_COMMAND=1",
  47. ENV_AUTH_USER_ID + "=" + com.ToStr(opts.AuthUser.ID),
  48. ENV_AUTH_USER_NAME + "=" + opts.AuthUser.Name,
  49. ENV_AUTH_USER_EMAIL + "=" + opts.AuthUser.Email,
  50. ENV_REPO_OWNER_NAME + "=" + opts.OwnerName,
  51. ENV_REPO_OWNER_SALT_MD5 + "=" + tool.MD5(opts.OwnerSalt),
  52. ENV_REPO_ID + "=" + com.ToStr(opts.RepoID),
  53. ENV_REPO_NAME + "=" + opts.RepoName,
  54. ENV_REPO_CUSTOM_HOOKS_PATH + "=" + path.Join(opts.RepoPath, "custom_hooks"),
  55. }
  56. return envs
  57. }
  58. // ___________ .___.__ __ ___________.__.__
  59. // \_ _____/ __| _/|__|/ |_ \_ _____/|__| | ____
  60. // | __)_ / __ | | \ __\ | __) | | | _/ __ \
  61. // | \/ /_/ | | || | | \ | | |_\ ___/
  62. // /_______ /\____ | |__||__| \___ / |__|____/\___ >
  63. // \/ \/ \/ \/
  64. // discardLocalRepoBranchChanges discards local commits/changes of
  65. // given branch to make sure it is even to remote branch.
  66. func discardLocalRepoBranchChanges(localPath, branch string) error {
  67. if !com.IsExist(localPath) {
  68. return nil
  69. }
  70. // No need to check if nothing in the repository.
  71. if !git.IsBranchExist(localPath, branch) {
  72. return nil
  73. }
  74. refName := "origin/" + branch
  75. if err := git.ResetHEAD(localPath, true, refName); err != nil {
  76. return fmt.Errorf("git reset --hard %s: %v", refName, err)
  77. }
  78. return nil
  79. }
  80. func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error {
  81. return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch)
  82. }
  83. // checkoutNewBranch checks out to a new branch from the a branch name.
  84. func checkoutNewBranch(repoPath, localPath, oldBranch, newBranch string) error {
  85. if err := git.Checkout(localPath, git.CheckoutOptions{
  86. Timeout: time.Duration(setting.Git.Timeout.Pull) * time.Second,
  87. Branch: newBranch,
  88. OldBranch: oldBranch,
  89. }); err != nil {
  90. return fmt.Errorf("git checkout -b %s %s: %v", newBranch, oldBranch, err)
  91. }
  92. return nil
  93. }
  94. func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
  95. return checkoutNewBranch(repo.RepoPath(), repo.LocalCopyPath(), oldBranch, newBranch)
  96. }
  97. type UpdateRepoFileOptions struct {
  98. LastCommitID string
  99. OldBranch string
  100. NewBranch string
  101. OldTreeName string
  102. NewTreeName string
  103. Message string
  104. Content string
  105. IsNewFile bool
  106. }
  107. // UpdateRepoFile adds or updates a file in repository.
  108. func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
  109. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  110. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  111. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  112. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  113. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  114. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  115. }
  116. repoPath := repo.RepoPath()
  117. localPath := repo.LocalCopyPath()
  118. if opts.OldBranch != opts.NewBranch {
  119. // Directly return error if new branch already exists in the server
  120. if git.IsBranchExist(repoPath, opts.NewBranch) {
  121. return errors.BranchAlreadyExists{opts.NewBranch}
  122. }
  123. // Otherwise, delete branch from local copy in case out of sync
  124. if git.IsBranchExist(localPath, opts.NewBranch) {
  125. if err = git.DeleteBranch(localPath, opts.NewBranch, git.DeleteBranchOptions{
  126. Force: true,
  127. }); err != nil {
  128. return fmt.Errorf("delete branch[%s]: %v", opts.NewBranch, err)
  129. }
  130. }
  131. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  132. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  133. }
  134. }
  135. oldFilePath := path.Join(localPath, opts.OldTreeName)
  136. filePath := path.Join(localPath, opts.NewTreeName)
  137. os.MkdirAll(path.Dir(filePath), os.ModePerm)
  138. // If it's meant to be a new file, make sure it doesn't exist.
  139. if opts.IsNewFile {
  140. if com.IsExist(filePath) {
  141. return ErrRepoFileAlreadyExist{filePath}
  142. }
  143. }
  144. // Ignore move step if it's a new file under a directory.
  145. // Otherwise, move the file when name changed.
  146. if com.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName {
  147. if err = git.MoveFile(localPath, opts.OldTreeName, opts.NewTreeName); err != nil {
  148. return fmt.Errorf("git mv %q %q: %v", opts.OldTreeName, opts.NewTreeName, err)
  149. }
  150. }
  151. if err = ioutil.WriteFile(filePath, []byte(opts.Content), 0666); err != nil {
  152. return fmt.Errorf("write file: %v", err)
  153. }
  154. if err = git.AddChanges(localPath, true); err != nil {
  155. return fmt.Errorf("git add --all: %v", err)
  156. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  157. Committer: doer.NewGitSig(),
  158. Message: opts.Message,
  159. }); err != nil {
  160. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  161. } else if err = git.PushWithEnvs(localPath, "origin", opts.NewBranch,
  162. ComposeHookEnvs(ComposeHookEnvsOptions{
  163. AuthUser: doer,
  164. OwnerName: repo.MustOwner().Name,
  165. OwnerSalt: repo.MustOwner().Salt,
  166. RepoID: repo.ID,
  167. RepoName: repo.Name,
  168. RepoPath: repo.RepoPath(),
  169. })); err != nil {
  170. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  171. }
  172. gitRepo, err := git.OpenRepository(repo.RepoPath())
  173. if err != nil {
  174. log.Error(2, "OpenRepository: %v", err)
  175. return nil
  176. }
  177. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  178. if err != nil {
  179. log.Error(2, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  180. return nil
  181. }
  182. // Simulate push event.
  183. pushCommits := &PushCommits{
  184. Len: 1,
  185. Commits: []*PushCommit{CommitToPushCommit(commit)},
  186. }
  187. oldCommitID := opts.LastCommitID
  188. if opts.NewBranch != opts.OldBranch {
  189. oldCommitID = git.EMPTY_SHA
  190. }
  191. if err := CommitRepoAction(CommitRepoActionOptions{
  192. PusherName: doer.Name,
  193. RepoOwnerID: repo.MustOwner().ID,
  194. RepoName: repo.Name,
  195. RefFullName: git.BRANCH_PREFIX + opts.NewBranch,
  196. OldCommitID: oldCommitID,
  197. NewCommitID: commit.ID.String(),
  198. Commits: pushCommits,
  199. }); err != nil {
  200. log.Error(2, "CommitRepoAction: %v", err)
  201. return nil
  202. }
  203. go AddTestPullRequestTask(doer, repo.ID, opts.NewBranch, true)
  204. if setting.Search.Do {
  205. StartIndexing(doer, repo.MustOwner(), repo)
  206. }
  207. return nil
  208. }
  209. // GetDiffPreview produces and returns diff result of a file which is not yet committed.
  210. func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *Diff, err error) {
  211. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  212. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  213. if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil {
  214. return nil, fmt.Errorf("discard local repo branch[%s] changes: %v", branch, err)
  215. } else if err = repo.UpdateLocalCopyBranch(branch); err != nil {
  216. return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err)
  217. }
  218. localPath := repo.LocalCopyPath()
  219. filePath := path.Join(localPath, treePath)
  220. os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
  221. if err = ioutil.WriteFile(filePath, []byte(content), 0666); err != nil {
  222. return nil, fmt.Errorf("write file: %v", err)
  223. }
  224. cmd := exec.Command("git", "diff", treePath)
  225. cmd.Dir = localPath
  226. cmd.Stderr = os.Stderr
  227. stdout, err := cmd.StdoutPipe()
  228. if err != nil {
  229. return nil, fmt.Errorf("get stdout pipe: %v", err)
  230. }
  231. if err = cmd.Start(); err != nil {
  232. return nil, fmt.Errorf("start: %v", err)
  233. }
  234. pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", repo.RepoPath()), cmd)
  235. defer process.Remove(pid)
  236. diff, err = ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdout)
  237. if err != nil {
  238. return nil, fmt.Errorf("parse path: %v", err)
  239. }
  240. if err = cmd.Wait(); err != nil {
  241. return nil, fmt.Errorf("wait: %v", err)
  242. }
  243. return diff, nil
  244. }
  245. // ________ .__ __ ___________.__.__
  246. // \______ \ ____ | | _____/ |_ ____ \_ _____/|__| | ____
  247. // | | \_/ __ \| | _/ __ \ __\/ __ \ | __) | | | _/ __ \
  248. // | ` \ ___/| |_\ ___/| | \ ___/ | \ | | |_\ ___/
  249. // /_______ /\___ >____/\___ >__| \___ > \___ / |__|____/\___ >
  250. // \/ \/ \/ \/ \/ \/
  251. //
  252. type DeleteRepoFileOptions struct {
  253. LastCommitID string
  254. OldBranch string
  255. NewBranch string
  256. TreePath string
  257. Message string
  258. }
  259. func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
  260. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  261. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  262. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  263. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  264. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  265. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  266. }
  267. if opts.OldBranch != opts.NewBranch {
  268. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  269. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  270. }
  271. }
  272. localPath := repo.LocalCopyPath()
  273. if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
  274. return fmt.Errorf("remove file %q: %v", opts.TreePath, err)
  275. }
  276. if err = git.AddChanges(localPath, true); err != nil {
  277. return fmt.Errorf("git add --all: %v", err)
  278. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  279. Committer: doer.NewGitSig(),
  280. Message: opts.Message,
  281. }); err != nil {
  282. return fmt.Errorf("commit changes to %q: %v", localPath, err)
  283. } else if err = git.PushWithEnvs(localPath, "origin", opts.NewBranch,
  284. ComposeHookEnvs(ComposeHookEnvsOptions{
  285. AuthUser: doer,
  286. OwnerName: repo.MustOwner().Name,
  287. OwnerSalt: repo.MustOwner().Salt,
  288. RepoID: repo.ID,
  289. RepoName: repo.Name,
  290. RepoPath: repo.RepoPath(),
  291. })); err != nil {
  292. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  293. }
  294. return nil
  295. }
  296. // ____ ___ .__ .___ ___________.___.__
  297. // | | \______ | | _________ __| _/ \_ _____/| | | ____ ______
  298. // | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/
  299. // | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \
  300. // |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ >
  301. // |__| \/ \/ \/ \/ \/
  302. //
  303. // Upload represent a uploaded file to a repo to be deleted when moved
  304. type Upload struct {
  305. ID int64
  306. UUID string `xorm:"uuid UNIQUE"`
  307. Name string
  308. }
  309. // UploadLocalPath returns where uploads is stored in local file system based on given UUID.
  310. func UploadLocalPath(uuid string) string {
  311. return path.Join(setting.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
  312. }
  313. // LocalPath returns where uploads are temporarily stored in local file system.
  314. func (upload *Upload) LocalPath() string {
  315. return UploadLocalPath(upload.UUID)
  316. }
  317. // NewUpload creates a new upload object.
  318. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
  319. if tool.IsMaliciousPath(name) {
  320. return nil, fmt.Errorf("malicious path detected: %s", name)
  321. }
  322. upload := &Upload{
  323. UUID: gouuid.NewV4().String(),
  324. Name: name,
  325. }
  326. localPath := upload.LocalPath()
  327. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  328. return nil, fmt.Errorf("mkdir all: %v", err)
  329. }
  330. fw, err := os.Create(localPath)
  331. if err != nil {
  332. return nil, fmt.Errorf("create: %v", err)
  333. }
  334. defer fw.Close()
  335. if _, err = fw.Write(buf); err != nil {
  336. return nil, fmt.Errorf("write: %v", err)
  337. } else if _, err = io.Copy(fw, file); err != nil {
  338. return nil, fmt.Errorf("copy: %v", err)
  339. }
  340. if _, err := x.Insert(upload); err != nil {
  341. return nil, err
  342. }
  343. return upload, nil
  344. }
  345. func GetUploadByUUID(uuid string) (*Upload, error) {
  346. upload := &Upload{UUID: uuid}
  347. has, err := x.Get(upload)
  348. if err != nil {
  349. return nil, err
  350. } else if !has {
  351. return nil, ErrUploadNotExist{0, uuid}
  352. }
  353. return upload, nil
  354. }
  355. func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
  356. if len(uuids) == 0 {
  357. return []*Upload{}, nil
  358. }
  359. // Silently drop invalid uuids.
  360. uploads := make([]*Upload, 0, len(uuids))
  361. return uploads, x.In("uuid", uuids).Find(&uploads)
  362. }
  363. func DeleteUploads(uploads ...*Upload) (err error) {
  364. if len(uploads) == 0 {
  365. return nil
  366. }
  367. sess := x.NewSession()
  368. defer sess.Close()
  369. if err = sess.Begin(); err != nil {
  370. return err
  371. }
  372. ids := make([]int64, len(uploads))
  373. for i := 0; i < len(uploads); i++ {
  374. ids[i] = uploads[i].ID
  375. }
  376. if _, err = sess.In("id", ids).Delete(new(Upload)); err != nil {
  377. return fmt.Errorf("delete uploads: %v", err)
  378. }
  379. for _, upload := range uploads {
  380. localPath := upload.LocalPath()
  381. if !com.IsFile(localPath) {
  382. continue
  383. }
  384. if err := os.Remove(localPath); err != nil {
  385. return fmt.Errorf("remove upload: %v", err)
  386. }
  387. }
  388. return sess.Commit()
  389. }
  390. func DeleteUpload(u *Upload) error {
  391. return DeleteUploads(u)
  392. }
  393. func DeleteUploadByUUID(uuid string) error {
  394. upload, err := GetUploadByUUID(uuid)
  395. if err != nil {
  396. if IsErrUploadNotExist(err) {
  397. return nil
  398. }
  399. return fmt.Errorf("get upload by UUID[%s]: %v", uuid, err)
  400. }
  401. if err := DeleteUpload(upload); err != nil {
  402. return fmt.Errorf("delete upload: %v", err)
  403. }
  404. return nil
  405. }
  406. type UploadRepoFileOptions struct {
  407. LastCommitID string
  408. OldBranch string
  409. NewBranch string
  410. TreePath string
  411. Message string
  412. Files []string // In UUID format
  413. }
  414. // isRepositoryGitPath returns true if given path is or resides inside ".git" path of the repository.
  415. func isRepositoryGitPath(path string) bool {
  416. return strings.HasSuffix(path, ".git") || strings.Contains(path, ".git"+string(os.PathSeparator))
  417. }
  418. func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) (err error) {
  419. if len(opts.Files) == 0 {
  420. return nil
  421. }
  422. uploads, err := GetUploadsByUUIDs(opts.Files)
  423. if err != nil {
  424. return fmt.Errorf("get uploads by UUIDs[%v]: %v", opts.Files, err)
  425. }
  426. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  427. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  428. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  429. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  430. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  431. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  432. }
  433. if opts.OldBranch != opts.NewBranch {
  434. if err = repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  435. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  436. }
  437. }
  438. localPath := repo.LocalCopyPath()
  439. dirPath := path.Join(localPath, opts.TreePath)
  440. os.MkdirAll(dirPath, os.ModePerm)
  441. log.Trace("localpath:%s", localPath)
  442. // prepare annex
  443. // Copy uploaded files into repository.
  444. for _, upload := range uploads {
  445. tmpPath := upload.LocalPath()
  446. targetPath := path.Join(dirPath, upload.Name)
  447. repoFileName := path.Join(opts.TreePath, upload.Name)
  448. if !com.IsFile(tmpPath) {
  449. continue
  450. }
  451. if err = com.Copy(tmpPath, targetPath); err != nil {
  452. return fmt.Errorf("copy: %v", err)
  453. }
  454. log.Trace("Check for annexing: %s,%s", upload.Name)
  455. if finfo, err := os.Stat(targetPath); err == nil {
  456. log.Trace("Filesize is:%s", finfo.Size())
  457. // Should we annex
  458. if finfo.Size() > setting.Repository.Upload.AnexFileMinSize*gannex.MEGABYTE {
  459. log.Trace("This file should be annexed: %s", upload.Name)
  460. // annex init in case it isnt yet
  461. if msg, err := gannex.AInit(localPath, "annex.backend"); err != nil {
  462. log.Error(1, "Annex init failed with error: %v,%s,%s", err, msg, repoFileName)
  463. }
  464. // worm for compatibility
  465. gannex.Md5(localPath)
  466. if msg, err := gannex.Add(repoFileName, localPath); err != nil {
  467. log.Error(1, "Annex add failed with error: %v,%s,%s", err, msg, repoFileName)
  468. }
  469. }
  470. } else {
  471. log.Error(1, "could not stat: %s", targetPath)
  472. }
  473. }
  474. if err = git.AddChanges(localPath, true); err != nil {
  475. return fmt.Errorf("git add --all: %v", err)
  476. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  477. Committer: doer.NewGitSig(),
  478. Message: opts.Message,
  479. }); err != nil {
  480. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  481. } else if err = git.PushWithEnvs(localPath, "origin", opts.NewBranch,
  482. ComposeHookEnvs(ComposeHookEnvsOptions{
  483. AuthUser: doer,
  484. OwnerName: repo.MustOwner().Name,
  485. OwnerSalt: repo.MustOwner().Salt,
  486. RepoID: repo.ID,
  487. RepoName: repo.Name,
  488. RepoPath: repo.RepoPath(),
  489. })); err != nil {
  490. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  491. }
  492. // Sometimes you need this twice
  493. if msg, err := gannex.ASync(localPath, "--content", "--no-pull"); err != nil {
  494. log.Error(1, "Annex sync failed with error: %v,%s", err, msg)
  495. } else {
  496. log.Trace("Annex sync:%s", msg)
  497. }
  498. if msg, err := gannex.ASync(localPath, "--content", "--no-pull"); err != nil {
  499. log.Error(1, "Annex sync failed with error: %v,%s", err, msg)
  500. } else {
  501. log.Trace("Annex sync:%s", msg)
  502. }
  503. gitRepo, err := git.OpenRepository(repo.RepoPath())
  504. if err != nil {
  505. log.Error(2, "OpenRepository: %v", err)
  506. return nil
  507. }
  508. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  509. if err != nil {
  510. log.Error(2, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  511. return nil
  512. }
  513. // Simulate push event.
  514. pushCommits := &PushCommits{
  515. Len: 1,
  516. Commits: []*PushCommit{CommitToPushCommit(commit)},
  517. }
  518. if err := CommitRepoAction(CommitRepoActionOptions{
  519. PusherName: doer.Name,
  520. RepoOwnerID: repo.MustOwner().ID,
  521. RepoName: repo.Name,
  522. RefFullName: git.BRANCH_PREFIX + opts.NewBranch,
  523. OldCommitID: opts.LastCommitID,
  524. NewCommitID: commit.ID.String(),
  525. Commits: pushCommits,
  526. }); err != nil {
  527. log.Error(2, "CommitRepoAction: %v", err)
  528. return nil
  529. }
  530. go AddTestPullRequestTask(doer, repo.ID, opts.NewBranch, true)
  531. // We better start out cleaning now. No use keeping files around with annex
  532. if msg, err := gannex.AUInit(localPath); err != nil {
  533. log.Error(1, "Annex uninit failed with error: %v,%s, at: %s/ This repository might fail at "+
  534. "subsequent uploads!", err, msg, localPath)
  535. }
  536. // Indexing support
  537. if setting.Search.Do {
  538. StartIndexing(doer, repo.MustOwner(), repo)
  539. }
  540. RemoveAllWithNotice("Cleaning out after upload", localPath)
  541. return DeleteUploads(uploads...)
  542. }
  543. func StartIndexing(user, owner *User, repo *Repository) {
  544. var ireq struct{ RepoID, RepoPath string }
  545. ireq.RepoID = fmt.Sprintf("%d", repo.ID)
  546. ireq.RepoPath = repo.FullName()
  547. data, err := json.Marshal(ireq)
  548. if err != nil {
  549. log.Trace("could not marshal index request :%+v", err)
  550. return
  551. }
  552. req, _ := http.NewRequest(http.MethodPost, setting.Search.IndexUrl, bytes.NewReader(data))
  553. client := http.Client{}
  554. resp, err := client.Do(req)
  555. if err != nil || resp.StatusCode != http.StatusOK {
  556. log.Trace("Error doing index request:%+v,%d", err)
  557. return
  558. }
  559. }