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
10 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  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", "initial 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. cloneLink, err := repo.CloneLink()
  456. if err != nil {
  457. return fmt.Errorf("CloneLink: %v", err)
  458. }
  459. match := map[string]string{
  460. "Name": repo.Name,
  461. "Description": repo.Description,
  462. "CloneURL.SSH": cloneLink.SSH,
  463. "CloneURL.HTTPS": cloneLink.HTTPS,
  464. }
  465. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  466. []byte(com.Expand(string(data), match)), 0644); err != nil {
  467. return fmt.Errorf("write README.md: %v", err)
  468. }
  469. // .gitignore
  470. if len(opts.Gitignores) > 0 {
  471. var buf bytes.Buffer
  472. names := strings.Split(opts.Gitignores, ",")
  473. for _, name := range names {
  474. data, err = getRepoInitFile("gitignore", name)
  475. if err != nil {
  476. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  477. }
  478. buf.WriteString("# ---> " + name + "\n")
  479. buf.Write(data)
  480. buf.WriteString("\n")
  481. }
  482. if buf.Len() > 0 {
  483. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  484. return fmt.Errorf("write .gitignore: %v", err)
  485. }
  486. }
  487. }
  488. // LICENSE
  489. if len(opts.License) > 0 {
  490. data, err = getRepoInitFile("license", opts.License)
  491. if err != nil {
  492. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  493. }
  494. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  495. return fmt.Errorf("write LICENSE: %v", err)
  496. }
  497. }
  498. return nil
  499. }
  500. // InitRepository initializes README and .gitignore if needed.
  501. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) error {
  502. // Somehow the directory could exist.
  503. if com.IsExist(repoPath) {
  504. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  505. }
  506. // Init bare new repository.
  507. os.MkdirAll(repoPath, os.ModePerm)
  508. _, stderr, err := process.ExecDir(-1, repoPath,
  509. fmt.Sprintf("initRepository(git init --bare): %s", repoPath), "git", "init", "--bare")
  510. if err != nil {
  511. return fmt.Errorf("git init --bare: %v - %s", err, stderr)
  512. }
  513. if err := createUpdateHook(repoPath); err != nil {
  514. return err
  515. }
  516. tmpDir := filepath.Join(os.TempDir(), com.ToStr(time.Now().Nanosecond()))
  517. // Initialize repository according to user's choice.
  518. if opts.AutoInit {
  519. os.MkdirAll(tmpDir, os.ModePerm)
  520. defer os.RemoveAll(tmpDir)
  521. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  522. return fmt.Errorf("prepareRepoCommit: %v", err)
  523. }
  524. // Apply changes and commit.
  525. if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
  526. return fmt.Errorf("initRepoCommit: %v", err)
  527. }
  528. } else {
  529. repo.IsBare = true
  530. }
  531. // Re-fetch the repository from database before updating it (else it would
  532. // override changes that were done earlier with sql)
  533. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  534. return fmt.Errorf("getRepositoryByID: %v", err)
  535. }
  536. repo.DefaultBranch = "master"
  537. if err = updateRepository(e, repo, false); err != nil {
  538. return fmt.Errorf("updateRepository: %v", err)
  539. }
  540. return nil
  541. }
  542. func createRepository(e *xorm.Session, u *User, repo *Repository) (err error) {
  543. if err = IsUsableName(repo.Name); err != nil {
  544. return err
  545. }
  546. has, err := isRepositoryExist(e, u, repo.Name)
  547. if err != nil {
  548. return fmt.Errorf("IsRepositoryExist: %v", err)
  549. } else if has {
  550. return ErrRepoAlreadyExist{u.Name, repo.Name}
  551. }
  552. if _, err = e.Insert(repo); err != nil {
  553. return err
  554. } else if _, err = e.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", u.Id); err != nil {
  555. return err
  556. }
  557. // Give access to all members in owner team.
  558. if u.IsOrganization() {
  559. t, err := u.getOwnerTeam(e)
  560. if err != nil {
  561. return fmt.Errorf("getOwnerTeam: %v", err)
  562. } else if err = t.addRepository(e, repo); err != nil {
  563. return fmt.Errorf("addRepository: %v", err)
  564. }
  565. } else {
  566. // Organization automatically called this in addRepository method.
  567. if err = repo.recalculateAccesses(e); err != nil {
  568. return fmt.Errorf("recalculateAccesses: %v", err)
  569. }
  570. }
  571. if err = watchRepo(e, u.Id, repo.ID, true); err != nil {
  572. return fmt.Errorf("watchRepo: %v", err)
  573. } else if err = newRepoAction(e, u, repo); err != nil {
  574. return fmt.Errorf("newRepoAction: %v", err)
  575. }
  576. return nil
  577. }
  578. // CreateRepository creates a repository for given user or organization.
  579. func CreateRepository(u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  580. repo := &Repository{
  581. OwnerID: u.Id,
  582. Owner: u,
  583. Name: opts.Name,
  584. LowerName: strings.ToLower(opts.Name),
  585. Description: opts.Description,
  586. IsPrivate: opts.IsPrivate,
  587. }
  588. sess := x.NewSession()
  589. defer sessionRelease(sess)
  590. if err = sess.Begin(); err != nil {
  591. return nil, err
  592. }
  593. if err = createRepository(sess, u, repo); err != nil {
  594. return nil, err
  595. }
  596. // No need for init mirror.
  597. if !opts.IsMirror {
  598. repoPath := RepoPath(u.Name, repo.Name)
  599. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  600. if err2 := os.RemoveAll(repoPath); err2 != nil {
  601. log.Error(4, "initRepository: %v", err)
  602. return nil, fmt.Errorf(
  603. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  604. }
  605. return nil, fmt.Errorf("initRepository: %v", err)
  606. }
  607. _, stderr, err := process.ExecDir(-1,
  608. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  609. "git", "update-server-info")
  610. if err != nil {
  611. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  612. }
  613. }
  614. return repo, sess.Commit()
  615. }
  616. // CountRepositories returns number of repositories.
  617. func CountRepositories() int64 {
  618. count, _ := x.Count(new(Repository))
  619. return count
  620. }
  621. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  622. // It also auto-gets corresponding users.
  623. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  624. repos := make([]*Repository, 0, num)
  625. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  626. return nil, err
  627. }
  628. for _, repo := range repos {
  629. repo.Owner = &User{Id: repo.OwnerID}
  630. has, err := x.Get(repo.Owner)
  631. if err != nil {
  632. return nil, err
  633. } else if !has {
  634. return nil, ErrUserNotExist{repo.OwnerID, ""}
  635. }
  636. }
  637. return repos, nil
  638. }
  639. // RepoPath returns repository path by given user and repository name.
  640. func RepoPath(userName, repoName string) string {
  641. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  642. }
  643. // TransferOwnership transfers all corresponding setting from old user to new one.
  644. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  645. newOwner, err := GetUserByName(newOwnerName)
  646. if err != nil {
  647. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  648. }
  649. // Check if new owner has repository with same name.
  650. has, err := IsRepositoryExist(newOwner, repo.Name)
  651. if err != nil {
  652. return fmt.Errorf("IsRepositoryExist: %v", err)
  653. } else if has {
  654. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  655. }
  656. sess := x.NewSession()
  657. defer sessionRelease(sess)
  658. if err = sess.Begin(); err != nil {
  659. return fmt.Errorf("sess.Begin: %v", err)
  660. }
  661. owner := repo.Owner
  662. // Note: we have to set value here to make sure recalculate accesses is based on
  663. // new owner.
  664. repo.OwnerID = newOwner.Id
  665. repo.Owner = newOwner
  666. // Update repository.
  667. if _, err := sess.Id(repo.ID).Update(repo); err != nil {
  668. return fmt.Errorf("update owner: %v", err)
  669. }
  670. // Remove redundant collaborators.
  671. collaborators, err := repo.GetCollaborators()
  672. if err != nil {
  673. return fmt.Errorf("GetCollaborators: %v", err)
  674. }
  675. // Dummy object.
  676. collaboration := &Collaboration{RepoID: repo.ID}
  677. for _, c := range collaborators {
  678. collaboration.UserID = c.Id
  679. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  680. if _, err = sess.Delete(collaboration); err != nil {
  681. return fmt.Errorf("remove collaborator '%d': %v", c.Id, err)
  682. }
  683. }
  684. }
  685. // Remove old team-repository relations.
  686. if owner.IsOrganization() {
  687. if err = owner.getTeams(sess); err != nil {
  688. return fmt.Errorf("getTeams: %v", err)
  689. }
  690. for _, t := range owner.Teams {
  691. if !t.hasRepository(sess, repo.ID) {
  692. continue
  693. }
  694. t.NumRepos--
  695. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  696. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  697. }
  698. }
  699. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  700. return fmt.Errorf("removeOrgRepo: %v", err)
  701. }
  702. }
  703. if newOwner.IsOrganization() {
  704. t, err := newOwner.GetOwnerTeam()
  705. if err != nil {
  706. return fmt.Errorf("GetOwnerTeam: %v", err)
  707. } else if err = t.addRepository(sess, repo); err != nil {
  708. return fmt.Errorf("add to owner team: %v", err)
  709. }
  710. } else {
  711. // Organization called this in addRepository method.
  712. if err = repo.recalculateAccesses(sess); err != nil {
  713. return fmt.Errorf("recalculateAccesses: %v", err)
  714. }
  715. }
  716. // Update repository count.
  717. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.Id); err != nil {
  718. return fmt.Errorf("increase new owner repository count: %v", err)
  719. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.Id); err != nil {
  720. return fmt.Errorf("decrease old owner repository count: %v", err)
  721. }
  722. if err = watchRepo(sess, newOwner.Id, repo.ID, true); err != nil {
  723. return fmt.Errorf("watchRepo: %v", err)
  724. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  725. return fmt.Errorf("transferRepoAction: %v", err)
  726. }
  727. // Change repository directory name.
  728. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  729. return fmt.Errorf("rename directory: %v", err)
  730. }
  731. return sess.Commit()
  732. }
  733. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  734. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  735. oldRepoName = strings.ToLower(oldRepoName)
  736. newRepoName = strings.ToLower(newRepoName)
  737. if err = IsUsableName(newRepoName); err != nil {
  738. return err
  739. }
  740. has, err := IsRepositoryExist(u, newRepoName)
  741. if err != nil {
  742. return fmt.Errorf("IsRepositoryExist: %v", err)
  743. } else if has {
  744. return ErrRepoAlreadyExist{u.Name, newRepoName}
  745. }
  746. // Change repository directory name.
  747. return os.Rename(RepoPath(u.LowerName, oldRepoName), RepoPath(u.LowerName, newRepoName))
  748. }
  749. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  750. repo.LowerName = strings.ToLower(repo.Name)
  751. if len(repo.Description) > 255 {
  752. repo.Description = repo.Description[:255]
  753. }
  754. if len(repo.Website) > 255 {
  755. repo.Website = repo.Website[:255]
  756. }
  757. if _, err = e.Id(repo.ID).AllCols().Update(repo); err != nil {
  758. return fmt.Errorf("update: %v", err)
  759. }
  760. if visibilityChanged {
  761. if err = repo.getOwner(e); err != nil {
  762. return fmt.Errorf("getOwner: %v", err)
  763. }
  764. if !repo.Owner.IsOrganization() {
  765. return nil
  766. }
  767. // Organization repository need to recalculate access table when visivility is changed.
  768. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  769. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  770. }
  771. }
  772. return nil
  773. }
  774. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  775. sess := x.NewSession()
  776. defer sessionRelease(sess)
  777. if err = sess.Begin(); err != nil {
  778. return err
  779. }
  780. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  781. return fmt.Errorf("updateRepository: %v", err)
  782. }
  783. return sess.Commit()
  784. }
  785. // DeleteRepository deletes a repository for a user or organization.
  786. func DeleteRepository(uid, repoID int64, userName string) error {
  787. repo := &Repository{ID: repoID, OwnerID: uid}
  788. has, err := x.Get(repo)
  789. if err != nil {
  790. return err
  791. } else if !has {
  792. return ErrRepoNotExist{repoID, uid, ""}
  793. }
  794. // In case is a organization.
  795. org, err := GetUserByID(uid)
  796. if err != nil {
  797. return err
  798. }
  799. if org.IsOrganization() {
  800. if err = org.GetTeams(); err != nil {
  801. return err
  802. }
  803. }
  804. sess := x.NewSession()
  805. defer sessionRelease(sess)
  806. if err = sess.Begin(); err != nil {
  807. return err
  808. }
  809. if org.IsOrganization() {
  810. for _, t := range org.Teams {
  811. if !t.hasRepository(sess, repoID) {
  812. continue
  813. } else if err = t.removeRepository(sess, repo, false); err != nil {
  814. return err
  815. }
  816. }
  817. }
  818. if _, err = sess.Delete(&Repository{ID: repoID}); err != nil {
  819. return err
  820. } else if _, err = sess.Delete(&Access{RepoID: repo.ID}); err != nil {
  821. return err
  822. } else if _, err = sess.Delete(&Action{RepoID: repo.ID}); err != nil {
  823. return err
  824. } else if _, err = sess.Delete(&Watch{RepoID: repoID}); err != nil {
  825. return err
  826. } else if _, err = sess.Delete(&Mirror{RepoID: repoID}); err != nil {
  827. return err
  828. } else if _, err = sess.Delete(&IssueUser{RepoID: repoID}); err != nil {
  829. return err
  830. } else if _, err = sess.Delete(&Milestone{RepoID: repoID}); err != nil {
  831. return err
  832. } else if _, err = sess.Delete(&Release{RepoId: repoID}); err != nil {
  833. return err
  834. } else if _, err = sess.Delete(&Collaboration{RepoID: repoID}); err != nil {
  835. return err
  836. }
  837. // Delete comments and attachments.
  838. issues := make([]*Issue, 0, 25)
  839. attachmentPaths := make([]string, 0, len(issues))
  840. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  841. return err
  842. }
  843. for i := range issues {
  844. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  845. return err
  846. }
  847. attachments := make([]*Attachment, 0, 5)
  848. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  849. return err
  850. }
  851. for j := range attachments {
  852. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  853. }
  854. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  855. return err
  856. }
  857. }
  858. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  859. return err
  860. }
  861. if repo.IsFork {
  862. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  863. return err
  864. }
  865. }
  866. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  867. return err
  868. }
  869. // Remove repository files.
  870. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  871. desc := fmt.Sprintf("delete repository files(%s/%s): %v", userName, repo.Name, err)
  872. log.Warn(desc)
  873. if err = CreateRepositoryNotice(desc); err != nil {
  874. log.Error(4, "add notice: %v", err)
  875. }
  876. }
  877. // Remove attachment files.
  878. for i := range attachmentPaths {
  879. if err = os.Remove(attachmentPaths[i]); err != nil {
  880. log.Warn("delete attachment: %v", err)
  881. }
  882. }
  883. return sess.Commit()
  884. }
  885. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  886. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  887. func GetRepositoryByRef(ref string) (*Repository, error) {
  888. n := strings.IndexByte(ref, byte('/'))
  889. if n < 2 {
  890. return nil, ErrInvalidReference
  891. }
  892. userName, repoName := ref[:n], ref[n+1:]
  893. user, err := GetUserByName(userName)
  894. if err != nil {
  895. return nil, err
  896. }
  897. return GetRepositoryByName(user.Id, repoName)
  898. }
  899. // GetRepositoryByName returns the repository by given name under user if exists.
  900. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  901. repo := &Repository{
  902. OwnerID: uid,
  903. LowerName: strings.ToLower(repoName),
  904. }
  905. has, err := x.Get(repo)
  906. if err != nil {
  907. return nil, err
  908. } else if !has {
  909. return nil, ErrRepoNotExist{0, uid, repoName}
  910. }
  911. return repo, err
  912. }
  913. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  914. repo := new(Repository)
  915. has, err := e.Id(id).Get(repo)
  916. if err != nil {
  917. return nil, err
  918. } else if !has {
  919. return nil, ErrRepoNotExist{id, 0, ""}
  920. }
  921. return repo, nil
  922. }
  923. // GetRepositoryByID returns the repository by given id if exists.
  924. func GetRepositoryByID(id int64) (*Repository, error) {
  925. return getRepositoryByID(x, id)
  926. }
  927. // GetRepositories returns a list of repositories of given user.
  928. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  929. repos := make([]*Repository, 0, 10)
  930. sess := x.Desc("updated")
  931. if !private {
  932. sess.Where("is_private=?", false)
  933. }
  934. return repos, sess.Find(&repos, &Repository{OwnerID: uid})
  935. }
  936. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  937. func GetRecentUpdatedRepositories(num int) (repos []*Repository, err error) {
  938. err = x.Where("is_private=?", false).Limit(num).Desc("updated").Find(&repos)
  939. return repos, err
  940. }
  941. // GetRepositoryCount returns the total number of repositories of user.
  942. func GetRepositoryCount(u *User) (int64, error) {
  943. return x.Count(&Repository{OwnerID: u.Id})
  944. }
  945. type SearchOption struct {
  946. Keyword string
  947. Uid int64
  948. Limit int
  949. Private bool
  950. }
  951. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  952. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  953. if len(opt.Keyword) == 0 {
  954. return repos, nil
  955. }
  956. opt.Keyword = strings.ToLower(opt.Keyword)
  957. repos = make([]*Repository, 0, opt.Limit)
  958. // Append conditions.
  959. sess := x.Limit(opt.Limit)
  960. if opt.Uid > 0 {
  961. sess.Where("owner_id=?", opt.Uid)
  962. }
  963. if !opt.Private {
  964. sess.And("is_private=false")
  965. }
  966. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  967. return repos, err
  968. }
  969. // DeleteRepositoryArchives deletes all repositories' archives.
  970. func DeleteRepositoryArchives() error {
  971. return x.Where("id > 0").Iterate(new(Repository),
  972. func(idx int, bean interface{}) error {
  973. repo := bean.(*Repository)
  974. if err := repo.GetOwner(); err != nil {
  975. return err
  976. }
  977. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  978. })
  979. }
  980. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  981. func RewriteRepositoryUpdateHook() error {
  982. return x.Where("id > 0").Iterate(new(Repository),
  983. func(idx int, bean interface{}) error {
  984. repo := bean.(*Repository)
  985. if err := repo.GetOwner(); err != nil {
  986. return err
  987. }
  988. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  989. })
  990. }
  991. var (
  992. // Prevent duplicate running tasks.
  993. isMirrorUpdating = false
  994. isGitFscking = false
  995. isCheckingRepos = false
  996. )
  997. // MirrorUpdate checks and updates mirror repositories.
  998. func MirrorUpdate() {
  999. if isMirrorUpdating {
  1000. return
  1001. }
  1002. isMirrorUpdating = true
  1003. defer func() { isMirrorUpdating = false }()
  1004. log.Trace("Doing: MirrorUpdate")
  1005. mirrors := make([]*Mirror, 0, 10)
  1006. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  1007. m := bean.(*Mirror)
  1008. if m.NextUpdate.After(time.Now()) {
  1009. return nil
  1010. }
  1011. if m.Repo == nil {
  1012. log.Error(4, "Disconnected mirror repository found: %d", m.ID)
  1013. return nil
  1014. }
  1015. repoPath, err := m.Repo.RepoPath()
  1016. if err != nil {
  1017. return fmt.Errorf("Repo.RepoPath: %v", err)
  1018. }
  1019. if _, stderr, err := process.ExecDir(10*time.Minute,
  1020. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  1021. "git", "remote", "update", "--prune"); err != nil {
  1022. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  1023. log.Error(4, desc)
  1024. if err = CreateRepositoryNotice(desc); err != nil {
  1025. log.Error(4, "CreateRepositoryNotice: %v", err)
  1026. }
  1027. return nil
  1028. }
  1029. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  1030. mirrors = append(mirrors, m)
  1031. return nil
  1032. }); err != nil {
  1033. log.Error(4, "MirrorUpdate: %v", err)
  1034. }
  1035. for i := range mirrors {
  1036. if err := UpdateMirror(mirrors[i]); err != nil {
  1037. log.Error(4, "UpdateMirror[%d]: %v", mirrors[i].ID, err)
  1038. }
  1039. }
  1040. }
  1041. // GitFsck calls 'git fsck' to check repository health.
  1042. func GitFsck() {
  1043. if isGitFscking {
  1044. return
  1045. }
  1046. isGitFscking = true
  1047. defer func() { isGitFscking = false }()
  1048. log.Trace("Doing: GitFsck")
  1049. args := append([]string{"fsck"}, setting.Cron.RepoHealthCheck.Args...)
  1050. if err := x.Where("id>0").Iterate(new(Repository),
  1051. func(idx int, bean interface{}) error {
  1052. repo := bean.(*Repository)
  1053. repoPath, err := repo.RepoPath()
  1054. if err != nil {
  1055. return fmt.Errorf("RepoPath: %v", err)
  1056. }
  1057. _, _, err = process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  1058. if err != nil {
  1059. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  1060. log.Warn(desc)
  1061. if err = CreateRepositoryNotice(desc); err != nil {
  1062. log.Error(4, "CreateRepositoryNotice: %v", err)
  1063. }
  1064. }
  1065. return nil
  1066. }); err != nil {
  1067. log.Error(4, "GitFsck: %v", err)
  1068. }
  1069. }
  1070. func GitGcRepos() error {
  1071. args := append([]string{"gc"}, setting.Git.GcArgs...)
  1072. return x.Where("id > 0").Iterate(new(Repository),
  1073. func(idx int, bean interface{}) error {
  1074. repo := bean.(*Repository)
  1075. if err := repo.GetOwner(); err != nil {
  1076. return err
  1077. }
  1078. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  1079. if err != nil {
  1080. return fmt.Errorf("%v: %v", err, stderr)
  1081. }
  1082. return nil
  1083. })
  1084. }
  1085. func CheckRepoStats() {
  1086. if isCheckingRepos {
  1087. return
  1088. }
  1089. isCheckingRepos = true
  1090. defer func() { isCheckingRepos = false }()
  1091. log.Trace("Doing: CheckRepoStats")
  1092. // ***** START: Watch *****
  1093. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)")
  1094. if err != nil {
  1095. log.Error(4, "Select repository check 'watch': %v", err)
  1096. return
  1097. }
  1098. for _, watch := range results {
  1099. repoID := com.StrTo(watch["id"]).MustInt64()
  1100. log.Trace("Updating repository count 'watch': %d", repoID)
  1101. _, err = x.Exec("UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?", repoID, repoID)
  1102. if err != nil {
  1103. log.Error(4, "Update repository check 'watch'[%d]: %v", repoID, err)
  1104. }
  1105. }
  1106. // ***** END: Watch *****
  1107. // ***** START: Star *****
  1108. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)")
  1109. if err != nil {
  1110. log.Error(4, "Select repository check 'star': %v", err)
  1111. return
  1112. }
  1113. for _, star := range results {
  1114. repoID := com.StrTo(star["id"]).MustInt64()
  1115. log.Trace("Updating repository count 'star': %d", repoID)
  1116. _, err = x.Exec("UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?", repoID, repoID)
  1117. if err != nil {
  1118. log.Error(4, "Update repository check 'star'[%d]: %v", repoID, err)
  1119. }
  1120. }
  1121. // ***** END: Star *****
  1122. // ***** START: Label *****
  1123. results, err = x.Query("SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)")
  1124. if err != nil {
  1125. log.Error(4, "Select label check 'num_issues': %v", err)
  1126. return
  1127. }
  1128. for _, label := range results {
  1129. labelID := com.StrTo(label["id"]).MustInt64()
  1130. log.Trace("Updating label count 'num_issues': %d", labelID)
  1131. _, err = x.Exec("UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?", labelID, labelID)
  1132. if err != nil {
  1133. log.Error(4, "Update label check 'num_issues'[%d]: %v", labelID, err)
  1134. }
  1135. }
  1136. // ***** END: Label *****
  1137. }
  1138. // _________ .__ .__ ___. __ .__
  1139. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  1140. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  1141. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  1142. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  1143. // \/ \/ \/ \/ \/
  1144. // A Collaboration is a relation between an individual and a repository
  1145. type Collaboration struct {
  1146. ID int64 `xorm:"pk autoincr"`
  1147. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1148. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1149. Created time.Time `xorm:"CREATED"`
  1150. }
  1151. // Add collaborator and accompanying access
  1152. func (repo *Repository) AddCollaborator(u *User) error {
  1153. collaboration := &Collaboration{
  1154. RepoID: repo.ID,
  1155. UserID: u.Id,
  1156. }
  1157. has, err := x.Get(collaboration)
  1158. if err != nil {
  1159. return err
  1160. } else if has {
  1161. return nil
  1162. }
  1163. if err = repo.GetOwner(); err != nil {
  1164. return fmt.Errorf("GetOwner: %v", err)
  1165. }
  1166. sess := x.NewSession()
  1167. defer sessionRelease(sess)
  1168. if err = sess.Begin(); err != nil {
  1169. return err
  1170. }
  1171. if _, err = sess.InsertOne(collaboration); err != nil {
  1172. return err
  1173. }
  1174. if repo.Owner.IsOrganization() {
  1175. err = repo.recalculateTeamAccesses(sess, 0)
  1176. } else {
  1177. err = repo.recalculateAccesses(sess)
  1178. }
  1179. if err != nil {
  1180. return fmt.Errorf("recalculateAccesses 'team=%v': %v", repo.Owner.IsOrganization(), err)
  1181. }
  1182. return sess.Commit()
  1183. }
  1184. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  1185. collaborations := make([]*Collaboration, 0)
  1186. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.ID}); err != nil {
  1187. return nil, err
  1188. }
  1189. users := make([]*User, len(collaborations))
  1190. for i, c := range collaborations {
  1191. user, err := getUserByID(e, c.UserID)
  1192. if err != nil {
  1193. return nil, err
  1194. }
  1195. users[i] = user
  1196. }
  1197. return users, nil
  1198. }
  1199. // GetCollaborators returns the collaborators for a repository
  1200. func (repo *Repository) GetCollaborators() ([]*User, error) {
  1201. return repo.getCollaborators(x)
  1202. }
  1203. // Delete collaborator and accompanying access
  1204. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  1205. collaboration := &Collaboration{
  1206. RepoID: repo.ID,
  1207. UserID: u.Id,
  1208. }
  1209. sess := x.NewSession()
  1210. defer sessionRelease(sess)
  1211. if err = sess.Begin(); err != nil {
  1212. return err
  1213. }
  1214. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  1215. return err
  1216. } else if err = repo.recalculateAccesses(sess); err != nil {
  1217. return err
  1218. }
  1219. return sess.Commit()
  1220. }
  1221. // __ __ __ .__
  1222. // / \ / \_____ _/ |_ ____ | |__
  1223. // \ \/\/ /\__ \\ __\/ ___\| | \
  1224. // \ / / __ \| | \ \___| Y \
  1225. // \__/\ / (____ /__| \___ >___| /
  1226. // \/ \/ \/ \/
  1227. // Watch is connection request for receiving repository notification.
  1228. type Watch struct {
  1229. ID int64 `xorm:"pk autoincr"`
  1230. UserID int64 `xorm:"UNIQUE(watch)"`
  1231. RepoID int64 `xorm:"UNIQUE(watch)"`
  1232. }
  1233. // IsWatching checks if user has watched given repository.
  1234. func IsWatching(uid, repoId int64) bool {
  1235. has, _ := x.Get(&Watch{0, uid, repoId})
  1236. return has
  1237. }
  1238. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1239. if watch {
  1240. if IsWatching(uid, repoId) {
  1241. return nil
  1242. }
  1243. if _, err = e.Insert(&Watch{RepoID: repoId, UserID: uid}); err != nil {
  1244. return err
  1245. }
  1246. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1247. } else {
  1248. if !IsWatching(uid, repoId) {
  1249. return nil
  1250. }
  1251. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1252. return err
  1253. }
  1254. _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", repoId)
  1255. }
  1256. return err
  1257. }
  1258. // Watch or unwatch repository.
  1259. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1260. return watchRepo(x, uid, repoId, watch)
  1261. }
  1262. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1263. watches := make([]*Watch, 0, 10)
  1264. err := e.Find(&watches, &Watch{RepoID: rid})
  1265. return watches, err
  1266. }
  1267. // GetWatchers returns all watchers of given repository.
  1268. func GetWatchers(rid int64) ([]*Watch, error) {
  1269. return getWatchers(x, rid)
  1270. }
  1271. func notifyWatchers(e Engine, act *Action) error {
  1272. // Add feeds for user self and all watchers.
  1273. watches, err := getWatchers(e, act.RepoID)
  1274. if err != nil {
  1275. return fmt.Errorf("get watchers: %v", err)
  1276. }
  1277. // Add feed for actioner.
  1278. act.UserID = act.ActUserID
  1279. if _, err = e.InsertOne(act); err != nil {
  1280. return fmt.Errorf("insert new actioner: %v", err)
  1281. }
  1282. for i := range watches {
  1283. if act.ActUserID == watches[i].UserID {
  1284. continue
  1285. }
  1286. act.ID = 0
  1287. act.UserID = watches[i].UserID
  1288. if _, err = e.InsertOne(act); err != nil {
  1289. return fmt.Errorf("insert new action: %v", err)
  1290. }
  1291. }
  1292. return nil
  1293. }
  1294. // NotifyWatchers creates batch of actions for every watcher.
  1295. func NotifyWatchers(act *Action) error {
  1296. return notifyWatchers(x, act)
  1297. }
  1298. // _________ __
  1299. // / _____// |______ _______
  1300. // \_____ \\ __\__ \\_ __ \
  1301. // / \| | / __ \| | \/
  1302. // /_______ /|__| (____ /__|
  1303. // \/ \/
  1304. type Star struct {
  1305. ID int64 `xorm:"pk autoincr"`
  1306. UID int64 `xorm:"uid UNIQUE(s)"`
  1307. RepoID int64 `xorm:"UNIQUE(s)"`
  1308. }
  1309. // Star or unstar repository.
  1310. func StarRepo(uid, repoId int64, star bool) (err error) {
  1311. if star {
  1312. if IsStaring(uid, repoId) {
  1313. return nil
  1314. }
  1315. if _, err = x.Insert(&Star{UID: uid, RepoID: repoId}); err != nil {
  1316. return err
  1317. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1318. return err
  1319. }
  1320. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1321. } else {
  1322. if !IsStaring(uid, repoId) {
  1323. return nil
  1324. }
  1325. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1326. return err
  1327. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1328. return err
  1329. }
  1330. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1331. }
  1332. return err
  1333. }
  1334. // IsStaring checks if user has starred given repository.
  1335. func IsStaring(uid, repoId int64) bool {
  1336. has, _ := x.Get(&Star{0, uid, repoId})
  1337. return has
  1338. }
  1339. // ___________ __
  1340. // \_ _____/__________| | __
  1341. // | __)/ _ \_ __ \ |/ /
  1342. // | \( <_> ) | \/ <
  1343. // \___ / \____/|__| |__|_ \
  1344. // \/ \/
  1345. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1346. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1347. repo := new(Repository)
  1348. has, _ := x.Where("owner_id=? AND fork_id=?", ownerID, repoID).Get(repo)
  1349. return repo, has
  1350. }
  1351. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1352. repo := &Repository{
  1353. OwnerID: u.Id,
  1354. Owner: u,
  1355. Name: name,
  1356. LowerName: strings.ToLower(name),
  1357. Description: desc,
  1358. IsPrivate: oldRepo.IsPrivate,
  1359. IsFork: true,
  1360. ForkID: oldRepo.ID,
  1361. }
  1362. sess := x.NewSession()
  1363. defer sessionRelease(sess)
  1364. if err = sess.Begin(); err != nil {
  1365. return nil, err
  1366. }
  1367. if err = createRepository(sess, u, repo); err != nil {
  1368. return nil, err
  1369. }
  1370. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  1371. return nil, err
  1372. }
  1373. oldRepoPath, err := oldRepo.RepoPath()
  1374. if err != nil {
  1375. return nil, fmt.Errorf("get old repository path: %v", err)
  1376. }
  1377. repoPath := RepoPath(u.Name, repo.Name)
  1378. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1379. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1380. "git", "clone", "--bare", oldRepoPath, repoPath)
  1381. if err != nil {
  1382. return nil, fmt.Errorf("git clone: %v", stderr)
  1383. }
  1384. _, stderr, err = process.ExecDir(-1,
  1385. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1386. "git", "update-server-info")
  1387. if err != nil {
  1388. return nil, fmt.Errorf("git update-server-info: %v", err)
  1389. }
  1390. if err = createUpdateHook(repoPath); err != nil {
  1391. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1392. }
  1393. return repo, sess.Commit()
  1394. }