migrations.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. // Copyright 2015 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 migrations
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. "github.com/go-xorm/xorm"
  17. "gopkg.in/ini.v1"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/setting"
  20. gouuid "github.com/gogits/gogs/modules/uuid"
  21. )
  22. const _MIN_DB_VER = 0
  23. type Migration interface {
  24. Description() string
  25. Migrate(*xorm.Engine) error
  26. }
  27. type migration struct {
  28. description string
  29. migrate func(*xorm.Engine) error
  30. }
  31. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  32. return &migration{desc, fn}
  33. }
  34. func (m *migration) Description() string {
  35. return m.description
  36. }
  37. func (m *migration) Migrate(x *xorm.Engine) error {
  38. return m.migrate(x)
  39. }
  40. // The version table. Should have only one row with id==1
  41. type Version struct {
  42. Id int64
  43. Version int64
  44. }
  45. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  46. // If you want to "retire" a migration, remove it from the top of the list and
  47. // update _MIN_VER_DB accordingly
  48. var migrations = []Migration{
  49. NewMigration("generate collaboration from access", accessToCollaboration), // V0 -> V1:v0.5.13
  50. NewMigration("make authorize 4 if team is owners", ownerTeamUpdate), // V1 -> V2:v0.5.13
  51. NewMigration("refactor access table to use id's", accessRefactor), // V2 -> V3:v0.5.13
  52. NewMigration("generate team-repo from team", teamToTeamRepo), // V3 -> V4:v0.5.13
  53. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  54. NewMigration("trim action compare URL prefix", trimCommitActionAppUrlPrefix), // V5 -> V6:v0.6.3
  55. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  56. NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4
  57. NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16
  58. NewMigration("clean up migrate repo info", cleanUpMigrateRepoInfo), // V9 -> V10:v0.6.20
  59. }
  60. // Migrate database to current version
  61. func Migrate(x *xorm.Engine) error {
  62. if err := x.Sync(new(Version)); err != nil {
  63. return fmt.Errorf("sync: %v", err)
  64. }
  65. currentVersion := &Version{Id: 1}
  66. has, err := x.Get(currentVersion)
  67. if err != nil {
  68. return fmt.Errorf("get: %v", err)
  69. } else if !has {
  70. // If the user table does not exist it is a fresh installation and we
  71. // can skip all migrations.
  72. needsMigration, err := x.IsTableExist("user")
  73. if err != nil {
  74. return err
  75. }
  76. if needsMigration {
  77. isEmpty, err := x.IsTableEmpty("user")
  78. if err != nil {
  79. return err
  80. }
  81. // If the user table is empty it is a fresh installation and we can
  82. // skip all migrations.
  83. needsMigration = !isEmpty
  84. }
  85. if !needsMigration {
  86. currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
  87. }
  88. if _, err = x.InsertOne(currentVersion); err != nil {
  89. return fmt.Errorf("insert: %v", err)
  90. }
  91. }
  92. v := currentVersion.Version
  93. if _MIN_DB_VER > v {
  94. log.Fatal(4, "Gogs no longer supports auto-migration from your previously installed version. Please try to upgrade to a lower version first, then upgrade to current version.")
  95. return nil
  96. }
  97. if int(v-_MIN_DB_VER) > len(migrations) {
  98. // User downgraded Gogs.
  99. currentVersion.Version = int64(len(migrations) + _MIN_DB_VER)
  100. _, err = x.Id(1).Update(currentVersion)
  101. return err
  102. }
  103. for i, m := range migrations[v-_MIN_DB_VER:] {
  104. log.Info("Migration: %s", m.Description())
  105. if err = m.Migrate(x); err != nil {
  106. return fmt.Errorf("do migrate: %v", err)
  107. }
  108. currentVersion.Version = v + int64(i) + 1
  109. if _, err = x.Id(1).Update(currentVersion); err != nil {
  110. return err
  111. }
  112. }
  113. return nil
  114. }
  115. func sessionRelease(sess *xorm.Session) {
  116. if !sess.IsCommitedOrRollbacked {
  117. sess.Rollback()
  118. }
  119. sess.Close()
  120. }
  121. func accessToCollaboration(x *xorm.Engine) (err error) {
  122. type Collaboration struct {
  123. ID int64 `xorm:"pk autoincr"`
  124. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  125. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  126. Created time.Time
  127. }
  128. if err = x.Sync(new(Collaboration)); err != nil {
  129. return fmt.Errorf("sync: %v", err)
  130. }
  131. results, err := x.Query("SELECT u.id AS `uid`, a.repo_name AS `repo`, a.mode AS `mode`, a.created as `created` FROM `access` a JOIN `user` u ON a.user_name=u.lower_name")
  132. if err != nil {
  133. if strings.Contains(err.Error(), "no such column") {
  134. return nil
  135. }
  136. return err
  137. }
  138. sess := x.NewSession()
  139. defer sessionRelease(sess)
  140. if err = sess.Begin(); err != nil {
  141. return err
  142. }
  143. offset := strings.Split(time.Now().String(), " ")[2]
  144. for _, result := range results {
  145. mode := com.StrTo(result["mode"]).MustInt64()
  146. // Collaborators must have write access.
  147. if mode < 2 {
  148. continue
  149. }
  150. userID := com.StrTo(result["uid"]).MustInt64()
  151. repoRefName := string(result["repo"])
  152. var created time.Time
  153. switch {
  154. case setting.UseSQLite3:
  155. created, _ = time.Parse(time.RFC3339, string(result["created"]))
  156. case setting.UseMySQL:
  157. created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
  158. case setting.UsePostgreSQL:
  159. created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
  160. }
  161. // find owner of repository
  162. parts := strings.SplitN(repoRefName, "/", 2)
  163. ownerName := parts[0]
  164. repoName := parts[1]
  165. results, err := sess.Query("SELECT u.id as `uid`, ou.uid as `memberid` FROM `user` u LEFT JOIN org_user ou ON ou.org_id=u.id WHERE u.lower_name=?", ownerName)
  166. if err != nil {
  167. return err
  168. }
  169. if len(results) < 1 {
  170. continue
  171. }
  172. ownerID := com.StrTo(results[0]["uid"]).MustInt64()
  173. if ownerID == userID {
  174. continue
  175. }
  176. // test if user is member of owning organization
  177. isMember := false
  178. for _, member := range results {
  179. memberID := com.StrTo(member["memberid"]).MustInt64()
  180. // We can skip all cases that a user is member of the owning organization
  181. if memberID == userID {
  182. isMember = true
  183. }
  184. }
  185. if isMember {
  186. continue
  187. }
  188. results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
  189. if err != nil {
  190. return err
  191. } else if len(results) < 1 {
  192. continue
  193. }
  194. collaboration := &Collaboration{
  195. UserID: userID,
  196. RepoID: com.StrTo(results[0]["id"]).MustInt64(),
  197. }
  198. has, err := sess.Get(collaboration)
  199. if err != nil {
  200. return err
  201. } else if has {
  202. continue
  203. }
  204. collaboration.Created = created
  205. if _, err = sess.InsertOne(collaboration); err != nil {
  206. return err
  207. }
  208. }
  209. return sess.Commit()
  210. }
  211. func ownerTeamUpdate(x *xorm.Engine) (err error) {
  212. if _, err := x.Exec("UPDATE `team` SET authorize=4 WHERE lower_name=?", "owners"); err != nil {
  213. return fmt.Errorf("update owner team table: %v", err)
  214. }
  215. return nil
  216. }
  217. func accessRefactor(x *xorm.Engine) (err error) {
  218. type (
  219. AccessMode int
  220. Access struct {
  221. ID int64 `xorm:"pk autoincr"`
  222. UserID int64 `xorm:"UNIQUE(s)"`
  223. RepoID int64 `xorm:"UNIQUE(s)"`
  224. Mode AccessMode
  225. }
  226. UserRepo struct {
  227. UserID int64
  228. RepoID int64
  229. }
  230. )
  231. // We consiously don't start a session yet as we make only reads for now, no writes
  232. accessMap := make(map[UserRepo]AccessMode, 50)
  233. results, err := x.Query("SELECT r.id AS `repo_id`, r.is_private AS `is_private`, r.owner_id AS `owner_id`, u.type AS `owner_type` FROM `repository` r LEFT JOIN `user` u ON r.owner_id=u.id")
  234. if err != nil {
  235. return fmt.Errorf("select repositories: %v", err)
  236. }
  237. for _, repo := range results {
  238. repoID := com.StrTo(repo["repo_id"]).MustInt64()
  239. isPrivate := com.StrTo(repo["is_private"]).MustInt() > 0
  240. ownerID := com.StrTo(repo["owner_id"]).MustInt64()
  241. ownerIsOrganization := com.StrTo(repo["owner_type"]).MustInt() > 0
  242. results, err := x.Query("SELECT `user_id` FROM `collaboration` WHERE repo_id=?", repoID)
  243. if err != nil {
  244. return fmt.Errorf("select collaborators: %v", err)
  245. }
  246. for _, user := range results {
  247. userID := com.StrTo(user["user_id"]).MustInt64()
  248. accessMap[UserRepo{userID, repoID}] = 2 // WRITE ACCESS
  249. }
  250. if !ownerIsOrganization {
  251. continue
  252. }
  253. // The minimum level to add a new access record,
  254. // because public repository has implicit open access.
  255. minAccessLevel := AccessMode(0)
  256. if !isPrivate {
  257. minAccessLevel = 1
  258. }
  259. repoString := "$" + string(repo["repo_id"]) + "|"
  260. results, err = x.Query("SELECT `id`,`authorize`,`repo_ids` FROM `team` WHERE org_id=? AND authorize>? ORDER BY `authorize` ASC", ownerID, int(minAccessLevel))
  261. if err != nil {
  262. if strings.Contains(err.Error(), "no such column") {
  263. return nil
  264. }
  265. return fmt.Errorf("select teams from org: %v", err)
  266. }
  267. for _, team := range results {
  268. if !strings.Contains(string(team["repo_ids"]), repoString) {
  269. continue
  270. }
  271. teamID := com.StrTo(team["id"]).MustInt64()
  272. mode := AccessMode(com.StrTo(team["authorize"]).MustInt())
  273. results, err := x.Query("SELECT `uid` FROM `team_user` WHERE team_id=?", teamID)
  274. if err != nil {
  275. return fmt.Errorf("select users from team: %v", err)
  276. }
  277. for _, user := range results {
  278. userID := com.StrTo(user["uid"]).MustInt64()
  279. accessMap[UserRepo{userID, repoID}] = mode
  280. }
  281. }
  282. }
  283. // Drop table can't be in a session (at least not in sqlite)
  284. if _, err = x.Exec("DROP TABLE `access`"); err != nil {
  285. return fmt.Errorf("drop access table: %v", err)
  286. }
  287. // Now we start writing so we make a session
  288. sess := x.NewSession()
  289. defer sessionRelease(sess)
  290. if err = sess.Begin(); err != nil {
  291. return err
  292. }
  293. if err = sess.Sync2(new(Access)); err != nil {
  294. return fmt.Errorf("sync: %v", err)
  295. }
  296. accesses := make([]*Access, 0, len(accessMap))
  297. for ur, mode := range accessMap {
  298. accesses = append(accesses, &Access{UserID: ur.UserID, RepoID: ur.RepoID, Mode: mode})
  299. }
  300. if _, err = sess.Insert(accesses); err != nil {
  301. return fmt.Errorf("insert accesses: %v", err)
  302. }
  303. return sess.Commit()
  304. }
  305. func teamToTeamRepo(x *xorm.Engine) error {
  306. type TeamRepo struct {
  307. ID int64 `xorm:"pk autoincr"`
  308. OrgID int64 `xorm:"INDEX"`
  309. TeamID int64 `xorm:"UNIQUE(s)"`
  310. RepoID int64 `xorm:"UNIQUE(s)"`
  311. }
  312. teamRepos := make([]*TeamRepo, 0, 50)
  313. results, err := x.Query("SELECT `id`,`org_id`,`repo_ids` FROM `team`")
  314. if err != nil {
  315. if strings.Contains(err.Error(), "no such column") {
  316. return nil
  317. }
  318. return fmt.Errorf("select teams: %v", err)
  319. }
  320. for _, team := range results {
  321. orgID := com.StrTo(team["org_id"]).MustInt64()
  322. teamID := com.StrTo(team["id"]).MustInt64()
  323. // #1032: legacy code can have duplicated IDs for same repository.
  324. mark := make(map[int64]bool)
  325. for _, idStr := range strings.Split(string(team["repo_ids"]), "|") {
  326. repoID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  327. if repoID == 0 || mark[repoID] {
  328. continue
  329. }
  330. mark[repoID] = true
  331. teamRepos = append(teamRepos, &TeamRepo{
  332. OrgID: orgID,
  333. TeamID: teamID,
  334. RepoID: repoID,
  335. })
  336. }
  337. }
  338. sess := x.NewSession()
  339. defer sessionRelease(sess)
  340. if err = sess.Begin(); err != nil {
  341. return err
  342. }
  343. if err = sess.Sync2(new(TeamRepo)); err != nil {
  344. return fmt.Errorf("sync2: %v", err)
  345. } else if _, err = sess.Insert(teamRepos); err != nil {
  346. return fmt.Errorf("insert team-repos: %v", err)
  347. }
  348. return sess.Commit()
  349. }
  350. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  351. cfg, err := ini.Load(setting.CustomConf)
  352. if err != nil {
  353. return fmt.Errorf("load custom config: %v", err)
  354. }
  355. cfg.DeleteSection("i18n")
  356. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  357. return fmt.Errorf("save custom config: %v", err)
  358. }
  359. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  360. return nil
  361. }
  362. func trimCommitActionAppUrlPrefix(x *xorm.Engine) error {
  363. type PushCommit struct {
  364. Sha1 string
  365. Message string
  366. AuthorEmail string
  367. AuthorName string
  368. }
  369. type PushCommits struct {
  370. Len int
  371. Commits []*PushCommit
  372. CompareUrl string
  373. }
  374. type Action struct {
  375. ID int64 `xorm:"pk autoincr"`
  376. Content string `xorm:"TEXT"`
  377. }
  378. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  379. if err != nil {
  380. return fmt.Errorf("select commit actions: %v", err)
  381. }
  382. sess := x.NewSession()
  383. defer sessionRelease(sess)
  384. if err = sess.Begin(); err != nil {
  385. return err
  386. }
  387. var pushCommits *PushCommits
  388. for _, action := range results {
  389. actID := com.StrTo(string(action["id"])).MustInt64()
  390. if actID == 0 {
  391. continue
  392. }
  393. pushCommits = new(PushCommits)
  394. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  395. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  396. }
  397. infos := strings.Split(pushCommits.CompareUrl, "/")
  398. if len(infos) <= 4 {
  399. continue
  400. }
  401. pushCommits.CompareUrl = strings.Join(infos[len(infos)-4:], "/")
  402. p, err := json.Marshal(pushCommits)
  403. if err != nil {
  404. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  405. }
  406. if _, err = sess.Id(actID).Update(&Action{
  407. Content: string(p),
  408. }); err != nil {
  409. return fmt.Errorf("update action[%d]: %v", actID, err)
  410. }
  411. }
  412. return sess.Commit()
  413. }
  414. func issueToIssueLabel(x *xorm.Engine) error {
  415. type IssueLabel struct {
  416. ID int64 `xorm:"pk autoincr"`
  417. IssueID int64 `xorm:"UNIQUE(s)"`
  418. LabelID int64 `xorm:"UNIQUE(s)"`
  419. }
  420. issueLabels := make([]*IssueLabel, 0, 50)
  421. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  422. if err != nil {
  423. if strings.Contains(err.Error(), "no such column") {
  424. return nil
  425. }
  426. return fmt.Errorf("select issues: %v", err)
  427. }
  428. for _, issue := range results {
  429. issueID := com.StrTo(issue["id"]).MustInt64()
  430. // Just in case legacy code can have duplicated IDs for same label.
  431. mark := make(map[int64]bool)
  432. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  433. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  434. if labelID == 0 || mark[labelID] {
  435. continue
  436. }
  437. mark[labelID] = true
  438. issueLabels = append(issueLabels, &IssueLabel{
  439. IssueID: issueID,
  440. LabelID: labelID,
  441. })
  442. }
  443. }
  444. sess := x.NewSession()
  445. defer sessionRelease(sess)
  446. if err = sess.Begin(); err != nil {
  447. return err
  448. }
  449. if err = sess.Sync2(new(IssueLabel)); err != nil {
  450. return fmt.Errorf("sync2: %v", err)
  451. } else if _, err = sess.Insert(issueLabels); err != nil {
  452. return fmt.Errorf("insert issue-labels: %v", err)
  453. }
  454. return sess.Commit()
  455. }
  456. func attachmentRefactor(x *xorm.Engine) error {
  457. type Attachment struct {
  458. ID int64 `xorm:"pk autoincr"`
  459. UUID string `xorm:"uuid INDEX"`
  460. // For rename purpose.
  461. Path string `xorm:"-"`
  462. NewPath string `xorm:"-"`
  463. }
  464. results, err := x.Query("SELECT * FROM `attachment`")
  465. if err != nil {
  466. return fmt.Errorf("select attachments: %v", err)
  467. }
  468. attachments := make([]*Attachment, 0, len(results))
  469. for _, attach := range results {
  470. if !com.IsExist(string(attach["path"])) {
  471. // If the attachment is already missing, there is no point to update it.
  472. continue
  473. }
  474. attachments = append(attachments, &Attachment{
  475. ID: com.StrTo(attach["id"]).MustInt64(),
  476. UUID: gouuid.NewV4().String(),
  477. Path: string(attach["path"]),
  478. })
  479. }
  480. sess := x.NewSession()
  481. defer sessionRelease(sess)
  482. if err = sess.Begin(); err != nil {
  483. return err
  484. }
  485. if err = sess.Sync2(new(Attachment)); err != nil {
  486. return fmt.Errorf("Sync2: %v", err)
  487. }
  488. // Note: Roll back for rename can be a dead loop,
  489. // so produces a backup file.
  490. var buf bytes.Buffer
  491. buf.WriteString("# old path -> new path\n")
  492. // Update database first because this is where error happens the most often.
  493. for _, attach := range attachments {
  494. if _, err = sess.Id(attach.ID).Update(attach); err != nil {
  495. return err
  496. }
  497. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  498. buf.WriteString(attach.Path)
  499. buf.WriteString("\t")
  500. buf.WriteString(attach.NewPath)
  501. buf.WriteString("\n")
  502. }
  503. // Then rename attachments.
  504. isSucceed := true
  505. defer func() {
  506. if isSucceed {
  507. return
  508. }
  509. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  510. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  511. fmt.Println("Fail to rename some attachments, old and new paths are saved into:", dumpPath)
  512. }()
  513. for _, attach := range attachments {
  514. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  515. isSucceed = false
  516. return err
  517. }
  518. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  519. isSucceed = false
  520. return err
  521. }
  522. }
  523. return sess.Commit()
  524. }
  525. func renamePullRequestFields(x *xorm.Engine) (err error) {
  526. type PullRequest struct {
  527. ID int64 `xorm:"pk autoincr"`
  528. PullID int64 `xorm:"INDEX"`
  529. PullIndex int64
  530. HeadBarcnh string
  531. IssueID int64 `xorm:"INDEX"`
  532. Index int64
  533. HeadBranch string
  534. }
  535. if err = x.Sync(new(PullRequest)); err != nil {
  536. return fmt.Errorf("sync: %v", err)
  537. }
  538. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  539. if err != nil {
  540. if strings.Contains(err.Error(), "no such column") {
  541. return nil
  542. }
  543. return fmt.Errorf("select pull requests: %v", err)
  544. }
  545. sess := x.NewSession()
  546. defer sessionRelease(sess)
  547. if err = sess.Begin(); err != nil {
  548. return err
  549. }
  550. var pull *PullRequest
  551. for _, pr := range results {
  552. pull = &PullRequest{
  553. ID: com.StrTo(pr["id"]).MustInt64(),
  554. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  555. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  556. HeadBranch: string(pr["head_barcnh"]),
  557. }
  558. if _, err = sess.Id(pull.ID).Update(pull); err != nil {
  559. return err
  560. }
  561. }
  562. return sess.Commit()
  563. }
  564. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  565. type (
  566. User struct {
  567. ID int64 `xorm:"pk autoincr"`
  568. LowerName string
  569. }
  570. Repository struct {
  571. ID int64 `xorm:"pk autoincr"`
  572. OwnerID int64
  573. LowerName string
  574. }
  575. )
  576. repos := make([]*Repository, 0, 25)
  577. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  578. return fmt.Errorf("select all non-mirror repositories: %v", err)
  579. }
  580. var user *User
  581. for _, repo := range repos {
  582. user = &User{ID: repo.OwnerID}
  583. has, err := x.Get(user)
  584. if err != nil {
  585. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  586. } else if !has {
  587. continue
  588. }
  589. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  590. // In case repository file is somehow missing.
  591. if !com.IsFile(configPath) {
  592. continue
  593. }
  594. cfg, err := ini.Load(configPath)
  595. if err != nil {
  596. return fmt.Errorf("open config file: %v", err)
  597. }
  598. cfg.DeleteSection("remote \"origin\"")
  599. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  600. return fmt.Errorf("save config file: %v", err)
  601. }
  602. }
  603. return nil
  604. }