repo.go 56 KB

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