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 42 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
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
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
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
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
10 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  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/go-xorm/xorm"
  22. "github.com/gogits/gogs/modules/base"
  23. "github.com/gogits/gogs/modules/bindata"
  24. "github.com/gogits/gogs/modules/git"
  25. "github.com/gogits/gogs/modules/log"
  26. "github.com/gogits/gogs/modules/process"
  27. "github.com/gogits/gogs/modules/setting"
  28. )
  29. const (
  30. _TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
  31. )
  32. var (
  33. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  34. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  35. ErrMirrorNotExist = errors.New("Mirror does not exist")
  36. ErrInvalidReference = errors.New("Invalid reference specified")
  37. ErrNameEmpty = errors.New("Name is empty")
  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 := 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. 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. // Git requires setting user.name and user.email in order to commit changes.
  92. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogs@fake.local"} {
  93. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  94. // ExitError indicates this config is not set
  95. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  96. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  97. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  98. }
  99. log.Info("Git config %s set to %s", configKey, defaultValue)
  100. } else {
  101. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  102. }
  103. }
  104. }
  105. // Set git some configurations.
  106. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  107. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  108. log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
  109. }
  110. }
  111. // Repository represents a git repository.
  112. type Repository struct {
  113. Id int64
  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(e Engine) (err error) {
  145. if repo.Owner == nil {
  146. repo.Owner, err = getUserById(e, repo.OwnerId)
  147. }
  148. return err
  149. }
  150. func (repo *Repository) GetOwner() (err error) {
  151. return repo.getOwner(x)
  152. }
  153. func (repo *Repository) GetMirror() (err error) {
  154. repo.Mirror, err = GetMirror(repo.Id)
  155. return err
  156. }
  157. func (repo *Repository) GetForkRepo() (err error) {
  158. if !repo.IsFork {
  159. return nil
  160. }
  161. repo.ForkRepo, err = GetRepositoryById(repo.ForkId)
  162. return err
  163. }
  164. func (repo *Repository) RepoPath() (string, error) {
  165. if err := repo.GetOwner(); err != nil {
  166. return "", err
  167. }
  168. return RepoPath(repo.Owner.Name, repo.Name), nil
  169. }
  170. func (repo *Repository) RepoLink() (string, error) {
  171. if err := repo.GetOwner(); err != nil {
  172. return "", err
  173. }
  174. return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
  175. }
  176. func (repo *Repository) HasAccess(u *User) bool {
  177. has, _ := HasAccess(u, repo, ACCESS_MODE_READ)
  178. return has
  179. }
  180. func (repo *Repository) IsOwnedBy(u *User) bool {
  181. return repo.OwnerId == u.Id
  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. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  191. has, err := e.Get(&Repository{
  192. OwnerId: u.Id,
  193. LowerName: strings.ToLower(repoName),
  194. })
  195. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  196. }
  197. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  198. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  199. return isRepositoryExist(x, u, repoName)
  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.SSHDomain, setting.SSHPort, repo.Owner.LowerName, repo.LowerName)
  214. } else {
  215. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.SSHDomain, 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. reservedNames = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  222. reservedPatterns = []string{"*.git", "*.keys"}
  223. )
  224. // IsUsableName checks if name is reserved or pattern of name is not allowed.
  225. func IsUsableName(name string) error {
  226. name = strings.TrimSpace(strings.ToLower(name))
  227. if utf8.RuneCountInString(name) == 0 {
  228. return ErrNameEmpty
  229. }
  230. for i := range reservedNames {
  231. if name == reservedNames[i] {
  232. return ErrNameReserved{name}
  233. }
  234. }
  235. for _, pat := range reservedPatterns {
  236. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  237. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  238. return ErrNamePatternNotAllowed{pat}
  239. }
  240. }
  241. return nil
  242. }
  243. // Mirror represents a mirror information of repository.
  244. type Mirror struct {
  245. Id int64
  246. RepoId int64
  247. RepoName string // <user name>/<repo name>
  248. Interval int // Hour.
  249. Updated time.Time `xorm:"UPDATED"`
  250. NextUpdate time.Time
  251. }
  252. func getMirror(e Engine, repoId int64) (*Mirror, error) {
  253. m := &Mirror{RepoId: repoId}
  254. has, err := e.Get(m)
  255. if err != nil {
  256. return nil, err
  257. } else if !has {
  258. return nil, ErrMirrorNotExist
  259. }
  260. return m, nil
  261. }
  262. // GetMirror returns mirror object by given repository ID.
  263. func GetMirror(repoId int64) (*Mirror, error) {
  264. return getMirror(x, repoId)
  265. }
  266. func updateMirror(e Engine, m *Mirror) error {
  267. _, err := e.Id(m.Id).Update(m)
  268. return err
  269. }
  270. func UpdateMirror(m *Mirror) error {
  271. return updateMirror(x, m)
  272. }
  273. // MirrorRepository creates a mirror repository from source.
  274. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  275. _, stderr, err := process.ExecTimeout(10*time.Minute,
  276. fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  277. "git", "clone", "--mirror", url, repoPath)
  278. if err != nil {
  279. return errors.New("git clone --mirror: " + stderr)
  280. }
  281. if _, err = x.InsertOne(&Mirror{
  282. RepoId: repoId,
  283. RepoName: strings.ToLower(userName + "/" + repoName),
  284. Interval: 24,
  285. NextUpdate: time.Now().Add(24 * time.Hour),
  286. }); err != nil {
  287. return err
  288. }
  289. return nil
  290. }
  291. // MigrateRepository migrates a existing repository from other project hosting.
  292. func MigrateRepository(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  293. repo, err := CreateRepository(u, name, desc, "", "", private, mirror, false)
  294. if err != nil {
  295. return nil, err
  296. }
  297. // Clone to temprory path and do the init commit.
  298. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  299. os.MkdirAll(tmpDir, os.ModePerm)
  300. repoPath := RepoPath(u.Name, name)
  301. if u.IsOrganization() {
  302. t, err := u.GetOwnerTeam()
  303. if err != nil {
  304. return nil, err
  305. }
  306. repo.NumWatches = t.NumMembers
  307. } else {
  308. repo.NumWatches = 1
  309. }
  310. repo.IsBare = false
  311. if mirror {
  312. if err = MirrorRepository(repo.Id, u.Name, repo.Name, repoPath, url); err != nil {
  313. return repo, err
  314. }
  315. repo.IsMirror = true
  316. return repo, UpdateRepository(repo, false)
  317. } else {
  318. os.RemoveAll(repoPath)
  319. }
  320. // FIXME: this command could for both migrate and mirror
  321. _, stderr, err := process.ExecTimeout(10*time.Minute,
  322. fmt.Sprintf("MigrateRepository: %s", repoPath),
  323. "git", "clone", "--mirror", "--bare", "--quiet", url, repoPath)
  324. if err != nil {
  325. return repo, fmt.Errorf("git clone --mirror --bare --quiet: %v", stderr)
  326. } else if err = createUpdateHook(repoPath); err != nil {
  327. return repo, fmt.Errorf("create update hook: %v", err)
  328. }
  329. // Check if repository has master branch, if so set it to default branch.
  330. gitRepo, err := git.OpenRepository(repoPath)
  331. if err != nil {
  332. return repo, fmt.Errorf("open git repository: %v", err)
  333. }
  334. if gitRepo.IsBranchExist("master") {
  335. repo.DefaultBranch = "master"
  336. }
  337. return repo, UpdateRepository(repo, false)
  338. }
  339. // initRepoCommit temporarily changes with work directory.
  340. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  341. var stderr string
  342. if _, stderr, err = process.ExecDir(-1,
  343. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  344. "git", "add", "--all"); err != nil {
  345. return errors.New("git add: " + stderr)
  346. }
  347. if _, stderr, err = process.ExecDir(-1,
  348. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  349. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  350. "-m", "Init commit"); err != nil {
  351. return errors.New("git commit: " + stderr)
  352. }
  353. if _, stderr, err = process.ExecDir(-1,
  354. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  355. "git", "push", "origin", "master"); err != nil {
  356. return errors.New("git push: " + stderr)
  357. }
  358. return nil
  359. }
  360. func createUpdateHook(repoPath string) error {
  361. return ioutil.WriteFile(path.Join(repoPath, "hooks/update"),
  362. []byte(fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"", setting.CustomConf)), 0777)
  363. }
  364. // InitRepository initializes README and .gitignore if needed.
  365. func initRepository(e Engine, repoPath string, u *User, repo *Repository, initReadme bool, repoLang, license string) error {
  366. // Somehow the directory could exist.
  367. if com.IsExist(repoPath) {
  368. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  369. }
  370. // Init bare new repository.
  371. os.MkdirAll(repoPath, os.ModePerm)
  372. _, stderr, err := process.ExecDir(-1, repoPath,
  373. fmt.Sprintf("initRepository(git init --bare): %s", repoPath),
  374. "git", "init", "--bare")
  375. if err != nil {
  376. return fmt.Errorf("git init --bare: %s", err)
  377. }
  378. if err := createUpdateHook(repoPath); err != nil {
  379. return err
  380. }
  381. // Initialize repository according to user's choice.
  382. fileName := map[string]string{}
  383. if initReadme {
  384. fileName["readme"] = "README.md"
  385. }
  386. if repoLang != "" {
  387. fileName["gitign"] = ".gitignore"
  388. }
  389. if license != "" {
  390. fileName["license"] = "LICENSE"
  391. }
  392. // Clone to temprory path and do the init commit.
  393. tmpDir := filepath.Join(os.TempDir(), com.ToStr(time.Now().Nanosecond()))
  394. os.MkdirAll(tmpDir, os.ModePerm)
  395. defer os.RemoveAll(tmpDir)
  396. _, stderr, err = process.Exec(
  397. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  398. "git", "clone", repoPath, tmpDir)
  399. if err != nil {
  400. return errors.New("git clone: " + stderr)
  401. }
  402. // README
  403. if initReadme {
  404. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  405. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  406. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  407. []byte(defaultReadme), 0644); err != nil {
  408. return err
  409. }
  410. }
  411. // FIXME: following two can be merged.
  412. // .gitignore
  413. // Copy custom file when available.
  414. customPath := path.Join(setting.CustomPath, "conf/gitignore", repoLang)
  415. targetPath := path.Join(tmpDir, fileName["gitign"])
  416. if com.IsFile(customPath) {
  417. if err := com.Copy(customPath, targetPath); err != nil {
  418. return fmt.Errorf("copy gitignore: %v", err)
  419. }
  420. } else if com.IsSliceContainsStr(Gitignores, repoLang) {
  421. if err = ioutil.WriteFile(targetPath,
  422. bindata.MustAsset(path.Join("conf/gitignore", repoLang)), 0644); err != nil {
  423. return fmt.Errorf("generate gitignore: %v", err)
  424. }
  425. } else {
  426. delete(fileName, "gitign")
  427. }
  428. // LICENSE
  429. customPath = path.Join(setting.CustomPath, "conf/license", license)
  430. targetPath = path.Join(tmpDir, fileName["license"])
  431. if com.IsFile(customPath) {
  432. if err = com.Copy(customPath, targetPath); err != nil {
  433. return fmt.Errorf("copy license: %v", err)
  434. }
  435. } else if com.IsSliceContainsStr(Licenses, license) {
  436. if err = ioutil.WriteFile(targetPath,
  437. bindata.MustAsset(path.Join("conf/license", license)), 0644); err != nil {
  438. return fmt.Errorf("generate license: %v", err)
  439. }
  440. } else {
  441. delete(fileName, "license")
  442. }
  443. if len(fileName) == 0 {
  444. // Re-fetch the repository from database before updating it (else it would
  445. // override changes that were done earlier with sql)
  446. if repo, err = getRepositoryById(e, repo.Id); err != nil {
  447. return err
  448. }
  449. repo.IsBare = true
  450. repo.DefaultBranch = "master"
  451. return updateRepository(e, repo, false)
  452. }
  453. // Apply changes and commit.
  454. return initRepoCommit(tmpDir, u.NewGitSig())
  455. }
  456. func createRepository(e *xorm.Session, u *User, repo *Repository) (err error) {
  457. if err = IsUsableName(repo.Name); err != nil {
  458. return err
  459. }
  460. has, err := isRepositoryExist(e, u, repo.Name)
  461. if err != nil {
  462. return fmt.Errorf("IsRepositoryExist: %v", err)
  463. } else if has {
  464. return ErrRepoAlreadyExist{u.Name, repo.Name}
  465. }
  466. if _, err = e.Insert(repo); err != nil {
  467. return err
  468. } else if _, err = e.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", u.Id); err != nil {
  469. return err
  470. }
  471. // Give access to all members in owner team.
  472. if u.IsOrganization() {
  473. t, err := u.getOwnerTeam(e)
  474. if err != nil {
  475. return fmt.Errorf("getOwnerTeam: %v", err)
  476. } else if err = t.addRepository(e, repo); err != nil {
  477. return fmt.Errorf("addRepository: %v", err)
  478. }
  479. } else {
  480. // Organization automatically called this in addRepository method.
  481. if err = repo.recalculateAccesses(e); err != nil {
  482. return fmt.Errorf("recalculateAccesses: %v", err)
  483. }
  484. }
  485. if err = watchRepo(e, u.Id, repo.Id, true); err != nil {
  486. return fmt.Errorf("watchRepo: %v", err)
  487. } else if err = newRepoAction(e, u, repo); err != nil {
  488. return fmt.Errorf("newRepoAction: %v", err)
  489. }
  490. return nil
  491. }
  492. // CreateRepository creates a repository for given user or organization.
  493. func CreateRepository(u *User, name, desc, lang, license string, isPrivate, isMirror, initReadme bool) (_ *Repository, err error) {
  494. repo := &Repository{
  495. OwnerId: u.Id,
  496. Owner: u,
  497. Name: name,
  498. LowerName: strings.ToLower(name),
  499. Description: desc,
  500. IsPrivate: isPrivate,
  501. }
  502. sess := x.NewSession()
  503. defer sessionRelease(sess)
  504. if err = sess.Begin(); err != nil {
  505. return nil, err
  506. }
  507. if err = createRepository(sess, u, repo); err != nil {
  508. return nil, err
  509. }
  510. // No need for init mirror.
  511. if !isMirror {
  512. repoPath := RepoPath(u.Name, repo.Name)
  513. if err = initRepository(sess, repoPath, u, repo, initReadme, lang, license); err != nil {
  514. if err2 := os.RemoveAll(repoPath); err2 != nil {
  515. log.Error(4, "initRepository: %v", err)
  516. return nil, fmt.Errorf(
  517. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  518. }
  519. return nil, fmt.Errorf("initRepository: %v", err)
  520. }
  521. _, stderr, err := process.ExecDir(-1,
  522. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  523. "git", "update-server-info")
  524. if err != nil {
  525. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  526. }
  527. }
  528. return repo, sess.Commit()
  529. }
  530. // CountRepositories returns number of repositories.
  531. func CountRepositories() int64 {
  532. count, _ := x.Count(new(Repository))
  533. return count
  534. }
  535. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  536. // It also auto-gets corresponding users.
  537. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  538. repos := make([]*Repository, 0, num)
  539. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  540. return nil, err
  541. }
  542. for _, repo := range repos {
  543. repo.Owner = &User{Id: repo.OwnerId}
  544. has, err := x.Get(repo.Owner)
  545. if err != nil {
  546. return nil, err
  547. } else if !has {
  548. return nil, ErrUserNotExist{repo.OwnerId, ""}
  549. }
  550. }
  551. return repos, nil
  552. }
  553. // RepoPath returns repository path by given user and repository name.
  554. func RepoPath(userName, repoName string) string {
  555. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  556. }
  557. // TransferOwnership transfers all corresponding setting from old user to new one.
  558. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  559. newOwner, err := GetUserByName(newOwnerName)
  560. if err != nil {
  561. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  562. }
  563. // Check if new owner has repository with same name.
  564. has, err := IsRepositoryExist(newOwner, repo.Name)
  565. if err != nil {
  566. return fmt.Errorf("IsRepositoryExist: %v", err)
  567. } else if has {
  568. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  569. }
  570. sess := x.NewSession()
  571. defer sessionRelease(sess)
  572. if err = sess.Begin(); err != nil {
  573. return fmt.Errorf("sess.Begin: %v", err)
  574. }
  575. owner := repo.Owner
  576. // Note: we have to set value here to make sure recalculate accesses is based on
  577. // new owner.
  578. repo.OwnerId = newOwner.Id
  579. repo.Owner = newOwner
  580. // Update repository.
  581. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  582. return fmt.Errorf("update owner: %v", err)
  583. }
  584. // Remove redundant collaborators.
  585. collaborators, err := repo.GetCollaborators()
  586. if err != nil {
  587. return fmt.Errorf("GetCollaborators: %v", err)
  588. }
  589. // Dummy object.
  590. collaboration := &Collaboration{RepoID: repo.Id}
  591. for _, c := range collaborators {
  592. collaboration.UserID = c.Id
  593. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  594. if _, err = sess.Delete(collaboration); err != nil {
  595. return fmt.Errorf("remove collaborator '%d': %v", c.Id, err)
  596. }
  597. }
  598. }
  599. // Remove old team-repository relations.
  600. if owner.IsOrganization() {
  601. if err = owner.getTeams(sess); err != nil {
  602. return fmt.Errorf("getTeams: %v", err)
  603. }
  604. for _, t := range owner.Teams {
  605. if !t.hasRepository(sess, repo.Id) {
  606. continue
  607. }
  608. t.NumRepos--
  609. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  610. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  611. }
  612. }
  613. if err = owner.removeOrgRepo(sess, repo.Id); err != nil {
  614. return fmt.Errorf("removeOrgRepo: %v", err)
  615. }
  616. }
  617. if newOwner.IsOrganization() {
  618. t, err := newOwner.GetOwnerTeam()
  619. if err != nil {
  620. return fmt.Errorf("GetOwnerTeam: %v", err)
  621. } else if err = t.addRepository(sess, repo); err != nil {
  622. return fmt.Errorf("add to owner team: %v", err)
  623. }
  624. } else {
  625. // Organization called this in addRepository method.
  626. if err = repo.recalculateAccesses(sess); err != nil {
  627. return fmt.Errorf("recalculateAccesses: %v", err)
  628. }
  629. }
  630. // Update repository count.
  631. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.Id); err != nil {
  632. return fmt.Errorf("increase new owner repository count: %v", err)
  633. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.Id); err != nil {
  634. return fmt.Errorf("decrease old owner repository count: %v", err)
  635. }
  636. if err = watchRepo(sess, newOwner.Id, repo.Id, true); err != nil {
  637. return fmt.Errorf("watchRepo: %v", err)
  638. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  639. return fmt.Errorf("transferRepoAction: %v", err)
  640. }
  641. // Update mirror information.
  642. if repo.IsMirror {
  643. mirror, err := getMirror(sess, repo.Id)
  644. if err != nil {
  645. return fmt.Errorf("getMirror: %v", err)
  646. }
  647. mirror.RepoName = newOwner.LowerName + "/" + repo.LowerName
  648. if err = updateMirror(sess, mirror); err != nil {
  649. return fmt.Errorf("updateMirror: %v", err)
  650. }
  651. }
  652. // Change repository directory name.
  653. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  654. return fmt.Errorf("rename directory: %v", err)
  655. }
  656. return sess.Commit()
  657. }
  658. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  659. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  660. oldRepoName = strings.ToLower(oldRepoName)
  661. newRepoName = strings.ToLower(newRepoName)
  662. if err = IsUsableName(newRepoName); err != nil {
  663. return err
  664. }
  665. has, err := IsRepositoryExist(u, newRepoName)
  666. if err != nil {
  667. return fmt.Errorf("IsRepositoryExist: %v", err)
  668. } else if has {
  669. return ErrRepoAlreadyExist{u.Name, newRepoName}
  670. }
  671. // Change repository directory name.
  672. return os.Rename(RepoPath(u.LowerName, oldRepoName), RepoPath(u.LowerName, newRepoName))
  673. }
  674. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  675. repo.LowerName = strings.ToLower(repo.Name)
  676. if len(repo.Description) > 255 {
  677. repo.Description = repo.Description[:255]
  678. }
  679. if len(repo.Website) > 255 {
  680. repo.Website = repo.Website[:255]
  681. }
  682. if _, err = e.Id(repo.Id).AllCols().Update(repo); err != nil {
  683. return fmt.Errorf("update: %v", err)
  684. }
  685. if visibilityChanged {
  686. if err = repo.getOwner(e); err != nil {
  687. return fmt.Errorf("getOwner: %v", err)
  688. }
  689. if !repo.Owner.IsOrganization() {
  690. return nil
  691. }
  692. // Organization repository need to recalculate access table when visivility is changed.
  693. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  694. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  695. }
  696. }
  697. return nil
  698. }
  699. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  700. sess := x.NewSession()
  701. defer sessionRelease(sess)
  702. if err = sess.Begin(); err != nil {
  703. return err
  704. }
  705. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  706. return fmt.Errorf("updateRepository: %v", err)
  707. }
  708. return sess.Commit()
  709. }
  710. // DeleteRepository deletes a repository for a user or organization.
  711. func DeleteRepository(uid, repoID int64, userName string) error {
  712. repo := &Repository{Id: repoID, OwnerId: uid}
  713. has, err := x.Get(repo)
  714. if err != nil {
  715. return err
  716. } else if !has {
  717. return ErrRepoNotExist{repoID, uid, ""}
  718. }
  719. // In case is a organization.
  720. org, err := GetUserById(uid)
  721. if err != nil {
  722. return err
  723. }
  724. if org.IsOrganization() {
  725. if err = org.GetTeams(); err != nil {
  726. return err
  727. }
  728. }
  729. sess := x.NewSession()
  730. defer sessionRelease(sess)
  731. if err = sess.Begin(); err != nil {
  732. return err
  733. }
  734. if org.IsOrganization() {
  735. for _, t := range org.Teams {
  736. if !t.hasRepository(sess, repoID) {
  737. continue
  738. } else if err = t.removeRepository(sess, repo, false); err != nil {
  739. return err
  740. }
  741. }
  742. }
  743. if _, err = sess.Delete(&Repository{Id: repoID}); err != nil {
  744. return err
  745. } else if _, err = sess.Delete(&Access{RepoID: repo.Id}); err != nil {
  746. return err
  747. } else if _, err = sess.Delete(&Action{RepoID: repo.Id}); err != nil {
  748. return err
  749. } else if _, err = sess.Delete(&Watch{RepoID: repoID}); err != nil {
  750. return err
  751. } else if _, err = sess.Delete(&Mirror{RepoId: repoID}); err != nil {
  752. return err
  753. } else if _, err = sess.Delete(&IssueUser{RepoId: repoID}); err != nil {
  754. return err
  755. } else if _, err = sess.Delete(&Milestone{RepoID: repoID}); err != nil {
  756. return err
  757. } else if _, err = sess.Delete(&Release{RepoId: repoID}); err != nil {
  758. return err
  759. } else if _, err = sess.Delete(&Collaboration{RepoID: repoID}); err != nil {
  760. return err
  761. }
  762. // Delete comments.
  763. issues := make([]*Issue, 0, 25)
  764. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  765. return err
  766. }
  767. for i := range issues {
  768. if _, err = sess.Delete(&Comment{IssueId: issues[i].ID}); err != nil {
  769. return err
  770. }
  771. }
  772. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  773. return err
  774. }
  775. if repo.IsFork {
  776. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkId); err != nil {
  777. return err
  778. }
  779. }
  780. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  781. return err
  782. }
  783. // Remove repository files.
  784. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  785. desc := fmt.Sprintf("delete repository files(%s/%s): %v", userName, repo.Name, err)
  786. log.Warn(desc)
  787. if err = CreateRepositoryNotice(desc); err != nil {
  788. log.Error(4, "add notice: %v", err)
  789. }
  790. }
  791. return sess.Commit()
  792. }
  793. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  794. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  795. func GetRepositoryByRef(ref string) (*Repository, error) {
  796. n := strings.IndexByte(ref, byte('/'))
  797. if n < 2 {
  798. return nil, ErrInvalidReference
  799. }
  800. userName, repoName := ref[:n], ref[n+1:]
  801. user, err := GetUserByName(userName)
  802. if err != nil {
  803. return nil, err
  804. }
  805. return GetRepositoryByName(user.Id, repoName)
  806. }
  807. // GetRepositoryByName returns the repository by given name under user if exists.
  808. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  809. repo := &Repository{
  810. OwnerId: uid,
  811. LowerName: strings.ToLower(repoName),
  812. }
  813. has, err := x.Get(repo)
  814. if err != nil {
  815. return nil, err
  816. } else if !has {
  817. return nil, ErrRepoNotExist{0, uid, repoName}
  818. }
  819. return repo, err
  820. }
  821. func getRepositoryById(e Engine, id int64) (*Repository, error) {
  822. repo := new(Repository)
  823. has, err := e.Id(id).Get(repo)
  824. if err != nil {
  825. return nil, err
  826. } else if !has {
  827. return nil, ErrRepoNotExist{id, 0, ""}
  828. }
  829. return repo, nil
  830. }
  831. // GetRepositoryById returns the repository by given id if exists.
  832. func GetRepositoryById(id int64) (*Repository, error) {
  833. return getRepositoryById(x, id)
  834. }
  835. // GetRepositories returns a list of repositories of given user.
  836. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  837. repos := make([]*Repository, 0, 10)
  838. sess := x.Desc("updated")
  839. if !private {
  840. sess.Where("is_private=?", false)
  841. }
  842. err := sess.Find(&repos, &Repository{OwnerId: uid})
  843. return repos, err
  844. }
  845. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  846. func GetRecentUpdatedRepositories(num int) (repos []*Repository, err error) {
  847. err = x.Where("is_private=?", false).Limit(num).Desc("updated").Find(&repos)
  848. return repos, err
  849. }
  850. // GetRepositoryCount returns the total number of repositories of user.
  851. func GetRepositoryCount(user *User) (int64, error) {
  852. return x.Count(&Repository{OwnerId: user.Id})
  853. }
  854. type SearchOption struct {
  855. Keyword string
  856. Uid int64
  857. Limit int
  858. Private bool
  859. }
  860. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  861. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  862. if len(opt.Keyword) == 0 {
  863. return repos, nil
  864. }
  865. opt.Keyword = strings.ToLower(opt.Keyword)
  866. repos = make([]*Repository, 0, opt.Limit)
  867. // Append conditions.
  868. sess := x.Limit(opt.Limit)
  869. if opt.Uid > 0 {
  870. sess.Where("owner_id=?", opt.Uid)
  871. }
  872. if !opt.Private {
  873. sess.And("is_private=false")
  874. }
  875. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  876. return repos, err
  877. }
  878. // DeleteRepositoryArchives deletes all repositories' archives.
  879. func DeleteRepositoryArchives() error {
  880. return x.Where("id > 0").Iterate(new(Repository),
  881. func(idx int, bean interface{}) error {
  882. repo := bean.(*Repository)
  883. if err := repo.GetOwner(); err != nil {
  884. return err
  885. }
  886. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  887. })
  888. }
  889. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  890. func RewriteRepositoryUpdateHook() error {
  891. return x.Where("id > 0").Iterate(new(Repository),
  892. func(idx int, bean interface{}) error {
  893. repo := bean.(*Repository)
  894. if err := repo.GetOwner(); err != nil {
  895. return err
  896. }
  897. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  898. })
  899. }
  900. var (
  901. // Prevent duplicate tasks.
  902. isMirrorUpdating = false
  903. isGitFscking = false
  904. isCheckingRepos = false
  905. )
  906. // MirrorUpdate checks and updates mirror repositories.
  907. func MirrorUpdate() {
  908. if isMirrorUpdating {
  909. return
  910. }
  911. isMirrorUpdating = true
  912. defer func() { isMirrorUpdating = false }()
  913. mirrors := make([]*Mirror, 0, 10)
  914. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  915. m := bean.(*Mirror)
  916. if m.NextUpdate.After(time.Now()) {
  917. return nil
  918. }
  919. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  920. if _, stderr, err := process.ExecDir(10*time.Minute,
  921. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  922. "git", "remote", "update", "--prune"); err != nil {
  923. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  924. log.Error(4, desc)
  925. if err = CreateRepositoryNotice(desc); err != nil {
  926. log.Error(4, "Fail to add notice: %v", err)
  927. }
  928. return nil
  929. }
  930. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  931. mirrors = append(mirrors, m)
  932. return nil
  933. }); err != nil {
  934. log.Error(4, "MirrorUpdate: %v", err)
  935. }
  936. for i := range mirrors {
  937. if err := UpdateMirror(mirrors[i]); err != nil {
  938. log.Error(4, "UpdateMirror", fmt.Sprintf("%s: %v", mirrors[i].RepoName, err))
  939. }
  940. }
  941. }
  942. // GitFsck calls 'git fsck' to check repository health.
  943. func GitFsck() {
  944. if isGitFscking {
  945. return
  946. }
  947. isGitFscking = true
  948. defer func() { isGitFscking = false }()
  949. args := append([]string{"fsck"}, setting.Git.Fsck.Args...)
  950. if err := x.Where("id > 0").Iterate(new(Repository),
  951. func(idx int, bean interface{}) error {
  952. repo := bean.(*Repository)
  953. if err := repo.GetOwner(); err != nil {
  954. return err
  955. }
  956. repoPath := RepoPath(repo.Owner.Name, repo.Name)
  957. _, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  958. if err != nil {
  959. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  960. log.Warn(desc)
  961. if err = CreateRepositoryNotice(desc); err != nil {
  962. log.Error(4, "Fail to add notice: %v", err)
  963. }
  964. }
  965. return nil
  966. }); err != nil {
  967. log.Error(4, "repo.Fsck: %v", err)
  968. }
  969. }
  970. func GitGcRepos() error {
  971. args := append([]string{"gc"}, setting.Git.GcArgs...)
  972. return x.Where("id > 0").Iterate(new(Repository),
  973. func(idx int, bean interface{}) error {
  974. repo := bean.(*Repository)
  975. if err := repo.GetOwner(); err != nil {
  976. return err
  977. }
  978. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  979. if err != nil {
  980. return fmt.Errorf("%v: %v", err, stderr)
  981. }
  982. return nil
  983. })
  984. }
  985. func CheckRepoStats() {
  986. if isCheckingRepos {
  987. return
  988. }
  989. isCheckingRepos = true
  990. defer func() { isCheckingRepos = false }()
  991. // Check count watchers
  992. results_watch, err := x.Query("SELECT r.id FROM `repository` r WHERE r.num_watches!=(SELECT count(*) FROM `watch` WHERE repo_id=r.id)")
  993. if err != nil {
  994. log.Error(4, "select repository check 'watch': %v", err)
  995. }
  996. for _, repo_id := range results_watch {
  997. log.Info("updating repository count 'watch'")
  998. repoID := com.StrTo(repo_id["id"]).MustInt64()
  999. _, err := x.Exec("UPDATE `repository` SET num_watches=(SELECT count(*) FROM `watch` WHERE repo_id=?) WHERE id=?", repoID, repoID)
  1000. if err != nil {
  1001. log.Error(4, "update repository check 'watch', repo %v: %v", repo_id, err)
  1002. }
  1003. }
  1004. // Check count stars
  1005. results_star, err := x.Query("SELECT s.id FROM `repository` s WHERE s.num_stars!=(SELECT count(*) FROM `star` WHERE repo_id=s.id)")
  1006. if err != nil {
  1007. log.Error(4, "select repository check 'star': %v", err)
  1008. }
  1009. for _, repo_id := range results_star {
  1010. log.Info("updating repository count 'star'")
  1011. repoID := com.StrTo(repo_id["id"]).MustInt64()
  1012. _, err := x.Exec("UPDATE `repository` SET .num_stars=(SELECT count(*) FROM `star` WHERE repo_id=?) WHERE id=?", repoID, repoID)
  1013. if err != nil {
  1014. log.Error(4, "update repository check 'star', repo %v: %v", repo_id, err)
  1015. }
  1016. }
  1017. }
  1018. // _________ .__ .__ ___. __ .__
  1019. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  1020. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  1021. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  1022. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  1023. // \/ \/ \/ \/ \/
  1024. // A Collaboration is a relation between an individual and a repository
  1025. type Collaboration struct {
  1026. ID int64 `xorm:"pk autoincr"`
  1027. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1028. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1029. Created time.Time `xorm:"CREATED"`
  1030. }
  1031. // Add collaborator and accompanying access
  1032. func (repo *Repository) AddCollaborator(u *User) error {
  1033. collaboration := &Collaboration{
  1034. RepoID: repo.Id,
  1035. UserID: u.Id,
  1036. }
  1037. has, err := x.Get(collaboration)
  1038. if err != nil {
  1039. return err
  1040. } else if has {
  1041. return nil
  1042. }
  1043. if err = repo.GetOwner(); err != nil {
  1044. return fmt.Errorf("GetOwner: %v", err)
  1045. }
  1046. sess := x.NewSession()
  1047. defer sessionRelease(sess)
  1048. if err = sess.Begin(); err != nil {
  1049. return err
  1050. }
  1051. if _, err = sess.InsertOne(collaboration); err != nil {
  1052. return err
  1053. }
  1054. if repo.Owner.IsOrganization() {
  1055. err = repo.recalculateTeamAccesses(sess, 0)
  1056. } else {
  1057. err = repo.recalculateAccesses(sess)
  1058. }
  1059. if err != nil {
  1060. return fmt.Errorf("recalculateAccesses 'team=%v': %v", repo.Owner.IsOrganization(), err)
  1061. }
  1062. return sess.Commit()
  1063. }
  1064. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  1065. collaborations := make([]*Collaboration, 0)
  1066. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.Id}); err != nil {
  1067. return nil, err
  1068. }
  1069. users := make([]*User, len(collaborations))
  1070. for i, c := range collaborations {
  1071. user, err := getUserById(e, c.UserID)
  1072. if err != nil {
  1073. return nil, err
  1074. }
  1075. users[i] = user
  1076. }
  1077. return users, nil
  1078. }
  1079. // GetCollaborators returns the collaborators for a repository
  1080. func (repo *Repository) GetCollaborators() ([]*User, error) {
  1081. return repo.getCollaborators(x)
  1082. }
  1083. // Delete collaborator and accompanying access
  1084. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  1085. collaboration := &Collaboration{
  1086. RepoID: repo.Id,
  1087. UserID: u.Id,
  1088. }
  1089. sess := x.NewSession()
  1090. defer sessionRelease(sess)
  1091. if err = sess.Begin(); err != nil {
  1092. return err
  1093. }
  1094. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  1095. return err
  1096. } else if err = repo.recalculateAccesses(sess); err != nil {
  1097. return err
  1098. }
  1099. return sess.Commit()
  1100. }
  1101. // __ __ __ .__
  1102. // / \ / \_____ _/ |_ ____ | |__
  1103. // \ \/\/ /\__ \\ __\/ ___\| | \
  1104. // \ / / __ \| | \ \___| Y \
  1105. // \__/\ / (____ /__| \___ >___| /
  1106. // \/ \/ \/ \/
  1107. // Watch is connection request for receiving repository notification.
  1108. type Watch struct {
  1109. ID int64 `xorm:"pk autoincr"`
  1110. UserID int64 `xorm:"UNIQUE(watch)"`
  1111. RepoID int64 `xorm:"UNIQUE(watch)"`
  1112. }
  1113. // IsWatching checks if user has watched given repository.
  1114. func IsWatching(uid, repoId int64) bool {
  1115. has, _ := x.Get(&Watch{0, uid, repoId})
  1116. return has
  1117. }
  1118. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1119. if watch {
  1120. if IsWatching(uid, repoId) {
  1121. return nil
  1122. }
  1123. if _, err = e.Insert(&Watch{RepoID: repoId, UserID: uid}); err != nil {
  1124. return err
  1125. }
  1126. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1127. } else {
  1128. if !IsWatching(uid, repoId) {
  1129. return nil
  1130. }
  1131. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1132. return err
  1133. }
  1134. _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", repoId)
  1135. }
  1136. return err
  1137. }
  1138. // Watch or unwatch repository.
  1139. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1140. return watchRepo(x, uid, repoId, watch)
  1141. }
  1142. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1143. watches := make([]*Watch, 0, 10)
  1144. err := e.Find(&watches, &Watch{RepoID: rid})
  1145. return watches, err
  1146. }
  1147. // GetWatchers returns all watchers of given repository.
  1148. func GetWatchers(rid int64) ([]*Watch, error) {
  1149. return getWatchers(x, rid)
  1150. }
  1151. func notifyWatchers(e Engine, act *Action) error {
  1152. // Add feeds for user self and all watchers.
  1153. watches, err := getWatchers(e, act.RepoID)
  1154. if err != nil {
  1155. return fmt.Errorf("get watchers: %v", err)
  1156. }
  1157. // Add feed for actioner.
  1158. act.UserID = act.ActUserID
  1159. if _, err = e.InsertOne(act); err != nil {
  1160. return fmt.Errorf("insert new actioner: %v", err)
  1161. }
  1162. for i := range watches {
  1163. if act.ActUserID == watches[i].UserID {
  1164. continue
  1165. }
  1166. act.ID = 0
  1167. act.UserID = watches[i].UserID
  1168. if _, err = e.InsertOne(act); err != nil {
  1169. return fmt.Errorf("insert new action: %v", err)
  1170. }
  1171. }
  1172. return nil
  1173. }
  1174. // NotifyWatchers creates batch of actions for every watcher.
  1175. func NotifyWatchers(act *Action) error {
  1176. return notifyWatchers(x, act)
  1177. }
  1178. // _________ __
  1179. // / _____// |______ _______
  1180. // \_____ \\ __\__ \\_ __ \
  1181. // / \| | / __ \| | \/
  1182. // /_______ /|__| (____ /__|
  1183. // \/ \/
  1184. type Star struct {
  1185. Id int64
  1186. Uid int64 `xorm:"UNIQUE(s)"`
  1187. RepoId int64 `xorm:"UNIQUE(s)"`
  1188. }
  1189. // Star or unstar repository.
  1190. func StarRepo(uid, repoId int64, star bool) (err error) {
  1191. if star {
  1192. if IsStaring(uid, repoId) {
  1193. return nil
  1194. }
  1195. if _, err = x.Insert(&Star{Uid: uid, RepoId: repoId}); err != nil {
  1196. return err
  1197. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1198. return err
  1199. }
  1200. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1201. } else {
  1202. if !IsStaring(uid, repoId) {
  1203. return nil
  1204. }
  1205. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1206. return err
  1207. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1208. return err
  1209. }
  1210. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1211. }
  1212. return err
  1213. }
  1214. // IsStaring checks if user has starred given repository.
  1215. func IsStaring(uid, repoId int64) bool {
  1216. has, _ := x.Get(&Star{0, uid, repoId})
  1217. return has
  1218. }
  1219. // ___________ __
  1220. // \_ _____/__________| | __
  1221. // | __)/ _ \_ __ \ |/ /
  1222. // | \( <_> ) | \/ <
  1223. // \___ / \____/|__| |__|_ \
  1224. // \/ \/
  1225. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1226. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1227. repo := new(Repository)
  1228. has, _ := x.Where("owner_id=? AND fork_id=?", ownerID, repoID).Get(repo)
  1229. return repo, has
  1230. }
  1231. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1232. repo := &Repository{
  1233. OwnerId: u.Id,
  1234. Owner: u,
  1235. Name: name,
  1236. LowerName: strings.ToLower(name),
  1237. Description: desc,
  1238. IsPrivate: oldRepo.IsPrivate,
  1239. IsFork: true,
  1240. ForkId: oldRepo.Id,
  1241. }
  1242. sess := x.NewSession()
  1243. defer sessionRelease(sess)
  1244. if err = sess.Begin(); err != nil {
  1245. return nil, err
  1246. }
  1247. if err = createRepository(sess, u, repo); err != nil {
  1248. return nil, err
  1249. }
  1250. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.Id); err != nil {
  1251. return nil, err
  1252. }
  1253. oldRepoPath, err := oldRepo.RepoPath()
  1254. if err != nil {
  1255. return nil, fmt.Errorf("get old repository path: %v", err)
  1256. }
  1257. repoPath := RepoPath(u.Name, repo.Name)
  1258. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1259. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1260. "git", "clone", "--bare", oldRepoPath, repoPath)
  1261. if err != nil {
  1262. return nil, fmt.Errorf("git clone: %v", stderr)
  1263. }
  1264. _, stderr, err = process.ExecDir(-1,
  1265. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1266. "git", "update-server-info")
  1267. if err != nil {
  1268. return nil, fmt.Errorf("git update-server-info: %v", err)
  1269. }
  1270. if err = createUpdateHook(repoPath); err != nil {
  1271. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1272. }
  1273. return repo, sess.Commit()
  1274. }