You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

518 lines
14 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "encoding/base64"
  8. "net/http"
  9. "time"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/context"
  12. "code.gitea.io/gitea/modules/git"
  13. "code.gitea.io/gitea/modules/repofiles"
  14. api "code.gitea.io/gitea/modules/structs"
  15. "code.gitea.io/gitea/routers/repo"
  16. )
  17. // GetRawFile get a file by path on a repository
  18. func GetRawFile(ctx *context.APIContext) {
  19. // swagger:operation GET /repos/{owner}/{repo}/raw/{filepath} repository repoGetRawFile
  20. // ---
  21. // summary: Get a file from a repository
  22. // produces:
  23. // - application/json
  24. // parameters:
  25. // - name: owner
  26. // in: path
  27. // description: owner of the repo
  28. // type: string
  29. // required: true
  30. // - name: repo
  31. // in: path
  32. // description: name of the repo
  33. // type: string
  34. // required: true
  35. // - name: filepath
  36. // in: path
  37. // description: filepath of the file to get
  38. // type: string
  39. // required: true
  40. // responses:
  41. // 200:
  42. // description: success
  43. // "404":
  44. // "$ref": "#/responses/notFound"
  45. if ctx.Repo.Repository.IsEmpty {
  46. ctx.NotFound()
  47. return
  48. }
  49. blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreePath)
  50. if err != nil {
  51. if git.IsErrNotExist(err) {
  52. ctx.NotFound()
  53. } else {
  54. ctx.Error(http.StatusInternalServerError, "GetBlobByPath", err)
  55. }
  56. return
  57. }
  58. if err = repo.ServeBlob(ctx.Context, blob); err != nil {
  59. ctx.Error(http.StatusInternalServerError, "ServeBlob", err)
  60. }
  61. }
  62. // GetArchive get archive of a repository
  63. func GetArchive(ctx *context.APIContext) {
  64. // swagger:operation GET /repos/{owner}/{repo}/archive/{archive} repository repoGetArchive
  65. // ---
  66. // summary: Get an archive of a repository
  67. // produces:
  68. // - application/json
  69. // parameters:
  70. // - name: owner
  71. // in: path
  72. // description: owner of the repo
  73. // type: string
  74. // required: true
  75. // - name: repo
  76. // in: path
  77. // description: name of the repo
  78. // type: string
  79. // required: true
  80. // - name: archive
  81. // in: path
  82. // description: archive to download, consisting of a git reference and archive
  83. // type: string
  84. // required: true
  85. // responses:
  86. // 200:
  87. // description: success
  88. // "404":
  89. // "$ref": "#/responses/notFound"
  90. repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame"))
  91. gitRepo, err := git.OpenRepository(repoPath)
  92. if err != nil {
  93. ctx.Error(http.StatusInternalServerError, "OpenRepository", err)
  94. return
  95. }
  96. ctx.Repo.GitRepo = gitRepo
  97. defer gitRepo.Close()
  98. repo.Download(ctx.Context)
  99. }
  100. // GetEditorconfig get editor config of a repository
  101. func GetEditorconfig(ctx *context.APIContext) {
  102. // swagger:operation GET /repos/{owner}/{repo}/editorconfig/{filepath} repository repoGetEditorConfig
  103. // ---
  104. // summary: Get the EditorConfig definitions of a file in a repository
  105. // produces:
  106. // - application/json
  107. // parameters:
  108. // - name: owner
  109. // in: path
  110. // description: owner of the repo
  111. // type: string
  112. // required: true
  113. // - name: repo
  114. // in: path
  115. // description: name of the repo
  116. // type: string
  117. // required: true
  118. // - name: filepath
  119. // in: path
  120. // description: filepath of file to get
  121. // type: string
  122. // required: true
  123. // responses:
  124. // 200:
  125. // description: success
  126. // "404":
  127. // "$ref": "#/responses/notFound"
  128. ec, err := ctx.Repo.GetEditorconfig()
  129. if err != nil {
  130. if git.IsErrNotExist(err) {
  131. ctx.NotFound(err)
  132. } else {
  133. ctx.Error(http.StatusInternalServerError, "GetEditorconfig", err)
  134. }
  135. return
  136. }
  137. fileName := ctx.Params("filename")
  138. def, err := ec.GetDefinitionForFilename(fileName)
  139. if def == nil {
  140. ctx.NotFound(err)
  141. return
  142. }
  143. ctx.JSON(http.StatusOK, def)
  144. }
  145. // CanWriteFiles returns true if repository is editable and user has proper access level.
  146. func CanWriteFiles(r *context.Repository) bool {
  147. return r.Permission.CanWrite(models.UnitTypeCode) && !r.Repository.IsMirror && !r.Repository.IsArchived
  148. }
  149. // CanReadFiles returns true if repository is readable and user has proper access level.
  150. func CanReadFiles(r *context.Repository) bool {
  151. return r.Permission.CanRead(models.UnitTypeCode)
  152. }
  153. // CreateFile handles API call for creating a file
  154. func CreateFile(ctx *context.APIContext, apiOpts api.CreateFileOptions) {
  155. // swagger:operation POST /repos/{owner}/{repo}/contents/{filepath} repository repoCreateFile
  156. // ---
  157. // summary: Create a file in a repository
  158. // consumes:
  159. // - application/json
  160. // produces:
  161. // - application/json
  162. // parameters:
  163. // - name: owner
  164. // in: path
  165. // description: owner of the repo
  166. // type: string
  167. // required: true
  168. // - name: repo
  169. // in: path
  170. // description: name of the repo
  171. // type: string
  172. // required: true
  173. // - name: filepath
  174. // in: path
  175. // description: path of the file to create
  176. // type: string
  177. // required: true
  178. // - name: body
  179. // in: body
  180. // required: true
  181. // schema:
  182. // "$ref": "#/definitions/CreateFileOptions"
  183. // responses:
  184. // "201":
  185. // "$ref": "#/responses/FileResponse"
  186. opts := &repofiles.UpdateRepoFileOptions{
  187. Content: apiOpts.Content,
  188. IsNewFile: true,
  189. Message: apiOpts.Message,
  190. TreePath: ctx.Params("*"),
  191. OldBranch: apiOpts.BranchName,
  192. NewBranch: apiOpts.NewBranchName,
  193. Committer: &repofiles.IdentityOptions{
  194. Name: apiOpts.Committer.Name,
  195. Email: apiOpts.Committer.Email,
  196. },
  197. Author: &repofiles.IdentityOptions{
  198. Name: apiOpts.Author.Name,
  199. Email: apiOpts.Author.Email,
  200. },
  201. Dates: &repofiles.CommitDateOptions{
  202. Author: apiOpts.Dates.Author,
  203. Committer: apiOpts.Dates.Committer,
  204. },
  205. }
  206. if opts.Dates.Author.IsZero() {
  207. opts.Dates.Author = time.Now()
  208. }
  209. if opts.Dates.Committer.IsZero() {
  210. opts.Dates.Committer = time.Now()
  211. }
  212. if opts.Message == "" {
  213. opts.Message = ctx.Tr("repo.editor.add", opts.TreePath)
  214. }
  215. if fileResponse, err := createOrUpdateFile(ctx, opts); err != nil {
  216. ctx.Error(http.StatusInternalServerError, "CreateFile", err)
  217. } else {
  218. ctx.JSON(http.StatusCreated, fileResponse)
  219. }
  220. }
  221. // UpdateFile handles API call for updating a file
  222. func UpdateFile(ctx *context.APIContext, apiOpts api.UpdateFileOptions) {
  223. // swagger:operation PUT /repos/{owner}/{repo}/contents/{filepath} repository repoUpdateFile
  224. // ---
  225. // summary: Update a file in a repository
  226. // consumes:
  227. // - application/json
  228. // produces:
  229. // - application/json
  230. // parameters:
  231. // - name: owner
  232. // in: path
  233. // description: owner of the repo
  234. // type: string
  235. // required: true
  236. // - name: repo
  237. // in: path
  238. // description: name of the repo
  239. // type: string
  240. // required: true
  241. // - name: filepath
  242. // in: path
  243. // description: path of the file to update
  244. // type: string
  245. // required: true
  246. // - name: body
  247. // in: body
  248. // required: true
  249. // schema:
  250. // "$ref": "#/definitions/UpdateFileOptions"
  251. // responses:
  252. // "200":
  253. // "$ref": "#/responses/FileResponse"
  254. opts := &repofiles.UpdateRepoFileOptions{
  255. Content: apiOpts.Content,
  256. SHA: apiOpts.SHA,
  257. IsNewFile: false,
  258. Message: apiOpts.Message,
  259. FromTreePath: apiOpts.FromPath,
  260. TreePath: ctx.Params("*"),
  261. OldBranch: apiOpts.BranchName,
  262. NewBranch: apiOpts.NewBranchName,
  263. Committer: &repofiles.IdentityOptions{
  264. Name: apiOpts.Committer.Name,
  265. Email: apiOpts.Committer.Email,
  266. },
  267. Author: &repofiles.IdentityOptions{
  268. Name: apiOpts.Author.Name,
  269. Email: apiOpts.Author.Email,
  270. },
  271. Dates: &repofiles.CommitDateOptions{
  272. Author: apiOpts.Dates.Author,
  273. Committer: apiOpts.Dates.Committer,
  274. },
  275. }
  276. if opts.Dates.Author.IsZero() {
  277. opts.Dates.Author = time.Now()
  278. }
  279. if opts.Dates.Committer.IsZero() {
  280. opts.Dates.Committer = time.Now()
  281. }
  282. if opts.Message == "" {
  283. opts.Message = ctx.Tr("repo.editor.update", opts.TreePath)
  284. }
  285. if fileResponse, err := createOrUpdateFile(ctx, opts); err != nil {
  286. ctx.Error(http.StatusInternalServerError, "UpdateFile", err)
  287. } else {
  288. ctx.JSON(http.StatusOK, fileResponse)
  289. }
  290. }
  291. // Called from both CreateFile or UpdateFile to handle both
  292. func createOrUpdateFile(ctx *context.APIContext, opts *repofiles.UpdateRepoFileOptions) (*api.FileResponse, error) {
  293. if !CanWriteFiles(ctx.Repo) {
  294. return nil, models.ErrUserDoesNotHaveAccessToRepo{
  295. UserID: ctx.User.ID,
  296. RepoName: ctx.Repo.Repository.LowerName,
  297. }
  298. }
  299. content, err := base64.StdEncoding.DecodeString(opts.Content)
  300. if err != nil {
  301. return nil, err
  302. }
  303. opts.Content = string(content)
  304. return repofiles.CreateOrUpdateRepoFile(ctx.Repo.Repository, ctx.User, opts)
  305. }
  306. // DeleteFile Delete a fle in a repository
  307. func DeleteFile(ctx *context.APIContext, apiOpts api.DeleteFileOptions) {
  308. // swagger:operation DELETE /repos/{owner}/{repo}/contents/{filepath} repository repoDeleteFile
  309. // ---
  310. // summary: Delete a file in a repository
  311. // consumes:
  312. // - application/json
  313. // produces:
  314. // - application/json
  315. // parameters:
  316. // - name: owner
  317. // in: path
  318. // description: owner of the repo
  319. // type: string
  320. // required: true
  321. // - name: repo
  322. // in: path
  323. // description: name of the repo
  324. // type: string
  325. // required: true
  326. // - name: filepath
  327. // in: path
  328. // description: path of the file to delete
  329. // type: string
  330. // required: true
  331. // - name: body
  332. // in: body
  333. // required: true
  334. // schema:
  335. // "$ref": "#/definitions/DeleteFileOptions"
  336. // responses:
  337. // "200":
  338. // "$ref": "#/responses/FileDeleteResponse"
  339. // "400":
  340. // "$ref": "#/responses/error"
  341. // "403":
  342. // "$ref": "#/responses/error"
  343. // "404":
  344. // "$ref": "#/responses/error"
  345. if !CanWriteFiles(ctx.Repo) {
  346. ctx.Error(http.StatusForbidden, "DeleteFile", models.ErrUserDoesNotHaveAccessToRepo{
  347. UserID: ctx.User.ID,
  348. RepoName: ctx.Repo.Repository.LowerName,
  349. })
  350. return
  351. }
  352. opts := &repofiles.DeleteRepoFileOptions{
  353. Message: apiOpts.Message,
  354. OldBranch: apiOpts.BranchName,
  355. NewBranch: apiOpts.NewBranchName,
  356. SHA: apiOpts.SHA,
  357. TreePath: ctx.Params("*"),
  358. Committer: &repofiles.IdentityOptions{
  359. Name: apiOpts.Committer.Name,
  360. Email: apiOpts.Committer.Email,
  361. },
  362. Author: &repofiles.IdentityOptions{
  363. Name: apiOpts.Author.Name,
  364. Email: apiOpts.Author.Email,
  365. },
  366. Dates: &repofiles.CommitDateOptions{
  367. Author: apiOpts.Dates.Author,
  368. Committer: apiOpts.Dates.Committer,
  369. },
  370. }
  371. if opts.Dates.Author.IsZero() {
  372. opts.Dates.Author = time.Now()
  373. }
  374. if opts.Dates.Committer.IsZero() {
  375. opts.Dates.Committer = time.Now()
  376. }
  377. if opts.Message == "" {
  378. opts.Message = ctx.Tr("repo.editor.delete", opts.TreePath)
  379. }
  380. if fileResponse, err := repofiles.DeleteRepoFile(ctx.Repo.Repository, ctx.User, opts); err != nil {
  381. if git.IsErrBranchNotExist(err) || models.IsErrRepoFileDoesNotExist(err) || git.IsErrNotExist(err) {
  382. ctx.Error(http.StatusNotFound, "DeleteFile", err)
  383. return
  384. } else if models.IsErrBranchAlreadyExists(err) ||
  385. models.IsErrFilenameInvalid(err) ||
  386. models.IsErrSHADoesNotMatch(err) ||
  387. models.IsErrCommitIDDoesNotMatch(err) ||
  388. models.IsErrSHAOrCommitIDNotProvided(err) {
  389. ctx.Error(http.StatusBadRequest, "DeleteFile", err)
  390. return
  391. } else if models.IsErrUserCannotCommit(err) {
  392. ctx.Error(http.StatusForbidden, "DeleteFile", err)
  393. return
  394. }
  395. ctx.Error(http.StatusInternalServerError, "DeleteFile", err)
  396. } else {
  397. ctx.JSON(http.StatusOK, fileResponse) // FIXME on APIv2: return http.StatusNoContent
  398. }
  399. }
  400. // GetContents Get the metadata and contents (if a file) of an entry in a repository, or a list of entries if a dir
  401. func GetContents(ctx *context.APIContext) {
  402. // swagger:operation GET /repos/{owner}/{repo}/contents/{filepath} repository repoGetContents
  403. // ---
  404. // summary: Gets the metadata and contents (if a file) of an entry in a repository, or a list of entries if a dir
  405. // produces:
  406. // - application/json
  407. // parameters:
  408. // - name: owner
  409. // in: path
  410. // description: owner of the repo
  411. // type: string
  412. // required: true
  413. // - name: repo
  414. // in: path
  415. // description: name of the repo
  416. // type: string
  417. // required: true
  418. // - name: filepath
  419. // in: path
  420. // description: path of the dir, file, symlink or submodule in the repo
  421. // type: string
  422. // required: true
  423. // - name: ref
  424. // in: query
  425. // description: "The name of the commit/branch/tag. Default the repository’s default branch (usually master)"
  426. // type: string
  427. // required: false
  428. // responses:
  429. // "200":
  430. // "$ref": "#/responses/ContentsResponse"
  431. // "404":
  432. // "$ref": "#/responses/notFound"
  433. if !CanReadFiles(ctx.Repo) {
  434. ctx.Error(http.StatusInternalServerError, "GetContentsOrList", models.ErrUserDoesNotHaveAccessToRepo{
  435. UserID: ctx.User.ID,
  436. RepoName: ctx.Repo.Repository.LowerName,
  437. })
  438. return
  439. }
  440. treePath := ctx.Params("*")
  441. ref := ctx.QueryTrim("ref")
  442. if fileList, err := repofiles.GetContentsOrList(ctx.Repo.Repository, treePath, ref); err != nil {
  443. if git.IsErrNotExist(err) {
  444. ctx.NotFound("GetContentsOrList", err)
  445. return
  446. }
  447. ctx.Error(http.StatusInternalServerError, "GetContentsOrList", err)
  448. } else {
  449. ctx.JSON(http.StatusOK, fileList)
  450. }
  451. }
  452. // GetContentsList Get the metadata of all the entries of the root dir
  453. func GetContentsList(ctx *context.APIContext) {
  454. // swagger:operation GET /repos/{owner}/{repo}/contents repository repoGetContentsList
  455. // ---
  456. // summary: Gets the metadata of all the entries of the root dir
  457. // produces:
  458. // - application/json
  459. // parameters:
  460. // - name: owner
  461. // in: path
  462. // description: owner of the repo
  463. // type: string
  464. // required: true
  465. // - name: repo
  466. // in: path
  467. // description: name of the repo
  468. // type: string
  469. // required: true
  470. // - name: ref
  471. // in: query
  472. // description: "The name of the commit/branch/tag. Default the repository’s default branch (usually master)"
  473. // type: string
  474. // required: false
  475. // responses:
  476. // "200":
  477. // "$ref": "#/responses/ContentsListResponse"
  478. // "404":
  479. // "$ref": "#/responses/notFound"
  480. // same as GetContents(), this function is here because swagger fails if path is empty in GetContents() interface
  481. GetContents(ctx)
  482. }