view.go 11 KB

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