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