view.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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/G-Node/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 not 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. c.Data["DoiInfo"] = doiInfo
  80. doi := GDoiRepo(c, setting.Doi.DoiBase)
  81. //ddata, err := ginDoi.GDoiMData(doi, "https://api.datacite.org/works/") //todo configure URL?
  82. c.Data["DoiReg"] = ginDoi.IsRegsitredDoi(doi)
  83. c.Data["doi"] = doi
  84. }
  85. }
  86. c.Data["LicenseExists"] = true
  87. if readmeFile != nil {
  88. c.Data["RawFileLink"] = ""
  89. c.Data["ReadmeInList"] = true
  90. c.Data["ReadmeExist"] = true
  91. buf := make([]byte, 1024)
  92. r, w := io.Pipe()
  93. defer r.Close()
  94. defer w.Close()
  95. go readmeFile.DataPipeline(w, w)
  96. if readmeFile.Size() > 0 {
  97. n, _ := r.Read(buf)
  98. buf = buf[:n]
  99. }
  100. isannex := tool.IsAnnexedFile(buf)
  101. dataRc, err := readmeFile.Data()
  102. if err != nil {
  103. c.ServerError("readmeFile.Data", err)
  104. return
  105. }
  106. if isannex {
  107. af, err := gannex.NewAFile(c.Repo.Repository.RepoPath(), "annex", readmeFile.Name(), buf)
  108. if err != nil {
  109. log.Trace("Could not get annex file: %v", err)
  110. c.ServerError("readmeFile.Data", err)
  111. return
  112. }
  113. afp, err := af.Open()
  114. defer afp.Close()
  115. if err != nil {
  116. c.ServerError("readmeFile.Data", err)
  117. log.Trace("Could not open annex file: %v", err)
  118. return
  119. }
  120. dataRc = bufio.NewReader(afp)
  121. }
  122. buf = make([]byte, 1024)
  123. n, _ := dataRc.Read(buf)
  124. buf = buf[:n]
  125. isTextFile := tool.IsTextFile(buf)
  126. c.Data["IsTextFile"] = isTextFile
  127. c.Data["FileName"] = readmeFile.Name()
  128. if isTextFile {
  129. d, _ := ioutil.ReadAll(dataRc)
  130. buf = append(buf, d...)
  131. switch markup.Detect(readmeFile.Name()) {
  132. case markup.MARKDOWN:
  133. c.Data["IsMarkdown"] = true
  134. buf = markup.Markdown(buf, treeLink, c.Repo.Repository.ComposeMetas())
  135. case markup.ORG_MODE:
  136. c.Data["IsMarkdown"] = true
  137. buf = markup.OrgMode(buf, treeLink, c.Repo.Repository.ComposeMetas())
  138. case markup.IPYTHON_NOTEBOOK:
  139. c.Data["IsIPythonNotebook"] = true
  140. c.Data["RawFileLink"] = c.Repo.RepoLink + "/raw/" + path.Join(c.Repo.BranchName, c.Repo.TreePath, readmeFile.Name())
  141. default:
  142. buf = bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1)
  143. }
  144. c.Data["FileContent"] = string(buf)
  145. }
  146. }
  147. // Show latest commit info of repository in table header,
  148. // or of directory if not in root directory.
  149. latestCommit := c.Repo.Commit
  150. if len(c.Repo.TreePath) > 0 {
  151. latestCommit, err = c.Repo.Commit.GetCommitByPath(c.Repo.TreePath)
  152. if err != nil {
  153. c.ServerError("GetCommitByPath", err)
  154. return
  155. }
  156. }
  157. c.Data["LatestCommit"] = latestCommit
  158. c.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  159. if c.Repo.CanEnableEditor() {
  160. c.Data["CanAddFile"] = true
  161. c.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  162. }
  163. }
  164. func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink string, cpt *captcha.Captcha) {
  165. c.Data["IsViewFile"] = true
  166. blob := entry.Blob()
  167. log.Trace("Blob size is %s", blob.Size())
  168. if blob.Size() > gannex.MEGABYTE*10 && setting.Service.EnableCaptcha && !cpt.VerifyReq(c.Req) && !c.IsLogged {
  169. c.Data["EnableCaptcha"] = true
  170. c.HTML(200, "repo/download")
  171. return
  172. }
  173. c.Data["FileSize"] = blob.Size()
  174. c.Data["FileName"] = blob.Name()
  175. c.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  176. c.Data["RawFileLink"] = rawLink + "/" + c.Repo.TreePath
  177. buf := make([]byte, 1024)
  178. r, w := io.Pipe()
  179. defer r.Close()
  180. defer w.Close()
  181. go blob.DataPipeline(w, w)
  182. if blob.Size() > 0 {
  183. n, _ := r.Read(buf)
  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.JSON:
  258. c.Data["IsJSON"] = true
  259. c.Data["RawFileContent"] = string(buf)
  260. fallthrough
  261. case markup.YAML:
  262. c.Data["IsYAML"] = true
  263. c.Data["RawFileContent"] = string(buf)
  264. fallthrough
  265. case markup.UNRECOGNIZED:
  266. if tool.IsOdmlFile(buf) {
  267. c.Data["IsOdML"] = true
  268. od := odml.Odml{}
  269. xml.Unmarshal(buf, &od)
  270. decoder := xml.NewDecoder(bytes.NewReader(buf))
  271. decoder.CharsetReader = charset.NewReaderLabel
  272. decoder.Decode(&od)
  273. data, _ := json.Marshal(od)
  274. c.Data["OdML"] = string(data)
  275. goto End
  276. } else {
  277. goto End
  278. }
  279. End:
  280. fallthrough
  281. default:
  282. // Building code view blocks with line number on server side.
  283. var fileContent string
  284. if err, content := template.ToUTF8WithErr(buf); err != nil {
  285. if err != nil {
  286. log.Error(4, "ToUTF8WithErr: %s", err)
  287. }
  288. fileContent = string(buf)
  289. } else {
  290. fileContent = content
  291. }
  292. var output bytes.Buffer
  293. lines := strings.Split(fileContent, "\n")
  294. if len(lines) > setting.UI.MaxLineHighlight {
  295. c.Data["HighlightClass"] = "nohighlight"
  296. }
  297. for index, line := range lines {
  298. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(strings.TrimRight(line, "\r"))) + "\n")
  299. }
  300. c.Data["FileContent"] = gotemplate.HTML(output.String())
  301. output.Reset()
  302. for i := 0; i < len(lines); i++ {
  303. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  304. }
  305. c.Data["LineNums"] = gotemplate.HTML(output.String())
  306. }
  307. if canEnableEditor && !isannex {
  308. c.Data["CanEditFile"] = true
  309. c.Data["EditFileTooltip"] = c.Tr("repo.editor.edit_this_file")
  310. } else if !c.Repo.IsViewBranch {
  311. c.Data["EditFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
  312. } else if !c.Repo.IsWriter() {
  313. c.Data["EditFileTooltip"] = c.Tr("repo.editor.fork_before_edit")
  314. }
  315. case tool.IsPDFFile(buf) && (c.Data["FileSize"].(int64) < setting.Repository.RawCaptchaMinFileSize*gannex.MEGABYTE ||
  316. c.IsLogged):
  317. c.Data["IsPDFFile"] = true
  318. case tool.IsVideoFile(buf) && (c.Data["FileSize"].(int64) < setting.Repository.RawCaptchaMinFileSize*gannex.MEGABYTE ||
  319. c.IsLogged):
  320. c.Data["IsVideoFile"] = true
  321. case tool.IsImageFile(buf) && (c.Data["FileSize"].(int64) < setting.Repository.RawCaptchaMinFileSize*gannex.MEGABYTE ||
  322. c.IsLogged):
  323. c.Data["IsImageFile"] = true
  324. case tool.IsAnnexedFile(buf) && (c.Data["FileSize"].(int64) < setting.Repository.RawCaptchaMinFileSize*gannex.MEGABYTE ||
  325. c.IsLogged):
  326. c.Data["IsAnnexedFile"] = true
  327. }
  328. if canEnableEditor {
  329. c.Data["CanDeleteFile"] = true
  330. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.delete_this_file")
  331. } else if !c.Repo.IsViewBranch {
  332. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
  333. } else if !c.Repo.IsWriter() {
  334. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_have_write_access")
  335. }
  336. }
  337. func renderAnnexFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  338. }
  339. func setEditorconfigIfExists(c *context.Context) {
  340. ec, err := c.Repo.GetEditorconfig()
  341. if err != nil && !git.IsErrNotExist(err) {
  342. log.Trace("setEditorconfigIfExists.GetEditorconfig [%d]: %v", c.Repo.Repository.ID, err)
  343. return
  344. }
  345. c.Data["Editorconfig"] = ec
  346. }
  347. func Home(c *context.Context, cpt *captcha.Captcha) {
  348. c.Data["PageIsViewFiles"] = true
  349. if c.Repo.Repository.IsBare {
  350. c.HTML(200, BARE)
  351. return
  352. }
  353. title := c.Repo.Repository.Owner.Name + "/" + c.Repo.Repository.Name
  354. if len(c.Repo.Repository.Description) > 0 {
  355. title += ": " + c.Repo.Repository.Description
  356. }
  357. c.Data["Title"] = title
  358. if c.Repo.BranchName != c.Repo.Repository.DefaultBranch {
  359. c.Data["Title"] = title + " @ " + c.Repo.BranchName
  360. }
  361. c.Data["RequireHighlightJS"] = true
  362. branchLink := c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  363. treeLink := branchLink
  364. rawLink := c.Repo.RepoLink + "/raw/" + c.Repo.BranchName
  365. isRootDir := false
  366. if len(c.Repo.TreePath) > 0 {
  367. treeLink += "/" + c.Repo.TreePath
  368. } else {
  369. isRootDir = true
  370. // Only show Git stats panel when view root directory
  371. var err error
  372. c.Repo.CommitsCount, err = c.Repo.Commit.CommitsCount()
  373. if err != nil {
  374. c.Handle(500, "CommitsCount", err)
  375. return
  376. }
  377. c.Data["CommitsCount"] = c.Repo.CommitsCount
  378. }
  379. c.Data["PageIsRepoHome"] = isRootDir
  380. // Get current entry user currently looking at.
  381. entry, err := c.Repo.Commit.GetTreeEntryByPath(c.Repo.TreePath)
  382. if err != nil {
  383. c.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  384. return
  385. }
  386. if entry.IsDir() {
  387. renderDirectory(c, treeLink)
  388. } else {
  389. renderFile(c, entry, treeLink, rawLink, cpt)
  390. }
  391. if c.Written() {
  392. return
  393. }
  394. setEditorconfigIfExists(c)
  395. if c.Written() {
  396. return
  397. }
  398. var treeNames []string
  399. paths := make([]string, 0, 5)
  400. if len(c.Repo.TreePath) > 0 {
  401. treeNames = strings.Split(c.Repo.TreePath, "/")
  402. for i := range treeNames {
  403. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  404. }
  405. c.Data["HasParentPath"] = true
  406. if len(paths)-2 >= 0 {
  407. c.Data["ParentPath"] = "/" + paths[len(paths)-2]
  408. }
  409. }
  410. c.Data["Paths"] = paths
  411. c.Data["TreeLink"] = treeLink
  412. c.Data["TreeNames"] = treeNames
  413. c.Data["BranchLink"] = branchLink
  414. c.HTML(200, HOME)
  415. }
  416. func RenderUserCards(c *context.Context, total int, getter func(page int) ([]*models.User, error), tpl string) {
  417. page := c.QueryInt("page")
  418. if page <= 0 {
  419. page = 1
  420. }
  421. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  422. c.Data["Page"] = pager
  423. items, err := getter(pager.Current())
  424. if err != nil {
  425. c.Handle(500, "getter", err)
  426. return
  427. }
  428. c.Data["Cards"] = items
  429. c.HTML(200, tpl)
  430. }
  431. func Watchers(c *context.Context) {
  432. c.Data["Title"] = c.Tr("repo.watchers")
  433. c.Data["CardsTitle"] = c.Tr("repo.watchers")
  434. c.Data["PageIsWatchers"] = true
  435. RenderUserCards(c, c.Repo.Repository.NumWatches, c.Repo.Repository.GetWatchers, WATCHERS)
  436. }
  437. func Stars(c *context.Context) {
  438. c.Data["Title"] = c.Tr("repo.stargazers")
  439. c.Data["CardsTitle"] = c.Tr("repo.stargazers")
  440. c.Data["PageIsStargazers"] = true
  441. RenderUserCards(c, c.Repo.Repository.NumStars, c.Repo.Repository.GetStargazers, WATCHERS)
  442. }
  443. func Forks(c *context.Context) {
  444. c.Data["Title"] = c.Tr("repos.forks")
  445. forks, err := c.Repo.Repository.GetForks()
  446. if err != nil {
  447. c.Handle(500, "GetForks", err)
  448. return
  449. }
  450. for _, fork := range forks {
  451. if err = fork.GetOwner(); err != nil {
  452. c.Handle(500, "GetOwner", err)
  453. return
  454. }
  455. }
  456. c.Data["Forks"] = forks
  457. c.HTML(200, FORKS)
  458. }
  459. // Get the (theoretical ) doi for a repository. Make sure its tge doi for the Base repo
  460. // in cas eits a repo from the doi user
  461. func GDoiRepo(c *context.Context, doiBAse string) string {
  462. repoN := c.Repo.Repository.FullName()
  463. // check whether this repo belongs to doi and is a fork
  464. if c.Repo.Repository.IsFork && c.Repo.Owner.Name == "doi" {
  465. repoN = c.Repo.Repository.BaseRepo.FullName()
  466. }
  467. return ginDoi.MakeDoi(ginDoi.RepoP2UUID(repoN), doiBAse)
  468. }