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

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