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

repo.go 53 kB

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