repo.go 11 KB

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