repo.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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(), " not found") ||
  176. strings.Contains(err.Error(), "could not read Username") {
  177. ctx.Data["Err_Auth"] = true
  178. ctx.RenderWithErr(ctx.Tr("form.auth_failed", strings.Replace(err.Error(), ":"+form.AuthPassword+"@", ":<password>@", 1)), MIGRATE, &form)
  179. return
  180. }
  181. handleCreateError(ctx, err, "MigratePost", MIGRATE, &form)
  182. }
  183. func Action(ctx *middleware.Context) {
  184. var err error
  185. switch ctx.Params(":action") {
  186. case "watch":
  187. err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.ID, true)
  188. case "unwatch":
  189. err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.ID, false)
  190. case "star":
  191. err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.ID, true)
  192. case "unstar":
  193. err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.ID, false)
  194. case "desc":
  195. if !ctx.Repo.IsOwner() {
  196. ctx.Error(404)
  197. return
  198. }
  199. ctx.Repo.Repository.Description = ctx.Query("desc")
  200. ctx.Repo.Repository.Website = ctx.Query("site")
  201. err = models.UpdateRepository(ctx.Repo.Repository, false)
  202. }
  203. if err != nil {
  204. log.Error(4, "Action(%s): %v", ctx.Params(":action"), err)
  205. ctx.JSON(200, map[string]interface{}{
  206. "ok": false,
  207. "err": err.Error(),
  208. })
  209. return
  210. }
  211. redirectTo := ctx.Query("redirect_to")
  212. if len(redirectTo) == 0 {
  213. redirectTo = ctx.Repo.RepoLink
  214. }
  215. ctx.Redirect(redirectTo)
  216. return
  217. ctx.JSON(200, map[string]interface{}{
  218. "ok": true,
  219. })
  220. }
  221. func Download(ctx *middleware.Context) {
  222. var (
  223. uri = ctx.Params("*")
  224. refName string
  225. ext string
  226. archivePath string
  227. archiveType git.ArchiveType
  228. )
  229. switch {
  230. case strings.HasSuffix(uri, ".zip"):
  231. ext = ".zip"
  232. archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/zip")
  233. archiveType = git.ZIP
  234. case strings.HasSuffix(uri, ".tar.gz"):
  235. ext = ".tar.gz"
  236. archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/targz")
  237. archiveType = git.TARGZ
  238. default:
  239. ctx.Error(404)
  240. return
  241. }
  242. refName = strings.TrimSuffix(uri, ext)
  243. if !com.IsDir(archivePath) {
  244. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  245. ctx.Handle(500, "Download -> os.MkdirAll(archivePath)", err)
  246. return
  247. }
  248. }
  249. // Get corresponding commit.
  250. var (
  251. commit *git.Commit
  252. err error
  253. )
  254. gitRepo := ctx.Repo.GitRepo
  255. if gitRepo.IsBranchExist(refName) {
  256. commit, err = gitRepo.GetCommitOfBranch(refName)
  257. if err != nil {
  258. ctx.Handle(500, "Download", err)
  259. return
  260. }
  261. } else if gitRepo.IsTagExist(refName) {
  262. commit, err = gitRepo.GetCommitOfTag(refName)
  263. if err != nil {
  264. ctx.Handle(500, "Download", err)
  265. return
  266. }
  267. } else if len(refName) == 40 {
  268. commit, err = gitRepo.GetCommit(refName)
  269. if err != nil {
  270. ctx.Handle(404, "Download", nil)
  271. return
  272. }
  273. } else {
  274. ctx.Error(404)
  275. return
  276. }
  277. archivePath = path.Join(archivePath, base.ShortSha(commit.ID.String())+ext)
  278. if !com.IsFile(archivePath) {
  279. if err := commit.CreateArchive(archivePath, archiveType); err != nil {
  280. ctx.Handle(500, "Download -> CreateArchive "+archivePath, err)
  281. return
  282. }
  283. }
  284. ctx.ServeFile(archivePath, ctx.Repo.Repository.Name+"-"+base.ShortSha(commit.ID.String())+ext)
  285. }