view.go 14 KB

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