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