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