repo.go 8.6 KB

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