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 41 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
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  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. "errors"
  7. "fmt"
  8. "html/template"
  9. "io/ioutil"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "sort"
  16. "strings"
  17. "time"
  18. "unicode/utf8"
  19. "github.com/Unknwon/cae/zip"
  20. "github.com/Unknwon/com"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/git"
  23. "github.com/gogits/gogs/modules/log"
  24. "github.com/gogits/gogs/modules/process"
  25. "github.com/gogits/gogs/modules/setting"
  26. )
  27. const (
  28. _TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
  29. )
  30. var (
  31. ErrRepoAlreadyExist = errors.New("Repository already exist")
  32. ErrRepoNotExist = errors.New("Repository does not exist")
  33. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  34. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  35. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  36. ErrMirrorNotExist = errors.New("Mirror does not exist")
  37. ErrInvalidReference = errors.New("Invalid reference specified")
  38. )
  39. var (
  40. Gitignores, Licenses []string
  41. )
  42. var (
  43. DescPattern = regexp.MustCompile(`https?://\S+`)
  44. )
  45. func LoadRepoConfig() {
  46. // Load .gitignore and license files.
  47. types := []string{"gitignore", "license"}
  48. typeFiles := make([][]string, 2)
  49. for i, t := range types {
  50. files, err := com.StatDir(path.Join("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. sort.Strings(Gitignores)
  71. sort.Strings(Licenses)
  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. // Check if server has user.email and user.name set correctly and set if they're not.
  92. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogitservice@gmail.com"} {
  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
  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. ForkRepo *Repository `xorm:"-"`
  141. Created time.Time `xorm:"CREATED"`
  142. Updated time.Time `xorm:"UPDATED"`
  143. }
  144. func (repo *Repository) GetOwner() (err error) {
  145. if repo.Owner == nil {
  146. repo.Owner, err = GetUserById(repo.OwnerId)
  147. }
  148. return err
  149. }
  150. func (repo *Repository) GetMirror() (err error) {
  151. repo.Mirror, err = GetMirror(repo.Id)
  152. return err
  153. }
  154. func (repo *Repository) GetForkRepo() (err error) {
  155. if !repo.IsFork {
  156. return nil
  157. }
  158. repo.ForkRepo, err = GetRepositoryById(repo.ForkId)
  159. return err
  160. }
  161. func (repo *Repository) RepoPath() (string, error) {
  162. if err := repo.GetOwner(); err != nil {
  163. return "", err
  164. }
  165. return RepoPath(repo.Owner.Name, repo.Name), nil
  166. }
  167. func (repo *Repository) RepoLink() (string, error) {
  168. if err := repo.GetOwner(); err != nil {
  169. return "", err
  170. }
  171. return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
  172. }
  173. func (repo *Repository) IsOwnedBy(u *User) bool {
  174. return repo.OwnerId == u.Id
  175. }
  176. func (repo *Repository) HasAccess(uname string) bool {
  177. if err := repo.GetOwner(); err != nil {
  178. return false
  179. }
  180. has, _ := HasAccess(uname, path.Join(repo.Owner.Name, repo.Name), READABLE)
  181. return has
  182. }
  183. // DescriptionHtml does special handles to description and return HTML string.
  184. func (repo *Repository) DescriptionHtml() template.HTML {
  185. sanitize := func(s string) string {
  186. return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
  187. }
  188. return template.HTML(DescPattern.ReplaceAllStringFunc(base.Sanitizer.Sanitize(repo.Description), sanitize))
  189. }
  190. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  191. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  192. repo := Repository{OwnerId: u.Id}
  193. has, err := x.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  194. if err != nil {
  195. return has, err
  196. } else if !has {
  197. return false, nil
  198. }
  199. return com.IsDir(RepoPath(u.Name, repoName)), nil
  200. }
  201. // CloneLink represents different types of clone URLs of repository.
  202. type CloneLink struct {
  203. SSH string
  204. HTTPS string
  205. Git string
  206. }
  207. // CloneLink returns clone URLs of repository.
  208. func (repo *Repository) CloneLink() (cl CloneLink, err error) {
  209. if err = repo.GetOwner(); err != nil {
  210. return cl, err
  211. }
  212. if setting.SSHPort != 22 {
  213. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.Domain, setting.SSHPort, repo.Owner.LowerName, repo.LowerName)
  214. } else {
  215. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.Domain, repo.Owner.LowerName, repo.LowerName)
  216. }
  217. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.LowerName, repo.LowerName)
  218. return cl, nil
  219. }
  220. var (
  221. illegalEquals = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  222. illegalSuffixs = []string{".git", ".keys"}
  223. )
  224. // IsLegalName returns false if name contains illegal characters.
  225. func IsLegalName(repoName string) bool {
  226. repoName = strings.ToLower(repoName)
  227. for _, char := range illegalEquals {
  228. if repoName == char {
  229. return false
  230. }
  231. }
  232. for _, char := range illegalSuffixs {
  233. if strings.HasSuffix(repoName, char) {
  234. return false
  235. }
  236. }
  237. return true
  238. }
  239. // Mirror represents a mirror information of repository.
  240. type Mirror struct {
  241. Id int64
  242. RepoId int64
  243. RepoName string // <user name>/<repo name>
  244. Interval int // Hour.
  245. Updated time.Time `xorm:"UPDATED"`
  246. NextUpdate time.Time
  247. }
  248. func GetMirror(repoId int64) (*Mirror, error) {
  249. m := &Mirror{RepoId: repoId}
  250. has, err := x.Get(m)
  251. if err != nil {
  252. return nil, err
  253. } else if !has {
  254. return nil, ErrMirrorNotExist
  255. }
  256. return m, nil
  257. }
  258. func UpdateMirror(m *Mirror) error {
  259. _, err := x.Id(m.Id).Update(m)
  260. return err
  261. }
  262. // MirrorRepository creates a mirror repository from source.
  263. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  264. _, stderr, err := process.ExecTimeout(10*time.Minute,
  265. fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  266. "git", "clone", "--mirror", url, repoPath)
  267. if err != nil {
  268. return errors.New("git clone --mirror: " + stderr)
  269. }
  270. if _, err = x.InsertOne(&Mirror{
  271. RepoId: repoId,
  272. RepoName: strings.ToLower(userName + "/" + repoName),
  273. Interval: 24,
  274. NextUpdate: time.Now().Add(24 * time.Hour),
  275. }); err != nil {
  276. return err
  277. }
  278. return nil
  279. }
  280. // MigrateRepository migrates a existing repository from other project hosting.
  281. func MigrateRepository(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  282. repo, err := CreateRepository(u, name, desc, "", "", private, mirror, false)
  283. if err != nil {
  284. return nil, err
  285. }
  286. // Clone to temprory path and do the init commit.
  287. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  288. os.MkdirAll(tmpDir, os.ModePerm)
  289. repoPath := RepoPath(u.Name, name)
  290. if u.IsOrganization() {
  291. t, err := u.GetOwnerTeam()
  292. if err != nil {
  293. return nil, err
  294. }
  295. repo.NumWatches = t.NumMembers
  296. } else {
  297. repo.NumWatches = 1
  298. }
  299. repo.IsBare = false
  300. if mirror {
  301. if err = MirrorRepository(repo.Id, u.Name, repo.Name, repoPath, url); err != nil {
  302. return repo, err
  303. }
  304. repo.IsMirror = true
  305. return repo, UpdateRepository(repo)
  306. } else {
  307. os.RemoveAll(repoPath)
  308. }
  309. // FIXME: this command could for both migrate and mirror
  310. _, stderr, err := process.ExecTimeout(10*time.Minute,
  311. fmt.Sprintf("MigrateRepository: %s", repoPath),
  312. "git", "clone", "--mirror", "--bare", url, repoPath)
  313. if err != nil {
  314. return repo, fmt.Errorf("git clone --mirror --bare: %v", stderr)
  315. } else if err = createUpdateHook(repoPath); err != nil {
  316. return repo, fmt.Errorf("create update hook: %v", err)
  317. }
  318. return repo, UpdateRepository(repo)
  319. }
  320. // extractGitBareZip extracts git-bare.zip to repository path.
  321. func extractGitBareZip(repoPath string) error {
  322. z, err := zip.Open(path.Join(setting.ConfRootPath, "content/git-bare.zip"))
  323. if err != nil {
  324. return err
  325. }
  326. defer z.Close()
  327. return z.ExtractTo(repoPath)
  328. }
  329. // initRepoCommit temporarily changes with work directory.
  330. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  331. var stderr string
  332. if _, stderr, err = process.ExecDir(-1,
  333. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  334. "git", "add", "--all"); err != nil {
  335. return errors.New("git add: " + stderr)
  336. }
  337. if _, stderr, err = process.ExecDir(-1,
  338. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  339. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  340. "-m", "Init commit"); err != nil {
  341. return errors.New("git commit: " + stderr)
  342. }
  343. if _, stderr, err = process.ExecDir(-1,
  344. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  345. "git", "push", "origin", "master"); err != nil {
  346. return errors.New("git push: " + stderr)
  347. }
  348. return nil
  349. }
  350. func createUpdateHook(repoPath string) error {
  351. return ioutil.WriteFile(path.Join(repoPath, "hooks/update"),
  352. []byte(fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"", setting.CustomConf)), 0777)
  353. }
  354. // InitRepository initializes README and .gitignore if needed.
  355. func initRepository(f string, u *User, repo *Repository, initReadme bool, repoLang, license string) error {
  356. repoPath := RepoPath(u.Name, repo.Name)
  357. // Create bare new repository.
  358. if err := extractGitBareZip(repoPath); err != nil {
  359. return err
  360. }
  361. if err := createUpdateHook(repoPath); err != nil {
  362. return err
  363. }
  364. // Initialize repository according to user's choice.
  365. fileName := map[string]string{}
  366. if initReadme {
  367. fileName["readme"] = "README.md"
  368. }
  369. if repoLang != "" {
  370. fileName["gitign"] = ".gitignore"
  371. }
  372. if license != "" {
  373. fileName["license"] = "LICENSE"
  374. }
  375. // Clone to temprory path and do the init commit.
  376. tmpDir := filepath.Join(os.TempDir(), com.ToStr(time.Now().Nanosecond()))
  377. os.MkdirAll(tmpDir, os.ModePerm)
  378. _, stderr, err := process.Exec(
  379. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  380. "git", "clone", repoPath, tmpDir)
  381. if err != nil {
  382. return errors.New("initRepository(git clone): " + stderr)
  383. }
  384. // README
  385. if initReadme {
  386. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  387. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  388. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  389. []byte(defaultReadme), 0644); err != nil {
  390. return err
  391. }
  392. }
  393. // .gitignore
  394. filePath := "conf/gitignore/" + repoLang
  395. if com.IsFile(filePath) {
  396. targetPath := path.Join(tmpDir, fileName["gitign"])
  397. if com.IsFile(filePath) {
  398. if err = com.Copy(filePath, targetPath); err != nil {
  399. return err
  400. }
  401. } else {
  402. // Check custom files.
  403. filePath = path.Join(setting.CustomPath, "conf/gitignore", repoLang)
  404. if com.IsFile(filePath) {
  405. if err := com.Copy(filePath, targetPath); err != nil {
  406. return err
  407. }
  408. }
  409. }
  410. } else {
  411. delete(fileName, "gitign")
  412. }
  413. // LICENSE
  414. filePath = "conf/license/" + license
  415. if com.IsFile(filePath) {
  416. targetPath := path.Join(tmpDir, fileName["license"])
  417. if com.IsFile(filePath) {
  418. if err = com.Copy(filePath, targetPath); err != nil {
  419. return err
  420. }
  421. } else {
  422. // Check custom files.
  423. filePath = path.Join(setting.CustomPath, "conf/license", license)
  424. if com.IsFile(filePath) {
  425. if err := com.Copy(filePath, targetPath); err != nil {
  426. return err
  427. }
  428. }
  429. }
  430. } else {
  431. delete(fileName, "license")
  432. }
  433. if len(fileName) == 0 {
  434. // Re-fetch the repository from database before updating it (else it would
  435. // override changes that were done earlier with sql)
  436. if repo, err = GetRepositoryById(repo.Id); err != nil {
  437. return err
  438. }
  439. repo.IsBare = true
  440. repo.DefaultBranch = "master"
  441. return UpdateRepository(repo)
  442. }
  443. // Apply changes and commit.
  444. return initRepoCommit(tmpDir, u.NewGitSig())
  445. }
  446. // CreateRepository creates a repository for given user or organization.
  447. func CreateRepository(u *User, name, desc, lang, license string, private, mirror, initReadme bool) (*Repository, error) {
  448. if !IsLegalName(name) {
  449. return nil, ErrRepoNameIllegal
  450. }
  451. isExist, err := IsRepositoryExist(u, name)
  452. if err != nil {
  453. return nil, err
  454. } else if isExist {
  455. return nil, ErrRepoAlreadyExist
  456. }
  457. sess := x.NewSession()
  458. defer sess.Close()
  459. if err = sess.Begin(); err != nil {
  460. return nil, err
  461. }
  462. repo := &Repository{
  463. OwnerId: u.Id,
  464. Owner: u,
  465. Name: name,
  466. LowerName: strings.ToLower(name),
  467. Description: desc,
  468. IsPrivate: private,
  469. }
  470. if _, err = sess.Insert(repo); err != nil {
  471. sess.Rollback()
  472. return nil, err
  473. }
  474. var t *Team // Owner team.
  475. mode := WRITABLE
  476. if mirror {
  477. mode = READABLE
  478. }
  479. access := &Access{
  480. UserName: u.LowerName,
  481. RepoName: path.Join(u.LowerName, repo.LowerName),
  482. Mode: mode,
  483. }
  484. // Give access to all members in owner team.
  485. if u.IsOrganization() {
  486. t, err = u.GetOwnerTeam()
  487. if err != nil {
  488. sess.Rollback()
  489. return nil, err
  490. }
  491. if err = t.GetMembers(); err != nil {
  492. sess.Rollback()
  493. return nil, err
  494. }
  495. for _, u := range t.Members {
  496. access.Id = 0
  497. access.UserName = u.LowerName
  498. if _, err = sess.Insert(access); err != nil {
  499. sess.Rollback()
  500. return nil, err
  501. }
  502. }
  503. } else {
  504. if _, err = sess.Insert(access); err != nil {
  505. sess.Rollback()
  506. return nil, err
  507. }
  508. }
  509. if _, err = sess.Exec(
  510. "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  511. sess.Rollback()
  512. return nil, err
  513. }
  514. // Update owner team info and count.
  515. if u.IsOrganization() {
  516. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  517. t.NumRepos++
  518. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  519. sess.Rollback()
  520. return nil, err
  521. }
  522. }
  523. if err = sess.Commit(); err != nil {
  524. return nil, err
  525. }
  526. if u.IsOrganization() {
  527. t, err := u.GetOwnerTeam()
  528. if err != nil {
  529. log.Error(4, "GetOwnerTeam: %v", err)
  530. } else {
  531. if err = t.GetMembers(); err != nil {
  532. log.Error(4, "GetMembers: %v", err)
  533. } else {
  534. for _, u := range t.Members {
  535. if err = WatchRepo(u.Id, repo.Id, true); err != nil {
  536. log.Error(4, "WatchRepo2: %v", err)
  537. }
  538. }
  539. }
  540. }
  541. } else {
  542. if err = WatchRepo(u.Id, repo.Id, true); err != nil {
  543. log.Error(4, "WatchRepo3: %v", err)
  544. }
  545. }
  546. if err = NewRepoAction(u, repo); err != nil {
  547. log.Error(4, "NewRepoAction: %v", err)
  548. }
  549. // No need for init mirror.
  550. if mirror {
  551. return repo, nil
  552. }
  553. repoPath := RepoPath(u.Name, repo.Name)
  554. if err = initRepository(repoPath, u, repo, initReadme, lang, license); err != nil {
  555. if err2 := os.RemoveAll(repoPath); err2 != nil {
  556. log.Error(4, "initRepository: %v", err)
  557. return nil, fmt.Errorf(
  558. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  559. }
  560. return nil, fmt.Errorf("initRepository: %v", err)
  561. }
  562. _, stderr, err := process.ExecDir(-1,
  563. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  564. "git", "update-server-info")
  565. if err != nil {
  566. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  567. }
  568. return repo, nil
  569. }
  570. // CountRepositories returns number of repositories.
  571. func CountRepositories() int64 {
  572. count, _ := x.Count(new(Repository))
  573. return count
  574. }
  575. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  576. // It also auto-gets corresponding users.
  577. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  578. repos := make([]*Repository, 0, num)
  579. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  580. return nil, err
  581. }
  582. for _, repo := range repos {
  583. repo.Owner = &User{Id: repo.OwnerId}
  584. has, err := x.Get(repo.Owner)
  585. if err != nil {
  586. return nil, err
  587. } else if !has {
  588. return nil, ErrUserNotExist
  589. }
  590. }
  591. return repos, nil
  592. }
  593. // RepoPath returns repository path by given user and repository name.
  594. func RepoPath(userName, repoName string) string {
  595. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  596. }
  597. // TransferOwnership transfers all corresponding setting from old user to new one.
  598. func TransferOwnership(u *User, newOwner string, repo *Repository) error {
  599. newUser, err := GetUserByName(newOwner)
  600. if err != nil {
  601. return fmt.Errorf("fail to get new owner(%s): %v", newOwner, err)
  602. }
  603. // Check if new owner has repository with same name.
  604. has, err := IsRepositoryExist(newUser, repo.Name)
  605. if err != nil {
  606. return err
  607. } else if has {
  608. return ErrRepoAlreadyExist
  609. }
  610. sess := x.NewSession()
  611. defer sess.Close()
  612. if err = sess.Begin(); err != nil {
  613. return err
  614. }
  615. owner := repo.Owner
  616. oldRepoLink := path.Join(owner.LowerName, repo.LowerName)
  617. // Delete all access first if current owner is an organization.
  618. if owner.IsOrganization() {
  619. if _, err = sess.Where("repo_name=?", oldRepoLink).Delete(new(Access)); err != nil {
  620. sess.Rollback()
  621. return fmt.Errorf("fail to delete current accesses: %v", err)
  622. }
  623. } else {
  624. // Delete current owner access.
  625. if _, err = sess.Where("repo_name=?", oldRepoLink).And("user_name=?", owner.LowerName).
  626. Delete(new(Access)); err != nil {
  627. sess.Rollback()
  628. return fmt.Errorf("fail to delete access(owner): %v", err)
  629. }
  630. // In case new owner has access.
  631. if _, err = sess.Where("repo_name=?", oldRepoLink).And("user_name=?", newUser.LowerName).
  632. Delete(new(Access)); err != nil {
  633. sess.Rollback()
  634. return fmt.Errorf("fail to delete access(new user): %v", err)
  635. }
  636. }
  637. // Change accesses to new repository path.
  638. if _, err = sess.Where("repo_name=?", oldRepoLink).
  639. Update(&Access{RepoName: path.Join(newUser.LowerName, repo.LowerName)}); err != nil {
  640. sess.Rollback()
  641. return fmt.Errorf("fail to update access(change reponame): %v", err)
  642. }
  643. // Update repository.
  644. repo.OwnerId = newUser.Id
  645. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  646. sess.Rollback()
  647. return err
  648. }
  649. // Update user repository number.
  650. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", newUser.Id); err != nil {
  651. sess.Rollback()
  652. return err
  653. }
  654. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", owner.Id); err != nil {
  655. sess.Rollback()
  656. return err
  657. }
  658. mode := WRITABLE
  659. if repo.IsMirror {
  660. mode = READABLE
  661. }
  662. // New owner is organization.
  663. if newUser.IsOrganization() {
  664. access := &Access{
  665. RepoName: path.Join(newUser.LowerName, repo.LowerName),
  666. Mode: mode,
  667. }
  668. // Give access to all members in owner team.
  669. t, err := newUser.GetOwnerTeam()
  670. if err != nil {
  671. sess.Rollback()
  672. return err
  673. }
  674. if err = t.GetMembers(); err != nil {
  675. sess.Rollback()
  676. return err
  677. }
  678. for _, u := range t.Members {
  679. access.Id = 0
  680. access.UserName = u.LowerName
  681. if _, err = sess.Insert(access); err != nil {
  682. sess.Rollback()
  683. return err
  684. }
  685. }
  686. // Update owner team info and count.
  687. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  688. t.NumRepos++
  689. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  690. sess.Rollback()
  691. return err
  692. }
  693. } else {
  694. access := &Access{
  695. RepoName: path.Join(newUser.LowerName, repo.LowerName),
  696. UserName: newUser.LowerName,
  697. Mode: mode,
  698. }
  699. if _, err = sess.Insert(access); err != nil {
  700. sess.Rollback()
  701. return fmt.Errorf("fail to insert access: %v", err)
  702. }
  703. }
  704. // Change repository directory name.
  705. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  706. sess.Rollback()
  707. return err
  708. }
  709. if err = sess.Commit(); err != nil {
  710. return err
  711. }
  712. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  713. log.Error(4, "WatchRepo", err)
  714. }
  715. if err = TransferRepoAction(u, newUser, repo); err != nil {
  716. return err
  717. }
  718. return nil
  719. }
  720. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  721. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  722. userName = strings.ToLower(userName)
  723. oldRepoName = strings.ToLower(oldRepoName)
  724. newRepoName = strings.ToLower(newRepoName)
  725. if !IsLegalName(newRepoName) {
  726. return ErrRepoNameIllegal
  727. }
  728. // Update accesses.
  729. accesses := make([]Access, 0, 10)
  730. if err = x.Find(&accesses, &Access{RepoName: userName + "/" + oldRepoName}); err != nil {
  731. return err
  732. }
  733. sess := x.NewSession()
  734. defer sess.Close()
  735. if err = sess.Begin(); err != nil {
  736. return err
  737. }
  738. for i := range accesses {
  739. accesses[i].RepoName = userName + "/" + newRepoName
  740. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  741. return err
  742. }
  743. }
  744. // Change repository directory name.
  745. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  746. sess.Rollback()
  747. return err
  748. }
  749. return sess.Commit()
  750. }
  751. func UpdateRepository(repo *Repository) error {
  752. repo.LowerName = strings.ToLower(repo.Name)
  753. if len(repo.Description) > 255 {
  754. repo.Description = repo.Description[:255]
  755. }
  756. if len(repo.Website) > 255 {
  757. repo.Website = repo.Website[:255]
  758. }
  759. _, err := x.Id(repo.Id).AllCols().Update(repo)
  760. return err
  761. }
  762. // DeleteRepository deletes a repository for a user or organization.
  763. func DeleteRepository(uid, repoId int64, userName string) error {
  764. repo := &Repository{Id: repoId, OwnerId: uid}
  765. has, err := x.Get(repo)
  766. if err != nil {
  767. return err
  768. } else if !has {
  769. return ErrRepoNotExist
  770. }
  771. // In case is a organization.
  772. org, err := GetUserById(uid)
  773. if err != nil {
  774. return err
  775. }
  776. if org.IsOrganization() {
  777. if err = org.GetTeams(); err != nil {
  778. return err
  779. }
  780. }
  781. sess := x.NewSession()
  782. defer sess.Close()
  783. if err = sess.Begin(); err != nil {
  784. return err
  785. }
  786. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  787. sess.Rollback()
  788. return err
  789. }
  790. // Delete all access.
  791. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  792. sess.Rollback()
  793. return err
  794. }
  795. if org.IsOrganization() {
  796. idStr := "$" + com.ToStr(repoId) + "|"
  797. for _, t := range org.Teams {
  798. if !strings.Contains(t.RepoIds, idStr) {
  799. continue
  800. }
  801. t.NumRepos--
  802. t.RepoIds = strings.Replace(t.RepoIds, idStr, "", 1)
  803. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  804. sess.Rollback()
  805. return err
  806. }
  807. }
  808. }
  809. if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  810. sess.Rollback()
  811. return err
  812. }
  813. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  814. sess.Rollback()
  815. return err
  816. }
  817. if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil {
  818. sess.Rollback()
  819. return err
  820. }
  821. if _, err = sess.Delete(&IssueUser{RepoId: repoId}); err != nil {
  822. sess.Rollback()
  823. return err
  824. }
  825. if _, err = sess.Delete(&Milestone{RepoId: repoId}); err != nil {
  826. sess.Rollback()
  827. return err
  828. }
  829. if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil {
  830. sess.Rollback()
  831. return err
  832. }
  833. // Delete comments.
  834. if err = x.Iterate(&Issue{RepoId: repoId}, func(idx int, bean interface{}) error {
  835. issue := bean.(*Issue)
  836. if _, err = sess.Delete(&Comment{IssueId: issue.Id}); err != nil {
  837. sess.Rollback()
  838. return err
  839. }
  840. return nil
  841. }); err != nil {
  842. sess.Rollback()
  843. return err
  844. }
  845. if _, err = sess.Delete(&Issue{RepoId: repoId}); err != nil {
  846. sess.Rollback()
  847. return err
  848. }
  849. if repo.IsFork {
  850. if _, err = sess.Exec("UPDATE `repository` SET num_forks = num_forks - 1 WHERE id = ?", repo.ForkId); err != nil {
  851. sess.Rollback()
  852. return err
  853. }
  854. }
  855. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", uid); err != nil {
  856. sess.Rollback()
  857. return err
  858. }
  859. // Remove repository files.
  860. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  861. desc := fmt.Sprintf("Fail to delete repository files(%s/%s): %v", userName, repo.Name, err)
  862. log.Warn(desc)
  863. if err = CreateRepositoryNotice(desc); err != nil {
  864. log.Error(4, "Fail to add notice: %v", err)
  865. }
  866. }
  867. return sess.Commit()
  868. }
  869. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  870. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  871. func GetRepositoryByRef(ref string) (*Repository, error) {
  872. n := strings.IndexByte(ref, byte('/'))
  873. if n < 2 {
  874. return nil, ErrInvalidReference
  875. }
  876. userName, repoName := ref[:n], ref[n+1:]
  877. user, err := GetUserByName(userName)
  878. if err != nil {
  879. return nil, err
  880. }
  881. return GetRepositoryByName(user.Id, repoName)
  882. }
  883. // GetRepositoryByName returns the repository by given name under user if exists.
  884. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  885. repo := &Repository{
  886. OwnerId: uid,
  887. LowerName: strings.ToLower(repoName),
  888. }
  889. has, err := x.Get(repo)
  890. if err != nil {
  891. return nil, err
  892. } else if !has {
  893. return nil, ErrRepoNotExist
  894. }
  895. return repo, err
  896. }
  897. // GetRepositoryById returns the repository by given id if exists.
  898. func GetRepositoryById(id int64) (*Repository, error) {
  899. repo := &Repository{}
  900. has, err := x.Id(id).Get(repo)
  901. if err != nil {
  902. return nil, err
  903. } else if !has {
  904. return nil, ErrRepoNotExist
  905. }
  906. return repo, nil
  907. }
  908. // GetRepositories returns a list of repositories of given user.
  909. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  910. repos := make([]*Repository, 0, 10)
  911. sess := x.Desc("updated")
  912. if !private {
  913. sess.Where("is_private=?", false)
  914. }
  915. err := sess.Find(&repos, &Repository{OwnerId: uid})
  916. return repos, err
  917. }
  918. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  919. func GetRecentUpdatedRepositories(num int) (repos []*Repository, err error) {
  920. err = x.Where("is_private=?", false).Limit(num).Desc("updated").Find(&repos)
  921. return repos, err
  922. }
  923. // GetRepositoryCount returns the total number of repositories of user.
  924. func GetRepositoryCount(user *User) (int64, error) {
  925. return x.Count(&Repository{OwnerId: user.Id})
  926. }
  927. // GetCollaboratorNames returns a list of user name of repository's collaborators.
  928. func GetCollaboratorNames(repoName string) ([]string, error) {
  929. accesses := make([]*Access, 0, 10)
  930. if err := x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil {
  931. return nil, err
  932. }
  933. names := make([]string, len(accesses))
  934. for i := range accesses {
  935. names[i] = accesses[i].UserName
  936. }
  937. return names, nil
  938. }
  939. // CollaborativeRepository represents a repository with collaborative information.
  940. type CollaborativeRepository struct {
  941. *Repository
  942. CanPush bool
  943. }
  944. // GetCollaborativeRepos returns a list of repositories that user is collaborator.
  945. func GetCollaborativeRepos(uname string) ([]*CollaborativeRepository, error) {
  946. uname = strings.ToLower(uname)
  947. accesses := make([]*Access, 0, 10)
  948. if err := x.Find(&accesses, &Access{UserName: uname}); err != nil {
  949. return nil, err
  950. }
  951. repos := make([]*CollaborativeRepository, 0, 10)
  952. for _, access := range accesses {
  953. infos := strings.Split(access.RepoName, "/")
  954. if infos[0] == uname {
  955. continue
  956. }
  957. u, err := GetUserByName(infos[0])
  958. if err != nil {
  959. return nil, err
  960. }
  961. repo, err := GetRepositoryByName(u.Id, infos[1])
  962. if err != nil {
  963. return nil, err
  964. }
  965. repo.Owner = u
  966. repos = append(repos, &CollaborativeRepository{repo, access.Mode == WRITABLE})
  967. }
  968. return repos, nil
  969. }
  970. // GetCollaborators returns a list of users of repository's collaborators.
  971. func GetCollaborators(repoName string) (us []*User, err error) {
  972. accesses := make([]*Access, 0, 10)
  973. if err = x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil {
  974. return nil, err
  975. }
  976. us = make([]*User, len(accesses))
  977. for i := range accesses {
  978. us[i], err = GetUserByName(accesses[i].UserName)
  979. if err != nil {
  980. return nil, err
  981. }
  982. }
  983. return us, nil
  984. }
  985. type SearchOption struct {
  986. Keyword string
  987. Uid int64
  988. Limit int
  989. Private bool
  990. }
  991. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  992. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  993. if len(opt.Keyword) == 0 {
  994. return repos, nil
  995. }
  996. opt.Keyword = strings.ToLower(opt.Keyword)
  997. repos = make([]*Repository, 0, opt.Limit)
  998. // Append conditions.
  999. sess := x.Limit(opt.Limit)
  1000. if opt.Uid > 0 {
  1001. sess.Where("owner_id=?", opt.Uid)
  1002. }
  1003. if !opt.Private {
  1004. sess.And("is_private=false")
  1005. }
  1006. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  1007. return repos, err
  1008. }
  1009. // DeleteRepositoryArchives deletes all repositories' archives.
  1010. func DeleteRepositoryArchives() error {
  1011. return x.Where("id > 0").Iterate(new(Repository),
  1012. func(idx int, bean interface{}) error {
  1013. repo := bean.(*Repository)
  1014. if err := repo.GetOwner(); err != nil {
  1015. return err
  1016. }
  1017. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  1018. })
  1019. }
  1020. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  1021. func RewriteRepositoryUpdateHook() error {
  1022. return x.Where("id > 0").Iterate(new(Repository),
  1023. func(idx int, bean interface{}) error {
  1024. repo := bean.(*Repository)
  1025. if err := repo.GetOwner(); err != nil {
  1026. return err
  1027. }
  1028. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  1029. })
  1030. }
  1031. var (
  1032. // Prevent duplicate tasks.
  1033. isMirrorUpdating = false
  1034. isGitFscking = false
  1035. )
  1036. // MirrorUpdate checks and updates mirror repositories.
  1037. func MirrorUpdate() {
  1038. if isMirrorUpdating {
  1039. return
  1040. }
  1041. isMirrorUpdating = true
  1042. defer func() { isMirrorUpdating = false }()
  1043. mirrors := make([]*Mirror, 0, 10)
  1044. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  1045. m := bean.(*Mirror)
  1046. if m.NextUpdate.After(time.Now()) {
  1047. return nil
  1048. }
  1049. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  1050. if _, stderr, err := process.ExecDir(10*time.Minute,
  1051. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  1052. "git", "remote", "update"); err != nil {
  1053. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  1054. log.Error(4, desc)
  1055. if err = CreateRepositoryNotice(desc); err != nil {
  1056. log.Error(4, "Fail to add notice: %v", err)
  1057. }
  1058. return nil
  1059. }
  1060. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  1061. mirrors = append(mirrors, m)
  1062. return nil
  1063. }); err != nil {
  1064. log.Error(4, "MirrorUpdate: %v", err)
  1065. }
  1066. for i := range mirrors {
  1067. if err := UpdateMirror(mirrors[i]); err != nil {
  1068. log.Error(4, "UpdateMirror", fmt.Sprintf("%s: %v", mirrors[i].RepoName, err))
  1069. }
  1070. }
  1071. }
  1072. // GitFsck calls 'git fsck' to check repository health.
  1073. func GitFsck() {
  1074. if isGitFscking {
  1075. return
  1076. }
  1077. isGitFscking = true
  1078. defer func() { isGitFscking = false }()
  1079. args := append([]string{"fsck"}, setting.Git.Fsck.Args...)
  1080. if err := x.Where("id > 0").Iterate(new(Repository),
  1081. func(idx int, bean interface{}) error {
  1082. repo := bean.(*Repository)
  1083. if err := repo.GetOwner(); err != nil {
  1084. return err
  1085. }
  1086. repoPath := RepoPath(repo.Owner.Name, repo.Name)
  1087. _, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  1088. if err != nil {
  1089. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  1090. log.Warn(desc)
  1091. if err = CreateRepositoryNotice(desc); err != nil {
  1092. log.Error(4, "Fail to add notice: %v", err)
  1093. }
  1094. }
  1095. return nil
  1096. }); err != nil {
  1097. log.Error(4, "repo.Fsck: %v", err)
  1098. }
  1099. }
  1100. func GitGcRepos() error {
  1101. args := append([]string{"gc"}, setting.Git.GcArgs...)
  1102. return x.Where("id > 0").Iterate(new(Repository),
  1103. func(idx int, bean interface{}) error {
  1104. repo := bean.(*Repository)
  1105. if err := repo.GetOwner(); err != nil {
  1106. return err
  1107. }
  1108. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  1109. if err != nil {
  1110. return fmt.Errorf("%v: %v", err, stderr)
  1111. }
  1112. return nil
  1113. })
  1114. }
  1115. // __ __ __ .__
  1116. // / \ / \_____ _/ |_ ____ | |__
  1117. // \ \/\/ /\__ \\ __\/ ___\| | \
  1118. // \ / / __ \| | \ \___| Y \
  1119. // \__/\ / (____ /__| \___ >___| /
  1120. // \/ \/ \/ \/
  1121. // Watch is connection request for receiving repository notification.
  1122. type Watch struct {
  1123. Id int64
  1124. UserId int64 `xorm:"UNIQUE(watch)"`
  1125. RepoId int64 `xorm:"UNIQUE(watch)"`
  1126. }
  1127. // IsWatching checks if user has watched given repository.
  1128. func IsWatching(uid, repoId int64) bool {
  1129. has, _ := x.Get(&Watch{0, uid, repoId})
  1130. return has
  1131. }
  1132. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1133. if watch {
  1134. if IsWatching(uid, repoId) {
  1135. return nil
  1136. }
  1137. if _, err = e.Insert(&Watch{RepoId: repoId, UserId: uid}); err != nil {
  1138. return err
  1139. }
  1140. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1141. } else {
  1142. if !IsWatching(uid, repoId) {
  1143. return nil
  1144. }
  1145. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1146. return err
  1147. }
  1148. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoId)
  1149. }
  1150. return err
  1151. }
  1152. // Watch or unwatch repository.
  1153. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1154. return watchRepo(x, uid, repoId, watch)
  1155. }
  1156. // GetWatchers returns all watchers of given repository.
  1157. func GetWatchers(rid int64) ([]*Watch, error) {
  1158. watches := make([]*Watch, 0, 10)
  1159. err := x.Find(&watches, &Watch{RepoId: rid})
  1160. return watches, err
  1161. }
  1162. // NotifyWatchers creates batch of actions for every watcher.
  1163. func NotifyWatchers(act *Action) error {
  1164. // Add feeds for user self and all watchers.
  1165. watches, err := GetWatchers(act.RepoId)
  1166. if err != nil {
  1167. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  1168. }
  1169. // Add feed for actioner.
  1170. act.UserId = act.ActUserId
  1171. if _, err = x.InsertOne(act); err != nil {
  1172. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  1173. }
  1174. for i := range watches {
  1175. if act.ActUserId == watches[i].UserId {
  1176. continue
  1177. }
  1178. act.Id = 0
  1179. act.UserId = watches[i].UserId
  1180. if _, err = x.InsertOne(act); err != nil {
  1181. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  1182. }
  1183. }
  1184. return nil
  1185. }
  1186. // _________ __
  1187. // / _____// |______ _______
  1188. // \_____ \\ __\__ \\_ __ \
  1189. // / \| | / __ \| | \/
  1190. // /_______ /|__| (____ /__|
  1191. // \/ \/
  1192. type Star struct {
  1193. Id int64
  1194. Uid int64 `xorm:"UNIQUE(s)"`
  1195. RepoId int64 `xorm:"UNIQUE(s)"`
  1196. }
  1197. // Star or unstar repository.
  1198. func StarRepo(uid, repoId int64, star bool) (err error) {
  1199. if star {
  1200. if IsStaring(uid, repoId) {
  1201. return nil
  1202. }
  1203. if _, err = x.Insert(&Star{Uid: uid, RepoId: repoId}); err != nil {
  1204. return err
  1205. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1206. return err
  1207. }
  1208. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1209. } else {
  1210. if !IsStaring(uid, repoId) {
  1211. return nil
  1212. }
  1213. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1214. return err
  1215. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1216. return err
  1217. }
  1218. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1219. }
  1220. return err
  1221. }
  1222. // IsStaring checks if user has starred given repository.
  1223. func IsStaring(uid, repoId int64) bool {
  1224. has, _ := x.Get(&Star{0, uid, repoId})
  1225. return has
  1226. }
  1227. // ___________ __
  1228. // \_ _____/__________| | __
  1229. // | __)/ _ \_ __ \ |/ /
  1230. // | \( <_> ) | \/ <
  1231. // \___ / \____/|__| |__|_ \
  1232. // \/ \/
  1233. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (*Repository, error) {
  1234. isExist, err := IsRepositoryExist(u, name)
  1235. if err != nil {
  1236. return nil, err
  1237. } else if isExist {
  1238. return nil, ErrRepoAlreadyExist
  1239. }
  1240. // In case the old repository is a fork.
  1241. if oldRepo.IsFork {
  1242. oldRepo, err = GetRepositoryById(oldRepo.ForkId)
  1243. if err != nil {
  1244. return nil, err
  1245. }
  1246. }
  1247. sess := x.NewSession()
  1248. defer sess.Close()
  1249. if err = sess.Begin(); err != nil {
  1250. return nil, err
  1251. }
  1252. repo := &Repository{
  1253. OwnerId: u.Id,
  1254. Owner: u,
  1255. Name: name,
  1256. LowerName: strings.ToLower(name),
  1257. Description: desc,
  1258. IsPrivate: oldRepo.IsPrivate,
  1259. IsFork: true,
  1260. ForkId: oldRepo.Id,
  1261. }
  1262. if _, err = sess.Insert(repo); err != nil {
  1263. sess.Rollback()
  1264. return nil, err
  1265. }
  1266. var t *Team // Owner team.
  1267. mode := WRITABLE
  1268. access := &Access{
  1269. UserName: u.LowerName,
  1270. RepoName: path.Join(u.LowerName, repo.LowerName),
  1271. Mode: mode,
  1272. }
  1273. // Give access to all members in owner team.
  1274. if u.IsOrganization() {
  1275. t, err = u.GetOwnerTeam()
  1276. if err != nil {
  1277. sess.Rollback()
  1278. return nil, err
  1279. }
  1280. if err = t.GetMembers(); err != nil {
  1281. sess.Rollback()
  1282. return nil, err
  1283. }
  1284. for _, u := range t.Members {
  1285. access.Id = 0
  1286. access.UserName = u.LowerName
  1287. if _, err = sess.Insert(access); err != nil {
  1288. sess.Rollback()
  1289. return nil, err
  1290. }
  1291. }
  1292. } else {
  1293. if _, err = sess.Insert(access); err != nil {
  1294. sess.Rollback()
  1295. return nil, err
  1296. }
  1297. }
  1298. if _, err = sess.Exec(
  1299. "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  1300. sess.Rollback()
  1301. return nil, err
  1302. }
  1303. // Update owner team info and count.
  1304. if u.IsOrganization() {
  1305. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  1306. t.NumRepos++
  1307. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  1308. sess.Rollback()
  1309. return nil, err
  1310. }
  1311. }
  1312. if u.IsOrganization() {
  1313. t, err := u.GetOwnerTeam()
  1314. if err != nil {
  1315. log.Error(4, "GetOwnerTeam: %v", err)
  1316. } else {
  1317. if err = t.GetMembers(); err != nil {
  1318. log.Error(4, "GetMembers: %v", err)
  1319. } else {
  1320. for _, u := range t.Members {
  1321. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  1322. log.Error(4, "WatchRepo2: %v", err)
  1323. }
  1324. }
  1325. }
  1326. }
  1327. } else {
  1328. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  1329. log.Error(4, "WatchRepo3: %v", err)
  1330. }
  1331. }
  1332. if err = NewRepoAction(u, repo); err != nil {
  1333. log.Error(4, "NewRepoAction: %v", err)
  1334. }
  1335. if _, err = sess.Exec(
  1336. "UPDATE `repository` SET num_forks = num_forks + 1 WHERE id = ?", oldRepo.Id); err != nil {
  1337. sess.Rollback()
  1338. return nil, err
  1339. }
  1340. oldRepoPath, err := oldRepo.RepoPath()
  1341. if err != nil {
  1342. sess.Rollback()
  1343. return nil, fmt.Errorf("fail to get repo path(%s): %v", oldRepo.Name, err)
  1344. }
  1345. if err = sess.Commit(); err != nil {
  1346. return nil, err
  1347. }
  1348. repoPath := RepoPath(u.Name, repo.Name)
  1349. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1350. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1351. "git", "clone", "--bare", oldRepoPath, repoPath)
  1352. if err != nil {
  1353. return nil, errors.New("ForkRepository(git clone): " + stderr)
  1354. }
  1355. _, stderr, err = process.ExecDir(-1,
  1356. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1357. "git", "update-server-info")
  1358. if err != nil {
  1359. return nil, errors.New("ForkRepository(git update-server-info): " + stderr)
  1360. }
  1361. return repo, nil
  1362. }