repo.go 48 KB

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