repo.go 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368
  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. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "sort"
  14. "strings"
  15. "time"
  16. "github.com/Unknwon/cae/zip"
  17. "github.com/Unknwon/com"
  18. "github.com/go-xorm/xorm"
  19. "github.com/mcuadros/go-version"
  20. log "gopkg.in/clog.v1"
  21. "gopkg.in/ini.v1"
  22. git "github.com/gogits/git-module"
  23. api "github.com/gogits/go-gogs-client"
  24. "github.com/gogits/gogs/models/errors"
  25. "github.com/gogits/gogs/pkg/bindata"
  26. "github.com/gogits/gogs/pkg/markup"
  27. "github.com/gogits/gogs/pkg/process"
  28. "github.com/gogits/gogs/pkg/setting"
  29. "github.com/gogits/gogs/pkg/sync"
  30. )
  31. var repoWorkingPool = sync.NewExclusivePool()
  32. var (
  33. Gitignores, Licenses, Readmes, LabelTemplates []string
  34. // Maximum items per page in forks, watchers and stars of a repo
  35. ItemsPerPage = 40
  36. )
  37. func LoadRepoConfig() {
  38. // Load .gitignore and license files and readme templates.
  39. types := []string{"gitignore", "license", "readme", "label"}
  40. typeFiles := make([][]string, 4)
  41. for i, t := range types {
  42. files, err := bindata.AssetDir("conf/" + t)
  43. if err != nil {
  44. log.Fatal(4, "Fail to get %s files: %v", t, err)
  45. }
  46. customPath := path.Join(setting.CustomPath, "conf", t)
  47. if com.IsDir(customPath) {
  48. customFiles, err := com.StatDir(customPath)
  49. if err != nil {
  50. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  51. }
  52. for _, f := range customFiles {
  53. if !com.IsSliceContainsStr(files, f) {
  54. files = append(files, f)
  55. }
  56. }
  57. }
  58. typeFiles[i] = files
  59. }
  60. Gitignores = typeFiles[0]
  61. Licenses = typeFiles[1]
  62. Readmes = typeFiles[2]
  63. LabelTemplates = typeFiles[3]
  64. sort.Strings(Gitignores)
  65. sort.Strings(Licenses)
  66. sort.Strings(Readmes)
  67. sort.Strings(LabelTemplates)
  68. // Filter out invalid names and promote preferred licenses.
  69. sortedLicenses := make([]string, 0, len(Licenses))
  70. for _, name := range setting.Repository.PreferredLicenses {
  71. if com.IsSliceContainsStr(Licenses, name) {
  72. sortedLicenses = append(sortedLicenses, name)
  73. }
  74. }
  75. for _, name := range Licenses {
  76. if !com.IsSliceContainsStr(setting.Repository.PreferredLicenses, name) {
  77. sortedLicenses = append(sortedLicenses, name)
  78. }
  79. }
  80. Licenses = sortedLicenses
  81. }
  82. func NewRepoContext() {
  83. zip.Verbose = false
  84. // Check Git installation.
  85. if _, err := exec.LookPath("git"); err != nil {
  86. log.Fatal(4, "Fail to test 'git' command: %v (forgotten install?)", err)
  87. }
  88. // Check Git version.
  89. var err error
  90. setting.Git.Version, err = git.BinVersion()
  91. if err != nil {
  92. log.Fatal(4, "Fail to get Git version: %v", err)
  93. }
  94. log.Info("Git Version: %s", setting.Git.Version)
  95. if version.Compare("1.7.1", setting.Git.Version, ">") {
  96. log.Fatal(4, "Gogs requires Git version greater or equal to 1.7.1")
  97. }
  98. git.HookDir = "custom_hooks"
  99. git.HookSampleDir = "hooks"
  100. git.DefaultCommitsPageSize = setting.UI.User.CommitsPagingNum
  101. // Git requires setting user.name and user.email in order to commit changes.
  102. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogs@fake.local"} {
  103. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  104. // ExitError indicates this config is not set
  105. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  106. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  107. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  108. }
  109. log.Info("Git config %s set to %s", configKey, defaultValue)
  110. } else {
  111. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  112. }
  113. }
  114. }
  115. // Set git some configurations.
  116. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  117. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  118. log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
  119. }
  120. RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp"))
  121. }
  122. // Repository contains information of a repository.
  123. type Repository struct {
  124. ID int64
  125. OwnerID int64 `xorm:"UNIQUE(s)"`
  126. Owner *User `xorm:"-"`
  127. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  128. Name string `xorm:"INDEX NOT NULL"`
  129. Description string
  130. Website string
  131. DefaultBranch string
  132. Size int64 `xorm:"NOT NULL DEFAULT 0"`
  133. NumWatches int
  134. NumStars int
  135. NumForks int
  136. NumIssues int
  137. NumClosedIssues int
  138. NumOpenIssues int `xorm:"-"`
  139. NumPulls int
  140. NumClosedPulls int
  141. NumOpenPulls int `xorm:"-"`
  142. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  143. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  144. NumOpenMilestones int `xorm:"-"`
  145. NumTags int `xorm:"-"`
  146. IsPrivate bool
  147. IsBare bool
  148. IsMirror bool
  149. *Mirror `xorm:"-"`
  150. // Advanced settings
  151. EnableWiki bool `xorm:"NOT NULL DEFAULT true"`
  152. AllowPublicWiki bool
  153. EnableExternalWiki bool
  154. ExternalWikiURL string
  155. EnableIssues bool `xorm:"NOT NULL DEFAULT true"`
  156. AllowPublicIssues bool
  157. EnableExternalTracker bool
  158. ExternalTrackerURL string
  159. ExternalTrackerFormat string
  160. ExternalTrackerStyle string
  161. ExternalMetas map[string]string `xorm:"-"`
  162. EnablePulls bool `xorm:"NOT NULL DEFAULT true"`
  163. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  164. ForkID int64
  165. BaseRepo *Repository `xorm:"-"`
  166. Created time.Time `xorm:"-"`
  167. CreatedUnix int64
  168. Updated time.Time `xorm:"-"`
  169. UpdatedUnix int64
  170. }
  171. func (repo *Repository) BeforeInsert() {
  172. repo.CreatedUnix = time.Now().Unix()
  173. repo.UpdatedUnix = repo.CreatedUnix
  174. }
  175. func (repo *Repository) BeforeUpdate() {
  176. repo.UpdatedUnix = time.Now().Unix()
  177. }
  178. func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
  179. switch colName {
  180. case "default_branch":
  181. // FIXME: use models migration to solve all at once.
  182. if len(repo.DefaultBranch) == 0 {
  183. repo.DefaultBranch = "master"
  184. }
  185. case "num_closed_issues":
  186. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  187. case "num_closed_pulls":
  188. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  189. case "num_closed_milestones":
  190. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  191. case "external_tracker_style":
  192. if len(repo.ExternalTrackerStyle) == 0 {
  193. repo.ExternalTrackerStyle = markup.ISSUE_NAME_STYLE_NUMERIC
  194. }
  195. case "created_unix":
  196. repo.Created = time.Unix(repo.CreatedUnix, 0).Local()
  197. case "updated_unix":
  198. repo.Updated = time.Unix(repo.UpdatedUnix, 0)
  199. }
  200. }
  201. func (repo *Repository) loadAttributes(e Engine) (err error) {
  202. if repo.Owner == nil {
  203. repo.Owner, err = getUserByID(e, repo.OwnerID)
  204. if err != nil {
  205. return fmt.Errorf("getUserByID [%d]: %v", repo.OwnerID, err)
  206. }
  207. }
  208. if repo.IsFork && repo.BaseRepo == nil {
  209. repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID)
  210. if err != nil {
  211. if errors.IsRepoNotExist(err) {
  212. repo.IsFork = false
  213. repo.ForkID = 0
  214. } else {
  215. return fmt.Errorf("getRepositoryByID [%d]: %v", repo.ForkID, err)
  216. }
  217. }
  218. }
  219. return nil
  220. }
  221. func (repo *Repository) LoadAttributes() error {
  222. return repo.loadAttributes(x)
  223. }
  224. // IsPartialPublic returns true if repository is public or allow public access to wiki or issues.
  225. func (repo *Repository) IsPartialPublic() bool {
  226. return !repo.IsPrivate || repo.AllowPublicWiki || repo.AllowPublicIssues
  227. }
  228. func (repo *Repository) CanGuestViewWiki() bool {
  229. return repo.EnableWiki && !repo.EnableExternalWiki && repo.AllowPublicWiki
  230. }
  231. func (repo *Repository) CanGuestViewIssues() bool {
  232. return repo.EnableIssues && !repo.EnableExternalTracker && repo.AllowPublicIssues
  233. }
  234. // MustOwner always returns a valid *User object to avoid conceptually impossible error handling.
  235. // It creates a fake object that contains error deftail when error occurs.
  236. func (repo *Repository) MustOwner() *User {
  237. return repo.mustOwner(x)
  238. }
  239. func (repo *Repository) FullName() string {
  240. return repo.MustOwner().Name + "/" + repo.Name
  241. }
  242. func (repo *Repository) HTMLURL() string {
  243. return setting.AppURL + repo.FullName()
  244. }
  245. // This method assumes following fields have been assigned with valid values:
  246. // Required - BaseRepo (if fork)
  247. // Arguments that are allowed to be nil: permission
  248. func (repo *Repository) APIFormat(permission *api.Permission) *api.Repository {
  249. cloneLink := repo.CloneLink()
  250. apiRepo := &api.Repository{
  251. ID: repo.ID,
  252. Owner: repo.Owner.APIFormat(),
  253. Name: repo.Name,
  254. FullName: repo.FullName(),
  255. Description: repo.Description,
  256. Private: repo.IsPrivate,
  257. Fork: repo.IsFork,
  258. Empty: repo.IsBare,
  259. Mirror: repo.IsMirror,
  260. Size: repo.Size,
  261. HTMLURL: repo.HTMLURL(),
  262. SSHURL: cloneLink.SSH,
  263. CloneURL: cloneLink.HTTPS,
  264. Website: repo.Website,
  265. Stars: repo.NumStars,
  266. Forks: repo.NumForks,
  267. Watchers: repo.NumWatches,
  268. OpenIssues: repo.NumOpenIssues,
  269. DefaultBranch: repo.DefaultBranch,
  270. Created: repo.Created,
  271. Updated: repo.Updated,
  272. Permissions: permission,
  273. }
  274. if repo.IsFork {
  275. // FIXME: check precise permission for base repository
  276. apiRepo.Parent = repo.BaseRepo.APIFormat(nil)
  277. }
  278. return apiRepo
  279. }
  280. func (repo *Repository) getOwner(e Engine) (err error) {
  281. if repo.Owner != nil {
  282. return nil
  283. }
  284. repo.Owner, err = getUserByID(e, repo.OwnerID)
  285. return err
  286. }
  287. func (repo *Repository) GetOwner() error {
  288. return repo.getOwner(x)
  289. }
  290. func (repo *Repository) mustOwner(e Engine) *User {
  291. if err := repo.getOwner(e); err != nil {
  292. return &User{
  293. Name: "error",
  294. FullName: err.Error(),
  295. }
  296. }
  297. return repo.Owner
  298. }
  299. func (repo *Repository) UpdateSize() error {
  300. countObject, err := git.GetRepoSize(repo.RepoPath())
  301. if err != nil {
  302. return fmt.Errorf("GetRepoSize: %v", err)
  303. }
  304. repo.Size = countObject.Size + countObject.SizePack
  305. if _, err = x.Id(repo.ID).Cols("size").Update(repo); err != nil {
  306. return fmt.Errorf("update size: %v", err)
  307. }
  308. return nil
  309. }
  310. // ComposeMetas composes a map of metas for rendering external issue tracker URL.
  311. func (repo *Repository) ComposeMetas() map[string]string {
  312. if !repo.EnableExternalTracker {
  313. return nil
  314. } else if repo.ExternalMetas == nil {
  315. repo.ExternalMetas = map[string]string{
  316. "format": repo.ExternalTrackerFormat,
  317. "user": repo.MustOwner().Name,
  318. "repo": repo.Name,
  319. }
  320. switch repo.ExternalTrackerStyle {
  321. case markup.ISSUE_NAME_STYLE_ALPHANUMERIC:
  322. repo.ExternalMetas["style"] = markup.ISSUE_NAME_STYLE_ALPHANUMERIC
  323. default:
  324. repo.ExternalMetas["style"] = markup.ISSUE_NAME_STYLE_NUMERIC
  325. }
  326. }
  327. return repo.ExternalMetas
  328. }
  329. // DeleteWiki removes the actual and local copy of repository wiki.
  330. func (repo *Repository) DeleteWiki() {
  331. wikiPaths := []string{repo.WikiPath(), repo.LocalWikiPath()}
  332. for _, wikiPath := range wikiPaths {
  333. RemoveAllWithNotice("Delete repository wiki", wikiPath)
  334. }
  335. }
  336. // getUsersWithAccesMode returns users that have at least given access mode to the repository.
  337. func (repo *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*User, err error) {
  338. if err = repo.getOwner(e); err != nil {
  339. return nil, err
  340. }
  341. accesses := make([]*Access, 0, 10)
  342. if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil {
  343. return nil, err
  344. }
  345. // Leave a seat for owner itself to append later, but if owner is an organization
  346. // and just waste 1 unit is cheaper than re-allocate memory once.
  347. users := make([]*User, 0, len(accesses)+1)
  348. if len(accesses) > 0 {
  349. userIDs := make([]int64, len(accesses))
  350. for i := 0; i < len(accesses); i++ {
  351. userIDs[i] = accesses[i].UserID
  352. }
  353. if err = e.In("id", userIDs).Find(&users); err != nil {
  354. return nil, err
  355. }
  356. }
  357. if !repo.Owner.IsOrganization() {
  358. users = append(users, repo.Owner)
  359. }
  360. return users, nil
  361. }
  362. // getAssignees returns a list of users who can be assigned to issues in this repository.
  363. func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
  364. return repo.getUsersWithAccesMode(e, ACCESS_MODE_READ)
  365. }
  366. // GetAssignees returns all users that have read access and can be assigned to issues
  367. // of the repository,
  368. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  369. return repo.getAssignees(x)
  370. }
  371. // GetAssigneeByID returns the user that has write access of repository by given ID.
  372. func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
  373. return GetAssigneeByID(repo, userID)
  374. }
  375. // GetWriters returns all users that have write access to the repository.
  376. func (repo *Repository) GetWriters() (_ []*User, err error) {
  377. return repo.getUsersWithAccesMode(x, ACCESS_MODE_WRITE)
  378. }
  379. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  380. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  381. return GetMilestoneByRepoID(repo.ID, milestoneID)
  382. }
  383. // IssueStats returns number of open and closed repository issues by given filter mode.
  384. func (repo *Repository) IssueStats(userID int64, filterMode FilterMode, isPull bool) (int64, int64) {
  385. return GetRepoIssueStats(repo.ID, userID, filterMode, isPull)
  386. }
  387. func (repo *Repository) GetMirror() (err error) {
  388. repo.Mirror, err = GetMirrorByRepoID(repo.ID)
  389. return err
  390. }
  391. func (repo *Repository) repoPath(e Engine) string {
  392. return RepoPath(repo.mustOwner(e).Name, repo.Name)
  393. }
  394. func (repo *Repository) RepoPath() string {
  395. return repo.repoPath(x)
  396. }
  397. func (repo *Repository) GitConfigPath() string {
  398. return filepath.Join(repo.RepoPath(), "config")
  399. }
  400. func (repo *Repository) RelLink() string {
  401. return "/" + repo.FullName()
  402. }
  403. func (repo *Repository) Link() string {
  404. return setting.AppSubURL + "/" + repo.FullName()
  405. }
  406. func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
  407. return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
  408. }
  409. func (repo *Repository) HasAccess(userID int64) bool {
  410. has, _ := HasAccess(userID, repo, ACCESS_MODE_READ)
  411. return has
  412. }
  413. func (repo *Repository) IsOwnedBy(userID int64) bool {
  414. return repo.OwnerID == userID
  415. }
  416. // CanBeForked returns true if repository meets the requirements of being forked.
  417. func (repo *Repository) CanBeForked() bool {
  418. return !repo.IsBare
  419. }
  420. // CanEnablePulls returns true if repository meets the requirements of accepting pulls.
  421. func (repo *Repository) CanEnablePulls() bool {
  422. return !repo.IsMirror && !repo.IsBare
  423. }
  424. // AllowPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
  425. func (repo *Repository) AllowsPulls() bool {
  426. return repo.CanEnablePulls() && repo.EnablePulls
  427. }
  428. func (repo *Repository) IsBranchRequirePullRequest(name string) bool {
  429. return IsBranchOfRepoRequirePullRequest(repo.ID, name)
  430. }
  431. // CanEnableEditor returns true if repository meets the requirements of web editor.
  432. func (repo *Repository) CanEnableEditor() bool {
  433. return !repo.IsMirror
  434. }
  435. // FIXME: should have a mutex to prevent producing same index for two issues that are created
  436. // closely enough.
  437. func (repo *Repository) NextIssueIndex() int64 {
  438. return int64(repo.NumIssues+repo.NumPulls) + 1
  439. }
  440. func (repo *Repository) LocalCopyPath() string {
  441. return path.Join(setting.AppDataPath, "tmp/local-repo", com.ToStr(repo.ID))
  442. }
  443. // UpdateLocalCopy fetches latest changes of given branch from repoPath to localPath.
  444. // It creates a new clone if local copy does not exist, but does not checks out to a
  445. // specific branch if the local copy belongs to a wiki.
  446. // For existing local copy, it checks out to target branch by default, and safe to
  447. // assume subsequent operations are against target branch when caller has confidence
  448. // about no race condition.
  449. func UpdateLocalCopyBranch(repoPath, localPath, branch string, isWiki bool) (err error) {
  450. if !com.IsExist(localPath) {
  451. // Checkout to a specific branch fails when wiki is an empty repository.
  452. if isWiki {
  453. branch = ""
  454. }
  455. if err = git.Clone(repoPath, localPath, git.CloneRepoOptions{
  456. Timeout: time.Duration(setting.Git.Timeout.Clone) * time.Second,
  457. Branch: branch,
  458. }); err != nil {
  459. return fmt.Errorf("git clone %s: %v", branch, err)
  460. }
  461. } else {
  462. if err = git.Fetch(localPath, git.FetchRemoteOptions{
  463. Prune: true,
  464. }); err != nil {
  465. return fmt.Errorf("git fetch: %v", err)
  466. }
  467. if err = git.Checkout(localPath, git.CheckoutOptions{
  468. Branch: branch,
  469. }); err != nil {
  470. return fmt.Errorf("git checkout %s: %v", branch, err)
  471. }
  472. // Reset to align with remote in case of force push.
  473. if err = git.ResetHEAD(localPath, true, "origin/"+branch); err != nil {
  474. return fmt.Errorf("git reset --hard origin/%s: %v", branch, err)
  475. }
  476. }
  477. return nil
  478. }
  479. // UpdateLocalCopyBranch makes sure local copy of repository in given branch is up-to-date.
  480. func (repo *Repository) UpdateLocalCopyBranch(branch string) error {
  481. return UpdateLocalCopyBranch(repo.RepoPath(), repo.LocalCopyPath(), branch, false)
  482. }
  483. // PatchPath returns corresponding patch file path of repository by given issue ID.
  484. func (repo *Repository) PatchPath(index int64) (string, error) {
  485. if err := repo.GetOwner(); err != nil {
  486. return "", err
  487. }
  488. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  489. }
  490. // SavePatch saves patch data to corresponding location by given issue ID.
  491. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  492. patchPath, err := repo.PatchPath(index)
  493. if err != nil {
  494. return fmt.Errorf("PatchPath: %v", err)
  495. }
  496. os.MkdirAll(filepath.Dir(patchPath), os.ModePerm)
  497. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  498. return fmt.Errorf("WriteFile: %v", err)
  499. }
  500. return nil
  501. }
  502. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  503. has, err := e.Get(&Repository{
  504. OwnerID: u.ID,
  505. LowerName: strings.ToLower(repoName),
  506. })
  507. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  508. }
  509. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  510. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  511. return isRepositoryExist(x, u, repoName)
  512. }
  513. // CloneLink represents different types of clone URLs of repository.
  514. type CloneLink struct {
  515. SSH string
  516. HTTPS string
  517. Git string
  518. }
  519. // ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name.
  520. func ComposeHTTPSCloneURL(owner, repo string) string {
  521. return fmt.Sprintf("%s%s/%s.git", setting.AppURL, owner, repo)
  522. }
  523. func (repo *Repository) cloneLink(isWiki bool) *CloneLink {
  524. repoName := repo.Name
  525. if isWiki {
  526. repoName += ".wiki"
  527. }
  528. repo.Owner = repo.MustOwner()
  529. cl := new(CloneLink)
  530. if setting.SSH.Port != 22 {
  531. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.SSH.Domain, setting.SSH.Port, repo.Owner.Name, repoName)
  532. } else {
  533. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  534. }
  535. cl.HTTPS = ComposeHTTPSCloneURL(repo.Owner.Name, repoName)
  536. return cl
  537. }
  538. // CloneLink returns clone URLs of repository.
  539. func (repo *Repository) CloneLink() (cl *CloneLink) {
  540. return repo.cloneLink(false)
  541. }
  542. type MigrateRepoOptions struct {
  543. Name string
  544. Description string
  545. IsPrivate bool
  546. IsMirror bool
  547. RemoteAddr string
  548. }
  549. /*
  550. GitHub, GitLab, Gogs: *.wiki.git
  551. BitBucket: *.git/wiki
  552. */
  553. var commonWikiURLSuffixes = []string{".wiki.git", ".git/wiki"}
  554. // wikiRemoteURL returns accessible repository URL for wiki if exists.
  555. // Otherwise, it returns an empty string.
  556. func wikiRemoteURL(remote string) string {
  557. remote = strings.TrimSuffix(remote, ".git")
  558. for _, suffix := range commonWikiURLSuffixes {
  559. wikiURL := remote + suffix
  560. if git.IsRepoURLAccessible(git.NetworkOptions{
  561. URL: wikiURL,
  562. }) {
  563. return wikiURL
  564. }
  565. }
  566. return ""
  567. }
  568. // MigrateRepository migrates a existing repository from other project hosting.
  569. func MigrateRepository(doer, owner *User, opts MigrateRepoOptions) (*Repository, error) {
  570. repo, err := CreateRepository(doer, owner, CreateRepoOptions{
  571. Name: opts.Name,
  572. Description: opts.Description,
  573. IsPrivate: opts.IsPrivate,
  574. IsMirror: opts.IsMirror,
  575. })
  576. if err != nil {
  577. return nil, err
  578. }
  579. repoPath := RepoPath(owner.Name, opts.Name)
  580. wikiPath := WikiPath(owner.Name, opts.Name)
  581. if owner.IsOrganization() {
  582. t, err := owner.GetOwnerTeam()
  583. if err != nil {
  584. return nil, err
  585. }
  586. repo.NumWatches = t.NumMembers
  587. } else {
  588. repo.NumWatches = 1
  589. }
  590. migrateTimeout := time.Duration(setting.Git.Timeout.Migrate) * time.Second
  591. RemoveAllWithNotice("Repository path erase before creation", repoPath)
  592. if err = git.Clone(opts.RemoteAddr, repoPath, git.CloneRepoOptions{
  593. Mirror: true,
  594. Quiet: true,
  595. Timeout: migrateTimeout,
  596. }); err != nil {
  597. return repo, fmt.Errorf("Clone: %v", err)
  598. }
  599. wikiRemotePath := wikiRemoteURL(opts.RemoteAddr)
  600. if len(wikiRemotePath) > 0 {
  601. RemoveAllWithNotice("Repository wiki path erase before creation", wikiPath)
  602. if err = git.Clone(wikiRemotePath, wikiPath, git.CloneRepoOptions{
  603. Mirror: true,
  604. Quiet: true,
  605. Timeout: migrateTimeout,
  606. }); err != nil {
  607. log.Trace("Fail to clone wiki: %v", err)
  608. RemoveAllWithNotice("Delete repository wiki for initialization failure", wikiPath)
  609. }
  610. }
  611. // Check if repository is empty.
  612. _, stderr, err := com.ExecCmdDir(repoPath, "git", "log", "-1")
  613. if err != nil {
  614. if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
  615. repo.IsBare = true
  616. } else {
  617. return repo, fmt.Errorf("check bare: %v - %s", err, stderr)
  618. }
  619. }
  620. if !repo.IsBare {
  621. // Try to get HEAD branch and set it as default branch.
  622. gitRepo, err := git.OpenRepository(repoPath)
  623. if err != nil {
  624. return repo, fmt.Errorf("OpenRepository: %v", err)
  625. }
  626. headBranch, err := gitRepo.GetHEADBranch()
  627. if err != nil {
  628. return repo, fmt.Errorf("GetHEADBranch: %v", err)
  629. }
  630. if headBranch != nil {
  631. repo.DefaultBranch = headBranch.Name
  632. }
  633. if err = repo.UpdateSize(); err != nil {
  634. log.Error(2, "UpdateSize [repo_id: %d]: %v", repo.ID, err)
  635. }
  636. }
  637. if opts.IsMirror {
  638. if _, err = x.InsertOne(&Mirror{
  639. RepoID: repo.ID,
  640. Interval: setting.Mirror.DefaultInterval,
  641. EnablePrune: true,
  642. NextUpdate: time.Now().Add(time.Duration(setting.Mirror.DefaultInterval) * time.Hour),
  643. }); err != nil {
  644. return repo, fmt.Errorf("InsertOne: %v", err)
  645. }
  646. repo.IsMirror = true
  647. return repo, UpdateRepository(repo, false)
  648. }
  649. return CleanUpMigrateInfo(repo)
  650. }
  651. // cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
  652. // This also removes possible user credentials.
  653. func cleanUpMigrateGitConfig(configPath string) error {
  654. cfg, err := ini.Load(configPath)
  655. if err != nil {
  656. return fmt.Errorf("open config file: %v", err)
  657. }
  658. cfg.DeleteSection("remote \"origin\"")
  659. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  660. return fmt.Errorf("save config file: %v", err)
  661. }
  662. return nil
  663. }
  664. var hooksTpls = map[string]string{
  665. "pre-receive": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n",
  666. "update": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n",
  667. "post-receive": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n",
  668. }
  669. func createDelegateHooks(repoPath string) (err error) {
  670. for _, name := range git.HookNames {
  671. hookPath := filepath.Join(repoPath, "hooks", name)
  672. if err = ioutil.WriteFile(hookPath,
  673. []byte(fmt.Sprintf(hooksTpls[name], setting.ScriptType, setting.AppPath, setting.CustomConf)),
  674. os.ModePerm); err != nil {
  675. return fmt.Errorf("create delegate hook '%s': %v", hookPath, err)
  676. }
  677. }
  678. return nil
  679. }
  680. // Finish migrating repository and/or wiki with things that don't need to be done for mirrors.
  681. func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
  682. repoPath := repo.RepoPath()
  683. if err := createDelegateHooks(repoPath); err != nil {
  684. return repo, fmt.Errorf("createDelegateHooks: %v", err)
  685. }
  686. if repo.HasWiki() {
  687. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  688. return repo, fmt.Errorf("createDelegateHooks.(wiki): %v", err)
  689. }
  690. }
  691. if err := cleanUpMigrateGitConfig(repo.GitConfigPath()); err != nil {
  692. return repo, fmt.Errorf("cleanUpMigrateGitConfig: %v", err)
  693. }
  694. if repo.HasWiki() {
  695. if err := cleanUpMigrateGitConfig(path.Join(repo.WikiPath(), "config")); err != nil {
  696. return repo, fmt.Errorf("cleanUpMigrateGitConfig.(wiki): %v", err)
  697. }
  698. }
  699. return repo, UpdateRepository(repo, false)
  700. }
  701. // initRepoCommit temporarily changes with work directory.
  702. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  703. var stderr string
  704. if _, stderr, err = process.ExecDir(-1,
  705. tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
  706. "git", "add", "--all"); err != nil {
  707. return fmt.Errorf("git add: %s", stderr)
  708. }
  709. if _, stderr, err = process.ExecDir(-1,
  710. tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
  711. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  712. "-m", "Initial commit"); err != nil {
  713. return fmt.Errorf("git commit: %s", stderr)
  714. }
  715. if _, stderr, err = process.ExecDir(-1,
  716. tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
  717. "git", "push", "origin", "master"); err != nil {
  718. return fmt.Errorf("git push: %s", stderr)
  719. }
  720. return nil
  721. }
  722. type CreateRepoOptions struct {
  723. Name string
  724. Description string
  725. Gitignores string
  726. License string
  727. Readme string
  728. IsPrivate bool
  729. IsMirror bool
  730. AutoInit bool
  731. }
  732. func getRepoInitFile(tp, name string) ([]byte, error) {
  733. relPath := path.Join("conf", tp, strings.TrimLeft(name, "./"))
  734. // Use custom file when available.
  735. customPath := path.Join(setting.CustomPath, relPath)
  736. if com.IsFile(customPath) {
  737. return ioutil.ReadFile(customPath)
  738. }
  739. return bindata.Asset(relPath)
  740. }
  741. func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  742. // Clone to temprory path and do the init commit.
  743. _, stderr, err := process.Exec(
  744. fmt.Sprintf("initRepository(git clone): %s", repoPath), "git", "clone", repoPath, tmpDir)
  745. if err != nil {
  746. return fmt.Errorf("git clone: %v - %s", err, stderr)
  747. }
  748. // README
  749. data, err := getRepoInitFile("readme", opts.Readme)
  750. if err != nil {
  751. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  752. }
  753. cloneLink := repo.CloneLink()
  754. match := map[string]string{
  755. "Name": repo.Name,
  756. "Description": repo.Description,
  757. "CloneURL.SSH": cloneLink.SSH,
  758. "CloneURL.HTTPS": cloneLink.HTTPS,
  759. }
  760. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  761. []byte(com.Expand(string(data), match)), 0644); err != nil {
  762. return fmt.Errorf("write README.md: %v", err)
  763. }
  764. // .gitignore
  765. if len(opts.Gitignores) > 0 {
  766. var buf bytes.Buffer
  767. names := strings.Split(opts.Gitignores, ",")
  768. for _, name := range names {
  769. data, err = getRepoInitFile("gitignore", name)
  770. if err != nil {
  771. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  772. }
  773. buf.WriteString("# ---> " + name + "\n")
  774. buf.Write(data)
  775. buf.WriteString("\n")
  776. }
  777. if buf.Len() > 0 {
  778. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  779. return fmt.Errorf("write .gitignore: %v", err)
  780. }
  781. }
  782. }
  783. // LICENSE
  784. if len(opts.License) > 0 {
  785. data, err = getRepoInitFile("license", opts.License)
  786. if err != nil {
  787. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  788. }
  789. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  790. return fmt.Errorf("write LICENSE: %v", err)
  791. }
  792. }
  793. return nil
  794. }
  795. // initRepository performs initial commit with chosen setup files on behave of doer.
  796. func initRepository(e Engine, repoPath string, doer *User, repo *Repository, opts CreateRepoOptions) (err error) {
  797. // Somehow the directory could exist.
  798. if com.IsExist(repoPath) {
  799. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  800. }
  801. // Init bare new repository.
  802. if err = git.InitRepository(repoPath, true); err != nil {
  803. return fmt.Errorf("InitRepository: %v", err)
  804. } else if err = createDelegateHooks(repoPath); err != nil {
  805. return fmt.Errorf("createDelegateHooks: %v", err)
  806. }
  807. tmpDir := filepath.Join(os.TempDir(), "gogs-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  808. // Initialize repository according to user's choice.
  809. if opts.AutoInit {
  810. os.MkdirAll(tmpDir, os.ModePerm)
  811. defer RemoveAllWithNotice("Delete repository for auto-initialization", tmpDir)
  812. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  813. return fmt.Errorf("prepareRepoCommit: %v", err)
  814. }
  815. // Apply changes and commit.
  816. if err = initRepoCommit(tmpDir, doer.NewGitSig()); err != nil {
  817. return fmt.Errorf("initRepoCommit: %v", err)
  818. }
  819. }
  820. // Re-fetch the repository from database before updating it (else it would
  821. // override changes that were done earlier with sql)
  822. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  823. return fmt.Errorf("getRepositoryByID: %v", err)
  824. }
  825. if !opts.AutoInit {
  826. repo.IsBare = true
  827. }
  828. repo.DefaultBranch = "master"
  829. if err = updateRepository(e, repo, false); err != nil {
  830. return fmt.Errorf("updateRepository: %v", err)
  831. }
  832. return nil
  833. }
  834. var (
  835. reservedRepoNames = []string{".", ".."}
  836. reservedRepoPatterns = []string{"*.git", "*.wiki"}
  837. )
  838. // IsUsableRepoName return an error if given name is a reserved name or pattern.
  839. func IsUsableRepoName(name string) error {
  840. return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
  841. }
  842. func createRepository(e *xorm.Session, doer, owner *User, repo *Repository) (err error) {
  843. if err = IsUsableRepoName(repo.Name); err != nil {
  844. return err
  845. }
  846. has, err := isRepositoryExist(e, owner, repo.Name)
  847. if err != nil {
  848. return fmt.Errorf("IsRepositoryExist: %v", err)
  849. } else if has {
  850. return ErrRepoAlreadyExist{owner.Name, repo.Name}
  851. }
  852. if _, err = e.Insert(repo); err != nil {
  853. return err
  854. }
  855. owner.NumRepos++
  856. // Remember visibility preference.
  857. owner.LastRepoVisibility = repo.IsPrivate
  858. if err = updateUser(e, owner); err != nil {
  859. return fmt.Errorf("updateUser: %v", err)
  860. }
  861. // Give access to all members in owner team.
  862. if owner.IsOrganization() {
  863. t, err := owner.getOwnerTeam(e)
  864. if err != nil {
  865. return fmt.Errorf("getOwnerTeam: %v", err)
  866. } else if err = t.addRepository(e, repo); err != nil {
  867. return fmt.Errorf("addRepository: %v", err)
  868. }
  869. } else {
  870. // Organization automatically called this in addRepository method.
  871. if err = repo.recalculateAccesses(e); err != nil {
  872. return fmt.Errorf("recalculateAccesses: %v", err)
  873. }
  874. }
  875. if err = watchRepo(e, owner.ID, repo.ID, true); err != nil {
  876. return fmt.Errorf("watchRepo: %v", err)
  877. } else if err = newRepoAction(e, doer, owner, repo); err != nil {
  878. return fmt.Errorf("newRepoAction: %v", err)
  879. }
  880. return repo.loadAttributes(e)
  881. }
  882. // CreateRepository creates a repository for given user or organization.
  883. func CreateRepository(doer, owner *User, opts CreateRepoOptions) (_ *Repository, err error) {
  884. if !owner.CanCreateRepo() {
  885. return nil, errors.ReachLimitOfRepo{owner.RepoCreationNum()}
  886. }
  887. repo := &Repository{
  888. OwnerID: owner.ID,
  889. Owner: owner,
  890. Name: opts.Name,
  891. LowerName: strings.ToLower(opts.Name),
  892. Description: opts.Description,
  893. IsPrivate: opts.IsPrivate,
  894. EnableWiki: true,
  895. EnableIssues: true,
  896. EnablePulls: true,
  897. }
  898. sess := x.NewSession()
  899. defer sess.Close()
  900. if err = sess.Begin(); err != nil {
  901. return nil, err
  902. }
  903. if err = createRepository(sess, doer, owner, repo); err != nil {
  904. return nil, err
  905. }
  906. // No need for init mirror.
  907. if !opts.IsMirror {
  908. repoPath := RepoPath(owner.Name, repo.Name)
  909. if err = initRepository(sess, repoPath, doer, repo, opts); err != nil {
  910. RemoveAllWithNotice("Delete repository for initialization failure", repoPath)
  911. return nil, fmt.Errorf("initRepository: %v", err)
  912. }
  913. _, stderr, err := process.ExecDir(-1,
  914. repoPath, fmt.Sprintf("CreateRepository 'git update-server-info': %s", repoPath),
  915. "git", "update-server-info")
  916. if err != nil {
  917. return nil, fmt.Errorf("CreateRepository 'git update-server-info': %s", stderr)
  918. }
  919. }
  920. return repo, sess.Commit()
  921. }
  922. func countRepositories(userID int64, private bool) int64 {
  923. sess := x.Where("id > 0")
  924. if userID > 0 {
  925. sess.And("owner_id = ?", userID)
  926. }
  927. if !private {
  928. sess.And("is_private=?", false)
  929. }
  930. count, err := sess.Count(new(Repository))
  931. if err != nil {
  932. log.Error(4, "countRepositories: %v", err)
  933. }
  934. return count
  935. }
  936. // CountRepositories returns number of repositories.
  937. // Argument private only takes effect when it is false,
  938. // set it true to count all repositories.
  939. func CountRepositories(private bool) int64 {
  940. return countRepositories(-1, private)
  941. }
  942. // CountUserRepositories returns number of repositories user owns.
  943. // Argument private only takes effect when it is false,
  944. // set it true to count all repositories.
  945. func CountUserRepositories(userID int64, private bool) int64 {
  946. return countRepositories(userID, private)
  947. }
  948. func Repositories(page, pageSize int) (_ []*Repository, err error) {
  949. repos := make([]*Repository, 0, pageSize)
  950. return repos, x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos)
  951. }
  952. // RepositoriesWithUsers returns number of repos in given page.
  953. func RepositoriesWithUsers(page, pageSize int) (_ []*Repository, err error) {
  954. repos, err := Repositories(page, pageSize)
  955. if err != nil {
  956. return nil, fmt.Errorf("Repositories: %v", err)
  957. }
  958. for i := range repos {
  959. if err = repos[i].GetOwner(); err != nil {
  960. return nil, err
  961. }
  962. }
  963. return repos, nil
  964. }
  965. // FilterRepositoryWithIssues selects repositories that are using interal issue tracker
  966. // and has disabled external tracker from given set.
  967. // It returns nil if result set is empty.
  968. func FilterRepositoryWithIssues(repoIDs []int64) ([]int64, error) {
  969. if len(repoIDs) == 0 {
  970. return nil, nil
  971. }
  972. repos := make([]*Repository, 0, len(repoIDs))
  973. if err := x.Where("enable_issues=?", true).
  974. And("enable_external_tracker=?", false).
  975. In("id", repoIDs).
  976. Cols("id").
  977. Find(&repos); err != nil {
  978. return nil, fmt.Errorf("filter valid repositories %v: %v", repoIDs, err)
  979. }
  980. if len(repos) == 0 {
  981. return nil, nil
  982. }
  983. repoIDs = make([]int64, len(repos))
  984. for i := range repos {
  985. repoIDs[i] = repos[i].ID
  986. }
  987. return repoIDs, nil
  988. }
  989. // RepoPath returns repository path by given user and repository name.
  990. func RepoPath(userName, repoName string) string {
  991. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  992. }
  993. // TransferOwnership transfers all corresponding setting from old user to new one.
  994. func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
  995. newOwner, err := GetUserByName(newOwnerName)
  996. if err != nil {
  997. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  998. }
  999. // Check if new owner has repository with same name.
  1000. has, err := IsRepositoryExist(newOwner, repo.Name)
  1001. if err != nil {
  1002. return fmt.Errorf("IsRepositoryExist: %v", err)
  1003. } else if has {
  1004. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  1005. }
  1006. sess := x.NewSession()
  1007. defer sess.Close()
  1008. if err = sess.Begin(); err != nil {
  1009. return fmt.Errorf("sess.Begin: %v", err)
  1010. }
  1011. owner := repo.Owner
  1012. // Note: we have to set value here to make sure recalculate accesses is based on
  1013. // new owner.
  1014. repo.OwnerID = newOwner.ID
  1015. repo.Owner = newOwner
  1016. // Update repository.
  1017. if _, err := sess.Id(repo.ID).Update(repo); err != nil {
  1018. return fmt.Errorf("update owner: %v", err)
  1019. }
  1020. // Remove redundant collaborators.
  1021. collaborators, err := repo.getCollaborators(sess)
  1022. if err != nil {
  1023. return fmt.Errorf("getCollaborators: %v", err)
  1024. }
  1025. // Dummy object.
  1026. collaboration := &Collaboration{RepoID: repo.ID}
  1027. for _, c := range collaborators {
  1028. collaboration.UserID = c.ID
  1029. if c.ID == newOwner.ID || newOwner.IsOrgMember(c.ID) {
  1030. if _, err = sess.Delete(collaboration); err != nil {
  1031. return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
  1032. }
  1033. }
  1034. }
  1035. // Remove old team-repository relations.
  1036. if owner.IsOrganization() {
  1037. if err = owner.getTeams(sess); err != nil {
  1038. return fmt.Errorf("getTeams: %v", err)
  1039. }
  1040. for _, t := range owner.Teams {
  1041. if !t.hasRepository(sess, repo.ID) {
  1042. continue
  1043. }
  1044. t.NumRepos--
  1045. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  1046. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  1047. }
  1048. }
  1049. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  1050. return fmt.Errorf("removeOrgRepo: %v", err)
  1051. }
  1052. }
  1053. if newOwner.IsOrganization() {
  1054. t, err := newOwner.getOwnerTeam(sess)
  1055. if err != nil {
  1056. return fmt.Errorf("getOwnerTeam: %v", err)
  1057. } else if err = t.addRepository(sess, repo); err != nil {
  1058. return fmt.Errorf("add to owner team: %v", err)
  1059. }
  1060. } else {
  1061. // Organization called this in addRepository method.
  1062. if err = repo.recalculateAccesses(sess); err != nil {
  1063. return fmt.Errorf("recalculateAccesses: %v", err)
  1064. }
  1065. }
  1066. // Update repository count.
  1067. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
  1068. return fmt.Errorf("increase new owner repository count: %v", err)
  1069. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.ID); err != nil {
  1070. return fmt.Errorf("decrease old owner repository count: %v", err)
  1071. }
  1072. if err = watchRepo(sess, newOwner.ID, repo.ID, true); err != nil {
  1073. return fmt.Errorf("watchRepo: %v", err)
  1074. } else if err = transferRepoAction(sess, doer, owner, repo); err != nil {
  1075. return fmt.Errorf("transferRepoAction: %v", err)
  1076. }
  1077. // Rename remote repository to new path and delete local copy.
  1078. os.MkdirAll(UserPath(newOwner.Name), os.ModePerm)
  1079. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  1080. return fmt.Errorf("rename repository directory: %v", err)
  1081. }
  1082. RemoveAllWithNotice("Delete repository local copy", repo.LocalCopyPath())
  1083. // Rename remote wiki repository to new path and delete local copy.
  1084. wikiPath := WikiPath(owner.Name, repo.Name)
  1085. if com.IsExist(wikiPath) {
  1086. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1087. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  1088. return fmt.Errorf("rename repository wiki: %v", err)
  1089. }
  1090. }
  1091. return sess.Commit()
  1092. }
  1093. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  1094. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  1095. oldRepoName = strings.ToLower(oldRepoName)
  1096. newRepoName = strings.ToLower(newRepoName)
  1097. if err = IsUsableRepoName(newRepoName); err != nil {
  1098. return err
  1099. }
  1100. has, err := IsRepositoryExist(u, newRepoName)
  1101. if err != nil {
  1102. return fmt.Errorf("IsRepositoryExist: %v", err)
  1103. } else if has {
  1104. return ErrRepoAlreadyExist{u.Name, newRepoName}
  1105. }
  1106. repo, err := GetRepositoryByName(u.ID, oldRepoName)
  1107. if err != nil {
  1108. return fmt.Errorf("GetRepositoryByName: %v", err)
  1109. }
  1110. // Change repository directory name
  1111. if err = os.Rename(repo.RepoPath(), RepoPath(u.Name, newRepoName)); err != nil {
  1112. return fmt.Errorf("rename repository directory: %v", err)
  1113. }
  1114. wikiPath := repo.WikiPath()
  1115. if com.IsExist(wikiPath) {
  1116. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  1117. return fmt.Errorf("rename repository wiki: %v", err)
  1118. }
  1119. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1120. }
  1121. RemoveAllWithNotice("Delete repository local copy", repo.LocalCopyPath())
  1122. return nil
  1123. }
  1124. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  1125. repos := make([]*Repository, 0, 10)
  1126. return repos, e.Where("fork_id=?", forkID).Find(&repos)
  1127. }
  1128. // GetRepositoriesByForkID returns all repositories with given fork ID.
  1129. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  1130. return getRepositoriesByForkID(x, forkID)
  1131. }
  1132. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  1133. repo.LowerName = strings.ToLower(repo.Name)
  1134. if len(repo.Description) > 255 {
  1135. repo.Description = repo.Description[:255]
  1136. }
  1137. if len(repo.Website) > 255 {
  1138. repo.Website = repo.Website[:255]
  1139. }
  1140. if _, err = e.Id(repo.ID).AllCols().Update(repo); err != nil {
  1141. return fmt.Errorf("update: %v", err)
  1142. }
  1143. if visibilityChanged {
  1144. if err = repo.getOwner(e); err != nil {
  1145. return fmt.Errorf("getOwner: %v", err)
  1146. }
  1147. if repo.Owner.IsOrganization() {
  1148. // Organization repository need to recalculate access table when visivility is changed
  1149. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  1150. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  1151. }
  1152. }
  1153. // Create/Remove git-daemon-export-ok for git-daemon
  1154. daemonExportFile := path.Join(repo.RepoPath(), "git-daemon-export-ok")
  1155. if repo.IsPrivate && com.IsExist(daemonExportFile) {
  1156. if err = os.Remove(daemonExportFile); err != nil {
  1157. log.Error(4, "Failed to remove %s: %v", daemonExportFile, err)
  1158. }
  1159. } else if !repo.IsPrivate && !com.IsExist(daemonExportFile) {
  1160. if f, err := os.Create(daemonExportFile); err != nil {
  1161. log.Error(4, "Failed to create %s: %v", daemonExportFile, err)
  1162. } else {
  1163. f.Close()
  1164. }
  1165. }
  1166. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1167. if err != nil {
  1168. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1169. }
  1170. for i := range forkRepos {
  1171. forkRepos[i].IsPrivate = repo.IsPrivate
  1172. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1173. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1174. }
  1175. }
  1176. // Change visibility of generated actions
  1177. if _, err = e.Where("repo_id = ?", repo.ID).Cols("is_private").Update(&Action{IsPrivate: repo.IsPrivate}); err != nil {
  1178. return fmt.Errorf("change action visibility of repository: %v", err)
  1179. }
  1180. }
  1181. return nil
  1182. }
  1183. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1184. sess := x.NewSession()
  1185. defer sess.Close()
  1186. if err = sess.Begin(); err != nil {
  1187. return err
  1188. }
  1189. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  1190. return fmt.Errorf("updateRepository: %v", err)
  1191. }
  1192. return sess.Commit()
  1193. }
  1194. // DeleteRepository deletes a repository for a user or organization.
  1195. func DeleteRepository(uid, repoID int64) error {
  1196. repo := &Repository{ID: repoID, OwnerID: uid}
  1197. has, err := x.Get(repo)
  1198. if err != nil {
  1199. return err
  1200. } else if !has {
  1201. return errors.RepoNotExist{repoID, uid, ""}
  1202. }
  1203. // In case is a organization.
  1204. org, err := GetUserByID(uid)
  1205. if err != nil {
  1206. return err
  1207. }
  1208. if org.IsOrganization() {
  1209. if err = org.GetTeams(); err != nil {
  1210. return err
  1211. }
  1212. }
  1213. sess := x.NewSession()
  1214. defer sess.Close()
  1215. if err = sess.Begin(); err != nil {
  1216. return err
  1217. }
  1218. if org.IsOrganization() {
  1219. for _, t := range org.Teams {
  1220. if !t.hasRepository(sess, repoID) {
  1221. continue
  1222. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1223. return err
  1224. }
  1225. }
  1226. }
  1227. if err = deleteBeans(sess,
  1228. &Repository{ID: repoID},
  1229. &Access{RepoID: repo.ID},
  1230. &Action{RepoID: repo.ID},
  1231. &Watch{RepoID: repoID},
  1232. &Star{RepoID: repoID},
  1233. &Mirror{RepoID: repoID},
  1234. &IssueUser{RepoID: repoID},
  1235. &Milestone{RepoID: repoID},
  1236. &Release{RepoID: repoID},
  1237. &Collaboration{RepoID: repoID},
  1238. &PullRequest{BaseRepoID: repoID},
  1239. &ProtectBranch{RepoID: repoID},
  1240. &ProtectBranchWhitelist{RepoID: repoID},
  1241. ); err != nil {
  1242. return fmt.Errorf("deleteBeans: %v", err)
  1243. }
  1244. // Delete comments and attachments.
  1245. issues := make([]*Issue, 0, 25)
  1246. attachmentPaths := make([]string, 0, len(issues))
  1247. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  1248. return err
  1249. }
  1250. for i := range issues {
  1251. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  1252. return err
  1253. }
  1254. attachments := make([]*Attachment, 0, 5)
  1255. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  1256. return err
  1257. }
  1258. for j := range attachments {
  1259. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1260. }
  1261. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  1262. return err
  1263. }
  1264. }
  1265. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1266. return err
  1267. }
  1268. if repo.IsFork {
  1269. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1270. return fmt.Errorf("decrease fork count: %v", err)
  1271. }
  1272. }
  1273. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1274. return err
  1275. }
  1276. if err = sess.Commit(); err != nil {
  1277. return fmt.Errorf("Commit: %v", err)
  1278. }
  1279. // Remove repository files.
  1280. repoPath := repo.RepoPath()
  1281. RemoveAllWithNotice("Delete repository files", repoPath)
  1282. repo.DeleteWiki()
  1283. // Remove attachment files.
  1284. for i := range attachmentPaths {
  1285. RemoveAllWithNotice("Delete attachment", attachmentPaths[i])
  1286. }
  1287. if repo.NumForks > 0 {
  1288. if _, err = x.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1289. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  1290. }
  1291. }
  1292. return nil
  1293. }
  1294. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  1295. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  1296. func GetRepositoryByRef(ref string) (*Repository, error) {
  1297. n := strings.IndexByte(ref, byte('/'))
  1298. if n < 2 {
  1299. return nil, errors.InvalidRepoReference{ref}
  1300. }
  1301. userName, repoName := ref[:n], ref[n+1:]
  1302. user, err := GetUserByName(userName)
  1303. if err != nil {
  1304. return nil, err
  1305. }
  1306. return GetRepositoryByName(user.ID, repoName)
  1307. }
  1308. // GetRepositoryByName returns the repository by given name under user if exists.
  1309. func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
  1310. repo := &Repository{
  1311. OwnerID: ownerID,
  1312. LowerName: strings.ToLower(name),
  1313. }
  1314. has, err := x.Get(repo)
  1315. if err != nil {
  1316. return nil, err
  1317. } else if !has {
  1318. return nil, errors.RepoNotExist{0, ownerID, name}
  1319. }
  1320. return repo, repo.LoadAttributes()
  1321. }
  1322. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1323. repo := new(Repository)
  1324. has, err := e.Id(id).Get(repo)
  1325. if err != nil {
  1326. return nil, err
  1327. } else if !has {
  1328. return nil, errors.RepoNotExist{id, 0, ""}
  1329. }
  1330. return repo, repo.loadAttributes(e)
  1331. }
  1332. // GetRepositoryByID returns the repository by given id if exists.
  1333. func GetRepositoryByID(id int64) (*Repository, error) {
  1334. return getRepositoryByID(x, id)
  1335. }
  1336. type UserRepoOptions struct {
  1337. UserID int64
  1338. Private bool
  1339. Page int
  1340. PageSize int
  1341. }
  1342. // GetUserRepositories returns a list of repositories of given user.
  1343. func GetUserRepositories(opts *UserRepoOptions) ([]*Repository, error) {
  1344. sess := x.Where("owner_id=?", opts.UserID).Desc("updated_unix")
  1345. if !opts.Private {
  1346. sess.And("is_private=?", false)
  1347. }
  1348. if opts.Page <= 0 {
  1349. opts.Page = 1
  1350. }
  1351. sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1352. repos := make([]*Repository, 0, opts.PageSize)
  1353. return repos, sess.Find(&repos)
  1354. }
  1355. // GetUserRepositories returns a list of mirror repositories of given user.
  1356. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1357. repos := make([]*Repository, 0, 10)
  1358. return repos, x.Where("owner_id = ?", userID).And("is_mirror = ?", true).Find(&repos)
  1359. }
  1360. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  1361. func GetRecentUpdatedRepositories(page, pageSize int) (repos []*Repository, err error) {
  1362. return repos, x.Limit(pageSize, (page-1)*pageSize).
  1363. Where("is_private=?", false).Limit(pageSize).Desc("updated_unix").Find(&repos)
  1364. }
  1365. // GetUserAndCollaborativeRepositories returns list of repositories the user owns and collaborates.
  1366. func GetUserAndCollaborativeRepositories(userID int64) ([]*Repository, error) {
  1367. repos := make([]*Repository, 0, 10)
  1368. if err := x.Alias("repo").
  1369. Join("INNER", "collaboration", "collaboration.repo_id = repo.id").
  1370. Where("collaboration.user_id = ?", userID).
  1371. Find(&repos); err != nil {
  1372. return nil, fmt.Errorf("select collaborative repositories: %v", err)
  1373. }
  1374. ownRepos := make([]*Repository, 0, 10)
  1375. if err := x.Where("owner_id = ?", userID).Find(&ownRepos); err != nil {
  1376. return nil, fmt.Errorf("select own repositories: %v", err)
  1377. }
  1378. return append(repos, ownRepos...), nil
  1379. }
  1380. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1381. return x.Count(&Repository{OwnerID: u.ID})
  1382. }
  1383. // GetRepositoryCount returns the total number of repositories of user.
  1384. func GetRepositoryCount(u *User) (int64, error) {
  1385. return getRepositoryCount(x, u)
  1386. }
  1387. type SearchRepoOptions struct {
  1388. Keyword string
  1389. OwnerID int64
  1390. UserID int64 // When set results will contain all public/private repositories user has access to
  1391. OrderBy string
  1392. Private bool // Include private repositories in results
  1393. Page int
  1394. PageSize int // Can be smaller than or equal to setting.ExplorePagingNum
  1395. }
  1396. // SearchRepositoryByName takes keyword and part of repository name to search,
  1397. // it returns results in given range and number of total results.
  1398. func SearchRepositoryByName(opts *SearchRepoOptions) (repos []*Repository, count int64, err error) {
  1399. if opts.Page <= 0 {
  1400. opts.Page = 1
  1401. }
  1402. repos = make([]*Repository, 0, opts.PageSize)
  1403. sess := x.Alias("repo")
  1404. // Attempt to find repositories that opts.UserID has access to,
  1405. // this does not include other people's private repositories even if opts.UserID is an admin.
  1406. if !opts.Private && opts.UserID > 0 {
  1407. sess.Join("LEFT", "access", "access.repo_id = repo.id").
  1408. Where("(repo.owner_id = ? OR access.user_id = ? OR repo.is_private = ?)", opts.UserID, opts.UserID, false)
  1409. } else {
  1410. // Only return public repositories if opts.Private is not set
  1411. if !opts.Private {
  1412. sess.And("repo.is_private = ?", false)
  1413. }
  1414. }
  1415. if len(opts.Keyword) > 0 {
  1416. sess.And("repo.lower_name LIKE ? OR repo.description LIKE ?", "%"+strings.ToLower(opts.Keyword)+"%", "%"+strings.ToLower(opts.Keyword)+"%")
  1417. }
  1418. if opts.OwnerID > 0 {
  1419. sess.And("repo.owner_id = ?", opts.OwnerID)
  1420. }
  1421. // We need all fields (repo.*) in final list but only ID (repo.id) is good enough for counting.
  1422. count, err = sess.Clone().Distinct("repo.id").Count(new(Repository))
  1423. if err != nil {
  1424. return nil, 0, fmt.Errorf("Count: %v", err)
  1425. }
  1426. if len(opts.OrderBy) > 0 {
  1427. sess.OrderBy("repo." + opts.OrderBy)
  1428. }
  1429. return repos, count, sess.Distinct("repo.*").Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&repos)
  1430. }
  1431. func DeleteOldRepositoryArchives() {
  1432. if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
  1433. return
  1434. }
  1435. taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
  1436. defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
  1437. log.Trace("Doing: DeleteOldRepositoryArchives")
  1438. formats := []string{"zip", "targz"}
  1439. oldestTime := time.Now().Add(-setting.Cron.RepoArchiveCleanup.OlderThan)
  1440. if err := x.Where("id > 0").Iterate(new(Repository),
  1441. func(idx int, bean interface{}) error {
  1442. repo := bean.(*Repository)
  1443. basePath := filepath.Join(repo.RepoPath(), "archives")
  1444. for _, format := range formats {
  1445. dirPath := filepath.Join(basePath, format)
  1446. if !com.IsDir(dirPath) {
  1447. continue
  1448. }
  1449. dir, err := os.Open(dirPath)
  1450. if err != nil {
  1451. log.Error(3, "Fail to open directory '%s': %v", dirPath, err)
  1452. continue
  1453. }
  1454. fis, err := dir.Readdir(0)
  1455. dir.Close()
  1456. if err != nil {
  1457. log.Error(3, "Fail to read directory '%s': %v", dirPath, err)
  1458. continue
  1459. }
  1460. for _, fi := range fis {
  1461. if fi.IsDir() || fi.ModTime().After(oldestTime) {
  1462. continue
  1463. }
  1464. archivePath := filepath.Join(dirPath, fi.Name())
  1465. if err = os.Remove(archivePath); err != nil {
  1466. desc := fmt.Sprintf("Fail to health delete archive '%s': %v", archivePath, err)
  1467. log.Warn(desc)
  1468. if err = CreateRepositoryNotice(desc); err != nil {
  1469. log.Error(3, "CreateRepositoryNotice: %v", err)
  1470. }
  1471. }
  1472. }
  1473. }
  1474. return nil
  1475. }); err != nil {
  1476. log.Error(2, "DeleteOldRepositoryArchives: %v", err)
  1477. }
  1478. }
  1479. // DeleteRepositoryArchives deletes all repositories' archives.
  1480. func DeleteRepositoryArchives() error {
  1481. if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
  1482. return nil
  1483. }
  1484. taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
  1485. defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
  1486. return x.Where("id > 0").Iterate(new(Repository),
  1487. func(idx int, bean interface{}) error {
  1488. repo := bean.(*Repository)
  1489. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1490. })
  1491. }
  1492. func gatherMissingRepoRecords() ([]*Repository, error) {
  1493. repos := make([]*Repository, 0, 10)
  1494. if err := x.Where("id > 0").Iterate(new(Repository),
  1495. func(idx int, bean interface{}) error {
  1496. repo := bean.(*Repository)
  1497. if !com.IsDir(repo.RepoPath()) {
  1498. repos = append(repos, repo)
  1499. }
  1500. return nil
  1501. }); err != nil {
  1502. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1503. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1504. }
  1505. }
  1506. return repos, nil
  1507. }
  1508. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1509. func DeleteMissingRepositories() error {
  1510. repos, err := gatherMissingRepoRecords()
  1511. if err != nil {
  1512. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1513. }
  1514. if len(repos) == 0 {
  1515. return nil
  1516. }
  1517. for _, repo := range repos {
  1518. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1519. if err := DeleteRepository(repo.OwnerID, repo.ID); err != nil {
  1520. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1521. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1522. }
  1523. }
  1524. }
  1525. return nil
  1526. }
  1527. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1528. func ReinitMissingRepositories() error {
  1529. repos, err := gatherMissingRepoRecords()
  1530. if err != nil {
  1531. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1532. }
  1533. if len(repos) == 0 {
  1534. return nil
  1535. }
  1536. for _, repo := range repos {
  1537. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1538. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  1539. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1540. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1541. }
  1542. }
  1543. }
  1544. return nil
  1545. }
  1546. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  1547. // to make sure the binary and custom conf path are up-to-date.
  1548. func SyncRepositoryHooks() error {
  1549. return x.Where("id > 0").Iterate(new(Repository),
  1550. func(idx int, bean interface{}) error {
  1551. repo := bean.(*Repository)
  1552. if err := createDelegateHooks(repo.RepoPath()); err != nil {
  1553. return err
  1554. }
  1555. if repo.HasWiki() {
  1556. return createDelegateHooks(repo.WikiPath())
  1557. }
  1558. return nil
  1559. })
  1560. }
  1561. // Prevent duplicate running tasks.
  1562. var taskStatusTable = sync.NewStatusTable()
  1563. const (
  1564. _MIRROR_UPDATE = "mirror_update"
  1565. _GIT_FSCK = "git_fsck"
  1566. _CHECK_REPO_STATS = "check_repos_stats"
  1567. _CLEAN_OLD_ARCHIVES = "clean_old_archives"
  1568. )
  1569. // GitFsck calls 'git fsck' to check repository health.
  1570. func GitFsck() {
  1571. if taskStatusTable.IsRunning(_GIT_FSCK) {
  1572. return
  1573. }
  1574. taskStatusTable.Start(_GIT_FSCK)
  1575. defer taskStatusTable.Stop(_GIT_FSCK)
  1576. log.Trace("Doing: GitFsck")
  1577. if err := x.Where("id>0").Iterate(new(Repository),
  1578. func(idx int, bean interface{}) error {
  1579. repo := bean.(*Repository)
  1580. repoPath := repo.RepoPath()
  1581. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1582. desc := fmt.Sprintf("Fail to health check repository '%s': %v", repoPath, err)
  1583. log.Warn(desc)
  1584. if err = CreateRepositoryNotice(desc); err != nil {
  1585. log.Error(3, "CreateRepositoryNotice: %v", err)
  1586. }
  1587. }
  1588. return nil
  1589. }); err != nil {
  1590. log.Error(2, "GitFsck: %v", err)
  1591. }
  1592. }
  1593. func GitGcRepos() error {
  1594. args := append([]string{"gc"}, setting.Git.GCArgs...)
  1595. return x.Where("id > 0").Iterate(new(Repository),
  1596. func(idx int, bean interface{}) error {
  1597. repo := bean.(*Repository)
  1598. if err := repo.GetOwner(); err != nil {
  1599. return err
  1600. }
  1601. _, stderr, err := process.ExecDir(
  1602. time.Duration(setting.Git.Timeout.GC)*time.Second,
  1603. RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection",
  1604. "git", args...)
  1605. if err != nil {
  1606. return fmt.Errorf("%v: %v", err, stderr)
  1607. }
  1608. return nil
  1609. })
  1610. }
  1611. type repoChecker struct {
  1612. querySQL, correctSQL string
  1613. desc string
  1614. }
  1615. func repoStatsCheck(checker *repoChecker) {
  1616. results, err := x.Query(checker.querySQL)
  1617. if err != nil {
  1618. log.Error(2, "Select %s: %v", checker.desc, err)
  1619. return
  1620. }
  1621. for _, result := range results {
  1622. id := com.StrTo(result["id"]).MustInt64()
  1623. log.Trace("Updating %s: %d", checker.desc, id)
  1624. _, err = x.Exec(checker.correctSQL, id, id)
  1625. if err != nil {
  1626. log.Error(2, "Update %s[%d]: %v", checker.desc, id, err)
  1627. }
  1628. }
  1629. }
  1630. func CheckRepoStats() {
  1631. if taskStatusTable.IsRunning(_CHECK_REPO_STATS) {
  1632. return
  1633. }
  1634. taskStatusTable.Start(_CHECK_REPO_STATS)
  1635. defer taskStatusTable.Stop(_CHECK_REPO_STATS)
  1636. log.Trace("Doing: CheckRepoStats")
  1637. checkers := []*repoChecker{
  1638. // Repository.NumWatches
  1639. {
  1640. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1641. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1642. "repository count 'num_watches'",
  1643. },
  1644. // Repository.NumStars
  1645. {
  1646. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1647. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1648. "repository count 'num_stars'",
  1649. },
  1650. // Label.NumIssues
  1651. {
  1652. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1653. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1654. "label count 'num_issues'",
  1655. },
  1656. // User.NumRepos
  1657. {
  1658. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1659. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1660. "user count 'num_repos'",
  1661. },
  1662. // Issue.NumComments
  1663. {
  1664. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1665. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1666. "issue count 'num_comments'",
  1667. },
  1668. }
  1669. for i := range checkers {
  1670. repoStatsCheck(checkers[i])
  1671. }
  1672. // ***** START: Repository.NumClosedIssues *****
  1673. desc := "repository count 'num_closed_issues'"
  1674. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false)
  1675. if err != nil {
  1676. log.Error(2, "Select %s: %v", desc, err)
  1677. } else {
  1678. for _, result := range results {
  1679. id := com.StrTo(result["id"]).MustInt64()
  1680. log.Trace("Updating %s: %d", desc, id)
  1681. _, err = x.Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id)
  1682. if err != nil {
  1683. log.Error(2, "Update %s[%d]: %v", desc, id, err)
  1684. }
  1685. }
  1686. }
  1687. // ***** END: Repository.NumClosedIssues *****
  1688. // FIXME: use checker when stop supporting old fork repo format.
  1689. // ***** START: Repository.NumForks *****
  1690. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1691. if err != nil {
  1692. log.Error(2, "Select repository count 'num_forks': %v", err)
  1693. } else {
  1694. for _, result := range results {
  1695. id := com.StrTo(result["id"]).MustInt64()
  1696. log.Trace("Updating repository count 'num_forks': %d", id)
  1697. repo, err := GetRepositoryByID(id)
  1698. if err != nil {
  1699. log.Error(2, "GetRepositoryByID[%d]: %v", id, err)
  1700. continue
  1701. }
  1702. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1703. if err != nil {
  1704. log.Error(2, "Select count of forks[%d]: %v", repo.ID, err)
  1705. continue
  1706. }
  1707. repo.NumForks = int(parseCountResult(rawResult))
  1708. if err = UpdateRepository(repo, false); err != nil {
  1709. log.Error(2, "UpdateRepository[%d]: %v", id, err)
  1710. continue
  1711. }
  1712. }
  1713. }
  1714. // ***** END: Repository.NumForks *****
  1715. }
  1716. type RepositoryList []*Repository
  1717. func (repos RepositoryList) loadAttributes(e Engine) error {
  1718. if len(repos) == 0 {
  1719. return nil
  1720. }
  1721. // Load owners
  1722. userSet := make(map[int64]*User)
  1723. for i := range repos {
  1724. userSet[repos[i].OwnerID] = nil
  1725. }
  1726. userIDs := make([]int64, 0, len(userSet))
  1727. for userID := range userSet {
  1728. userIDs = append(userIDs, userID)
  1729. }
  1730. users := make([]*User, 0, len(userIDs))
  1731. if err := e.Where("id > 0").In("id", userIDs).Find(&users); err != nil {
  1732. return fmt.Errorf("find users: %v", err)
  1733. }
  1734. for i := range users {
  1735. userSet[users[i].ID] = users[i]
  1736. }
  1737. for i := range repos {
  1738. repos[i].Owner = userSet[repos[i].OwnerID]
  1739. }
  1740. // Load base repositories
  1741. repoSet := make(map[int64]*Repository)
  1742. for i := range repos {
  1743. if repos[i].IsFork {
  1744. repoSet[repos[i].ForkID] = nil
  1745. }
  1746. }
  1747. baseIDs := make([]int64, 0, len(repoSet))
  1748. for baseID := range repoSet {
  1749. baseIDs = append(baseIDs, baseID)
  1750. }
  1751. baseRepos := make([]*Repository, 0, len(baseIDs))
  1752. if err := e.Where("id > 0").In("id", baseIDs).Find(&baseRepos); err != nil {
  1753. return fmt.Errorf("find base repositories: %v", err)
  1754. }
  1755. for i := range baseRepos {
  1756. repoSet[baseRepos[i].ID] = baseRepos[i]
  1757. }
  1758. for i := range repos {
  1759. if repos[i].IsFork {
  1760. repos[i].BaseRepo = repoSet[repos[i].ForkID]
  1761. }
  1762. }
  1763. return nil
  1764. }
  1765. func (repos RepositoryList) LoadAttributes() error {
  1766. return repos.loadAttributes(x)
  1767. }
  1768. type MirrorRepositoryList []*Repository
  1769. func (repos MirrorRepositoryList) loadAttributes(e Engine) error {
  1770. if len(repos) == 0 {
  1771. return nil
  1772. }
  1773. // Load mirrors.
  1774. repoIDs := make([]int64, 0, len(repos))
  1775. for i := range repos {
  1776. if !repos[i].IsMirror {
  1777. continue
  1778. }
  1779. repoIDs = append(repoIDs, repos[i].ID)
  1780. }
  1781. mirrors := make([]*Mirror, 0, len(repoIDs))
  1782. if err := e.Where("id > 0").In("repo_id", repoIDs).Find(&mirrors); err != nil {
  1783. return fmt.Errorf("find mirrors: %v", err)
  1784. }
  1785. set := make(map[int64]*Mirror)
  1786. for i := range mirrors {
  1787. set[mirrors[i].RepoID] = mirrors[i]
  1788. }
  1789. for i := range repos {
  1790. repos[i].Mirror = set[repos[i].ID]
  1791. }
  1792. return nil
  1793. }
  1794. func (repos MirrorRepositoryList) LoadAttributes() error {
  1795. return repos.loadAttributes(x)
  1796. }
  1797. // __ __ __ .__
  1798. // / \ / \_____ _/ |_ ____ | |__
  1799. // \ \/\/ /\__ \\ __\/ ___\| | \
  1800. // \ / / __ \| | \ \___| Y \
  1801. // \__/\ / (____ /__| \___ >___| /
  1802. // \/ \/ \/ \/
  1803. // Watch is connection request for receiving repository notification.
  1804. type Watch struct {
  1805. ID int64
  1806. UserID int64 `xorm:"UNIQUE(watch)"`
  1807. RepoID int64 `xorm:"UNIQUE(watch)"`
  1808. }
  1809. func isWatching(e Engine, userID, repoID int64) bool {
  1810. has, _ := e.Get(&Watch{0, userID, repoID})
  1811. return has
  1812. }
  1813. // IsWatching checks if user has watched given repository.
  1814. func IsWatching(userID, repoID int64) bool {
  1815. return isWatching(x, userID, repoID)
  1816. }
  1817. func watchRepo(e Engine, userID, repoID int64, watch bool) (err error) {
  1818. if watch {
  1819. if isWatching(e, userID, repoID) {
  1820. return nil
  1821. }
  1822. if _, err = e.Insert(&Watch{RepoID: repoID, UserID: userID}); err != nil {
  1823. return err
  1824. }
  1825. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoID)
  1826. } else {
  1827. if !isWatching(e, userID, repoID) {
  1828. return nil
  1829. }
  1830. if _, err = e.Delete(&Watch{0, userID, repoID}); err != nil {
  1831. return err
  1832. }
  1833. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoID)
  1834. }
  1835. return err
  1836. }
  1837. // Watch or unwatch repository.
  1838. func WatchRepo(userID, repoID int64, watch bool) (err error) {
  1839. return watchRepo(x, userID, repoID, watch)
  1840. }
  1841. func getWatchers(e Engine, repoID int64) ([]*Watch, error) {
  1842. watches := make([]*Watch, 0, 10)
  1843. return watches, e.Find(&watches, &Watch{RepoID: repoID})
  1844. }
  1845. // GetWatchers returns all watchers of given repository.
  1846. func GetWatchers(repoID int64) ([]*Watch, error) {
  1847. return getWatchers(x, repoID)
  1848. }
  1849. // Repository.GetWatchers returns range of users watching given repository.
  1850. func (repo *Repository) GetWatchers(page int) ([]*User, error) {
  1851. users := make([]*User, 0, ItemsPerPage)
  1852. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("watch.repo_id=?", repo.ID)
  1853. if setting.UsePostgreSQL {
  1854. sess = sess.Join("LEFT", "watch", `"user".id=watch.user_id`)
  1855. } else {
  1856. sess = sess.Join("LEFT", "watch", "user.id=watch.user_id")
  1857. }
  1858. return users, sess.Find(&users)
  1859. }
  1860. func notifyWatchers(e Engine, act *Action) error {
  1861. // Add feeds for user self and all watchers.
  1862. watchers, err := getWatchers(e, act.RepoID)
  1863. if err != nil {
  1864. return fmt.Errorf("getWatchers: %v", err)
  1865. }
  1866. // Reset ID to reuse Action object
  1867. act.ID = 0
  1868. // Add feed for actioner.
  1869. act.UserID = act.ActUserID
  1870. if _, err = e.Insert(act); err != nil {
  1871. return fmt.Errorf("insert new action: %v", err)
  1872. }
  1873. for i := range watchers {
  1874. if act.ActUserID == watchers[i].UserID {
  1875. continue
  1876. }
  1877. act.ID = 0
  1878. act.UserID = watchers[i].UserID
  1879. if _, err = e.Insert(act); err != nil {
  1880. return fmt.Errorf("insert new action: %v", err)
  1881. }
  1882. }
  1883. return nil
  1884. }
  1885. // NotifyWatchers creates batch of actions for every watcher.
  1886. func NotifyWatchers(act *Action) error {
  1887. return notifyWatchers(x, act)
  1888. }
  1889. // _________ __
  1890. // / _____// |______ _______
  1891. // \_____ \\ __\__ \\_ __ \
  1892. // / \| | / __ \| | \/
  1893. // /_______ /|__| (____ /__|
  1894. // \/ \/
  1895. type Star struct {
  1896. ID int64
  1897. UID int64 `xorm:"UNIQUE(s)"`
  1898. RepoID int64 `xorm:"UNIQUE(s)"`
  1899. }
  1900. // Star or unstar repository.
  1901. func StarRepo(userID, repoID int64, star bool) (err error) {
  1902. if star {
  1903. if IsStaring(userID, repoID) {
  1904. return nil
  1905. }
  1906. if _, err = x.Insert(&Star{UID: userID, RepoID: repoID}); err != nil {
  1907. return err
  1908. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoID); err != nil {
  1909. return err
  1910. }
  1911. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", userID)
  1912. } else {
  1913. if !IsStaring(userID, repoID) {
  1914. return nil
  1915. }
  1916. if _, err = x.Delete(&Star{0, userID, repoID}); err != nil {
  1917. return err
  1918. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoID); err != nil {
  1919. return err
  1920. }
  1921. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", userID)
  1922. }
  1923. return err
  1924. }
  1925. // IsStaring checks if user has starred given repository.
  1926. func IsStaring(userID, repoID int64) bool {
  1927. has, _ := x.Get(&Star{0, userID, repoID})
  1928. return has
  1929. }
  1930. func (repo *Repository) GetStargazers(page int) ([]*User, error) {
  1931. users := make([]*User, 0, ItemsPerPage)
  1932. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("star.repo_id=?", repo.ID)
  1933. if setting.UsePostgreSQL {
  1934. sess = sess.Join("LEFT", "star", `"user".id=star.uid`)
  1935. } else {
  1936. sess = sess.Join("LEFT", "star", "user.id=star.uid")
  1937. }
  1938. return users, sess.Find(&users)
  1939. }
  1940. // ___________ __
  1941. // \_ _____/__________| | __
  1942. // | __)/ _ \_ __ \ |/ /
  1943. // | \( <_> ) | \/ <
  1944. // \___ / \____/|__| |__|_ \
  1945. // \/ \/
  1946. // HasForkedRepo checks if given user has already forked a repository.
  1947. // When user has already forked, it returns true along with the repository.
  1948. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool, error) {
  1949. repo := new(Repository)
  1950. has, err := x.Where("owner_id = ? AND fork_id = ?", ownerID, repoID).Get(repo)
  1951. if err != nil {
  1952. return nil, false, err
  1953. } else if !has {
  1954. return nil, false, nil
  1955. }
  1956. return repo, true, repo.LoadAttributes()
  1957. }
  1958. // ForkRepository creates a fork of target repository under another user domain.
  1959. func ForkRepository(doer, owner *User, baseRepo *Repository, name, desc string) (_ *Repository, err error) {
  1960. repo := &Repository{
  1961. OwnerID: owner.ID,
  1962. Owner: owner,
  1963. Name: name,
  1964. LowerName: strings.ToLower(name),
  1965. Description: desc,
  1966. DefaultBranch: baseRepo.DefaultBranch,
  1967. IsPrivate: baseRepo.IsPrivate,
  1968. IsFork: true,
  1969. ForkID: baseRepo.ID,
  1970. }
  1971. sess := x.NewSession()
  1972. defer sess.Close()
  1973. if err = sess.Begin(); err != nil {
  1974. return nil, err
  1975. }
  1976. if err = createRepository(sess, doer, owner, repo); err != nil {
  1977. return nil, err
  1978. } else if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", baseRepo.ID); err != nil {
  1979. return nil, err
  1980. }
  1981. repoPath := repo.repoPath(sess)
  1982. RemoveAllWithNotice("Repository path erase before creation", repoPath)
  1983. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1984. fmt.Sprintf("ForkRepository 'git clone': %s/%s", owner.Name, repo.Name),
  1985. "git", "clone", "--bare", baseRepo.RepoPath(), repoPath)
  1986. if err != nil {
  1987. return nil, fmt.Errorf("git clone: %v", stderr)
  1988. }
  1989. _, stderr, err = process.ExecDir(-1,
  1990. repoPath, fmt.Sprintf("ForkRepository 'git update-server-info': %s", repoPath),
  1991. "git", "update-server-info")
  1992. if err != nil {
  1993. return nil, fmt.Errorf("git update-server-info: %v", err)
  1994. }
  1995. if err = createDelegateHooks(repoPath); err != nil {
  1996. return nil, fmt.Errorf("createDelegateHooks: %v", err)
  1997. }
  1998. if err = sess.Commit(); err != nil {
  1999. return nil, fmt.Errorf("Commit: %v", err)
  2000. }
  2001. if err = repo.UpdateSize(); err != nil {
  2002. log.Error(2, "UpdateSize [repo_id: %d]: %v", repo.ID, err)
  2003. }
  2004. if err = PrepareWebhooks(baseRepo, HOOK_EVENT_FORK, &api.ForkPayload{
  2005. Forkee: repo.APIFormat(nil),
  2006. Repo: baseRepo.APIFormat(nil),
  2007. Sender: doer.APIFormat(),
  2008. }); err != nil {
  2009. log.Error(2, "PrepareWebhooks [repo_id: %d]: %v", baseRepo.ID, err)
  2010. }
  2011. return repo, nil
  2012. }
  2013. func (repo *Repository) GetForks() ([]*Repository, error) {
  2014. forks := make([]*Repository, 0, repo.NumForks)
  2015. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  2016. }
  2017. // __________ .__
  2018. // \______ \____________ ____ ____ | |__
  2019. // | | _/\_ __ \__ \ / \_/ ___\| | \
  2020. // | | \ | | \// __ \| | \ \___| Y \
  2021. // |______ / |__| (____ /___| /\___ >___| /
  2022. // \/ \/ \/ \/ \/
  2023. //
  2024. func (repo *Repository) CreateNewBranch(doer *User, oldBranchName, branchName string) (err error) {
  2025. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  2026. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  2027. localPath := repo.LocalCopyPath()
  2028. if err = discardLocalRepoBranchChanges(localPath, oldBranchName); err != nil {
  2029. return fmt.Errorf("discardLocalRepoChanges: %v", err)
  2030. } else if err = repo.UpdateLocalCopyBranch(oldBranchName); err != nil {
  2031. return fmt.Errorf("UpdateLocalCopyBranch: %v", err)
  2032. }
  2033. if err = repo.CheckoutNewBranch(oldBranchName, branchName); err != nil {
  2034. return fmt.Errorf("CreateNewBranch: %v", err)
  2035. }
  2036. if err = git.Push(localPath, "origin", branchName); err != nil {
  2037. return fmt.Errorf("Push: %v", err)
  2038. }
  2039. return nil
  2040. }