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