repo.go 8.6 KB

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