repo.go 69 KB

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