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

repo.go 47KB

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