repo.go 57 KB

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