repo.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. "github.com/G-Node/gogs/internal/conf"
  15. "github.com/G-Node/gogs/internal/context"
  16. "github.com/G-Node/gogs/internal/db"
  17. "github.com/G-Node/gogs/internal/form"
  18. "github.com/G-Node/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. c.Data["auto_init"] = conf.Repository.AutoInit
  66. ctxUser := checkContextUser(c, c.QueryInt64("org"))
  67. if c.Written() {
  68. return
  69. }
  70. c.Data["ContextUser"] = ctxUser
  71. c.Success(CREATE)
  72. }
  73. func handleCreateError(c *context.Context, owner *db.User, err error, name, tpl string, form interface{}) {
  74. switch {
  75. case db.IsErrReachLimitOfRepo(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.IsErrNameNotAllowed(err):
  81. c.Data["Err_RepoName"] = true
  82. c.RenderWithErr(c.Tr("repo.form.name_not_allowed", err.(db.ErrNameNotAllowed).Value()), tpl, form)
  83. default:
  84. c.Error(err, name)
  85. }
  86. }
  87. func CreatePost(c *context.Context, f form.CreateRepo) {
  88. c.Data["Title"] = c.Tr("new_repo")
  89. c.Data["Gitignores"] = db.Gitignores
  90. c.Data["Licenses"] = db.Licenses
  91. c.Data["Readmes"] = db.Readmes
  92. ctxUser := checkContextUser(c, f.UserID)
  93. if c.Written() {
  94. return
  95. }
  96. c.Data["ContextUser"] = ctxUser
  97. if c.HasError() {
  98. c.Success(CREATE)
  99. return
  100. }
  101. repo, err := db.CreateRepository(c.User, ctxUser, db.CreateRepoOptions{
  102. Name: f.RepoName,
  103. Description: f.Description,
  104. Gitignores: f.Gitignores,
  105. License: f.License,
  106. Readme: f.Readme,
  107. IsPrivate: f.Private || conf.Repository.ForcePrivate,
  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. IsMirror: f.Mirror,
  170. RemoteAddr: remoteAddr,
  171. })
  172. if err == nil {
  173. log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, f.RepoName)
  174. c.Redirect(conf.Server.Subpath + "/" + ctxUser.Name + "/" + f.RepoName)
  175. return
  176. }
  177. if repo != nil {
  178. if errDelete := db.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil {
  179. log.Error("DeleteRepository: %v", errDelete)
  180. }
  181. }
  182. if strings.Contains(err.Error(), "Authentication failed") ||
  183. strings.Contains(err.Error(), "could not read Username") {
  184. c.Data["Err_Auth"] = true
  185. c.RenderWithErr(c.Tr("form.auth_failed", db.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
  186. return
  187. } else if strings.Contains(err.Error(), "fatal:") {
  188. c.Data["Err_CloneAddr"] = true
  189. c.RenderWithErr(c.Tr("repo.migrate.failed", db.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
  190. return
  191. }
  192. handleCreateError(c, ctxUser, err, "MigratePost", MIGRATE, &f)
  193. }
  194. func Action(c *context.Context) {
  195. var err error
  196. switch c.Params(":action") {
  197. case "watch":
  198. err = db.WatchRepo(c.User.ID, c.Repo.Repository.ID, true)
  199. case "unwatch":
  200. if userID := c.QueryInt64("user_id"); userID != 0 {
  201. if c.User.IsAdmin {
  202. err = db.WatchRepo(userID, c.Repo.Repository.ID, false)
  203. }
  204. } else {
  205. err = db.WatchRepo(c.User.ID, c.Repo.Repository.ID, false)
  206. }
  207. case "star":
  208. err = db.StarRepo(c.User.ID, c.Repo.Repository.ID, true)
  209. case "unstar":
  210. err = db.StarRepo(c.User.ID, c.Repo.Repository.ID, false)
  211. case "desc": // FIXME: this is not used
  212. if !c.Repo.IsOwner() {
  213. c.NotFound()
  214. return
  215. }
  216. c.Repo.Repository.Description = c.Query("desc")
  217. c.Repo.Repository.Website = c.Query("site")
  218. err = db.UpdateRepository(c.Repo.Repository, false)
  219. }
  220. if err != nil {
  221. c.Errorf(err, "action %q", c.Params(":action"))
  222. return
  223. }
  224. redirectTo := c.Query("redirect_to")
  225. if !tool.IsSameSiteURLPath(redirectTo) {
  226. redirectTo = c.Repo.RepoLink
  227. }
  228. c.Redirect(redirectTo)
  229. }
  230. func Download(c *context.Context) {
  231. var (
  232. uri = c.Params("*")
  233. refName string
  234. ext string
  235. archivePath string
  236. archiveFormat git.ArchiveFormat
  237. )
  238. switch {
  239. case strings.HasSuffix(uri, ".zip"):
  240. ext = ".zip"
  241. archivePath = filepath.Join(c.Repo.GitRepo.Path(), "archives", "zip")
  242. archiveFormat = git.ArchiveZip
  243. case strings.HasSuffix(uri, ".tar.gz"):
  244. ext = ".tar.gz"
  245. archivePath = filepath.Join(c.Repo.GitRepo.Path(), "archives", "targz")
  246. archiveFormat = git.ArchiveTarGz
  247. default:
  248. log.Trace("Unknown format: %s", uri)
  249. c.NotFound()
  250. return
  251. }
  252. refName = strings.TrimSuffix(uri, ext)
  253. if !com.IsDir(archivePath) {
  254. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  255. c.Error(err, "create archive directory")
  256. return
  257. }
  258. }
  259. // Get corresponding commit.
  260. var (
  261. commit *git.Commit
  262. err error
  263. )
  264. gitRepo := c.Repo.GitRepo
  265. if gitRepo.HasBranch(refName) {
  266. commit, err = gitRepo.BranchCommit(refName)
  267. if err != nil {
  268. c.Error(err, "get branch commit")
  269. return
  270. }
  271. } else if gitRepo.HasTag(refName) {
  272. commit, err = gitRepo.TagCommit(refName)
  273. if err != nil {
  274. c.Error(err, "get tag commit")
  275. return
  276. }
  277. } else if len(refName) >= 7 && len(refName) <= 40 {
  278. commit, err = gitRepo.CatFileCommit(refName)
  279. if err != nil {
  280. c.NotFound()
  281. return
  282. }
  283. } else {
  284. c.NotFound()
  285. return
  286. }
  287. archivePath = path.Join(archivePath, tool.ShortSHA1(commit.ID.String())+ext)
  288. if !com.IsFile(archivePath) {
  289. if err := commit.CreateArchive(archiveFormat, archivePath); err != nil {
  290. c.Error(err, "creates archive")
  291. return
  292. }
  293. }
  294. c.ServeFile(archivePath, c.Repo.Repository.Name+"-"+refName+ext)
  295. }