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

repo.go 52 kB

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