You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 55 kB

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