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