repo.go 44 KB

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