view.go 12 KB

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