repo.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. // Copyright 2014 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 repo
  5. import (
  6. "fmt"
  7. "os"
  8. "path"
  9. "strings"
  10. "github.com/Unknwon/com"
  11. "github.com/gogits/gogs/models"
  12. "github.com/gogits/gogs/modules/auth"
  13. "github.com/gogits/gogs/modules/base"
  14. "github.com/gogits/gogs/modules/git"
  15. "github.com/gogits/gogs/modules/log"
  16. "github.com/gogits/gogs/modules/middleware"
  17. "github.com/gogits/gogs/modules/setting"
  18. )
  19. const (
  20. CREATE base.TplName = "repo/create"
  21. MIGRATE base.TplName = "repo/migrate"
  22. )
  23. func checkContextUser(ctx *middleware.Context, uid int64) *models.User {
  24. orgs, err := models.GetOwnedOrgsByUserIDDesc(ctx.User.Id, "updated")
  25. if err != nil {
  26. ctx.Handle(500, "GetOwnedOrgsByUserIDDesc", err)
  27. return nil
  28. }
  29. ctx.Data["Orgs"] = orgs
  30. // Not equal means current user is an organization.
  31. if uid == ctx.User.Id || uid == 0 {
  32. return ctx.User
  33. }
  34. org, err := models.GetUserByID(uid)
  35. if models.IsErrUserNotExist(err) {
  36. return ctx.User
  37. }
  38. if err != nil {
  39. ctx.Handle(500, "GetUserByID", fmt.Errorf("[%d]: %v", uid, err))
  40. return nil
  41. }
  42. // Check ownership of organization.
  43. if !org.IsOrganization() || !org.IsOwnedBy(ctx.User.Id) {
  44. ctx.Error(403)
  45. return nil
  46. }
  47. return org
  48. }
  49. func Create(ctx *middleware.Context) {
  50. ctx.Data["Title"] = ctx.Tr("new_repo")
  51. // Give default value for template to render.
  52. ctx.Data["Gitignores"] = models.Gitignores
  53. ctx.Data["Licenses"] = models.Licenses
  54. ctx.Data["Readmes"] = models.Readmes
  55. ctx.Data["readme"] = "Default"
  56. ctx.Data["private"] = ctx.User.LastRepoVisibility
  57. ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
  58. ctxUser := checkContextUser(ctx, ctx.QueryInt64("org"))
  59. if ctx.Written() {
  60. return
  61. }
  62. ctx.Data["ContextUser"] = ctxUser
  63. ctx.HTML(200, CREATE)
  64. }
  65. func handleCreateError(ctx *middleware.Context, err error, name string, tpl base.TplName, form interface{}) {
  66. switch {
  67. case models.IsErrRepoAlreadyExist(err):
  68. ctx.Data["Err_RepoName"] = true
  69. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tpl, form)
  70. case models.IsErrNameReserved(err):
  71. ctx.Data["Err_RepoName"] = true
  72. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form)
  73. case models.IsErrNamePatternNotAllowed(err):
  74. ctx.Data["Err_RepoName"] = true
  75. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form)
  76. default:
  77. ctx.Handle(500, name, err)
  78. }
  79. }
  80. func CreatePost(ctx *middleware.Context, form auth.CreateRepoForm) {
  81. ctx.Data["Title"] = ctx.Tr("new_repo")
  82. ctx.Data["Gitignores"] = models.Gitignores
  83. ctx.Data["Licenses"] = models.Licenses
  84. ctx.Data["Readmes"] = models.Readmes
  85. ctxUser := checkContextUser(ctx, form.Uid)
  86. if ctx.Written() {
  87. return
  88. }
  89. ctx.Data["ContextUser"] = ctxUser
  90. if ctx.HasError() {
  91. ctx.HTML(200, CREATE)
  92. return
  93. }
  94. repo, err := models.CreateRepository(ctxUser, models.CreateRepoOptions{
  95. Name: form.RepoName,
  96. Description: form.Description,
  97. Gitignores: form.Gitignores,
  98. License: form.License,
  99. Readme: form.Readme,
  100. IsPrivate: form.Private || setting.Repository.ForcePrivate,
  101. AutoInit: form.AutoInit,
  102. })
  103. if err == nil {
  104. log.Trace("Repository created[%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name)
  105. ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + repo.Name)
  106. return
  107. }
  108. if repo != nil {
  109. if errDelete := models.DeleteRepository(ctxUser.Id, repo.ID); errDelete != nil {
  110. log.Error(4, "DeleteRepository: %v", errDelete)
  111. }
  112. }
  113. handleCreateError(ctx, err, "CreatePost", CREATE, &form)
  114. }
  115. func Migrate(ctx *middleware.Context) {
  116. ctx.Data["Title"] = ctx.Tr("new_migrate")
  117. ctx.Data["private"] = ctx.User.LastRepoVisibility
  118. ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
  119. ctxUser := checkContextUser(ctx, ctx.QueryInt64("org"))
  120. if ctx.Written() {
  121. return
  122. }
  123. ctx.Data["ContextUser"] = ctxUser
  124. ctx.HTML(200, MIGRATE)
  125. }
  126. func MigratePost(ctx *middleware.Context, form auth.MigrateRepoForm) {
  127. ctx.Data["Title"] = ctx.Tr("new_migrate")
  128. ctxUser := checkContextUser(ctx, form.Uid)
  129. if ctx.Written() {
  130. return
  131. }
  132. ctx.Data["ContextUser"] = ctxUser
  133. if ctx.HasError() {
  134. ctx.HTML(200, MIGRATE)
  135. return
  136. }
  137. remoteAddr, err := form.ParseRemoteAddr(ctx.User)
  138. if err != nil {
  139. if models.IsErrInvalidCloneAddr(err) {
  140. ctx.Data["Err_CloneAddr"] = true
  141. addrErr := err.(models.ErrInvalidCloneAddr)
  142. switch {
  143. case addrErr.IsURLError:
  144. ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &form)
  145. case addrErr.IsPermissionDenied:
  146. ctx.RenderWithErr(ctx.Tr("repo.migrate.permission_denied"), MIGRATE, &form)
  147. case addrErr.IsInvalidPath:
  148. ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), MIGRATE, &form)
  149. default:
  150. ctx.Handle(500, "Unknown error", err)
  151. }
  152. } else {
  153. ctx.Handle(500, "ParseRemoteAddr", err)
  154. }
  155. return
  156. }
  157. repo, err := models.MigrateRepository(ctxUser, models.MigrateRepoOptions{
  158. Name: form.RepoName,
  159. Description: form.Description,
  160. IsPrivate: form.Private || setting.Repository.ForcePrivate,
  161. IsMirror: form.Mirror,
  162. RemoteAddr: remoteAddr,
  163. })
  164. if err == nil {
  165. log.Trace("Repository migrated[%d]: %s/%s", repo.ID, ctxUser.Name, form.RepoName)
  166. ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + form.RepoName)
  167. return
  168. }
  169. if repo != nil {
  170. if errDelete := models.DeleteRepository(ctxUser.Id, repo.ID); errDelete != nil {
  171. log.Error(4, "DeleteRepository: %v", errDelete)
  172. }
  173. }
  174. if strings.Contains(err.Error(), "Authentication failed") ||
  175. strings.Contains(err.Error(), "could not read Username") {
  176. ctx.Data["Err_Auth"] = true
  177. ctx.RenderWithErr(ctx.Tr("form.auth_failed", strings.Replace(err.Error(), ":"+form.AuthPassword+"@", ":<password>@", 1)), MIGRATE, &form)
  178. return
  179. } else if strings.Contains(err.Error(), "fatal:") {
  180. ctx.Data["Err_CloneAddr"] = true
  181. ctx.RenderWithErr(ctx.Tr("repo.migrate.failed", strings.Replace(err.Error(), ":"+form.AuthPassword+"@", ":<password>@", 1)), MIGRATE, &form)
  182. return
  183. }
  184. handleCreateError(ctx, err, "MigratePost", MIGRATE, &form)
  185. }
  186. func Action(ctx *middleware.Context) {
  187. var err error
  188. switch ctx.Params(":action") {
  189. case "watch":
  190. err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.ID, true)
  191. case "unwatch":
  192. err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.ID, false)
  193. case "star":
  194. err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.ID, true)
  195. case "unstar":
  196. err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.ID, false)
  197. case "desc":
  198. if !ctx.Repo.IsOwner() {
  199. ctx.Error(404)
  200. return
  201. }
  202. ctx.Repo.Repository.Description = ctx.Query("desc")
  203. ctx.Repo.Repository.Website = ctx.Query("site")
  204. err = models.UpdateRepository(ctx.Repo.Repository, false)
  205. }
  206. if err != nil {
  207. log.Error(4, "Action(%s): %v", ctx.Params(":action"), err)
  208. ctx.JSON(200, map[string]interface{}{
  209. "ok": false,
  210. "err": err.Error(),
  211. })
  212. return
  213. }
  214. redirectTo := ctx.Query("redirect_to")
  215. if len(redirectTo) == 0 {
  216. redirectTo = ctx.Repo.RepoLink
  217. }
  218. ctx.Redirect(redirectTo)
  219. }
  220. func Download(ctx *middleware.Context) {
  221. var (
  222. uri = ctx.Params("*")
  223. refName string
  224. ext string
  225. archivePath string
  226. archiveType git.ArchiveType
  227. )
  228. switch {
  229. case strings.HasSuffix(uri, ".zip"):
  230. ext = ".zip"
  231. archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/zip")
  232. archiveType = git.ZIP
  233. case strings.HasSuffix(uri, ".tar.gz"):
  234. ext = ".tar.gz"
  235. archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/targz")
  236. archiveType = git.TARGZ
  237. default:
  238. ctx.Error(404)
  239. return
  240. }
  241. refName = strings.TrimSuffix(uri, ext)
  242. if !com.IsDir(archivePath) {
  243. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  244. ctx.Handle(500, "Download -> os.MkdirAll(archivePath)", err)
  245. return
  246. }
  247. }
  248. // Get corresponding commit.
  249. var (
  250. commit *git.Commit
  251. err error
  252. )
  253. gitRepo := ctx.Repo.GitRepo
  254. if gitRepo.IsBranchExist(refName) {
  255. commit, err = gitRepo.GetCommitOfBranch(refName)
  256. if err != nil {
  257. ctx.Handle(500, "Download", err)
  258. return
  259. }
  260. } else if gitRepo.IsTagExist(refName) {
  261. commit, err = gitRepo.GetCommitOfTag(refName)
  262. if err != nil {
  263. ctx.Handle(500, "Download", err)
  264. return
  265. }
  266. } else if len(refName) == 40 {
  267. commit, err = gitRepo.GetCommit(refName)
  268. if err != nil {
  269. ctx.Handle(404, "Download", nil)
  270. return
  271. }
  272. } else {
  273. ctx.Error(404)
  274. return
  275. }
  276. archivePath = path.Join(archivePath, base.ShortSha(commit.ID.String())+ext)
  277. if !com.IsFile(archivePath) {
  278. if err := commit.CreateArchive(archivePath, archiveType); err != nil {
  279. ctx.Handle(500, "Download -> CreateArchive "+archivePath, err)
  280. return
  281. }
  282. }
  283. ctx.ServeFile(archivePath, ctx.Repo.Repository.Name+"-"+base.ShortSha(commit.ID.String())+ext)
  284. }