repo.go 8.3 KB

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