You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "github.com/go-martini/martini"
  13. "github.com/gogits/gogs/models"
  14. "github.com/gogits/gogs/modules/auth"
  15. "github.com/gogits/gogs/modules/base"
  16. "github.com/gogits/gogs/modules/log"
  17. "github.com/gogits/gogs/modules/middleware"
  18. )
  19. func Create(ctx *middleware.Context, form auth.CreateRepoForm) {
  20. ctx.Data["Title"] = "Create repository"
  21. ctx.Data["PageIsNewRepo"] = true // For navbar arrow.
  22. ctx.Data["LanguageIgns"] = models.LanguageIgns
  23. ctx.Data["Licenses"] = models.Licenses
  24. if ctx.Req.Method == "GET" {
  25. ctx.HTML(200, "repo/create")
  26. return
  27. }
  28. if ctx.HasError() {
  29. ctx.HTML(200, "repo/create")
  30. return
  31. }
  32. _, err := models.CreateRepository(ctx.User, form.RepoName, form.Description,
  33. form.Language, form.License, form.Visibility == "private", form.InitReadme == "on")
  34. if err == nil {
  35. log.Trace("%s Repository created: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, form.RepoName)
  36. ctx.Redirect("/" + ctx.User.Name + "/" + form.RepoName)
  37. return
  38. } else if err == models.ErrRepoAlreadyExist {
  39. ctx.RenderWithErr("Repository name has already been used", "repo/create", &form)
  40. return
  41. } else if err == models.ErrRepoNameIllegal {
  42. ctx.RenderWithErr(models.ErrRepoNameIllegal.Error(), "repo/create", &form)
  43. return
  44. }
  45. ctx.Handle(200, "repo.Create", err)
  46. }
  47. func Mirror(ctx *middleware.Context, form auth.CreateRepoForm) {
  48. ctx.Data["Title"] = "Mirror repository"
  49. ctx.Data["PageIsNewRepo"] = true // For navbar arrow.
  50. if ctx.Req.Method == "GET" {
  51. ctx.HTML(200, "repo/mirror")
  52. return
  53. }
  54. if ctx.HasError() {
  55. ctx.HTML(200, "repo/mirror")
  56. return
  57. }
  58. _, err := models.CreateRepository(ctx.User, form.RepoName, form.Description,
  59. "", form.License, form.Visibility == "private", false)
  60. if err == nil {
  61. log.Trace("%s Repository created: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, form.RepoName)
  62. ctx.Redirect("/" + ctx.User.Name + "/" + form.RepoName)
  63. return
  64. } else if err == models.ErrRepoAlreadyExist {
  65. ctx.RenderWithErr("Repository name has already been used", "repo/mirror", &form)
  66. return
  67. } else if err == models.ErrRepoNameIllegal {
  68. ctx.RenderWithErr(models.ErrRepoNameIllegal.Error(), "repo/mirror", &form)
  69. return
  70. }
  71. ctx.Handle(200, "repo.Mirror", err)
  72. }
  73. func Single(ctx *middleware.Context, params martini.Params) {
  74. branchName := ctx.Repo.BranchName
  75. commitId := ctx.Repo.CommitId
  76. userName := ctx.Repo.Owner.Name
  77. repoName := ctx.Repo.Repository.Name
  78. repoLink := ctx.Repo.RepoLink
  79. branchLink := ctx.Repo.RepoLink + "/src/" + branchName
  80. rawLink := ctx.Repo.RepoLink + "/raw/" + branchName
  81. // Get tree path
  82. treename := params["_1"]
  83. if len(treename) > 0 && treename[len(treename)-1] == '/' {
  84. ctx.Redirect(repoLink + "/src/" + branchName + "/" + treename[:len(treename)-1])
  85. return
  86. }
  87. ctx.Data["IsRepoToolbarSource"] = true
  88. // Branches.
  89. brs, err := models.GetBranches(userName, repoName)
  90. if err != nil {
  91. ctx.Handle(404, "repo.Single(GetBranches)", err)
  92. return
  93. }
  94. ctx.Data["Branches"] = brs
  95. isViewBranch := ctx.Repo.IsBranch
  96. ctx.Data["IsViewBranch"] = isViewBranch
  97. repoFile, err := models.GetTargetFile(userName, repoName,
  98. branchName, commitId, treename)
  99. if err != nil && err != models.ErrRepoFileNotExist {
  100. ctx.Handle(404, "repo.Single(GetTargetFile)", err)
  101. return
  102. }
  103. if len(treename) != 0 && repoFile == nil {
  104. ctx.Handle(404, "repo.Single", nil)
  105. return
  106. }
  107. if repoFile != nil && repoFile.IsFile() {
  108. if blob, err := repoFile.LookupBlob(); err != nil {
  109. ctx.Handle(404, "repo.Single(repoFile.LookupBlob)", err)
  110. } else {
  111. ctx.Data["FileSize"] = repoFile.Size
  112. ctx.Data["IsFile"] = true
  113. ctx.Data["FileName"] = repoFile.Name
  114. ext := path.Ext(repoFile.Name)
  115. if len(ext) > 0 {
  116. ext = ext[1:]
  117. }
  118. ctx.Data["FileExt"] = ext
  119. ctx.Data["FileLink"] = rawLink + "/" + treename
  120. data := blob.Contents()
  121. _, isTextFile := base.IsTextFile(data)
  122. _, isImageFile := base.IsImageFile(data)
  123. ctx.Data["FileIsText"] = isTextFile
  124. if isImageFile {
  125. ctx.Data["IsImageFile"] = true
  126. } else {
  127. readmeExist := base.IsMarkdownFile(repoFile.Name) || base.IsReadmeFile(repoFile.Name)
  128. ctx.Data["ReadmeExist"] = readmeExist
  129. if readmeExist {
  130. ctx.Data["FileContent"] = string(base.RenderMarkdown(data, ""))
  131. } else {
  132. if isTextFile {
  133. ctx.Data["FileContent"] = string(data)
  134. }
  135. }
  136. }
  137. }
  138. } else {
  139. // Directory and file list.
  140. files, err := models.GetReposFiles(userName, repoName, ctx.Repo.CommitId, treename)
  141. if err != nil {
  142. ctx.Handle(404, "repo.Single(GetReposFiles)", err)
  143. return
  144. }
  145. ctx.Data["Files"] = files
  146. var readmeFile *models.RepoFile
  147. for _, f := range files {
  148. if !f.IsFile() || !base.IsReadmeFile(f.Name) {
  149. continue
  150. } else {
  151. readmeFile = f
  152. break
  153. }
  154. }
  155. if readmeFile != nil {
  156. ctx.Data["ReadmeInSingle"] = true
  157. ctx.Data["ReadmeExist"] = true
  158. if blob, err := readmeFile.LookupBlob(); err != nil {
  159. ctx.Handle(404, "repo.Single(readmeFile.LookupBlob)", err)
  160. return
  161. } else {
  162. ctx.Data["FileSize"] = readmeFile.Size
  163. ctx.Data["FileLink"] = rawLink + "/" + treename
  164. data := blob.Contents()
  165. _, isTextFile := base.IsTextFile(data)
  166. ctx.Data["FileIsText"] = isTextFile
  167. ctx.Data["FileName"] = readmeFile.Name
  168. if isTextFile {
  169. ctx.Data["FileContent"] = string(base.RenderMarkdown(data, branchLink))
  170. }
  171. }
  172. }
  173. }
  174. ctx.Data["Username"] = userName
  175. ctx.Data["Reponame"] = repoName
  176. var treenames []string
  177. Paths := make([]string, 0)
  178. if len(treename) > 0 {
  179. treenames = strings.Split(treename, "/")
  180. for i, _ := range treenames {
  181. Paths = append(Paths, strings.Join(treenames[0:i+1], "/"))
  182. }
  183. ctx.Data["HasParentPath"] = true
  184. if len(Paths)-2 >= 0 {
  185. ctx.Data["ParentPath"] = "/" + Paths[len(Paths)-2]
  186. }
  187. }
  188. ctx.Data["LastCommit"] = ctx.Repo.Commit
  189. ctx.Data["Paths"] = Paths
  190. ctx.Data["Treenames"] = treenames
  191. ctx.Data["BranchLink"] = branchLink
  192. ctx.HTML(200, "repo/single")
  193. }
  194. func SingleDownload(ctx *middleware.Context, params martini.Params) {
  195. // Get tree path
  196. treename := params["_1"]
  197. branchName := params["branchname"]
  198. userName := params["username"]
  199. repoName := params["reponame"]
  200. var commitId string
  201. if !models.IsBranchExist(userName, repoName, branchName) {
  202. commitId = branchName
  203. branchName = ""
  204. }
  205. repoFile, err := models.GetTargetFile(userName, repoName,
  206. branchName, commitId, treename)
  207. if err != nil {
  208. ctx.Handle(404, "repo.SingleDownload(GetTargetFile)", err)
  209. return
  210. }
  211. blob, err := repoFile.LookupBlob()
  212. if err != nil {
  213. ctx.Handle(404, "repo.SingleDownload(LookupBlob)", err)
  214. return
  215. }
  216. data := blob.Contents()
  217. contentType, isTextFile := base.IsTextFile(data)
  218. _, isImageFile := base.IsImageFile(data)
  219. ctx.Res.Header().Set("Content-Type", contentType)
  220. if !isTextFile && !isImageFile {
  221. ctx.Res.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(treename))
  222. ctx.Res.Header().Set("Content-Transfer-Encoding", "binary")
  223. }
  224. ctx.Res.Write(data)
  225. }
  226. func basicEncode(username, password string) string {
  227. auth := username + ":" + password
  228. return base64.StdEncoding.EncodeToString([]byte(auth))
  229. }
  230. func basicDecode(encoded string) (user string, name string, err error) {
  231. var s []byte
  232. s, err = base64.StdEncoding.DecodeString(encoded)
  233. if err != nil {
  234. return
  235. }
  236. a := strings.Split(string(s), ":")
  237. if len(a) == 2 {
  238. user, name = a[0], a[1]
  239. } else {
  240. err = errors.New("decode failed")
  241. }
  242. return
  243. }
  244. func authRequired(ctx *middleware.Context) {
  245. ctx.ResponseWriter.Header().Set("WWW-Authenticate", "Basic realm=\".\"")
  246. ctx.Data["ErrorMsg"] = "no basic auth and digit auth"
  247. ctx.HTML(401, fmt.Sprintf("status/401"))
  248. }
  249. func Setting(ctx *middleware.Context, params martini.Params) {
  250. if !ctx.Repo.IsOwner {
  251. ctx.Handle(404, "repo.Setting", nil)
  252. return
  253. }
  254. ctx.Data["IsRepoToolbarSetting"] = true
  255. var title string
  256. if t, ok := ctx.Data["Title"].(string); ok {
  257. title = t
  258. }
  259. ctx.Data["Title"] = title + " - settings"
  260. ctx.HTML(200, "repo/setting")
  261. }
  262. func SettingPost(ctx *middleware.Context) {
  263. if !ctx.Repo.IsOwner {
  264. ctx.Error(404)
  265. return
  266. }
  267. switch ctx.Query("action") {
  268. case "update":
  269. isNameChanged := false
  270. newRepoName := ctx.Query("name")
  271. // Check if repository name has been changed.
  272. if ctx.Repo.Repository.Name != newRepoName {
  273. isExist, err := models.IsRepositoryExist(ctx.Repo.Owner, newRepoName)
  274. if err != nil {
  275. ctx.Handle(404, "repo.SettingPost(update: check existence)", err)
  276. return
  277. } else if isExist {
  278. ctx.RenderWithErr("Repository name has been taken in your repositories.", "repo/setting", nil)
  279. return
  280. } else if err = models.ChangeRepositoryName(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name, newRepoName); err != nil {
  281. ctx.Handle(404, "repo.SettingPost(change repository name)", err)
  282. return
  283. }
  284. log.Trace("%s Repository name changed: %s/%s -> %s", ctx.Req.RequestURI, ctx.User.Name, ctx.Repo.Repository.Name, newRepoName)
  285. isNameChanged = true
  286. ctx.Repo.Repository.Name = newRepoName
  287. }
  288. ctx.Repo.Repository.Description = ctx.Query("desc")
  289. ctx.Repo.Repository.Website = ctx.Query("site")
  290. ctx.Repo.Repository.IsGoget = ctx.Query("goget") == "on"
  291. if err := models.UpdateRepository(ctx.Repo.Repository); err != nil {
  292. ctx.Handle(404, "repo.SettingPost(update)", err)
  293. return
  294. }
  295. ctx.Data["IsSuccess"] = true
  296. if isNameChanged {
  297. ctx.Redirect(fmt.Sprintf("/%s/%s/settings", ctx.Repo.Owner.Name, ctx.Repo.Repository.Name))
  298. } else {
  299. ctx.HTML(200, "repo/setting")
  300. }
  301. log.Trace("%s Repository updated: %s/%s", ctx.Req.RequestURI, ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  302. case "transfer":
  303. if len(ctx.Repo.Repository.Name) == 0 || ctx.Repo.Repository.Name != ctx.Query("repository") {
  304. ctx.RenderWithErr("Please make sure you entered repository name is correct.", "repo/setting", nil)
  305. return
  306. }
  307. newOwner := ctx.Query("owner")
  308. // Check if new owner exists.
  309. isExist, err := models.IsUserExist(newOwner)
  310. if err != nil {
  311. ctx.Handle(404, "repo.SettingPost(transfer: check existence)", err)
  312. return
  313. } else if !isExist {
  314. ctx.RenderWithErr("Please make sure you entered owner name is correct.", "repo/setting", nil)
  315. return
  316. } else if err = models.TransferOwnership(ctx.User, newOwner, ctx.Repo.Repository); err != nil {
  317. ctx.Handle(404, "repo.SettingPost(transfer repository)", err)
  318. return
  319. }
  320. log.Trace("%s Repository transfered: %s/%s -> %s", ctx.Req.RequestURI, ctx.User.Name, ctx.Repo.Repository.Name, newOwner)
  321. ctx.Redirect("/")
  322. return
  323. case "delete":
  324. if len(ctx.Repo.Repository.Name) == 0 || ctx.Repo.Repository.Name != ctx.Query("repository") {
  325. ctx.RenderWithErr("Please make sure you entered repository name is correct.", "repo/setting", nil)
  326. return
  327. }
  328. if err := models.DeleteRepository(ctx.User.Id, ctx.Repo.Repository.Id, ctx.User.LowerName); err != nil {
  329. ctx.Handle(200, "repo.Delete", err)
  330. return
  331. }
  332. log.Trace("%s Repository deleted: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.Repo.Repository.LowerName)
  333. ctx.Redirect("/")
  334. }
  335. }
  336. func Action(ctx *middleware.Context, params martini.Params) {
  337. var err error
  338. switch params["action"] {
  339. case "watch":
  340. err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.Id, true)
  341. case "unwatch":
  342. err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.Id, false)
  343. case "desc":
  344. if !ctx.Repo.IsOwner {
  345. ctx.Error(404)
  346. return
  347. }
  348. ctx.Repo.Repository.Description = ctx.Query("desc")
  349. ctx.Repo.Repository.Website = ctx.Query("site")
  350. err = models.UpdateRepository(ctx.Repo.Repository)
  351. }
  352. if err != nil {
  353. log.Error("repo.Action(%s): %v", params["action"], err)
  354. ctx.JSON(200, map[string]interface{}{
  355. "ok": false,
  356. "err": err.Error(),
  357. })
  358. return
  359. }
  360. ctx.JSON(200, map[string]interface{}{
  361. "ok": true,
  362. })
  363. }