view.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. "bytes"
  7. "fmt"
  8. gotemplate "html/template"
  9. "io/ioutil"
  10. "path"
  11. "strings"
  12. "github.com/go-macaron/captcha"
  13. "github.com/unknwon/paginater"
  14. log "gopkg.in/clog.v1"
  15. "github.com/G-Node/git-module"
  16. "github.com/G-Node/libgin/libgin/annex"
  17. "github.com/G-Node/gogs/internal/context"
  18. "github.com/G-Node/gogs/internal/db"
  19. "github.com/G-Node/gogs/internal/markup"
  20. "github.com/G-Node/gogs/internal/setting"
  21. "github.com/G-Node/gogs/internal/template"
  22. "github.com/G-Node/gogs/internal/template/highlight"
  23. "github.com/G-Node/gogs/internal/tool"
  24. )
  25. const (
  26. BARE = "repo/bare"
  27. HOME = "repo/home"
  28. WATCHERS = "repo/watchers"
  29. FORKS = "repo/forks"
  30. )
  31. func renderDirectory(c *context.Context, treeLink string) {
  32. tree, err := c.Repo.Commit.SubTree(c.Repo.TreePath)
  33. if err != nil {
  34. c.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  35. return
  36. }
  37. entries, err := tree.ListEntries()
  38. if err != nil {
  39. c.ServerError("ListEntries", err)
  40. return
  41. }
  42. entries.Sort()
  43. c.Data["Files"], err = entries.GetCommitsInfoWithCustomConcurrency(c.Repo.Commit, c.Repo.TreePath, setting.Repository.CommitsFetchConcurrency)
  44. if err != nil {
  45. c.ServerError("GetCommitsInfoWithCustomConcurrency", err)
  46. return
  47. }
  48. if c.Data["HasDataCite"].(bool) {
  49. if entry, err := tree.GetBlobByPath("datacite.yml"); err != nil {
  50. readDataciteFile(entry, c)
  51. }
  52. }
  53. var readmeFile *git.Blob
  54. for _, entry := range entries {
  55. if entry.IsDir() || !markup.IsReadmeFile(entry.Name()) {
  56. continue
  57. }
  58. // TODO: collect all possible README files and show with priority.
  59. readmeFile = entry.Blob()
  60. break
  61. }
  62. if readmeFile != nil {
  63. c.Data["RawFileLink"] = ""
  64. c.Data["ReadmeInList"] = true
  65. c.Data["ReadmeExist"] = true
  66. dataRc, err := readmeFile.Data()
  67. if err != nil {
  68. c.ServerError("readmeFile.Data", err)
  69. return
  70. }
  71. buf := make([]byte, 1024)
  72. n, _ := dataRc.Read(buf)
  73. buf = buf[:n]
  74. // GIN mod: Replace existing buf and reader with annexed content buf and reader
  75. buf, dataRc, err = resolveAnnexedContent(c, buf, dataRc)
  76. if err != nil {
  77. return
  78. }
  79. isTextFile := tool.IsTextFile(buf)
  80. c.Data["IsTextFile"] = isTextFile
  81. c.Data["FileName"] = readmeFile.Name()
  82. if isTextFile {
  83. d, _ := ioutil.ReadAll(dataRc)
  84. buf = append(buf, d...)
  85. switch markup.Detect(readmeFile.Name()) {
  86. case markup.MARKDOWN:
  87. c.Data["IsMarkdown"] = true
  88. buf = markup.Markdown(buf, treeLink, c.Repo.Repository.ComposeMetas())
  89. case markup.ORG_MODE:
  90. c.Data["IsMarkdown"] = true
  91. buf = markup.OrgMode(buf, treeLink, c.Repo.Repository.ComposeMetas())
  92. case markup.IPYTHON_NOTEBOOK:
  93. c.Data["IsIPythonNotebook"] = true
  94. c.Data["RawFileLink"] = c.Repo.RepoLink + "/raw/" + path.Join(c.Repo.BranchName, c.Repo.TreePath, readmeFile.Name())
  95. default:
  96. buf = bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1)
  97. }
  98. c.Data["FileContent"] = string(buf)
  99. }
  100. }
  101. // Show latest commit info of repository in table header,
  102. // or of directory if not in root directory.
  103. latestCommit := c.Repo.Commit
  104. if len(c.Repo.TreePath) > 0 {
  105. latestCommit, err = c.Repo.Commit.GetCommitByPath(c.Repo.TreePath)
  106. if err != nil {
  107. c.ServerError("GetCommitByPath", err)
  108. return
  109. }
  110. }
  111. c.Data["LatestCommit"] = latestCommit
  112. c.Data["LatestCommitUser"] = db.ValidateCommitWithEmail(latestCommit)
  113. if c.Repo.CanEnableEditor() {
  114. c.Data["CanAddFile"] = true
  115. c.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  116. }
  117. }
  118. func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink string, cpt *captcha.Captcha) {
  119. c.Data["IsViewFile"] = true
  120. blob := entry.Blob()
  121. dataRc, err := blob.Data()
  122. if err != nil {
  123. c.Handle(500, "Data", err)
  124. return
  125. }
  126. c.Data["FileSize"] = blob.Size()
  127. c.Data["FileName"] = blob.Name()
  128. c.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  129. c.Data["RawFileLink"] = rawLink + "/" + c.Repo.TreePath
  130. buf := make([]byte, 1024)
  131. n, _ := dataRc.Read(buf)
  132. buf = buf[:n]
  133. // GIN mod: Replace existing buf and reader with annexed content buf and
  134. // reader (only if it's an annexed ptr file)
  135. buf, dataRc, err = resolveAnnexedContent(c, buf, dataRc)
  136. if err != nil {
  137. return
  138. }
  139. isTextFile := tool.IsTextFile(buf)
  140. c.Data["IsTextFile"] = isTextFile
  141. // Assume file is not editable first.
  142. if !isTextFile {
  143. c.Data["EditFileTooltip"] = c.Tr("repo.editor.cannot_edit_non_text_files")
  144. }
  145. canEnableEditor := c.Repo.CanEnableEditor()
  146. switch {
  147. case isTextFile:
  148. // GIN mod: Use c.Data["FileSize"] which is replaced by annexed content
  149. // size in resolveAnnexedContent() when necessary
  150. if c.Data["FileSize"].(int64) >= setting.UI.MaxDisplayFileSize {
  151. c.Data["IsFileTooLarge"] = true
  152. break
  153. }
  154. c.Data["ReadmeExist"] = markup.IsReadmeFile(blob.Name())
  155. d, _ := ioutil.ReadAll(dataRc)
  156. buf = append(buf, d...)
  157. switch markup.Detect(blob.Name()) {
  158. case markup.MARKDOWN:
  159. c.Data["IsMarkdown"] = true
  160. c.Data["FileContent"] = string(markup.Markdown(buf, path.Dir(treeLink), c.Repo.Repository.ComposeMetas()))
  161. case markup.ORG_MODE:
  162. c.Data["IsMarkdown"] = true
  163. c.Data["FileContent"] = string(markup.OrgMode(buf, path.Dir(treeLink), c.Repo.Repository.ComposeMetas()))
  164. case markup.IPYTHON_NOTEBOOK:
  165. c.Data["IsIPythonNotebook"] = true
  166. // GIN mod: JSON, YAML, and odML render support with jsTree
  167. case markup.JSON:
  168. c.Data["IsJSON"] = true
  169. c.Data["RawFileContent"] = string(buf)
  170. fallthrough
  171. case markup.YAML:
  172. c.Data["IsYAML"] = true
  173. c.Data["RawFileContent"] = string(buf)
  174. fallthrough
  175. case markup.XML:
  176. // pass XML down to ODML checker
  177. fallthrough
  178. case markup.ODML:
  179. if tool.IsODMLFile(buf) {
  180. c.Data["IsODML"] = true
  181. c.Data["ODML"] = string(markup.MarshalODML(buf))
  182. }
  183. fallthrough
  184. default:
  185. // Building code view blocks with line number on server side.
  186. var fileContent string
  187. if err, content := template.ToUTF8WithErr(buf); err != nil {
  188. if err != nil {
  189. log.Error(4, "ToUTF8WithErr: %s", err)
  190. }
  191. fileContent = string(buf)
  192. } else {
  193. fileContent = content
  194. }
  195. var output bytes.Buffer
  196. lines := strings.Split(fileContent, "\n")
  197. // Remove blank line at the end of file
  198. if len(lines) > 0 && len(lines[len(lines)-1]) == 0 {
  199. lines = lines[:len(lines)-1]
  200. }
  201. // > GIN
  202. if len(lines) > setting.UI.MaxLineHighlight {
  203. c.Data["HighlightClass"] = "nohighlight"
  204. }
  205. // < GIN
  206. for index, line := range lines {
  207. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(strings.TrimRight(line, "\r"))) + "\n")
  208. }
  209. c.Data["FileContent"] = gotemplate.HTML(output.String())
  210. output.Reset()
  211. for i := 0; i < len(lines); i++ {
  212. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  213. }
  214. c.Data["LineNums"] = gotemplate.HTML(output.String())
  215. }
  216. isannex := tool.IsAnnexedFile(buf)
  217. if canEnableEditor && !isannex {
  218. c.Data["CanEditFile"] = true
  219. c.Data["EditFileTooltip"] = c.Tr("repo.editor.edit_this_file")
  220. } else if !c.Repo.IsViewBranch {
  221. c.Data["EditFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
  222. } else if !c.Repo.IsWriter() {
  223. c.Data["EditFileTooltip"] = c.Tr("repo.editor.fork_before_edit")
  224. }
  225. case tool.IsPDFFile(buf) && (c.Data["FileSize"].(int64) < setting.Repository.RawCaptchaMinFileSize*annex.MEGABYTE ||
  226. c.IsLogged):
  227. c.Data["IsPDFFile"] = true
  228. case tool.IsVideoFile(buf) && (c.Data["FileSize"].(int64) < setting.Repository.RawCaptchaMinFileSize*annex.MEGABYTE ||
  229. c.IsLogged):
  230. c.Data["IsVideoFile"] = true
  231. case tool.IsImageFile(buf) && (c.Data["FileSize"].(int64) < setting.Repository.RawCaptchaMinFileSize*annex.MEGABYTE ||
  232. c.IsLogged):
  233. c.Data["IsImageFile"] = true
  234. case tool.IsAnnexedFile(buf) && (c.Data["FileSize"].(int64) < setting.Repository.RawCaptchaMinFileSize*annex.MEGABYTE ||
  235. c.IsLogged):
  236. c.Data["IsAnnexedFile"] = true
  237. }
  238. if canEnableEditor {
  239. c.Data["CanDeleteFile"] = true
  240. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.delete_this_file")
  241. } else if !c.Repo.IsViewBranch {
  242. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
  243. } else if !c.Repo.IsWriter() {
  244. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_have_write_access")
  245. }
  246. }
  247. func setEditorconfigIfExists(c *context.Context) {
  248. ec, err := c.Repo.GetEditorconfig()
  249. if err != nil && !git.IsErrNotExist(err) {
  250. log.Trace("setEditorconfigIfExists.GetEditorconfig [%d]: %v", c.Repo.Repository.ID, err)
  251. return
  252. }
  253. c.Data["Editorconfig"] = ec
  254. }
  255. func Home(c *context.Context, cpt *captcha.Captcha) {
  256. c.Data["PageIsViewFiles"] = true
  257. if c.Repo.Repository.IsBare {
  258. c.HTML(200, BARE)
  259. return
  260. }
  261. title := c.Repo.Repository.Owner.Name + "/" + c.Repo.Repository.Name
  262. if len(c.Repo.Repository.Description) > 0 {
  263. title += ": " + c.Repo.Repository.Description
  264. }
  265. c.Data["Title"] = title
  266. if c.Repo.BranchName != c.Repo.Repository.DefaultBranch {
  267. c.Data["Title"] = title + " @ " + c.Repo.BranchName
  268. }
  269. c.Data["RequireHighlightJS"] = true
  270. branchLink := c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  271. treeLink := branchLink
  272. rawLink := c.Repo.RepoLink + "/raw/" + c.Repo.BranchName
  273. isRootDir := false
  274. if len(c.Repo.TreePath) > 0 {
  275. treeLink += "/" + c.Repo.TreePath
  276. } else {
  277. isRootDir = true
  278. // Only show Git stats panel when view root directory
  279. var err error
  280. c.Repo.CommitsCount, err = c.Repo.Commit.CommitsCount()
  281. if err != nil {
  282. c.Handle(500, "CommitsCount", err)
  283. return
  284. }
  285. c.Data["CommitsCount"] = c.Repo.CommitsCount
  286. }
  287. c.Data["PageIsRepoHome"] = isRootDir
  288. // Get current entry user currently looking at.
  289. entry, err := c.Repo.Commit.GetTreeEntryByPath(c.Repo.TreePath)
  290. if err != nil {
  291. c.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  292. return
  293. }
  294. if entry.IsDir() {
  295. renderDirectory(c, treeLink)
  296. } else {
  297. renderFile(c, entry, treeLink, rawLink, cpt)
  298. }
  299. if c.Written() {
  300. return
  301. }
  302. setEditorconfigIfExists(c)
  303. if c.Written() {
  304. return
  305. }
  306. var treeNames []string
  307. paths := make([]string, 0, 5)
  308. if len(c.Repo.TreePath) > 0 {
  309. treeNames = strings.Split(c.Repo.TreePath, "/")
  310. for i := range treeNames {
  311. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  312. }
  313. c.Data["HasParentPath"] = true
  314. if len(paths)-2 >= 0 {
  315. c.Data["ParentPath"] = "/" + paths[len(paths)-2]
  316. }
  317. }
  318. c.Data["Paths"] = paths
  319. c.Data["TreeLink"] = treeLink
  320. c.Data["TreeNames"] = treeNames
  321. c.Data["BranchLink"] = branchLink
  322. c.HTML(200, HOME)
  323. }
  324. func RenderUserCards(c *context.Context, total int, getter func(page int) ([]*db.User, error), tpl string) {
  325. page := c.QueryInt("page")
  326. if page <= 0 {
  327. page = 1
  328. }
  329. pager := paginater.New(total, db.ItemsPerPage, page, 5)
  330. c.Data["Page"] = pager
  331. items, err := getter(pager.Current())
  332. if err != nil {
  333. c.Handle(500, "getter", err)
  334. return
  335. }
  336. c.Data["Cards"] = items
  337. c.HTML(200, tpl)
  338. }
  339. func Watchers(c *context.Context) {
  340. c.Data["Title"] = c.Tr("repo.watchers")
  341. c.Data["CardsTitle"] = c.Tr("repo.watchers")
  342. c.Data["PageIsWatchers"] = true
  343. RenderUserCards(c, c.Repo.Repository.NumWatches, c.Repo.Repository.GetWatchers, WATCHERS)
  344. }
  345. func Stars(c *context.Context) {
  346. c.Data["Title"] = c.Tr("repo.stargazers")
  347. c.Data["CardsTitle"] = c.Tr("repo.stargazers")
  348. c.Data["PageIsStargazers"] = true
  349. RenderUserCards(c, c.Repo.Repository.NumStars, c.Repo.Repository.GetStargazers, WATCHERS)
  350. }
  351. func Forks(c *context.Context) {
  352. c.Data["Title"] = c.Tr("repos.forks")
  353. forks, err := c.Repo.Repository.GetForks()
  354. if err != nil {
  355. c.Handle(500, "GetForks", err)
  356. return
  357. }
  358. for _, fork := range forks {
  359. if err = fork.GetOwner(); err != nil {
  360. c.Handle(500, "GetOwner", err)
  361. return
  362. }
  363. }
  364. c.Data["Forks"] = forks
  365. c.HTML(200, FORKS)
  366. }