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 45 kB

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