view.go 13 KB

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