repo.go 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "html/template"
  10. "io/ioutil"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "path/filepath"
  15. "regexp"
  16. "sort"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/Unknwon/cae/zip"
  21. "github.com/Unknwon/com"
  22. "github.com/go-xorm/xorm"
  23. "gopkg.in/ini.v1"
  24. "github.com/gogits/gogs/modules/base"
  25. "github.com/gogits/gogs/modules/bindata"
  26. "github.com/gogits/gogs/modules/git"
  27. "github.com/gogits/gogs/modules/log"
  28. "github.com/gogits/gogs/modules/process"
  29. "github.com/gogits/gogs/modules/setting"
  30. )
  31. const (
  32. _TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
  33. )
  34. var (
  35. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  36. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  37. ErrMirrorNotExist = errors.New("Mirror does not exist")
  38. ErrInvalidReference = errors.New("Invalid reference specified")
  39. ErrNameEmpty = errors.New("Name is empty")
  40. )
  41. var (
  42. Gitignores, Licenses, Readmes []string
  43. // Maximum items per page in forks, watchers and stars of a repo
  44. ItemsPerPage = 54
  45. )
  46. func LoadRepoConfig() {
  47. // Load .gitignore and license files and readme templates.
  48. types := []string{"gitignore", "license", "readme"}
  49. typeFiles := make([][]string, 3)
  50. for i, t := range types {
  51. files, err := bindata.AssetDir("conf/" + t)
  52. if err != nil {
  53. log.Fatal(4, "Fail to get %s files: %v", t, err)
  54. }
  55. customPath := path.Join(setting.CustomPath, "conf", t)
  56. if com.IsDir(customPath) {
  57. customFiles, err := com.StatDir(customPath)
  58. if err != nil {
  59. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  60. }
  61. for _, f := range customFiles {
  62. if !com.IsSliceContainsStr(files, f) {
  63. files = append(files, f)
  64. }
  65. }
  66. }
  67. typeFiles[i] = files
  68. }
  69. Gitignores = typeFiles[0]
  70. Licenses = typeFiles[1]
  71. Readmes = typeFiles[2]
  72. sort.Strings(Gitignores)
  73. sort.Strings(Licenses)
  74. sort.Strings(Readmes)
  75. }
  76. func NewRepoContext() {
  77. zip.Verbose = false
  78. // Check Git installation.
  79. if _, err := exec.LookPath("git"); err != nil {
  80. log.Fatal(4, "Fail to test 'git' command: %v (forgotten install?)", err)
  81. }
  82. // Check Git version.
  83. ver, err := git.GetVersion()
  84. if err != nil {
  85. log.Fatal(4, "Fail to get Git version: %v", err)
  86. }
  87. reqVer, err := git.ParseVersion("1.7.1")
  88. if err != nil {
  89. log.Fatal(4, "Fail to parse required Git version: %v", err)
  90. }
  91. if ver.LessThan(reqVer) {
  92. log.Fatal(4, "Gogs requires Git version greater or equal to 1.7.1")
  93. }
  94. log.Info("Git Version: %s", ver.String())
  95. // Git requires setting user.name and user.email in order to commit changes.
  96. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogs@fake.local"} {
  97. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  98. // ExitError indicates this config is not set
  99. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  100. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  101. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  102. }
  103. log.Info("Git config %s set to %s", configKey, defaultValue)
  104. } else {
  105. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  106. }
  107. }
  108. }
  109. // Set git some configurations.
  110. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  111. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  112. log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
  113. }
  114. }
  115. // Repository represents a git repository.
  116. type Repository struct {
  117. ID int64 `xorm:"pk autoincr"`
  118. OwnerID int64 `xorm:"UNIQUE(s)"`
  119. Owner *User `xorm:"-"`
  120. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  121. Name string `xorm:"INDEX NOT NULL"`
  122. Description string
  123. Website string
  124. DefaultBranch string
  125. NumWatches int
  126. NumStars int
  127. NumForks int
  128. NumIssues int
  129. NumClosedIssues int
  130. NumOpenIssues int `xorm:"-"`
  131. NumPulls int
  132. NumClosedPulls int
  133. NumOpenPulls int `xorm:"-"`
  134. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  135. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  136. NumOpenMilestones int `xorm:"-"`
  137. NumTags int `xorm:"-"`
  138. IsPrivate bool
  139. IsBare bool
  140. IsMirror bool
  141. *Mirror `xorm:"-"`
  142. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  143. ForkID int64
  144. BaseRepo *Repository `xorm:"-"`
  145. Created time.Time `xorm:"CREATED"`
  146. Updated time.Time `xorm:"UPDATED"`
  147. }
  148. func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
  149. switch colName {
  150. case "num_closed_issues":
  151. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  152. case "num_closed_pulls":
  153. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  154. case "num_closed_milestones":
  155. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  156. case "updated":
  157. repo.Updated = regulateTimeZone(repo.Updated)
  158. }
  159. }
  160. func (repo *Repository) getOwner(e Engine) (err error) {
  161. if repo.Owner != nil {
  162. return nil
  163. }
  164. repo.Owner, err = getUserByID(e, repo.OwnerID)
  165. return err
  166. }
  167. func (repo *Repository) GetOwner() error {
  168. return repo.getOwner(x)
  169. }
  170. // GetAssignees returns all users that have write access of repository.
  171. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  172. if err = repo.GetOwner(); err != nil {
  173. return nil, err
  174. }
  175. accesses := make([]*Access, 0, 10)
  176. if err = x.Where("repo_id=? AND mode>=?", repo.ID, ACCESS_MODE_WRITE).Find(&accesses); err != nil {
  177. return nil, err
  178. }
  179. users := make([]*User, 0, len(accesses)+1) // Just waste 1 unit does not matter.
  180. if !repo.Owner.IsOrganization() {
  181. users = append(users, repo.Owner)
  182. }
  183. var u *User
  184. for i := range accesses {
  185. u, err = GetUserByID(accesses[i].UserID)
  186. if err != nil {
  187. return nil, err
  188. }
  189. users = append(users, u)
  190. }
  191. return users, nil
  192. }
  193. // GetAssigneeByID returns the user that has write access of repository by given ID.
  194. func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
  195. return GetAssigneeByID(repo, userID)
  196. }
  197. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  198. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  199. return GetRepoMilestoneByID(repo.ID, milestoneID)
  200. }
  201. // IssueStats returns number of open and closed repository issues by given filter mode.
  202. func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int64, int64) {
  203. return GetRepoIssueStats(repo.ID, uid, filterMode, isPull)
  204. }
  205. func (repo *Repository) GetMirror() (err error) {
  206. repo.Mirror, err = GetMirror(repo.ID)
  207. return err
  208. }
  209. func (repo *Repository) GetBaseRepo() (err error) {
  210. if !repo.IsFork {
  211. return nil
  212. }
  213. repo.BaseRepo, err = GetRepositoryByID(repo.ForkID)
  214. return err
  215. }
  216. func (repo *Repository) repoPath(e Engine) (string, error) {
  217. if err := repo.getOwner(e); err != nil {
  218. return "", err
  219. }
  220. return RepoPath(repo.Owner.Name, repo.Name), nil
  221. }
  222. func (repo *Repository) RepoPath() (string, error) {
  223. return repo.repoPath(x)
  224. }
  225. func (repo *Repository) RepoLink() (string, error) {
  226. if err := repo.GetOwner(); err != nil {
  227. return "", err
  228. }
  229. return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
  230. }
  231. func (repo *Repository) HasAccess(u *User) bool {
  232. has, _ := HasAccess(u, repo, ACCESS_MODE_READ)
  233. return has
  234. }
  235. func (repo *Repository) IsOwnedBy(userID int64) bool {
  236. return repo.OwnerID == userID
  237. }
  238. // CanBeForked returns true if repository meets the requirements of being forked.
  239. func (repo *Repository) CanBeForked() bool {
  240. return !repo.IsBare && !repo.IsMirror
  241. }
  242. func (repo *Repository) NextIssueIndex() int64 {
  243. return int64(repo.NumIssues+repo.NumPulls) + 1
  244. }
  245. var (
  246. DescPattern = regexp.MustCompile(`https?://\S+`)
  247. )
  248. // DescriptionHtml does special handles to description and return HTML string.
  249. func (repo *Repository) DescriptionHtml() template.HTML {
  250. sanitize := func(s string) string {
  251. return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
  252. }
  253. return template.HTML(DescPattern.ReplaceAllStringFunc(base.Sanitizer.Sanitize(repo.Description), sanitize))
  254. }
  255. func (repo *Repository) LocalCopyPath() string {
  256. return path.Join(setting.AppDataPath, "tmp/local", com.ToStr(repo.ID))
  257. }
  258. // UpdateLocalCopy makes sure the local copy of repository is up-to-date.
  259. func (repo *Repository) UpdateLocalCopy() error {
  260. repoPath, err := repo.RepoPath()
  261. if err != nil {
  262. return err
  263. }
  264. localPath := repo.LocalCopyPath()
  265. if !com.IsExist(localPath) {
  266. _, stderr, err := process.Exec(
  267. fmt.Sprintf("UpdateLocalCopy(git clone): %s", repoPath), "git", "clone", repoPath, localPath)
  268. if err != nil {
  269. return fmt.Errorf("git clone: %v - %s", err, stderr)
  270. }
  271. } else {
  272. _, stderr, err := process.ExecDir(-1, localPath,
  273. fmt.Sprintf("UpdateLocalCopy(git pull): %s", repoPath), "git", "pull")
  274. if err != nil {
  275. return fmt.Errorf("git pull: %v - %s", err, stderr)
  276. }
  277. }
  278. return nil
  279. }
  280. // PatchPath returns corresponding patch file path of repository by given issue ID.
  281. func (repo *Repository) PatchPath(index int64) (string, error) {
  282. if err := repo.GetOwner(); err != nil {
  283. return "", err
  284. }
  285. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  286. }
  287. // SavePatch saves patch data to corresponding location by given issue ID.
  288. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  289. patchPath, err := repo.PatchPath(index)
  290. if err != nil {
  291. return fmt.Errorf("PatchPath: %v", err)
  292. }
  293. os.MkdirAll(path.Dir(patchPath), os.ModePerm)
  294. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  295. return fmt.Errorf("WriteFile: %v", err)
  296. }
  297. return nil
  298. }
  299. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  300. has, err := e.Get(&Repository{
  301. OwnerID: u.Id,
  302. LowerName: strings.ToLower(repoName),
  303. })
  304. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  305. }
  306. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  307. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  308. return isRepositoryExist(x, u, repoName)
  309. }
  310. // CloneLink represents different types of clone URLs of repository.
  311. type CloneLink struct {
  312. SSH string
  313. HTTPS string
  314. Git string
  315. }
  316. // CloneLink returns clone URLs of repository.
  317. func (repo *Repository) CloneLink() (cl CloneLink, err error) {
  318. if err = repo.GetOwner(); err != nil {
  319. return cl, err
  320. }
  321. if setting.SSHPort != 22 {
  322. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.SSHDomain, setting.SSHPort, repo.Owner.LowerName, repo.LowerName)
  323. } else {
  324. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.SSHDomain, repo.Owner.LowerName, repo.LowerName)
  325. }
  326. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.LowerName, repo.LowerName)
  327. return cl, nil
  328. }
  329. var (
  330. reservedNames = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  331. reservedPatterns = []string{"*.git", "*.keys"}
  332. )
  333. // IsUsableName checks if name is reserved or pattern of name is not allowed.
  334. func IsUsableName(name string) error {
  335. name = strings.TrimSpace(strings.ToLower(name))
  336. if utf8.RuneCountInString(name) == 0 {
  337. return ErrNameEmpty
  338. }
  339. for i := range reservedNames {
  340. if name == reservedNames[i] {
  341. return ErrNameReserved{name}
  342. }
  343. }
  344. for _, pat := range reservedPatterns {
  345. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  346. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  347. return ErrNamePatternNotAllowed{pat}
  348. }
  349. }
  350. return nil
  351. }
  352. // Mirror represents a mirror information of repository.
  353. type Mirror struct {
  354. ID int64 `xorm:"pk autoincr"`
  355. RepoID int64
  356. Repo *Repository `xorm:"-"`
  357. Interval int // Hour.
  358. Updated time.Time `xorm:"UPDATED"`
  359. NextUpdate time.Time
  360. }
  361. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
  362. var err error
  363. switch colName {
  364. case "repo_id":
  365. m.Repo, err = GetRepositoryByID(m.RepoID)
  366. if err != nil {
  367. log.Error(3, "GetRepositoryByID[%d]: %v", m.ID, err)
  368. }
  369. }
  370. }
  371. func getMirror(e Engine, repoId int64) (*Mirror, error) {
  372. m := &Mirror{RepoID: repoId}
  373. has, err := e.Get(m)
  374. if err != nil {
  375. return nil, err
  376. } else if !has {
  377. return nil, ErrMirrorNotExist
  378. }
  379. return m, nil
  380. }
  381. // GetMirror returns mirror object by given repository ID.
  382. func GetMirror(repoId int64) (*Mirror, error) {
  383. return getMirror(x, repoId)
  384. }
  385. func updateMirror(e Engine, m *Mirror) error {
  386. _, err := e.Id(m.ID).Update(m)
  387. return err
  388. }
  389. func UpdateMirror(m *Mirror) error {
  390. return updateMirror(x, m)
  391. }
  392. // MirrorRepository creates a mirror repository from source.
  393. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  394. _, stderr, err := process.ExecTimeout(10*time.Minute,
  395. fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  396. "git", "clone", "--mirror", url, repoPath)
  397. if err != nil {
  398. return errors.New("git clone --mirror: " + stderr)
  399. }
  400. if _, err = x.InsertOne(&Mirror{
  401. RepoID: repoId,
  402. Interval: 24,
  403. NextUpdate: time.Now().Add(24 * time.Hour),
  404. }); err != nil {
  405. return err
  406. }
  407. return nil
  408. }
  409. type MigrateRepoOptions struct {
  410. Name string
  411. Description string
  412. IsPrivate bool
  413. IsMirror bool
  414. RemoteAddr string
  415. }
  416. // MigrateRepository migrates a existing repository from other project hosting.
  417. func MigrateRepository(u *User, opts MigrateRepoOptions) (*Repository, error) {
  418. repo, err := CreateRepository(u, CreateRepoOptions{
  419. Name: opts.Name,
  420. Description: opts.Description,
  421. IsPrivate: opts.IsPrivate,
  422. IsMirror: opts.IsMirror,
  423. })
  424. if err != nil {
  425. return nil, err
  426. }
  427. // Clone to temprory path and do the init commit.
  428. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  429. os.MkdirAll(tmpDir, os.ModePerm)
  430. repoPath := RepoPath(u.Name, opts.Name)
  431. if u.IsOrganization() {
  432. t, err := u.GetOwnerTeam()
  433. if err != nil {
  434. return nil, err
  435. }
  436. repo.NumWatches = t.NumMembers
  437. } else {
  438. repo.NumWatches = 1
  439. }
  440. repo.IsBare = false
  441. if opts.IsMirror {
  442. if err = MirrorRepository(repo.ID, u.Name, repo.Name, repoPath, opts.RemoteAddr); err != nil {
  443. return repo, err
  444. }
  445. repo.IsMirror = true
  446. return repo, UpdateRepository(repo, false)
  447. } else {
  448. os.RemoveAll(repoPath)
  449. }
  450. // FIXME: this command could for both migrate and mirror
  451. _, stderr, err := process.ExecTimeout(10*time.Minute,
  452. fmt.Sprintf("MigrateRepository: %s", repoPath),
  453. "git", "clone", "--mirror", "--bare", "--quiet", opts.RemoteAddr, repoPath)
  454. if err != nil {
  455. return repo, fmt.Errorf("git clone --mirror --bare --quiet: %v", stderr)
  456. } else if err = createUpdateHook(repoPath); err != nil {
  457. return repo, fmt.Errorf("create update hook: %v", err)
  458. }
  459. // Clean up mirror info which prevents "push --all".
  460. configPath := filepath.Join(repoPath, "/config")
  461. cfg, err := ini.Load(configPath)
  462. if err != nil {
  463. return repo, fmt.Errorf("open config file: %v", err)
  464. }
  465. cfg.DeleteSection("remote \"origin\"")
  466. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  467. return repo, fmt.Errorf("save config file: %v", err)
  468. }
  469. // Check if repository is empty.
  470. _, stderr, err = com.ExecCmdDir(repoPath, "git", "log", "-1")
  471. if err != nil {
  472. if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
  473. repo.IsBare = true
  474. } else {
  475. return repo, fmt.Errorf("check bare: %v - %s", err, stderr)
  476. }
  477. }
  478. // Check if repository has master branch, if so set it to default branch.
  479. gitRepo, err := git.OpenRepository(repoPath)
  480. if err != nil {
  481. return repo, fmt.Errorf("open git repository: %v", err)
  482. }
  483. if gitRepo.IsBranchExist("master") {
  484. repo.DefaultBranch = "master"
  485. }
  486. return repo, UpdateRepository(repo, false)
  487. }
  488. // initRepoCommit temporarily changes with work directory.
  489. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  490. var stderr string
  491. if _, stderr, err = process.ExecDir(-1,
  492. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  493. "git", "add", "--all"); err != nil {
  494. return fmt.Errorf("git add: %s", stderr)
  495. }
  496. if _, stderr, err = process.ExecDir(-1,
  497. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  498. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  499. "-m", "initial commit"); err != nil {
  500. return fmt.Errorf("git commit: %s", stderr)
  501. }
  502. if _, stderr, err = process.ExecDir(-1,
  503. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  504. "git", "push", "origin", "master"); err != nil {
  505. return fmt.Errorf("git push: %s", stderr)
  506. }
  507. return nil
  508. }
  509. func createUpdateHook(repoPath string) error {
  510. hookPath := path.Join(repoPath, "hooks/update")
  511. os.MkdirAll(path.Dir(hookPath), os.ModePerm)
  512. return ioutil.WriteFile(hookPath,
  513. []byte(fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"", setting.CustomConf)), 0777)
  514. }
  515. type CreateRepoOptions struct {
  516. Name string
  517. Description string
  518. Gitignores string
  519. License string
  520. Readme string
  521. IsPrivate bool
  522. IsMirror bool
  523. AutoInit bool
  524. }
  525. func getRepoInitFile(tp, name string) ([]byte, error) {
  526. relPath := path.Join("conf", tp, name)
  527. // Use custom file when available.
  528. customPath := path.Join(setting.CustomPath, relPath)
  529. if com.IsFile(customPath) {
  530. return ioutil.ReadFile(customPath)
  531. }
  532. return bindata.Asset(relPath)
  533. }
  534. func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  535. // Clone to temprory path and do the init commit.
  536. _, stderr, err := process.Exec(
  537. fmt.Sprintf("initRepository(git clone): %s", repoPath), "git", "clone", repoPath, tmpDir)
  538. if err != nil {
  539. return fmt.Errorf("git clone: %v - %s", err, stderr)
  540. }
  541. // README
  542. data, err := getRepoInitFile("readme", opts.Readme)
  543. if err != nil {
  544. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  545. }
  546. cloneLink, err := repo.CloneLink()
  547. if err != nil {
  548. return fmt.Errorf("CloneLink: %v", err)
  549. }
  550. match := map[string]string{
  551. "Name": repo.Name,
  552. "Description": repo.Description,
  553. "CloneURL.SSH": cloneLink.SSH,
  554. "CloneURL.HTTPS": cloneLink.HTTPS,
  555. }
  556. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  557. []byte(com.Expand(string(data), match)), 0644); err != nil {
  558. return fmt.Errorf("write README.md: %v", err)
  559. }
  560. // .gitignore
  561. if len(opts.Gitignores) > 0 {
  562. var buf bytes.Buffer
  563. names := strings.Split(opts.Gitignores, ",")
  564. for _, name := range names {
  565. data, err = getRepoInitFile("gitignore", name)
  566. if err != nil {
  567. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  568. }
  569. buf.WriteString("# ---> " + name + "\n")
  570. buf.Write(data)
  571. buf.WriteString("\n")
  572. }
  573. if buf.Len() > 0 {
  574. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  575. return fmt.Errorf("write .gitignore: %v", err)
  576. }
  577. }
  578. }
  579. // LICENSE
  580. if len(opts.License) > 0 {
  581. data, err = getRepoInitFile("license", opts.License)
  582. if err != nil {
  583. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  584. }
  585. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  586. return fmt.Errorf("write LICENSE: %v", err)
  587. }
  588. }
  589. return nil
  590. }
  591. // InitRepository initializes README and .gitignore if needed.
  592. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) error {
  593. // Somehow the directory could exist.
  594. if com.IsExist(repoPath) {
  595. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  596. }
  597. // Init bare new repository.
  598. os.MkdirAll(repoPath, os.ModePerm)
  599. _, stderr, err := process.ExecDir(-1, repoPath,
  600. fmt.Sprintf("initRepository(git init --bare): %s", repoPath), "git", "init", "--bare")
  601. if err != nil {
  602. return fmt.Errorf("git init --bare: %v - %s", err, stderr)
  603. }
  604. if err := createUpdateHook(repoPath); err != nil {
  605. return err
  606. }
  607. tmpDir := filepath.Join(os.TempDir(), "gogs-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  608. // Initialize repository according to user's choice.
  609. if opts.AutoInit {
  610. os.MkdirAll(tmpDir, os.ModePerm)
  611. defer os.RemoveAll(tmpDir)
  612. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  613. return fmt.Errorf("prepareRepoCommit: %v", err)
  614. }
  615. // Apply changes and commit.
  616. if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
  617. return fmt.Errorf("initRepoCommit: %v", err)
  618. }
  619. }
  620. // Re-fetch the repository from database before updating it (else it would
  621. // override changes that were done earlier with sql)
  622. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  623. return fmt.Errorf("getRepositoryByID: %v", err)
  624. }
  625. if !opts.AutoInit {
  626. repo.IsBare = true
  627. }
  628. repo.DefaultBranch = "master"
  629. if err = updateRepository(e, repo, false); err != nil {
  630. return fmt.Errorf("updateRepository: %v", err)
  631. }
  632. return nil
  633. }
  634. func createRepository(e *xorm.Session, u *User, repo *Repository) (err error) {
  635. if err = IsUsableName(repo.Name); err != nil {
  636. return err
  637. }
  638. has, err := isRepositoryExist(e, u, repo.Name)
  639. if err != nil {
  640. return fmt.Errorf("IsRepositoryExist: %v", err)
  641. } else if has {
  642. return ErrRepoAlreadyExist{u.Name, repo.Name}
  643. }
  644. if _, err = e.Insert(repo); err != nil {
  645. return err
  646. }
  647. u.NumRepos++
  648. // Remember visibility preference.
  649. u.LastRepoVisibility = repo.IsPrivate
  650. if err = updateUser(e, u); err != nil {
  651. return fmt.Errorf("updateUser: %v", err)
  652. }
  653. // Give access to all members in owner team.
  654. if u.IsOrganization() {
  655. t, err := u.getOwnerTeam(e)
  656. if err != nil {
  657. return fmt.Errorf("getOwnerTeam: %v", err)
  658. } else if err = t.addRepository(e, repo); err != nil {
  659. return fmt.Errorf("addRepository: %v", err)
  660. }
  661. } else {
  662. // Organization automatically called this in addRepository method.
  663. if err = repo.recalculateAccesses(e); err != nil {
  664. return fmt.Errorf("recalculateAccesses: %v", err)
  665. }
  666. }
  667. if err = watchRepo(e, u.Id, repo.ID, true); err != nil {
  668. return fmt.Errorf("watchRepo: %v", err)
  669. } else if err = newRepoAction(e, u, repo); err != nil {
  670. return fmt.Errorf("newRepoAction: %v", err)
  671. }
  672. return nil
  673. }
  674. // CreateRepository creates a repository for given user or organization.
  675. func CreateRepository(u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  676. repo := &Repository{
  677. OwnerID: u.Id,
  678. Owner: u,
  679. Name: opts.Name,
  680. LowerName: strings.ToLower(opts.Name),
  681. Description: opts.Description,
  682. IsPrivate: opts.IsPrivate,
  683. }
  684. sess := x.NewSession()
  685. defer sessionRelease(sess)
  686. if err = sess.Begin(); err != nil {
  687. return nil, err
  688. }
  689. if err = createRepository(sess, u, repo); err != nil {
  690. return nil, err
  691. }
  692. // No need for init mirror.
  693. if !opts.IsMirror {
  694. repoPath := RepoPath(u.Name, repo.Name)
  695. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  696. if err2 := os.RemoveAll(repoPath); err2 != nil {
  697. log.Error(4, "initRepository: %v", err)
  698. return nil, fmt.Errorf(
  699. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  700. }
  701. return nil, fmt.Errorf("initRepository: %v", err)
  702. }
  703. _, stderr, err := process.ExecDir(-1,
  704. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  705. "git", "update-server-info")
  706. if err != nil {
  707. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  708. }
  709. }
  710. return repo, sess.Commit()
  711. }
  712. func countRepositories(showPrivate bool) int64 {
  713. sess := x.NewSession()
  714. if !showPrivate {
  715. sess.Where("is_private=", false)
  716. }
  717. count, _ := sess.Count(new(Repository))
  718. return count
  719. }
  720. // CountRepositories returns number of repositories.
  721. func CountRepositories() int64 {
  722. return countRepositories(true)
  723. }
  724. // CountPublicRepositories returns number of public repositories.
  725. func CountPublicRepositories() int64 {
  726. return countRepositories(false)
  727. }
  728. // RepositoriesWithUsers returns number of repos in given page.
  729. func RepositoriesWithUsers(page, pageSize int) (_ []*Repository, err error) {
  730. repos := make([]*Repository, 0, pageSize)
  731. if err = x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos); err != nil {
  732. return nil, err
  733. }
  734. for i := range repos {
  735. if err = repos[i].GetOwner(); err != nil {
  736. return nil, err
  737. }
  738. }
  739. return repos, nil
  740. }
  741. // RepoPath returns repository path by given user and repository name.
  742. func RepoPath(userName, repoName string) string {
  743. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  744. }
  745. // TransferOwnership transfers all corresponding setting from old user to new one.
  746. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  747. newOwner, err := GetUserByName(newOwnerName)
  748. if err != nil {
  749. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  750. }
  751. // Check if new owner has repository with same name.
  752. has, err := IsRepositoryExist(newOwner, repo.Name)
  753. if err != nil {
  754. return fmt.Errorf("IsRepositoryExist: %v", err)
  755. } else if has {
  756. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  757. }
  758. sess := x.NewSession()
  759. defer sessionRelease(sess)
  760. if err = sess.Begin(); err != nil {
  761. return fmt.Errorf("sess.Begin: %v", err)
  762. }
  763. owner := repo.Owner
  764. // Note: we have to set value here to make sure recalculate accesses is based on
  765. // new owner.
  766. repo.OwnerID = newOwner.Id
  767. repo.Owner = newOwner
  768. // Update repository.
  769. if _, err := sess.Id(repo.ID).Update(repo); err != nil {
  770. return fmt.Errorf("update owner: %v", err)
  771. }
  772. // Remove redundant collaborators.
  773. collaborators, err := repo.getCollaborators(sess)
  774. if err != nil {
  775. return fmt.Errorf("getCollaborators: %v", err)
  776. }
  777. // Dummy object.
  778. collaboration := &Collaboration{RepoID: repo.ID}
  779. for _, c := range collaborators {
  780. collaboration.UserID = c.Id
  781. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  782. if _, err = sess.Delete(collaboration); err != nil {
  783. return fmt.Errorf("remove collaborator '%d': %v", c.Id, err)
  784. }
  785. }
  786. }
  787. // Remove old team-repository relations.
  788. if owner.IsOrganization() {
  789. if err = owner.getTeams(sess); err != nil {
  790. return fmt.Errorf("getTeams: %v", err)
  791. }
  792. for _, t := range owner.Teams {
  793. if !t.hasRepository(sess, repo.ID) {
  794. continue
  795. }
  796. t.NumRepos--
  797. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  798. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  799. }
  800. }
  801. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  802. return fmt.Errorf("removeOrgRepo: %v", err)
  803. }
  804. }
  805. if newOwner.IsOrganization() {
  806. t, err := newOwner.getOwnerTeam(sess)
  807. if err != nil {
  808. return fmt.Errorf("getOwnerTeam: %v", err)
  809. } else if err = t.addRepository(sess, repo); err != nil {
  810. return fmt.Errorf("add to owner team: %v", err)
  811. }
  812. } else {
  813. // Organization called this in addRepository method.
  814. if err = repo.recalculateAccesses(sess); err != nil {
  815. return fmt.Errorf("recalculateAccesses: %v", err)
  816. }
  817. }
  818. // Update repository count.
  819. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.Id); err != nil {
  820. return fmt.Errorf("increase new owner repository count: %v", err)
  821. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.Id); err != nil {
  822. return fmt.Errorf("decrease old owner repository count: %v", err)
  823. }
  824. if err = watchRepo(sess, newOwner.Id, repo.ID, true); err != nil {
  825. return fmt.Errorf("watchRepo: %v", err)
  826. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  827. return fmt.Errorf("transferRepoAction: %v", err)
  828. }
  829. // Change repository directory name.
  830. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  831. return fmt.Errorf("rename directory: %v", err)
  832. }
  833. return sess.Commit()
  834. }
  835. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  836. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  837. oldRepoName = strings.ToLower(oldRepoName)
  838. newRepoName = strings.ToLower(newRepoName)
  839. if err = IsUsableName(newRepoName); err != nil {
  840. return err
  841. }
  842. has, err := IsRepositoryExist(u, newRepoName)
  843. if err != nil {
  844. return fmt.Errorf("IsRepositoryExist: %v", err)
  845. } else if has {
  846. return ErrRepoAlreadyExist{u.Name, newRepoName}
  847. }
  848. // Change repository directory name.
  849. return os.Rename(RepoPath(u.LowerName, oldRepoName), RepoPath(u.LowerName, newRepoName))
  850. }
  851. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  852. repos := make([]*Repository, 0, 10)
  853. return repos, e.Where("fork_id=?", forkID).Find(&repos)
  854. }
  855. // GetRepositoriesByForkID returns all repositories with given fork ID.
  856. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  857. return getRepositoriesByForkID(x, forkID)
  858. }
  859. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  860. repo.LowerName = strings.ToLower(repo.Name)
  861. if len(repo.Description) > 255 {
  862. repo.Description = repo.Description[:255]
  863. }
  864. if len(repo.Website) > 255 {
  865. repo.Website = repo.Website[:255]
  866. }
  867. if _, err = e.Id(repo.ID).AllCols().Update(repo); err != nil {
  868. return fmt.Errorf("update: %v", err)
  869. }
  870. if visibilityChanged {
  871. if err = repo.getOwner(e); err != nil {
  872. return fmt.Errorf("getOwner: %v", err)
  873. }
  874. if repo.Owner.IsOrganization() {
  875. // Organization repository need to recalculate access table when visivility is changed.
  876. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  877. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  878. }
  879. }
  880. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  881. if err != nil {
  882. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  883. }
  884. for i := range forkRepos {
  885. forkRepos[i].IsPrivate = repo.IsPrivate
  886. if err = updateRepository(e, forkRepos[i], true); err != nil {
  887. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  888. }
  889. }
  890. }
  891. return nil
  892. }
  893. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  894. sess := x.NewSession()
  895. defer sessionRelease(sess)
  896. if err = sess.Begin(); err != nil {
  897. return err
  898. }
  899. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  900. return fmt.Errorf("updateRepository: %v", err)
  901. }
  902. return sess.Commit()
  903. }
  904. // DeleteRepository deletes a repository for a user or organization.
  905. func DeleteRepository(uid, repoID int64) error {
  906. repo := &Repository{ID: repoID, OwnerID: uid}
  907. has, err := x.Get(repo)
  908. if err != nil {
  909. return err
  910. } else if !has {
  911. return ErrRepoNotExist{repoID, uid, ""}
  912. }
  913. // In case is a organization.
  914. org, err := GetUserByID(uid)
  915. if err != nil {
  916. return err
  917. }
  918. if org.IsOrganization() {
  919. if err = org.GetTeams(); err != nil {
  920. return err
  921. }
  922. }
  923. sess := x.NewSession()
  924. defer sessionRelease(sess)
  925. if err = sess.Begin(); err != nil {
  926. return err
  927. }
  928. if org.IsOrganization() {
  929. for _, t := range org.Teams {
  930. if !t.hasRepository(sess, repoID) {
  931. continue
  932. } else if err = t.removeRepository(sess, repo, false); err != nil {
  933. return err
  934. }
  935. }
  936. }
  937. if _, err = sess.Delete(&Repository{ID: repoID}); err != nil {
  938. return err
  939. } else if _, err = sess.Delete(&Access{RepoID: repo.ID}); err != nil {
  940. return err
  941. } else if _, err = sess.Delete(&Action{RepoID: repo.ID}); err != nil {
  942. return err
  943. } else if _, err = sess.Delete(&Watch{RepoID: repoID}); err != nil {
  944. return err
  945. } else if _, err = sess.Delete(&Mirror{RepoID: repoID}); err != nil {
  946. return err
  947. } else if _, err = sess.Delete(&IssueUser{RepoID: repoID}); err != nil {
  948. return err
  949. } else if _, err = sess.Delete(&Milestone{RepoID: repoID}); err != nil {
  950. return err
  951. } else if _, err = sess.Delete(&Release{RepoId: repoID}); err != nil {
  952. return err
  953. } else if _, err = sess.Delete(&Collaboration{RepoID: repoID}); err != nil {
  954. return err
  955. } else if _, err = sess.Delete(&PullRequest{BaseRepoID: repoID}); err != nil {
  956. return err
  957. }
  958. // Delete comments and attachments.
  959. issues := make([]*Issue, 0, 25)
  960. attachmentPaths := make([]string, 0, len(issues))
  961. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  962. return err
  963. }
  964. for i := range issues {
  965. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  966. return err
  967. }
  968. attachments := make([]*Attachment, 0, 5)
  969. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  970. return err
  971. }
  972. for j := range attachments {
  973. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  974. }
  975. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  976. return err
  977. }
  978. }
  979. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  980. return err
  981. }
  982. if repo.IsFork {
  983. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  984. return fmt.Errorf("decrease fork count: %v", err)
  985. }
  986. }
  987. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  988. return err
  989. }
  990. // Remove repository files.
  991. repoPath, err := repo.repoPath(sess)
  992. if err != nil {
  993. return fmt.Errorf("RepoPath: %v", err)
  994. }
  995. if err = os.RemoveAll(repoPath); err != nil {
  996. desc := fmt.Sprintf("delete repository files[%s]: %v", repoPath, err)
  997. log.Warn(desc)
  998. if err = CreateRepositoryNotice(desc); err != nil {
  999. log.Error(4, "CreateRepositoryNotice: %v", err)
  1000. }
  1001. }
  1002. // Remove attachment files.
  1003. for i := range attachmentPaths {
  1004. if err = os.Remove(attachmentPaths[i]); err != nil {
  1005. log.Warn("delete attachment: %v", err)
  1006. }
  1007. }
  1008. if err = sess.Commit(); err != nil {
  1009. return fmt.Errorf("Commit: %v", err)
  1010. }
  1011. if repo.NumForks > 0 {
  1012. if repo.IsPrivate {
  1013. forkRepos, err := GetRepositoriesByForkID(repo.ID)
  1014. if err != nil {
  1015. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1016. }
  1017. for i := range forkRepos {
  1018. if err = DeleteRepository(forkRepos[i].OwnerID, forkRepos[i].ID); err != nil {
  1019. log.Error(4, "updateRepository[%d]: %v", forkRepos[i].ID, err)
  1020. }
  1021. }
  1022. } else {
  1023. if _, err = x.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1024. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  1025. }
  1026. }
  1027. }
  1028. return nil
  1029. }
  1030. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  1031. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  1032. func GetRepositoryByRef(ref string) (*Repository, error) {
  1033. n := strings.IndexByte(ref, byte('/'))
  1034. if n < 2 {
  1035. return nil, ErrInvalidReference
  1036. }
  1037. userName, repoName := ref[:n], ref[n+1:]
  1038. user, err := GetUserByName(userName)
  1039. if err != nil {
  1040. return nil, err
  1041. }
  1042. return GetRepositoryByName(user.Id, repoName)
  1043. }
  1044. // GetRepositoryByName returns the repository by given name under user if exists.
  1045. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  1046. repo := &Repository{
  1047. OwnerID: uid,
  1048. LowerName: strings.ToLower(repoName),
  1049. }
  1050. has, err := x.Get(repo)
  1051. if err != nil {
  1052. return nil, err
  1053. } else if !has {
  1054. return nil, ErrRepoNotExist{0, uid, repoName}
  1055. }
  1056. return repo, err
  1057. }
  1058. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1059. repo := new(Repository)
  1060. has, err := e.Id(id).Get(repo)
  1061. if err != nil {
  1062. return nil, err
  1063. } else if !has {
  1064. return nil, ErrRepoNotExist{id, 0, ""}
  1065. }
  1066. return repo, nil
  1067. }
  1068. // GetRepositoryByID returns the repository by given id if exists.
  1069. func GetRepositoryByID(id int64) (*Repository, error) {
  1070. return getRepositoryByID(x, id)
  1071. }
  1072. // GetRepositories returns a list of repositories of given user.
  1073. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  1074. repos := make([]*Repository, 0, 10)
  1075. sess := x.Desc("updated")
  1076. if !private {
  1077. sess.Where("is_private=?", false)
  1078. }
  1079. return repos, sess.Find(&repos, &Repository{OwnerID: uid})
  1080. }
  1081. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  1082. func GetRecentUpdatedRepositories(page int) (repos []*Repository, err error) {
  1083. return repos, x.Limit(setting.ExplorePagingNum, (page-1)*setting.ExplorePagingNum).
  1084. Where("is_private=?", false).Limit(setting.ExplorePagingNum).Desc("updated").Find(&repos)
  1085. }
  1086. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1087. return x.Count(&Repository{OwnerID: u.Id})
  1088. }
  1089. // GetRepositoryCount returns the total number of repositories of user.
  1090. func GetRepositoryCount(u *User) (int64, error) {
  1091. return getRepositoryCount(x, u)
  1092. }
  1093. type SearchOption struct {
  1094. Keyword string
  1095. Uid int64
  1096. Limit int
  1097. Private bool
  1098. }
  1099. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  1100. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  1101. if len(opt.Keyword) == 0 {
  1102. return repos, nil
  1103. }
  1104. opt.Keyword = strings.ToLower(opt.Keyword)
  1105. repos = make([]*Repository, 0, opt.Limit)
  1106. // Append conditions.
  1107. sess := x.Limit(opt.Limit)
  1108. if opt.Uid > 0 {
  1109. sess.Where("owner_id=?", opt.Uid)
  1110. }
  1111. if !opt.Private {
  1112. sess.And("is_private=?", false)
  1113. }
  1114. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  1115. return repos, err
  1116. }
  1117. // DeleteRepositoryArchives deletes all repositories' archives.
  1118. func DeleteRepositoryArchives() error {
  1119. return x.Where("id > 0").Iterate(new(Repository),
  1120. func(idx int, bean interface{}) error {
  1121. repo := bean.(*Repository)
  1122. repoPath, err := repo.RepoPath()
  1123. if err != nil {
  1124. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepositoryArchives[%d]: %v", repo.ID, err)); err2 != nil {
  1125. log.Error(4, "CreateRepositoryNotice: %v", err2)
  1126. }
  1127. return nil
  1128. }
  1129. return os.RemoveAll(filepath.Join(repoPath, "archives"))
  1130. })
  1131. }
  1132. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  1133. func RewriteRepositoryUpdateHook() error {
  1134. return x.Where("id > 0").Iterate(new(Repository),
  1135. func(idx int, bean interface{}) error {
  1136. repo := bean.(*Repository)
  1137. if err := repo.GetOwner(); err != nil {
  1138. return err
  1139. }
  1140. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  1141. })
  1142. }
  1143. var (
  1144. // Prevent duplicate running tasks.
  1145. isMirrorUpdating = false
  1146. isGitFscking = false
  1147. isCheckingRepos = false
  1148. )
  1149. // MirrorUpdate checks and updates mirror repositories.
  1150. func MirrorUpdate() {
  1151. if isMirrorUpdating {
  1152. return
  1153. }
  1154. isMirrorUpdating = true
  1155. defer func() { isMirrorUpdating = false }()
  1156. log.Trace("Doing: MirrorUpdate")
  1157. mirrors := make([]*Mirror, 0, 10)
  1158. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  1159. m := bean.(*Mirror)
  1160. if m.NextUpdate.After(time.Now()) {
  1161. return nil
  1162. }
  1163. if m.Repo == nil {
  1164. log.Error(4, "Disconnected mirror repository found: %d", m.ID)
  1165. return nil
  1166. }
  1167. repoPath, err := m.Repo.RepoPath()
  1168. if err != nil {
  1169. return fmt.Errorf("Repo.RepoPath: %v", err)
  1170. }
  1171. if _, stderr, err := process.ExecDir(10*time.Minute,
  1172. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  1173. "git", "remote", "update", "--prune"); err != nil {
  1174. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  1175. log.Error(4, desc)
  1176. if err = CreateRepositoryNotice(desc); err != nil {
  1177. log.Error(4, "CreateRepositoryNotice: %v", err)
  1178. }
  1179. return nil
  1180. }
  1181. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  1182. mirrors = append(mirrors, m)
  1183. return nil
  1184. }); err != nil {
  1185. log.Error(4, "MirrorUpdate: %v", err)
  1186. }
  1187. for i := range mirrors {
  1188. if err := UpdateMirror(mirrors[i]); err != nil {
  1189. log.Error(4, "UpdateMirror[%d]: %v", mirrors[i].ID, err)
  1190. }
  1191. }
  1192. }
  1193. // GitFsck calls 'git fsck' to check repository health.
  1194. func GitFsck() {
  1195. if isGitFscking {
  1196. return
  1197. }
  1198. isGitFscking = true
  1199. defer func() { isGitFscking = false }()
  1200. log.Trace("Doing: GitFsck")
  1201. args := append([]string{"fsck"}, setting.Cron.RepoHealthCheck.Args...)
  1202. if err := x.Where("id>0").Iterate(new(Repository),
  1203. func(idx int, bean interface{}) error {
  1204. repo := bean.(*Repository)
  1205. repoPath, err := repo.RepoPath()
  1206. if err != nil {
  1207. return fmt.Errorf("RepoPath: %v", err)
  1208. }
  1209. _, _, err = process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  1210. if err != nil {
  1211. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  1212. log.Warn(desc)
  1213. if err = CreateRepositoryNotice(desc); err != nil {
  1214. log.Error(4, "CreateRepositoryNotice: %v", err)
  1215. }
  1216. }
  1217. return nil
  1218. }); err != nil {
  1219. log.Error(4, "GitFsck: %v", err)
  1220. }
  1221. }
  1222. func GitGcRepos() error {
  1223. args := append([]string{"gc"}, setting.Git.GcArgs...)
  1224. return x.Where("id > 0").Iterate(new(Repository),
  1225. func(idx int, bean interface{}) error {
  1226. repo := bean.(*Repository)
  1227. if err := repo.GetOwner(); err != nil {
  1228. return err
  1229. }
  1230. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  1231. if err != nil {
  1232. return fmt.Errorf("%v: %v", err, stderr)
  1233. }
  1234. return nil
  1235. })
  1236. }
  1237. type repoChecker struct {
  1238. querySQL, correctSQL string
  1239. desc string
  1240. }
  1241. func repoStatsCheck(checker *repoChecker) {
  1242. results, err := x.Query(checker.querySQL)
  1243. if err != nil {
  1244. log.Error(4, "Select %s: %v", checker.desc, err)
  1245. return
  1246. }
  1247. for _, result := range results {
  1248. id := com.StrTo(result["id"]).MustInt64()
  1249. log.Trace("Updating %s: %d", checker.desc, id)
  1250. _, err = x.Exec(checker.correctSQL, id, id)
  1251. if err != nil {
  1252. log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
  1253. }
  1254. }
  1255. }
  1256. func CheckRepoStats() {
  1257. if isCheckingRepos {
  1258. return
  1259. }
  1260. isCheckingRepos = true
  1261. defer func() { isCheckingRepos = false }()
  1262. log.Trace("Doing: CheckRepoStats")
  1263. checkers := []*repoChecker{
  1264. // Repository.NumWatches
  1265. {
  1266. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1267. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1268. "repository count 'num_watches'",
  1269. },
  1270. // Repository.NumStars
  1271. {
  1272. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1273. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1274. "repository count 'num_stars'",
  1275. },
  1276. // Label.NumIssues
  1277. {
  1278. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1279. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1280. "label count 'num_issues'",
  1281. },
  1282. // User.NumRepos
  1283. {
  1284. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1285. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1286. "user count 'num_repos'",
  1287. },
  1288. // Issue.NumComments
  1289. {
  1290. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1291. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1292. "issue count 'num_comments'",
  1293. },
  1294. }
  1295. for i := range checkers {
  1296. repoStatsCheck(checkers[i])
  1297. }
  1298. // FIXME: use checker when v0.8, stop supporting old fork repo format.
  1299. // ***** START: Repository.NumForks *****
  1300. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1301. if err != nil {
  1302. log.Error(4, "Select repository count 'num_forks': %v", err)
  1303. } else {
  1304. for _, result := range results {
  1305. id := com.StrTo(result["id"]).MustInt64()
  1306. log.Trace("Updating repository count 'num_forks': %d", id)
  1307. repo, err := GetRepositoryByID(id)
  1308. if err != nil {
  1309. log.Error(4, "GetRepositoryByID[%d]: %v", id, err)
  1310. continue
  1311. }
  1312. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1313. if err != nil {
  1314. log.Error(4, "Select count of forks[%d]: %v", repo.ID, err)
  1315. continue
  1316. }
  1317. repo.NumForks = int(parseCountResult(rawResult))
  1318. if err = UpdateRepository(repo, false); err != nil {
  1319. log.Error(4, "UpdateRepository[%d]: %v", id, err)
  1320. continue
  1321. }
  1322. }
  1323. }
  1324. // ***** END: Repository.NumForks *****
  1325. }
  1326. // _________ .__ .__ ___. __ .__
  1327. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  1328. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  1329. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  1330. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  1331. // \/ \/ \/ \/ \/
  1332. // A Collaboration is a relation between an individual and a repository
  1333. type Collaboration struct {
  1334. ID int64 `xorm:"pk autoincr"`
  1335. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1336. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1337. Created time.Time `xorm:"CREATED"`
  1338. }
  1339. // Add collaborator and accompanying access
  1340. func (repo *Repository) AddCollaborator(u *User) error {
  1341. collaboration := &Collaboration{
  1342. RepoID: repo.ID,
  1343. UserID: u.Id,
  1344. }
  1345. has, err := x.Get(collaboration)
  1346. if err != nil {
  1347. return err
  1348. } else if has {
  1349. return nil
  1350. }
  1351. if err = repo.GetOwner(); err != nil {
  1352. return fmt.Errorf("GetOwner: %v", err)
  1353. }
  1354. sess := x.NewSession()
  1355. defer sessionRelease(sess)
  1356. if err = sess.Begin(); err != nil {
  1357. return err
  1358. }
  1359. if _, err = sess.InsertOne(collaboration); err != nil {
  1360. return err
  1361. }
  1362. if repo.Owner.IsOrganization() {
  1363. err = repo.recalculateTeamAccesses(sess, 0)
  1364. } else {
  1365. err = repo.recalculateAccesses(sess)
  1366. }
  1367. if err != nil {
  1368. return fmt.Errorf("recalculateAccesses 'team=%v': %v", repo.Owner.IsOrganization(), err)
  1369. }
  1370. return sess.Commit()
  1371. }
  1372. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  1373. collaborations := make([]*Collaboration, 0)
  1374. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.ID}); err != nil {
  1375. return nil, err
  1376. }
  1377. users := make([]*User, len(collaborations))
  1378. for i, c := range collaborations {
  1379. user, err := getUserByID(e, c.UserID)
  1380. if err != nil {
  1381. return nil, err
  1382. }
  1383. users[i] = user
  1384. }
  1385. return users, nil
  1386. }
  1387. // GetCollaborators returns the collaborators for a repository
  1388. func (repo *Repository) GetCollaborators() ([]*User, error) {
  1389. return repo.getCollaborators(x)
  1390. }
  1391. // Delete collaborator and accompanying access
  1392. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  1393. collaboration := &Collaboration{
  1394. RepoID: repo.ID,
  1395. UserID: u.Id,
  1396. }
  1397. sess := x.NewSession()
  1398. defer sessionRelease(sess)
  1399. if err = sess.Begin(); err != nil {
  1400. return err
  1401. }
  1402. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  1403. return err
  1404. } else if err = repo.recalculateAccesses(sess); err != nil {
  1405. return err
  1406. }
  1407. return sess.Commit()
  1408. }
  1409. // __ __ __ .__
  1410. // / \ / \_____ _/ |_ ____ | |__
  1411. // \ \/\/ /\__ \\ __\/ ___\| | \
  1412. // \ / / __ \| | \ \___| Y \
  1413. // \__/\ / (____ /__| \___ >___| /
  1414. // \/ \/ \/ \/
  1415. // Watch is connection request for receiving repository notification.
  1416. type Watch struct {
  1417. ID int64 `xorm:"pk autoincr"`
  1418. UserID int64 `xorm:"UNIQUE(watch)"`
  1419. RepoID int64 `xorm:"UNIQUE(watch)"`
  1420. }
  1421. func isWatching(e Engine, uid, repoId int64) bool {
  1422. has, _ := e.Get(&Watch{0, uid, repoId})
  1423. return has
  1424. }
  1425. // IsWatching checks if user has watched given repository.
  1426. func IsWatching(uid, repoId int64) bool {
  1427. return isWatching(x, uid, repoId)
  1428. }
  1429. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1430. if watch {
  1431. if isWatching(e, uid, repoId) {
  1432. return nil
  1433. }
  1434. if _, err = e.Insert(&Watch{RepoID: repoId, UserID: uid}); err != nil {
  1435. return err
  1436. }
  1437. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1438. } else {
  1439. if !isWatching(e, uid, repoId) {
  1440. return nil
  1441. }
  1442. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1443. return err
  1444. }
  1445. _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", repoId)
  1446. }
  1447. return err
  1448. }
  1449. // Watch or unwatch repository.
  1450. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1451. return watchRepo(x, uid, repoId, watch)
  1452. }
  1453. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1454. watches := make([]*Watch, 0, 10)
  1455. err := e.Find(&watches, &Watch{RepoID: rid})
  1456. return watches, err
  1457. }
  1458. // GetWatchers returns all watchers of given repository.
  1459. func GetWatchers(rid int64) ([]*Watch, error) {
  1460. return getWatchers(x, rid)
  1461. }
  1462. // Repository.GetWatchers returns all users watching given repository.
  1463. func (repo *Repository) GetWatchers(offset int) ([]*User, error) {
  1464. users := make([]*User, 0, 10)
  1465. offset = (offset - 1) * ItemsPerPage
  1466. err := x.Limit(ItemsPerPage, offset).Where("repo_id=?", repo.ID).Join("LEFT", "watch", "user.id=watch.user_id").Find(&users)
  1467. return users, err
  1468. }
  1469. func notifyWatchers(e Engine, act *Action) error {
  1470. // Add feeds for user self and all watchers.
  1471. watches, err := getWatchers(e, act.RepoID)
  1472. if err != nil {
  1473. return fmt.Errorf("get watchers: %v", err)
  1474. }
  1475. // Add feed for actioner.
  1476. act.UserID = act.ActUserID
  1477. if _, err = e.InsertOne(act); err != nil {
  1478. return fmt.Errorf("insert new actioner: %v", err)
  1479. }
  1480. for i := range watches {
  1481. if act.ActUserID == watches[i].UserID {
  1482. continue
  1483. }
  1484. act.ID = 0
  1485. act.UserID = watches[i].UserID
  1486. if _, err = e.InsertOne(act); err != nil {
  1487. return fmt.Errorf("insert new action: %v", err)
  1488. }
  1489. }
  1490. return nil
  1491. }
  1492. // NotifyWatchers creates batch of actions for every watcher.
  1493. func NotifyWatchers(act *Action) error {
  1494. return notifyWatchers(x, act)
  1495. }
  1496. // _________ __
  1497. // / _____// |______ _______
  1498. // \_____ \\ __\__ \\_ __ \
  1499. // / \| | / __ \| | \/
  1500. // /_______ /|__| (____ /__|
  1501. // \/ \/
  1502. type Star struct {
  1503. ID int64 `xorm:"pk autoincr"`
  1504. UID int64 `xorm:"UNIQUE(s)"`
  1505. RepoID int64 `xorm:"UNIQUE(s)"`
  1506. }
  1507. // Star or unstar repository.
  1508. func StarRepo(uid, repoId int64, star bool) (err error) {
  1509. if star {
  1510. if IsStaring(uid, repoId) {
  1511. return nil
  1512. }
  1513. if _, err = x.Insert(&Star{UID: uid, RepoID: repoId}); err != nil {
  1514. return err
  1515. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1516. return err
  1517. }
  1518. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1519. } else {
  1520. if !IsStaring(uid, repoId) {
  1521. return nil
  1522. }
  1523. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1524. return err
  1525. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1526. return err
  1527. }
  1528. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1529. }
  1530. return err
  1531. }
  1532. // IsStaring checks if user has starred given repository.
  1533. func IsStaring(uid, repoId int64) bool {
  1534. has, _ := x.Get(&Star{0, uid, repoId})
  1535. return has
  1536. }
  1537. func (repo *Repository) GetStars(offset int) ([]*User, error) {
  1538. users := make([]*User, 0, 10)
  1539. offset = (offset - 1) * ItemsPerPage
  1540. err := x.Limit(ItemsPerPage, offset).Where("repo_id=?", repo.ID).Join("LEFT", "star", "user.id=star.uid").Find(&users)
  1541. return users, err
  1542. }
  1543. // ___________ __
  1544. // \_ _____/__________| | __
  1545. // | __)/ _ \_ __ \ |/ /
  1546. // | \( <_> ) | \/ <
  1547. // \___ / \____/|__| |__|_ \
  1548. // \/ \/
  1549. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1550. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1551. repo := new(Repository)
  1552. has, _ := x.Where("owner_id=? AND fork_id=?", ownerID, repoID).Get(repo)
  1553. return repo, has
  1554. }
  1555. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1556. repo := &Repository{
  1557. OwnerID: u.Id,
  1558. Owner: u,
  1559. Name: name,
  1560. LowerName: strings.ToLower(name),
  1561. Description: desc,
  1562. DefaultBranch: oldRepo.DefaultBranch,
  1563. IsPrivate: oldRepo.IsPrivate,
  1564. IsFork: true,
  1565. ForkID: oldRepo.ID,
  1566. }
  1567. sess := x.NewSession()
  1568. defer sessionRelease(sess)
  1569. if err = sess.Begin(); err != nil {
  1570. return nil, err
  1571. }
  1572. if err = createRepository(sess, u, repo); err != nil {
  1573. return nil, err
  1574. }
  1575. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  1576. return nil, err
  1577. }
  1578. oldRepoPath, err := oldRepo.RepoPath()
  1579. if err != nil {
  1580. return nil, fmt.Errorf("get old repository path: %v", err)
  1581. }
  1582. repoPath := RepoPath(u.Name, repo.Name)
  1583. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1584. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1585. "git", "clone", "--bare", oldRepoPath, repoPath)
  1586. if err != nil {
  1587. return nil, fmt.Errorf("git clone: %v", stderr)
  1588. }
  1589. _, stderr, err = process.ExecDir(-1,
  1590. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1591. "git", "update-server-info")
  1592. if err != nil {
  1593. return nil, fmt.Errorf("git update-server-info: %v", err)
  1594. }
  1595. if err = createUpdateHook(repoPath); err != nil {
  1596. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1597. }
  1598. return repo, sess.Commit()
  1599. }
  1600. func (repo *Repository) GetForks() ([]*Repository, error) {
  1601. forks := make([]*Repository, 0, 10)
  1602. err := x.Find(&forks, &Repository{ForkID: repo.ID})
  1603. return forks, err
  1604. }