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.

repo.go 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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. "fmt"
  8. "net/http"
  9. "strings"
  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/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. api "code.gitea.io/gitea/modules/structs"
  16. "code.gitea.io/gitea/modules/util"
  17. "code.gitea.io/gitea/modules/validation"
  18. "code.gitea.io/gitea/routers/api/v1/utils"
  19. repo_service "code.gitea.io/gitea/services/repository"
  20. )
  21. var searchOrderByMap = map[string]map[string]models.SearchOrderBy{
  22. "asc": {
  23. "alpha": models.SearchOrderByAlphabetically,
  24. "created": models.SearchOrderByOldest,
  25. "updated": models.SearchOrderByLeastUpdated,
  26. "size": models.SearchOrderBySize,
  27. "id": models.SearchOrderByID,
  28. },
  29. "desc": {
  30. "alpha": models.SearchOrderByAlphabeticallyReverse,
  31. "created": models.SearchOrderByNewest,
  32. "updated": models.SearchOrderByRecentUpdated,
  33. "size": models.SearchOrderBySizeReverse,
  34. "id": models.SearchOrderByIDReverse,
  35. },
  36. }
  37. // Search repositories via options
  38. func Search(ctx *context.APIContext) {
  39. // swagger:operation GET /repos/search repository repoSearch
  40. // ---
  41. // summary: Search for repositories
  42. // produces:
  43. // - application/json
  44. // parameters:
  45. // - name: q
  46. // in: query
  47. // description: keyword
  48. // type: string
  49. // - name: topic
  50. // in: query
  51. // description: Limit search to repositories with keyword as topic
  52. // type: boolean
  53. // - name: includeDesc
  54. // in: query
  55. // description: include search of keyword within repository description
  56. // type: boolean
  57. // - name: uid
  58. // in: query
  59. // description: search only for repos that the user with the given id owns or contributes to
  60. // type: integer
  61. // format: int64
  62. // - name: priority_owner_id
  63. // in: query
  64. // description: repo owner to prioritize in the results
  65. // type: integer
  66. // format: int64
  67. // - name: starredBy
  68. // in: query
  69. // description: search only for repos that the user with the given id has starred
  70. // type: integer
  71. // format: int64
  72. // - name: private
  73. // in: query
  74. // description: include private repositories this user has access to (defaults to true)
  75. // type: boolean
  76. // - name: template
  77. // in: query
  78. // description: include template repositories this user has access to (defaults to true)
  79. // type: boolean
  80. // - name: mode
  81. // in: query
  82. // description: type of repository to search for. Supported values are
  83. // "fork", "source", "mirror" and "collaborative"
  84. // type: string
  85. // - name: exclusive
  86. // in: query
  87. // description: if `uid` is given, search only for repos that the user owns
  88. // type: boolean
  89. // - name: sort
  90. // in: query
  91. // description: sort repos by attribute. Supported values are
  92. // "alpha", "created", "updated", "size", and "id".
  93. // Default is "alpha"
  94. // type: string
  95. // - name: order
  96. // in: query
  97. // description: sort order, either "asc" (ascending) or "desc" (descending).
  98. // Default is "asc", ignored if "sort" is not specified.
  99. // type: string
  100. // - name: page
  101. // in: query
  102. // description: page number of results to return (1-based)
  103. // type: integer
  104. // - name: limit
  105. // in: query
  106. // description: page size of results, maximum page size is 50
  107. // type: integer
  108. // responses:
  109. // "200":
  110. // "$ref": "#/responses/SearchResults"
  111. // "422":
  112. // "$ref": "#/responses/validationError"
  113. opts := &models.SearchRepoOptions{
  114. ListOptions: utils.GetListOptions(ctx),
  115. Actor: ctx.User,
  116. Keyword: strings.Trim(ctx.Query("q"), " "),
  117. OwnerID: ctx.QueryInt64("uid"),
  118. PriorityOwnerID: ctx.QueryInt64("priority_owner_id"),
  119. TopicOnly: ctx.QueryBool("topic"),
  120. Collaborate: util.OptionalBoolNone,
  121. Private: ctx.IsSigned && (ctx.Query("private") == "" || ctx.QueryBool("private")),
  122. Template: util.OptionalBoolNone,
  123. StarredByID: ctx.QueryInt64("starredBy"),
  124. IncludeDescription: ctx.QueryBool("includeDesc"),
  125. }
  126. if ctx.Query("template") != "" {
  127. opts.Template = util.OptionalBoolOf(ctx.QueryBool("template"))
  128. }
  129. if ctx.QueryBool("exclusive") {
  130. opts.Collaborate = util.OptionalBoolFalse
  131. }
  132. var mode = ctx.Query("mode")
  133. switch mode {
  134. case "source":
  135. opts.Fork = util.OptionalBoolFalse
  136. opts.Mirror = util.OptionalBoolFalse
  137. case "fork":
  138. opts.Fork = util.OptionalBoolTrue
  139. case "mirror":
  140. opts.Mirror = util.OptionalBoolTrue
  141. case "collaborative":
  142. opts.Mirror = util.OptionalBoolFalse
  143. opts.Collaborate = util.OptionalBoolTrue
  144. case "":
  145. default:
  146. ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid search mode: \"%s\"", mode))
  147. return
  148. }
  149. var sortMode = ctx.Query("sort")
  150. if len(sortMode) > 0 {
  151. var sortOrder = ctx.Query("order")
  152. if len(sortOrder) == 0 {
  153. sortOrder = "asc"
  154. }
  155. if searchModeMap, ok := searchOrderByMap[sortOrder]; ok {
  156. if orderBy, ok := searchModeMap[sortMode]; ok {
  157. opts.OrderBy = orderBy
  158. } else {
  159. ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid sort mode: \"%s\"", sortMode))
  160. return
  161. }
  162. } else {
  163. ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid sort order: \"%s\"", sortOrder))
  164. return
  165. }
  166. }
  167. var err error
  168. repos, count, err := models.SearchRepository(opts)
  169. if err != nil {
  170. ctx.JSON(http.StatusInternalServerError, api.SearchError{
  171. OK: false,
  172. Error: err.Error(),
  173. })
  174. return
  175. }
  176. results := make([]*api.Repository, len(repos))
  177. for i, repo := range repos {
  178. if err = repo.GetOwner(); err != nil {
  179. ctx.JSON(http.StatusInternalServerError, api.SearchError{
  180. OK: false,
  181. Error: err.Error(),
  182. })
  183. return
  184. }
  185. accessMode, err := models.AccessLevel(ctx.User, repo)
  186. if err != nil {
  187. ctx.JSON(http.StatusInternalServerError, api.SearchError{
  188. OK: false,
  189. Error: err.Error(),
  190. })
  191. }
  192. results[i] = repo.APIFormat(accessMode)
  193. }
  194. ctx.SetLinkHeader(int(count), opts.PageSize)
  195. ctx.Header().Set("X-Total-Count", fmt.Sprintf("%d", count))
  196. ctx.JSON(http.StatusOK, api.SearchResults{
  197. OK: true,
  198. Data: results,
  199. })
  200. }
  201. // CreateUserRepo create a repository for a user
  202. func CreateUserRepo(ctx *context.APIContext, owner *models.User, opt api.CreateRepoOption) {
  203. if opt.AutoInit && opt.Readme == "" {
  204. opt.Readme = "Default"
  205. }
  206. repo, err := repo_service.CreateRepository(ctx.User, owner, models.CreateRepoOptions{
  207. Name: opt.Name,
  208. Description: opt.Description,
  209. IssueLabels: opt.IssueLabels,
  210. Gitignores: opt.Gitignores,
  211. License: opt.License,
  212. Readme: opt.Readme,
  213. IsPrivate: opt.Private,
  214. AutoInit: opt.AutoInit,
  215. })
  216. if err != nil {
  217. if models.IsErrRepoAlreadyExist(err) {
  218. ctx.Error(http.StatusConflict, "", "The repository with the same name already exists.")
  219. } else if models.IsErrNameReserved(err) ||
  220. models.IsErrNamePatternNotAllowed(err) {
  221. ctx.Error(http.StatusUnprocessableEntity, "", err)
  222. } else {
  223. ctx.Error(http.StatusInternalServerError, "CreateRepository", err)
  224. }
  225. return
  226. }
  227. ctx.JSON(http.StatusCreated, repo.APIFormat(models.AccessModeOwner))
  228. }
  229. // Create one repository of mine
  230. func Create(ctx *context.APIContext, opt api.CreateRepoOption) {
  231. // swagger:operation POST /user/repos repository user createCurrentUserRepo
  232. // ---
  233. // summary: Create a repository
  234. // consumes:
  235. // - application/json
  236. // produces:
  237. // - application/json
  238. // parameters:
  239. // - name: body
  240. // in: body
  241. // schema:
  242. // "$ref": "#/definitions/CreateRepoOption"
  243. // responses:
  244. // "201":
  245. // "$ref": "#/responses/Repository"
  246. // "409":
  247. // description: The repository with the same name already exists.
  248. // "422":
  249. // "$ref": "#/responses/validationError"
  250. if ctx.User.IsOrganization() {
  251. // Shouldn't reach this condition, but just in case.
  252. ctx.Error(http.StatusUnprocessableEntity, "", "not allowed creating repository for organization")
  253. return
  254. }
  255. CreateUserRepo(ctx, ctx.User, opt)
  256. }
  257. // CreateOrgRepoDeprecated create one repository of the organization
  258. func CreateOrgRepoDeprecated(ctx *context.APIContext, opt api.CreateRepoOption) {
  259. // swagger:operation POST /org/{org}/repos organization createOrgRepoDeprecated
  260. // ---
  261. // summary: Create a repository in an organization
  262. // deprecated: true
  263. // consumes:
  264. // - application/json
  265. // produces:
  266. // - application/json
  267. // parameters:
  268. // - name: org
  269. // in: path
  270. // description: name of organization
  271. // type: string
  272. // required: true
  273. // - name: body
  274. // in: body
  275. // schema:
  276. // "$ref": "#/definitions/CreateRepoOption"
  277. // responses:
  278. // "201":
  279. // "$ref": "#/responses/Repository"
  280. // "422":
  281. // "$ref": "#/responses/validationError"
  282. // "403":
  283. // "$ref": "#/responses/forbidden"
  284. CreateOrgRepo(ctx, opt)
  285. }
  286. // CreateOrgRepo create one repository of the organization
  287. func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) {
  288. // swagger:operation POST /orgs/{org}/repos organization createOrgRepo
  289. // ---
  290. // summary: Create a repository in an organization
  291. // consumes:
  292. // - application/json
  293. // produces:
  294. // - application/json
  295. // parameters:
  296. // - name: org
  297. // in: path
  298. // description: name of organization
  299. // type: string
  300. // required: true
  301. // - name: body
  302. // in: body
  303. // schema:
  304. // "$ref": "#/definitions/CreateRepoOption"
  305. // responses:
  306. // "201":
  307. // "$ref": "#/responses/Repository"
  308. // "404":
  309. // "$ref": "#/responses/notFound"
  310. // "403":
  311. // "$ref": "#/responses/forbidden"
  312. org, err := models.GetOrgByName(ctx.Params(":org"))
  313. if err != nil {
  314. if models.IsErrOrgNotExist(err) {
  315. ctx.Error(http.StatusUnprocessableEntity, "", err)
  316. } else {
  317. ctx.Error(http.StatusInternalServerError, "GetOrgByName", err)
  318. }
  319. return
  320. }
  321. if !models.HasOrgVisible(org, ctx.User) {
  322. ctx.NotFound("HasOrgVisible", nil)
  323. return
  324. }
  325. if !ctx.User.IsAdmin {
  326. canCreate, err := org.CanCreateOrgRepo(ctx.User.ID)
  327. if err != nil {
  328. ctx.ServerError("CanCreateOrgRepo", err)
  329. return
  330. } else if !canCreate {
  331. ctx.Error(http.StatusForbidden, "", "Given user is not allowed to create repository in organization.")
  332. return
  333. }
  334. }
  335. CreateUserRepo(ctx, org, opt)
  336. }
  337. // Get one repository
  338. func Get(ctx *context.APIContext) {
  339. // swagger:operation GET /repos/{owner}/{repo} repository repoGet
  340. // ---
  341. // summary: Get a repository
  342. // produces:
  343. // - application/json
  344. // parameters:
  345. // - name: owner
  346. // in: path
  347. // description: owner of the repo
  348. // type: string
  349. // required: true
  350. // - name: repo
  351. // in: path
  352. // description: name of the repo
  353. // type: string
  354. // required: true
  355. // responses:
  356. // "200":
  357. // "$ref": "#/responses/Repository"
  358. ctx.JSON(http.StatusOK, ctx.Repo.Repository.APIFormat(ctx.Repo.AccessMode))
  359. }
  360. // GetByID returns a single Repository
  361. func GetByID(ctx *context.APIContext) {
  362. // swagger:operation GET /repositories/{id} repository repoGetByID
  363. // ---
  364. // summary: Get a repository by id
  365. // produces:
  366. // - application/json
  367. // parameters:
  368. // - name: id
  369. // in: path
  370. // description: id of the repo to get
  371. // type: integer
  372. // format: int64
  373. // required: true
  374. // responses:
  375. // "200":
  376. // "$ref": "#/responses/Repository"
  377. repo, err := models.GetRepositoryByID(ctx.ParamsInt64(":id"))
  378. if err != nil {
  379. if models.IsErrRepoNotExist(err) {
  380. ctx.NotFound()
  381. } else {
  382. ctx.Error(http.StatusInternalServerError, "GetRepositoryByID", err)
  383. }
  384. return
  385. }
  386. perm, err := models.GetUserRepoPermission(repo, ctx.User)
  387. if err != nil {
  388. ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
  389. return
  390. } else if !perm.HasAccess() {
  391. ctx.NotFound()
  392. return
  393. }
  394. ctx.JSON(http.StatusOK, repo.APIFormat(perm.AccessMode))
  395. }
  396. // Edit edit repository properties
  397. func Edit(ctx *context.APIContext, opts api.EditRepoOption) {
  398. // swagger:operation PATCH /repos/{owner}/{repo} repository repoEdit
  399. // ---
  400. // summary: Edit a repository's properties. Only fields that are set will be changed.
  401. // produces:
  402. // - application/json
  403. // parameters:
  404. // - name: owner
  405. // in: path
  406. // description: owner of the repo to edit
  407. // type: string
  408. // required: true
  409. // - name: repo
  410. // in: path
  411. // description: name of the repo to edit
  412. // type: string
  413. // required: true
  414. // required: true
  415. // - name: body
  416. // in: body
  417. // description: "Properties of a repo that you can edit"
  418. // schema:
  419. // "$ref": "#/definitions/EditRepoOption"
  420. // responses:
  421. // "200":
  422. // "$ref": "#/responses/Repository"
  423. // "403":
  424. // "$ref": "#/responses/forbidden"
  425. // "422":
  426. // "$ref": "#/responses/validationError"
  427. if err := updateBasicProperties(ctx, opts); err != nil {
  428. return
  429. }
  430. if err := updateRepoUnits(ctx, opts); err != nil {
  431. return
  432. }
  433. if opts.Archived != nil {
  434. if err := updateRepoArchivedState(ctx, opts); err != nil {
  435. return
  436. }
  437. }
  438. ctx.JSON(http.StatusOK, ctx.Repo.Repository.APIFormat(ctx.Repo.AccessMode))
  439. }
  440. // updateBasicProperties updates the basic properties of a repo: Name, Description, Website and Visibility
  441. func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) error {
  442. owner := ctx.Repo.Owner
  443. repo := ctx.Repo.Repository
  444. newRepoName := repo.Name
  445. if opts.Name != nil {
  446. newRepoName = *opts.Name
  447. }
  448. // Check if repository name has been changed and not just a case change
  449. if repo.LowerName != strings.ToLower(newRepoName) {
  450. if err := repo_service.ChangeRepositoryName(ctx.User, repo, newRepoName); err != nil {
  451. switch {
  452. case models.IsErrRepoAlreadyExist(err):
  453. ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name is already taken [name: %s]", newRepoName), err)
  454. case models.IsErrNameReserved(err):
  455. ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name is reserved [name: %s]", newRepoName), err)
  456. case models.IsErrNamePatternNotAllowed(err):
  457. ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name's pattern is not allowed [name: %s, pattern: %s]", newRepoName, err.(models.ErrNamePatternNotAllowed).Pattern), err)
  458. default:
  459. ctx.Error(http.StatusUnprocessableEntity, "ChangeRepositoryName", err)
  460. }
  461. return err
  462. }
  463. log.Trace("Repository name changed: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newRepoName)
  464. }
  465. // Update the name in the repo object for the response
  466. repo.Name = newRepoName
  467. repo.LowerName = strings.ToLower(newRepoName)
  468. if opts.Description != nil {
  469. repo.Description = *opts.Description
  470. }
  471. if opts.Website != nil {
  472. repo.Website = *opts.Website
  473. }
  474. visibilityChanged := false
  475. if opts.Private != nil {
  476. // Visibility of forked repository is forced sync with base repository.
  477. if repo.IsFork {
  478. *opts.Private = repo.BaseRepo.IsPrivate
  479. }
  480. visibilityChanged = repo.IsPrivate != *opts.Private
  481. // when ForcePrivate enabled, you could change public repo to private, but only admin users can change private to public
  482. if visibilityChanged && setting.Repository.ForcePrivate && !*opts.Private && !ctx.User.IsAdmin {
  483. err := fmt.Errorf("cannot change private repository to public")
  484. ctx.Error(http.StatusUnprocessableEntity, "Force Private enabled", err)
  485. return err
  486. }
  487. repo.IsPrivate = *opts.Private
  488. }
  489. if opts.Template != nil {
  490. repo.IsTemplate = *opts.Template
  491. }
  492. // Default branch only updated if changed and exist
  493. if opts.DefaultBranch != nil && repo.DefaultBranch != *opts.DefaultBranch && ctx.Repo.GitRepo.IsBranchExist(*opts.DefaultBranch) {
  494. if err := ctx.Repo.GitRepo.SetDefaultBranch(*opts.DefaultBranch); err != nil {
  495. if !git.IsErrUnsupportedVersion(err) {
  496. ctx.Error(http.StatusInternalServerError, "SetDefaultBranch", err)
  497. return err
  498. }
  499. }
  500. repo.DefaultBranch = *opts.DefaultBranch
  501. }
  502. if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
  503. ctx.Error(http.StatusInternalServerError, "UpdateRepository", err)
  504. return err
  505. }
  506. log.Trace("Repository basic settings updated: %s/%s", owner.Name, repo.Name)
  507. return nil
  508. }
  509. // updateRepoUnits updates repo units: Issue settings, Wiki settings, PR settings
  510. func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error {
  511. owner := ctx.Repo.Owner
  512. repo := ctx.Repo.Repository
  513. var units []models.RepoUnit
  514. var deleteUnitTypes []models.UnitType
  515. if opts.HasIssues != nil {
  516. if *opts.HasIssues && opts.ExternalTracker != nil && !models.UnitTypeExternalTracker.UnitGlobalDisabled() {
  517. // Check that values are valid
  518. if !validation.IsValidExternalURL(opts.ExternalTracker.ExternalTrackerURL) {
  519. err := fmt.Errorf("External tracker URL not valid")
  520. ctx.Error(http.StatusUnprocessableEntity, "Invalid external tracker URL", err)
  521. return err
  522. }
  523. if len(opts.ExternalTracker.ExternalTrackerFormat) != 0 && !validation.IsValidExternalTrackerURLFormat(opts.ExternalTracker.ExternalTrackerFormat) {
  524. err := fmt.Errorf("External tracker URL format not valid")
  525. ctx.Error(http.StatusUnprocessableEntity, "Invalid external tracker URL format", err)
  526. return err
  527. }
  528. units = append(units, models.RepoUnit{
  529. RepoID: repo.ID,
  530. Type: models.UnitTypeExternalTracker,
  531. Config: &models.ExternalTrackerConfig{
  532. ExternalTrackerURL: opts.ExternalTracker.ExternalTrackerURL,
  533. ExternalTrackerFormat: opts.ExternalTracker.ExternalTrackerFormat,
  534. ExternalTrackerStyle: opts.ExternalTracker.ExternalTrackerStyle,
  535. },
  536. })
  537. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeIssues)
  538. } else if *opts.HasIssues && opts.ExternalTracker == nil && !models.UnitTypeIssues.UnitGlobalDisabled() {
  539. // Default to built-in tracker
  540. var config *models.IssuesConfig
  541. if opts.InternalTracker != nil {
  542. config = &models.IssuesConfig{
  543. EnableTimetracker: opts.InternalTracker.EnableTimeTracker,
  544. AllowOnlyContributorsToTrackTime: opts.InternalTracker.AllowOnlyContributorsToTrackTime,
  545. EnableDependencies: opts.InternalTracker.EnableIssueDependencies,
  546. }
  547. } else if unit, err := repo.GetUnit(models.UnitTypeIssues); err != nil {
  548. // Unit type doesn't exist so we make a new config file with default values
  549. config = &models.IssuesConfig{
  550. EnableTimetracker: true,
  551. AllowOnlyContributorsToTrackTime: true,
  552. EnableDependencies: true,
  553. }
  554. } else {
  555. config = unit.IssuesConfig()
  556. }
  557. units = append(units, models.RepoUnit{
  558. RepoID: repo.ID,
  559. Type: models.UnitTypeIssues,
  560. Config: config,
  561. })
  562. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeExternalTracker)
  563. } else if !*opts.HasIssues {
  564. if !models.UnitTypeExternalTracker.UnitGlobalDisabled() {
  565. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeExternalTracker)
  566. }
  567. if !models.UnitTypeIssues.UnitGlobalDisabled() {
  568. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeIssues)
  569. }
  570. }
  571. }
  572. if opts.HasWiki != nil {
  573. if *opts.HasWiki && opts.ExternalWiki != nil && !models.UnitTypeExternalWiki.UnitGlobalDisabled() {
  574. // Check that values are valid
  575. if !validation.IsValidExternalURL(opts.ExternalWiki.ExternalWikiURL) {
  576. err := fmt.Errorf("External wiki URL not valid")
  577. ctx.Error(http.StatusUnprocessableEntity, "", "Invalid external wiki URL")
  578. return err
  579. }
  580. units = append(units, models.RepoUnit{
  581. RepoID: repo.ID,
  582. Type: models.UnitTypeExternalWiki,
  583. Config: &models.ExternalWikiConfig{
  584. ExternalWikiURL: opts.ExternalWiki.ExternalWikiURL,
  585. },
  586. })
  587. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeWiki)
  588. } else if *opts.HasWiki && opts.ExternalWiki == nil && !models.UnitTypeWiki.UnitGlobalDisabled() {
  589. config := &models.UnitConfig{}
  590. units = append(units, models.RepoUnit{
  591. RepoID: repo.ID,
  592. Type: models.UnitTypeWiki,
  593. Config: config,
  594. })
  595. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeExternalWiki)
  596. } else if !*opts.HasWiki {
  597. if !models.UnitTypeExternalWiki.UnitGlobalDisabled() {
  598. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeExternalWiki)
  599. }
  600. if !models.UnitTypeWiki.UnitGlobalDisabled() {
  601. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeWiki)
  602. }
  603. }
  604. }
  605. if opts.HasPullRequests != nil {
  606. if *opts.HasPullRequests && !models.UnitTypePullRequests.UnitGlobalDisabled() {
  607. // We do allow setting individual PR settings through the API, so
  608. // we get the config settings and then set them
  609. // if those settings were provided in the opts.
  610. unit, err := repo.GetUnit(models.UnitTypePullRequests)
  611. var config *models.PullRequestsConfig
  612. if err != nil {
  613. // Unit type doesn't exist so we make a new config file with default values
  614. config = &models.PullRequestsConfig{
  615. IgnoreWhitespaceConflicts: false,
  616. AllowMerge: true,
  617. AllowRebase: true,
  618. AllowRebaseMerge: true,
  619. AllowSquash: true,
  620. }
  621. } else {
  622. config = unit.PullRequestsConfig()
  623. }
  624. if opts.IgnoreWhitespaceConflicts != nil {
  625. config.IgnoreWhitespaceConflicts = *opts.IgnoreWhitespaceConflicts
  626. }
  627. if opts.AllowMerge != nil {
  628. config.AllowMerge = *opts.AllowMerge
  629. }
  630. if opts.AllowRebase != nil {
  631. config.AllowRebase = *opts.AllowRebase
  632. }
  633. if opts.AllowRebaseMerge != nil {
  634. config.AllowRebaseMerge = *opts.AllowRebaseMerge
  635. }
  636. if opts.AllowSquash != nil {
  637. config.AllowSquash = *opts.AllowSquash
  638. }
  639. units = append(units, models.RepoUnit{
  640. RepoID: repo.ID,
  641. Type: models.UnitTypePullRequests,
  642. Config: config,
  643. })
  644. } else if !*opts.HasPullRequests && !models.UnitTypePullRequests.UnitGlobalDisabled() {
  645. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypePullRequests)
  646. }
  647. }
  648. if err := models.UpdateRepositoryUnits(repo, units, deleteUnitTypes); err != nil {
  649. ctx.Error(http.StatusInternalServerError, "UpdateRepositoryUnits", err)
  650. return err
  651. }
  652. log.Trace("Repository advanced settings updated: %s/%s", owner.Name, repo.Name)
  653. return nil
  654. }
  655. // updateRepoArchivedState updates repo's archive state
  656. func updateRepoArchivedState(ctx *context.APIContext, opts api.EditRepoOption) error {
  657. repo := ctx.Repo.Repository
  658. // archive / un-archive
  659. if opts.Archived != nil {
  660. if repo.IsMirror {
  661. err := fmt.Errorf("repo is a mirror, cannot archive/un-archive")
  662. ctx.Error(http.StatusUnprocessableEntity, err.Error(), err)
  663. return err
  664. }
  665. if *opts.Archived {
  666. if err := repo.SetArchiveRepoState(*opts.Archived); err != nil {
  667. log.Error("Tried to archive a repo: %s", err)
  668. ctx.Error(http.StatusInternalServerError, "ArchiveRepoState", err)
  669. return err
  670. }
  671. log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  672. } else {
  673. if err := repo.SetArchiveRepoState(*opts.Archived); err != nil {
  674. log.Error("Tried to un-archive a repo: %s", err)
  675. ctx.Error(http.StatusInternalServerError, "ArchiveRepoState", err)
  676. return err
  677. }
  678. log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  679. }
  680. }
  681. return nil
  682. }
  683. // Delete one repository
  684. func Delete(ctx *context.APIContext) {
  685. // swagger:operation DELETE /repos/{owner}/{repo} repository repoDelete
  686. // ---
  687. // summary: Delete a repository
  688. // produces:
  689. // - application/json
  690. // parameters:
  691. // - name: owner
  692. // in: path
  693. // description: owner of the repo to delete
  694. // type: string
  695. // required: true
  696. // - name: repo
  697. // in: path
  698. // description: name of the repo to delete
  699. // type: string
  700. // required: true
  701. // responses:
  702. // "204":
  703. // "$ref": "#/responses/empty"
  704. // "403":
  705. // "$ref": "#/responses/forbidden"
  706. owner := ctx.Repo.Owner
  707. repo := ctx.Repo.Repository
  708. canDelete, err := repo.CanUserDelete(ctx.User)
  709. if err != nil {
  710. ctx.Error(http.StatusInternalServerError, "CanUserDelete", err)
  711. return
  712. } else if !canDelete {
  713. ctx.Error(http.StatusForbidden, "", "Given user is not owner of organization.")
  714. return
  715. }
  716. if err := repo_service.DeleteRepository(ctx.User, repo); err != nil {
  717. ctx.Error(http.StatusInternalServerError, "DeleteRepository", err)
  718. return
  719. }
  720. log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name)
  721. ctx.Status(http.StatusNoContent)
  722. }