repo.go 70 KB

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