repo.go 8.6 KB

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