repo.go 8.4 KB

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