repo.go 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032
  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. "sync"
  19. "time"
  20. "unicode/utf8"
  21. "github.com/Unknwon/cae/zip"
  22. "github.com/Unknwon/com"
  23. "github.com/go-xorm/xorm"
  24. "github.com/mcuadros/go-version"
  25. "gopkg.in/ini.v1"
  26. "github.com/gogits/git-shell"
  27. api "github.com/gogits/go-gogs-client"
  28. "github.com/gogits/gogs/modules/base"
  29. "github.com/gogits/gogs/modules/bindata"
  30. "github.com/gogits/gogs/modules/log"
  31. "github.com/gogits/gogs/modules/process"
  32. "github.com/gogits/gogs/modules/setting"
  33. )
  34. const (
  35. _TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
  36. )
  37. var (
  38. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  39. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  40. ErrMirrorNotExist = errors.New("Mirror does not exist")
  41. ErrInvalidReference = errors.New("Invalid reference specified")
  42. ErrNameEmpty = errors.New("Name is empty")
  43. )
  44. var (
  45. Gitignores, Licenses, Readmes []string
  46. // Maximum items per page in forks, watchers and stars of a repo
  47. ItemsPerPage = 40
  48. )
  49. func LoadRepoConfig() {
  50. // Load .gitignore and license files and readme templates.
  51. types := []string{"gitignore", "license", "readme"}
  52. typeFiles := make([][]string, 3)
  53. for i, t := range types {
  54. files, err := bindata.AssetDir("conf/" + t)
  55. if err != nil {
  56. log.Fatal(4, "Fail to get %s files: %v", t, err)
  57. }
  58. customPath := path.Join(setting.CustomPath, "conf", t)
  59. if com.IsDir(customPath) {
  60. customFiles, err := com.StatDir(customPath)
  61. if err != nil {
  62. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  63. }
  64. for _, f := range customFiles {
  65. if !com.IsSliceContainsStr(files, f) {
  66. files = append(files, f)
  67. }
  68. }
  69. }
  70. typeFiles[i] = files
  71. }
  72. Gitignores = typeFiles[0]
  73. Licenses = typeFiles[1]
  74. Readmes = typeFiles[2]
  75. sort.Strings(Gitignores)
  76. sort.Strings(Licenses)
  77. sort.Strings(Readmes)
  78. }
  79. func NewRepoContext() {
  80. zip.Verbose = false
  81. // Check Git installation.
  82. if _, err := exec.LookPath("git"); err != nil {
  83. log.Fatal(4, "Fail to test 'git' command: %v (forgotten install?)", err)
  84. }
  85. // Check Git version.
  86. gitVer, err := git.Version()
  87. if err != nil {
  88. log.Fatal(4, "Fail to get Git version: %v", err)
  89. }
  90. log.Info("Git Version: %s", gitVer)
  91. if version.Compare("1.7.1", gitVer, ">") {
  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. // Advanced settings
  142. EnableWiki bool `xorm:"NOT NULL DEFAULT true"`
  143. EnableIssues bool `xorm:"NOT NULL DEFAULT true"`
  144. EnableExternalTracker bool
  145. ExternalTrackerFormat string
  146. ExternalMetas map[string]string `xorm:"-"`
  147. EnablePulls bool `xorm:"NOT NULL DEFAULT true"`
  148. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  149. ForkID int64
  150. BaseRepo *Repository `xorm:"-"`
  151. Created time.Time `xorm:"CREATED"`
  152. Updated time.Time `xorm:"UPDATED"`
  153. }
  154. func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
  155. switch colName {
  156. case "num_closed_issues":
  157. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  158. case "num_closed_pulls":
  159. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  160. case "num_closed_milestones":
  161. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  162. case "updated":
  163. repo.Updated = regulateTimeZone(repo.Updated)
  164. }
  165. }
  166. func (repo *Repository) getOwner(e Engine) (err error) {
  167. if repo.Owner != nil {
  168. return nil
  169. }
  170. repo.Owner, err = getUserByID(e, repo.OwnerID)
  171. return err
  172. }
  173. func (repo *Repository) GetOwner() error {
  174. return repo.getOwner(x)
  175. }
  176. func (repo *Repository) mustOwner(e Engine) *User {
  177. if err := repo.getOwner(e); err != nil {
  178. return &User{
  179. Name: "error",
  180. FullName: err.Error(),
  181. }
  182. }
  183. return repo.Owner
  184. }
  185. // MustOwner always returns a valid *User object to avoid
  186. // conceptually impossible error handling.
  187. // It creates a fake object that contains error deftail
  188. // when error occurs.
  189. func (repo *Repository) MustOwner() *User {
  190. return repo.mustOwner(x)
  191. }
  192. // ComposeMetas composes a map of metas for rendering external issue tracker URL.
  193. func (repo *Repository) ComposeMetas() map[string]string {
  194. if !repo.EnableExternalTracker {
  195. return nil
  196. } else if repo.ExternalMetas == nil {
  197. repo.ExternalMetas = map[string]string{
  198. "format": repo.ExternalTrackerFormat,
  199. "user": repo.MustOwner().Name,
  200. "repo": repo.Name,
  201. }
  202. }
  203. return repo.ExternalMetas
  204. }
  205. // GetAssignees returns all users that have write access of repository.
  206. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  207. if err = repo.GetOwner(); err != nil {
  208. return nil, err
  209. }
  210. accesses := make([]*Access, 0, 10)
  211. if err = x.Where("repo_id=? AND mode>=?", repo.ID, ACCESS_MODE_WRITE).Find(&accesses); err != nil {
  212. return nil, err
  213. }
  214. users := make([]*User, 0, len(accesses)+1) // Just waste 1 unit does not matter.
  215. if !repo.Owner.IsOrganization() {
  216. users = append(users, repo.Owner)
  217. }
  218. var u *User
  219. for i := range accesses {
  220. u, err = GetUserByID(accesses[i].UserID)
  221. if err != nil {
  222. return nil, err
  223. }
  224. users = append(users, u)
  225. }
  226. return users, nil
  227. }
  228. // GetAssigneeByID returns the user that has write access of repository by given ID.
  229. func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
  230. return GetAssigneeByID(repo, userID)
  231. }
  232. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  233. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  234. return GetRepoMilestoneByID(repo.ID, milestoneID)
  235. }
  236. // IssueStats returns number of open and closed repository issues by given filter mode.
  237. func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int64, int64) {
  238. return GetRepoIssueStats(repo.ID, uid, filterMode, isPull)
  239. }
  240. func (repo *Repository) GetMirror() (err error) {
  241. repo.Mirror, err = GetMirror(repo.ID)
  242. return err
  243. }
  244. func (repo *Repository) GetBaseRepo() (err error) {
  245. if !repo.IsFork {
  246. return nil
  247. }
  248. repo.BaseRepo, err = GetRepositoryByID(repo.ForkID)
  249. return err
  250. }
  251. func (repo *Repository) repoPath(e Engine) string {
  252. return RepoPath(repo.mustOwner(e).Name, repo.Name)
  253. }
  254. func (repo *Repository) RepoPath() string {
  255. return repo.repoPath(x)
  256. }
  257. func (repo *Repository) GitConfigPath() string {
  258. return filepath.Join(repo.RepoPath(), "config")
  259. }
  260. func (repo *Repository) RepoLink() string {
  261. return setting.AppSubUrl + "/" + repo.MustOwner().Name + "/" + repo.Name
  262. }
  263. func (repo *Repository) FullRepoLink() string {
  264. return setting.AppUrl + repo.MustOwner().Name + "/" + repo.Name
  265. }
  266. func (repo *Repository) HasAccess(u *User) bool {
  267. has, _ := HasAccess(u, repo, ACCESS_MODE_READ)
  268. return has
  269. }
  270. func (repo *Repository) IsOwnedBy(userID int64) bool {
  271. return repo.OwnerID == userID
  272. }
  273. // CanBeForked returns true if repository meets the requirements of being forked.
  274. func (repo *Repository) CanBeForked() bool {
  275. return !repo.IsBare && !repo.IsMirror
  276. }
  277. func (repo *Repository) NextIssueIndex() int64 {
  278. return int64(repo.NumIssues+repo.NumPulls) + 1
  279. }
  280. var (
  281. DescPattern = regexp.MustCompile(`https?://\S+`)
  282. )
  283. // DescriptionHtml does special handles to description and return HTML string.
  284. func (repo *Repository) DescriptionHtml() template.HTML {
  285. sanitize := func(s string) string {
  286. return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
  287. }
  288. return template.HTML(DescPattern.ReplaceAllStringFunc(base.Sanitizer.Sanitize(repo.Description), sanitize))
  289. }
  290. func (repo *Repository) LocalCopyPath() string {
  291. return path.Join(setting.AppDataPath, "tmp/local", com.ToStr(repo.ID))
  292. }
  293. func updateLocalCopy(repoPath, localPath string) error {
  294. if !com.IsExist(localPath) {
  295. if err := git.Clone(repoPath, localPath, git.CloneRepoOptions{}); err != nil {
  296. return fmt.Errorf("Clone: %v", err)
  297. }
  298. } else {
  299. if err := git.Pull(localPath, true); err != nil {
  300. return fmt.Errorf("Pull: %v", err)
  301. }
  302. }
  303. return nil
  304. }
  305. // UpdateLocalCopy makes sure the local copy of repository is up-to-date.
  306. func (repo *Repository) UpdateLocalCopy() error {
  307. return updateLocalCopy(repo.RepoPath(), repo.LocalCopyPath())
  308. }
  309. // PatchPath returns corresponding patch file path of repository by given issue ID.
  310. func (repo *Repository) PatchPath(index int64) (string, error) {
  311. if err := repo.GetOwner(); err != nil {
  312. return "", err
  313. }
  314. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  315. }
  316. // SavePatch saves patch data to corresponding location by given issue ID.
  317. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  318. patchPath, err := repo.PatchPath(index)
  319. if err != nil {
  320. return fmt.Errorf("PatchPath: %v", err)
  321. }
  322. os.MkdirAll(filepath.Dir(patchPath), os.ModePerm)
  323. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  324. return fmt.Errorf("WriteFile: %v", err)
  325. }
  326. return nil
  327. }
  328. // ComposePayload composes and returns *api.PayloadRepo corresponding to the repository.
  329. func (repo *Repository) ComposePayload() *api.PayloadRepo {
  330. cl := repo.CloneLink()
  331. return &api.PayloadRepo{
  332. ID: repo.ID,
  333. Name: repo.LowerName,
  334. URL: repo.FullRepoLink(),
  335. SSHURL: cl.SSH,
  336. CloneURL: cl.HTTPS,
  337. Description: repo.Description,
  338. Website: repo.Website,
  339. Watchers: repo.NumWatches,
  340. Owner: &api.PayloadAuthor{
  341. Name: repo.MustOwner().DisplayName(),
  342. Email: repo.MustOwner().Email,
  343. UserName: repo.MustOwner().Name,
  344. },
  345. Private: repo.IsPrivate,
  346. }
  347. }
  348. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  349. has, err := e.Get(&Repository{
  350. OwnerID: u.Id,
  351. LowerName: strings.ToLower(repoName),
  352. })
  353. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  354. }
  355. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  356. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  357. return isRepositoryExist(x, u, repoName)
  358. }
  359. // CloneLink represents different types of clone URLs of repository.
  360. type CloneLink struct {
  361. SSH string
  362. HTTPS string
  363. Git string
  364. }
  365. func (repo *Repository) cloneLink(isWiki bool) *CloneLink {
  366. repoName := repo.Name
  367. if isWiki {
  368. repoName += ".wiki"
  369. }
  370. repo.Owner = repo.MustOwner()
  371. cl := new(CloneLink)
  372. if setting.SSHPort != 22 {
  373. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.SSHDomain, setting.SSHPort, repo.Owner.Name, repoName)
  374. } else {
  375. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.SSHDomain, repo.Owner.Name, repoName)
  376. }
  377. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.Name, repoName)
  378. return cl
  379. }
  380. // CloneLink returns clone URLs of repository.
  381. func (repo *Repository) CloneLink() (cl *CloneLink) {
  382. return repo.cloneLink(false)
  383. }
  384. var (
  385. reservedNames = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  386. reservedPatterns = []string{"*.git", "*.keys", "*.wiki"}
  387. )
  388. // IsUsableName checks if name is reserved or pattern of name is not allowed.
  389. func IsUsableName(name string) error {
  390. name = strings.TrimSpace(strings.ToLower(name))
  391. if utf8.RuneCountInString(name) == 0 {
  392. return ErrNameEmpty
  393. }
  394. for i := range reservedNames {
  395. if name == reservedNames[i] {
  396. return ErrNameReserved{name}
  397. }
  398. }
  399. for _, pat := range reservedPatterns {
  400. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  401. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  402. return ErrNamePatternNotAllowed{pat}
  403. }
  404. }
  405. return nil
  406. }
  407. // Mirror represents a mirror information of repository.
  408. type Mirror struct {
  409. ID int64 `xorm:"pk autoincr"`
  410. RepoID int64
  411. Repo *Repository `xorm:"-"`
  412. Interval int // Hour.
  413. Updated time.Time `xorm:"UPDATED"`
  414. NextUpdate time.Time
  415. address string `xorm:"-"`
  416. }
  417. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
  418. var err error
  419. switch colName {
  420. case "repo_id":
  421. m.Repo, err = GetRepositoryByID(m.RepoID)
  422. if err != nil {
  423. log.Error(3, "GetRepositoryByID[%d]: %v", m.ID, err)
  424. }
  425. }
  426. }
  427. func (m *Mirror) readAddress() {
  428. if len(m.address) > 0 {
  429. return
  430. }
  431. cfg, err := ini.Load(m.Repo.GitConfigPath())
  432. if err != nil {
  433. log.Error(4, "Load: %v", err)
  434. return
  435. }
  436. m.address = cfg.Section("remote \"origin\"").Key("url").Value()
  437. }
  438. // HandleCloneUserCredentials replaces user credentials from HTTP/HTTPS URL
  439. // with placeholder <credentials>.
  440. // It will fail for any other forms of clone addresses.
  441. func HandleCloneUserCredentials(url string, mosaics bool) string {
  442. i := strings.Index(url, "@")
  443. if i == -1 {
  444. return url
  445. }
  446. start := strings.Index(url, "://")
  447. if start == -1 {
  448. return url
  449. }
  450. if mosaics {
  451. return url[:start+3] + "<credentials>" + url[i:]
  452. }
  453. return url[:start+3] + url[i+1:]
  454. }
  455. // Address returns mirror address from Git repository config without credentials.
  456. func (m *Mirror) Address() string {
  457. m.readAddress()
  458. return HandleCloneUserCredentials(m.address, false)
  459. }
  460. // FullAddress returns mirror address from Git repository config.
  461. func (m *Mirror) FullAddress() string {
  462. m.readAddress()
  463. return m.address
  464. }
  465. // SaveAddress writes new address to Git repository config.
  466. func (m *Mirror) SaveAddress(addr string) error {
  467. configPath := m.Repo.GitConfigPath()
  468. cfg, err := ini.Load(configPath)
  469. if err != nil {
  470. return fmt.Errorf("Load: %v", err)
  471. }
  472. cfg.Section("remote \"origin\"").Key("url").SetValue(addr)
  473. return cfg.SaveToIndent(configPath, "\t")
  474. }
  475. func getMirror(e Engine, repoId int64) (*Mirror, error) {
  476. m := &Mirror{RepoID: repoId}
  477. has, err := e.Get(m)
  478. if err != nil {
  479. return nil, err
  480. } else if !has {
  481. return nil, ErrMirrorNotExist
  482. }
  483. return m, nil
  484. }
  485. // GetMirror returns mirror object by given repository ID.
  486. func GetMirror(repoId int64) (*Mirror, error) {
  487. return getMirror(x, repoId)
  488. }
  489. func updateMirror(e Engine, m *Mirror) error {
  490. _, err := e.Id(m.ID).Update(m)
  491. return err
  492. }
  493. func UpdateMirror(m *Mirror) error {
  494. return updateMirror(x, m)
  495. }
  496. func createUpdateHook(repoPath string) error {
  497. return git.SetUpdateHook(repoPath,
  498. fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+setting.AppPath+"\"", setting.CustomConf))
  499. }
  500. type MigrateRepoOptions struct {
  501. Name string
  502. Description string
  503. IsPrivate bool
  504. IsMirror bool
  505. RemoteAddr string
  506. }
  507. // MigrateRepository migrates a existing repository from other project hosting.
  508. func MigrateRepository(u *User, opts MigrateRepoOptions) (*Repository, error) {
  509. repo, err := CreateRepository(u, CreateRepoOptions{
  510. Name: opts.Name,
  511. Description: opts.Description,
  512. IsPrivate: opts.IsPrivate,
  513. IsMirror: opts.IsMirror,
  514. })
  515. if err != nil {
  516. return nil, err
  517. }
  518. // Clone to temprory path and do the init commit.
  519. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  520. os.MkdirAll(tmpDir, os.ModePerm)
  521. repoPath := RepoPath(u.Name, opts.Name)
  522. if u.IsOrganization() {
  523. t, err := u.GetOwnerTeam()
  524. if err != nil {
  525. return nil, err
  526. }
  527. repo.NumWatches = t.NumMembers
  528. } else {
  529. repo.NumWatches = 1
  530. }
  531. os.RemoveAll(repoPath)
  532. if err = git.Clone(opts.RemoteAddr, repoPath, git.CloneRepoOptions{
  533. Mirror: true,
  534. Quiet: true,
  535. Timeout: 10 * time.Minute,
  536. }); err != nil {
  537. return repo, fmt.Errorf("Clone: %v", err)
  538. }
  539. if opts.IsMirror {
  540. if _, err = x.InsertOne(&Mirror{
  541. RepoID: repo.ID,
  542. Interval: 24,
  543. NextUpdate: time.Now().Add(24 * time.Hour),
  544. }); err != nil {
  545. return repo, fmt.Errorf("InsertOne: %v", err)
  546. }
  547. repo.IsMirror = true
  548. return repo, UpdateRepository(repo, false)
  549. }
  550. if err = createUpdateHook(repoPath); err != nil {
  551. return repo, fmt.Errorf("createUpdateHook: %v", err)
  552. }
  553. // Clean up mirror info which prevents "push --all".
  554. // This also removes possible user credentials.
  555. configPath := repo.GitConfigPath()
  556. cfg, err := ini.Load(configPath)
  557. if err != nil {
  558. return repo, fmt.Errorf("open config file: %v", err)
  559. }
  560. cfg.DeleteSection("remote \"origin\"")
  561. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  562. return repo, fmt.Errorf("save config file: %v", err)
  563. }
  564. // Check if repository is empty.
  565. _, stderr, err := com.ExecCmdDir(repoPath, "git", "log", "-1")
  566. if err != nil {
  567. if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
  568. repo.IsBare = true
  569. } else {
  570. return repo, fmt.Errorf("check bare: %v - %s", err, stderr)
  571. }
  572. }
  573. // Try to get HEAD branch and set it as default branch.
  574. gitRepo, err := git.OpenRepository(repoPath)
  575. if err != nil {
  576. log.Error(4, "OpenRepository: %v", err)
  577. return repo, nil
  578. }
  579. headBranch, err := gitRepo.GetHEADBranch()
  580. if err != nil {
  581. log.Error(4, "GetHEADBranch: %v", err)
  582. return repo, nil
  583. }
  584. if headBranch != nil {
  585. repo.DefaultBranch = headBranch.Name
  586. }
  587. return repo, UpdateRepository(repo, false)
  588. }
  589. // initRepoCommit temporarily changes with work directory.
  590. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  591. var stderr string
  592. if _, stderr, err = process.ExecDir(-1,
  593. tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
  594. "git", "add", "--all"); err != nil {
  595. return fmt.Errorf("git add: %s", stderr)
  596. }
  597. if _, stderr, err = process.ExecDir(-1,
  598. tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
  599. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  600. "-m", "initial commit"); err != nil {
  601. return fmt.Errorf("git commit: %s", stderr)
  602. }
  603. if _, stderr, err = process.ExecDir(-1,
  604. tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
  605. "git", "push", "origin", "master"); err != nil {
  606. return fmt.Errorf("git push: %s", stderr)
  607. }
  608. return nil
  609. }
  610. type CreateRepoOptions struct {
  611. Name string
  612. Description string
  613. Gitignores string
  614. License string
  615. Readme string
  616. IsPrivate bool
  617. IsMirror bool
  618. AutoInit bool
  619. }
  620. func getRepoInitFile(tp, name string) ([]byte, error) {
  621. relPath := path.Join("conf", tp, name)
  622. // Use custom file when available.
  623. customPath := path.Join(setting.CustomPath, relPath)
  624. if com.IsFile(customPath) {
  625. return ioutil.ReadFile(customPath)
  626. }
  627. return bindata.Asset(relPath)
  628. }
  629. func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  630. // Clone to temprory path and do the init commit.
  631. _, stderr, err := process.Exec(
  632. fmt.Sprintf("initRepository(git clone): %s", repoPath), "git", "clone", repoPath, tmpDir)
  633. if err != nil {
  634. return fmt.Errorf("git clone: %v - %s", err, stderr)
  635. }
  636. // README
  637. data, err := getRepoInitFile("readme", opts.Readme)
  638. if err != nil {
  639. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  640. }
  641. cloneLink := repo.CloneLink()
  642. match := map[string]string{
  643. "Name": repo.Name,
  644. "Description": repo.Description,
  645. "CloneURL.SSH": cloneLink.SSH,
  646. "CloneURL.HTTPS": cloneLink.HTTPS,
  647. }
  648. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  649. []byte(com.Expand(string(data), match)), 0644); err != nil {
  650. return fmt.Errorf("write README.md: %v", err)
  651. }
  652. // .gitignore
  653. if len(opts.Gitignores) > 0 {
  654. var buf bytes.Buffer
  655. names := strings.Split(opts.Gitignores, ",")
  656. for _, name := range names {
  657. data, err = getRepoInitFile("gitignore", name)
  658. if err != nil {
  659. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  660. }
  661. buf.WriteString("# ---> " + name + "\n")
  662. buf.Write(data)
  663. buf.WriteString("\n")
  664. }
  665. if buf.Len() > 0 {
  666. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  667. return fmt.Errorf("write .gitignore: %v", err)
  668. }
  669. }
  670. }
  671. // LICENSE
  672. if len(opts.License) > 0 {
  673. data, err = getRepoInitFile("license", opts.License)
  674. if err != nil {
  675. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  676. }
  677. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  678. return fmt.Errorf("write LICENSE: %v", err)
  679. }
  680. }
  681. return nil
  682. }
  683. // InitRepository initializes README and .gitignore if needed.
  684. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) (err error) {
  685. // Somehow the directory could exist.
  686. if com.IsExist(repoPath) {
  687. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  688. }
  689. // Init bare new repository.
  690. if err = git.InitRepository(repoPath, true); err != nil {
  691. return fmt.Errorf("InitRepository: %v", err)
  692. } else if err = createUpdateHook(repoPath); err != nil {
  693. return fmt.Errorf("createUpdateHook: %v", err)
  694. }
  695. tmpDir := filepath.Join(os.TempDir(), "gogs-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  696. // Initialize repository according to user's choice.
  697. if opts.AutoInit {
  698. os.MkdirAll(tmpDir, os.ModePerm)
  699. defer os.RemoveAll(tmpDir)
  700. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  701. return fmt.Errorf("prepareRepoCommit: %v", err)
  702. }
  703. // Apply changes and commit.
  704. if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
  705. return fmt.Errorf("initRepoCommit: %v", err)
  706. }
  707. }
  708. // Re-fetch the repository from database before updating it (else it would
  709. // override changes that were done earlier with sql)
  710. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  711. return fmt.Errorf("getRepositoryByID: %v", err)
  712. }
  713. if !opts.AutoInit {
  714. repo.IsBare = true
  715. }
  716. repo.DefaultBranch = "master"
  717. if err = updateRepository(e, repo, false); err != nil {
  718. return fmt.Errorf("updateRepository: %v", err)
  719. }
  720. return nil
  721. }
  722. func createRepository(e *xorm.Session, u *User, repo *Repository) (err error) {
  723. if err = IsUsableName(repo.Name); err != nil {
  724. return err
  725. }
  726. has, err := isRepositoryExist(e, u, repo.Name)
  727. if err != nil {
  728. return fmt.Errorf("IsRepositoryExist: %v", err)
  729. } else if has {
  730. return ErrRepoAlreadyExist{u.Name, repo.Name}
  731. }
  732. if _, err = e.Insert(repo); err != nil {
  733. return err
  734. }
  735. u.NumRepos++
  736. // Remember visibility preference.
  737. u.LastRepoVisibility = repo.IsPrivate
  738. if err = updateUser(e, u); err != nil {
  739. return fmt.Errorf("updateUser: %v", err)
  740. }
  741. // Give access to all members in owner team.
  742. if u.IsOrganization() {
  743. t, err := u.getOwnerTeam(e)
  744. if err != nil {
  745. return fmt.Errorf("getOwnerTeam: %v", err)
  746. } else if err = t.addRepository(e, repo); err != nil {
  747. return fmt.Errorf("addRepository: %v", err)
  748. }
  749. } else {
  750. // Organization automatically called this in addRepository method.
  751. if err = repo.recalculateAccesses(e); err != nil {
  752. return fmt.Errorf("recalculateAccesses: %v", err)
  753. }
  754. }
  755. if err = watchRepo(e, u.Id, repo.ID, true); err != nil {
  756. return fmt.Errorf("watchRepo: %v", err)
  757. } else if err = newRepoAction(e, u, repo); err != nil {
  758. return fmt.Errorf("newRepoAction: %v", err)
  759. }
  760. return nil
  761. }
  762. // CreateRepository creates a repository for given user or organization.
  763. func CreateRepository(u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  764. repo := &Repository{
  765. OwnerID: u.Id,
  766. Owner: u,
  767. Name: opts.Name,
  768. LowerName: strings.ToLower(opts.Name),
  769. Description: opts.Description,
  770. IsPrivate: opts.IsPrivate,
  771. EnableWiki: true,
  772. EnableIssues: true,
  773. EnablePulls: true,
  774. }
  775. sess := x.NewSession()
  776. defer sessionRelease(sess)
  777. if err = sess.Begin(); err != nil {
  778. return nil, err
  779. }
  780. if err = createRepository(sess, u, repo); err != nil {
  781. return nil, err
  782. }
  783. // No need for init mirror.
  784. if !opts.IsMirror {
  785. repoPath := RepoPath(u.Name, repo.Name)
  786. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  787. if err2 := os.RemoveAll(repoPath); err2 != nil {
  788. log.Error(4, "initRepository: %v", err)
  789. return nil, fmt.Errorf(
  790. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  791. }
  792. return nil, fmt.Errorf("initRepository: %v", err)
  793. }
  794. _, stderr, err := process.ExecDir(-1,
  795. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  796. "git", "update-server-info")
  797. if err != nil {
  798. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  799. }
  800. }
  801. return repo, sess.Commit()
  802. }
  803. func countRepositories(showPrivate bool) int64 {
  804. sess := x.NewSession()
  805. if !showPrivate {
  806. sess.Where("is_private=", false)
  807. }
  808. count, _ := sess.Count(new(Repository))
  809. return count
  810. }
  811. // CountRepositories returns number of repositories.
  812. func CountRepositories() int64 {
  813. return countRepositories(true)
  814. }
  815. // CountPublicRepositories returns number of public repositories.
  816. func CountPublicRepositories() int64 {
  817. return countRepositories(false)
  818. }
  819. // RepositoriesWithUsers returns number of repos in given page.
  820. func RepositoriesWithUsers(page, pageSize int) (_ []*Repository, err error) {
  821. repos := make([]*Repository, 0, pageSize)
  822. if err = x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos); err != nil {
  823. return nil, err
  824. }
  825. for i := range repos {
  826. if err = repos[i].GetOwner(); err != nil {
  827. return nil, err
  828. }
  829. }
  830. return repos, nil
  831. }
  832. // RepoPath returns repository path by given user and repository name.
  833. func RepoPath(userName, repoName string) string {
  834. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  835. }
  836. // TransferOwnership transfers all corresponding setting from old user to new one.
  837. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  838. newOwner, err := GetUserByName(newOwnerName)
  839. if err != nil {
  840. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  841. }
  842. // Check if new owner has repository with same name.
  843. has, err := IsRepositoryExist(newOwner, repo.Name)
  844. if err != nil {
  845. return fmt.Errorf("IsRepositoryExist: %v", err)
  846. } else if has {
  847. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  848. }
  849. sess := x.NewSession()
  850. defer sessionRelease(sess)
  851. if err = sess.Begin(); err != nil {
  852. return fmt.Errorf("sess.Begin: %v", err)
  853. }
  854. owner := repo.Owner
  855. // Note: we have to set value here to make sure recalculate accesses is based on
  856. // new owner.
  857. repo.OwnerID = newOwner.Id
  858. repo.Owner = newOwner
  859. // Update repository.
  860. if _, err := sess.Id(repo.ID).Update(repo); err != nil {
  861. return fmt.Errorf("update owner: %v", err)
  862. }
  863. // Remove redundant collaborators.
  864. collaborators, err := repo.getCollaborators(sess)
  865. if err != nil {
  866. return fmt.Errorf("getCollaborators: %v", err)
  867. }
  868. // Dummy object.
  869. collaboration := &Collaboration{RepoID: repo.ID}
  870. for _, c := range collaborators {
  871. collaboration.UserID = c.Id
  872. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  873. if _, err = sess.Delete(collaboration); err != nil {
  874. return fmt.Errorf("remove collaborator '%d': %v", c.Id, err)
  875. }
  876. }
  877. }
  878. // Remove old team-repository relations.
  879. if owner.IsOrganization() {
  880. if err = owner.getTeams(sess); err != nil {
  881. return fmt.Errorf("getTeams: %v", err)
  882. }
  883. for _, t := range owner.Teams {
  884. if !t.hasRepository(sess, repo.ID) {
  885. continue
  886. }
  887. t.NumRepos--
  888. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  889. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  890. }
  891. }
  892. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  893. return fmt.Errorf("removeOrgRepo: %v", err)
  894. }
  895. }
  896. if newOwner.IsOrganization() {
  897. t, err := newOwner.getOwnerTeam(sess)
  898. if err != nil {
  899. return fmt.Errorf("getOwnerTeam: %v", err)
  900. } else if err = t.addRepository(sess, repo); err != nil {
  901. return fmt.Errorf("add to owner team: %v", err)
  902. }
  903. } else {
  904. // Organization called this in addRepository method.
  905. if err = repo.recalculateAccesses(sess); err != nil {
  906. return fmt.Errorf("recalculateAccesses: %v", err)
  907. }
  908. }
  909. // Update repository count.
  910. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.Id); err != nil {
  911. return fmt.Errorf("increase new owner repository count: %v", err)
  912. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.Id); err != nil {
  913. return fmt.Errorf("decrease old owner repository count: %v", err)
  914. }
  915. if err = watchRepo(sess, newOwner.Id, repo.ID, true); err != nil {
  916. return fmt.Errorf("watchRepo: %v", err)
  917. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  918. return fmt.Errorf("transferRepoAction: %v", err)
  919. }
  920. // Change repository directory name.
  921. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  922. return fmt.Errorf("rename repository directory: %v", err)
  923. }
  924. wikiPath := WikiPath(owner.Name, repo.Name)
  925. if com.IsExist(wikiPath) {
  926. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  927. return fmt.Errorf("rename repository wiki: %v", err)
  928. }
  929. }
  930. return sess.Commit()
  931. }
  932. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  933. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  934. oldRepoName = strings.ToLower(oldRepoName)
  935. newRepoName = strings.ToLower(newRepoName)
  936. if err = IsUsableName(newRepoName); err != nil {
  937. return err
  938. }
  939. has, err := IsRepositoryExist(u, newRepoName)
  940. if err != nil {
  941. return fmt.Errorf("IsRepositoryExist: %v", err)
  942. } else if has {
  943. return ErrRepoAlreadyExist{u.Name, newRepoName}
  944. }
  945. // Change repository directory name.
  946. if err = os.Rename(RepoPath(u.Name, oldRepoName), RepoPath(u.Name, newRepoName)); err != nil {
  947. return fmt.Errorf("rename repository directory: %v", err)
  948. }
  949. wikiPath := WikiPath(u.Name, oldRepoName)
  950. if com.IsExist(wikiPath) {
  951. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  952. return fmt.Errorf("rename repository wiki: %v", err)
  953. }
  954. }
  955. return nil
  956. }
  957. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  958. repos := make([]*Repository, 0, 10)
  959. return repos, e.Where("fork_id=?", forkID).Find(&repos)
  960. }
  961. // GetRepositoriesByForkID returns all repositories with given fork ID.
  962. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  963. return getRepositoriesByForkID(x, forkID)
  964. }
  965. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  966. repo.LowerName = strings.ToLower(repo.Name)
  967. if len(repo.Description) > 255 {
  968. repo.Description = repo.Description[:255]
  969. }
  970. if len(repo.Website) > 255 {
  971. repo.Website = repo.Website[:255]
  972. }
  973. if _, err = e.Id(repo.ID).AllCols().Update(repo); err != nil {
  974. return fmt.Errorf("update: %v", err)
  975. }
  976. if visibilityChanged {
  977. if err = repo.getOwner(e); err != nil {
  978. return fmt.Errorf("getOwner: %v", err)
  979. }
  980. if repo.Owner.IsOrganization() {
  981. // Organization repository need to recalculate access table when visivility is changed.
  982. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  983. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  984. }
  985. }
  986. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  987. if err != nil {
  988. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  989. }
  990. for i := range forkRepos {
  991. forkRepos[i].IsPrivate = repo.IsPrivate
  992. if err = updateRepository(e, forkRepos[i], true); err != nil {
  993. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  994. }
  995. }
  996. }
  997. return nil
  998. }
  999. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1000. sess := x.NewSession()
  1001. defer sessionRelease(sess)
  1002. if err = sess.Begin(); err != nil {
  1003. return err
  1004. }
  1005. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  1006. return fmt.Errorf("updateRepository: %v", err)
  1007. }
  1008. return sess.Commit()
  1009. }
  1010. // DeleteRepository deletes a repository for a user or organization.
  1011. func DeleteRepository(uid, repoID int64) error {
  1012. repo := &Repository{ID: repoID, OwnerID: uid}
  1013. has, err := x.Get(repo)
  1014. if err != nil {
  1015. return err
  1016. } else if !has {
  1017. return ErrRepoNotExist{repoID, uid, ""}
  1018. }
  1019. // In case is a organization.
  1020. org, err := GetUserByID(uid)
  1021. if err != nil {
  1022. return err
  1023. }
  1024. if org.IsOrganization() {
  1025. if err = org.GetTeams(); err != nil {
  1026. return err
  1027. }
  1028. }
  1029. sess := x.NewSession()
  1030. defer sessionRelease(sess)
  1031. if err = sess.Begin(); err != nil {
  1032. return err
  1033. }
  1034. if org.IsOrganization() {
  1035. for _, t := range org.Teams {
  1036. if !t.hasRepository(sess, repoID) {
  1037. continue
  1038. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1039. return err
  1040. }
  1041. }
  1042. }
  1043. if err = deleteBeans(sess,
  1044. &Repository{ID: repoID},
  1045. &Access{RepoID: repo.ID},
  1046. &Action{RepoID: repo.ID},
  1047. &Watch{RepoID: repoID},
  1048. &Star{RepoID: repoID},
  1049. &Mirror{RepoID: repoID},
  1050. &IssueUser{RepoID: repoID},
  1051. &Milestone{RepoID: repoID},
  1052. &Release{RepoID: repoID},
  1053. &Collaboration{RepoID: repoID},
  1054. &PullRequest{BaseRepoID: repoID},
  1055. ); err != nil {
  1056. return fmt.Errorf("deleteBeans: %v", err)
  1057. }
  1058. // Delete comments and attachments.
  1059. issues := make([]*Issue, 0, 25)
  1060. attachmentPaths := make([]string, 0, len(issues))
  1061. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  1062. return err
  1063. }
  1064. for i := range issues {
  1065. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  1066. return err
  1067. }
  1068. attachments := make([]*Attachment, 0, 5)
  1069. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  1070. return err
  1071. }
  1072. for j := range attachments {
  1073. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1074. }
  1075. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  1076. return err
  1077. }
  1078. }
  1079. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1080. return err
  1081. }
  1082. if repo.IsFork {
  1083. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1084. return fmt.Errorf("decrease fork count: %v", err)
  1085. }
  1086. }
  1087. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1088. return err
  1089. }
  1090. // Remove repository files.
  1091. repoPath := repo.repoPath(sess)
  1092. if err = os.RemoveAll(repoPath); err != nil {
  1093. desc := fmt.Sprintf("delete repository files [%s]: %v", repoPath, err)
  1094. log.Warn(desc)
  1095. if err = CreateRepositoryNotice(desc); err != nil {
  1096. log.Error(4, "CreateRepositoryNotice: %v", err)
  1097. }
  1098. }
  1099. wikiPath := repo.WikiPath()
  1100. if err = os.RemoveAll(wikiPath); err != nil {
  1101. desc := fmt.Sprintf("delete repository wiki [%s]: %v", wikiPath, err)
  1102. log.Warn(desc)
  1103. if err = CreateRepositoryNotice(desc); err != nil {
  1104. log.Error(4, "CreateRepositoryNotice: %v", err)
  1105. }
  1106. }
  1107. // Remove attachment files.
  1108. for i := range attachmentPaths {
  1109. if err = os.Remove(attachmentPaths[i]); err != nil {
  1110. log.Warn("delete attachment: %v", err)
  1111. }
  1112. }
  1113. if err = sess.Commit(); err != nil {
  1114. return fmt.Errorf("Commit: %v", err)
  1115. }
  1116. if repo.NumForks > 0 {
  1117. if repo.IsPrivate {
  1118. forkRepos, err := GetRepositoriesByForkID(repo.ID)
  1119. if err != nil {
  1120. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1121. }
  1122. for i := range forkRepos {
  1123. if err = DeleteRepository(forkRepos[i].OwnerID, forkRepos[i].ID); err != nil {
  1124. log.Error(4, "updateRepository[%d]: %v", forkRepos[i].ID, err)
  1125. }
  1126. }
  1127. } else {
  1128. if _, err = x.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1129. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  1130. }
  1131. }
  1132. }
  1133. return nil
  1134. }
  1135. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  1136. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  1137. func GetRepositoryByRef(ref string) (*Repository, error) {
  1138. n := strings.IndexByte(ref, byte('/'))
  1139. if n < 2 {
  1140. return nil, ErrInvalidReference
  1141. }
  1142. userName, repoName := ref[:n], ref[n+1:]
  1143. user, err := GetUserByName(userName)
  1144. if err != nil {
  1145. return nil, err
  1146. }
  1147. return GetRepositoryByName(user.Id, repoName)
  1148. }
  1149. // GetRepositoryByName returns the repository by given name under user if exists.
  1150. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  1151. repo := &Repository{
  1152. OwnerID: uid,
  1153. LowerName: strings.ToLower(repoName),
  1154. }
  1155. has, err := x.Get(repo)
  1156. if err != nil {
  1157. return nil, err
  1158. } else if !has {
  1159. return nil, ErrRepoNotExist{0, uid, repoName}
  1160. }
  1161. return repo, err
  1162. }
  1163. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1164. repo := new(Repository)
  1165. has, err := e.Id(id).Get(repo)
  1166. if err != nil {
  1167. return nil, err
  1168. } else if !has {
  1169. return nil, ErrRepoNotExist{id, 0, ""}
  1170. }
  1171. return repo, nil
  1172. }
  1173. // GetRepositoryByID returns the repository by given id if exists.
  1174. func GetRepositoryByID(id int64) (*Repository, error) {
  1175. return getRepositoryByID(x, id)
  1176. }
  1177. // GetRepositories returns a list of repositories of given user.
  1178. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  1179. repos := make([]*Repository, 0, 10)
  1180. sess := x.Desc("updated")
  1181. if !private {
  1182. sess.Where("is_private=?", false)
  1183. }
  1184. return repos, sess.Find(&repos, &Repository{OwnerID: uid})
  1185. }
  1186. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  1187. func GetRecentUpdatedRepositories(page int) (repos []*Repository, err error) {
  1188. return repos, x.Limit(setting.ExplorePagingNum, (page-1)*setting.ExplorePagingNum).
  1189. Where("is_private=?", false).Limit(setting.ExplorePagingNum).Desc("updated").Find(&repos)
  1190. }
  1191. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1192. return x.Count(&Repository{OwnerID: u.Id})
  1193. }
  1194. // GetRepositoryCount returns the total number of repositories of user.
  1195. func GetRepositoryCount(u *User) (int64, error) {
  1196. return getRepositoryCount(x, u)
  1197. }
  1198. type SearchOption struct {
  1199. Keyword string
  1200. Uid int64
  1201. Limit int
  1202. Private bool
  1203. }
  1204. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  1205. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  1206. if len(opt.Keyword) == 0 {
  1207. return repos, nil
  1208. }
  1209. opt.Keyword = strings.ToLower(opt.Keyword)
  1210. repos = make([]*Repository, 0, opt.Limit)
  1211. // Append conditions.
  1212. sess := x.Limit(opt.Limit)
  1213. if opt.Uid > 0 {
  1214. sess.Where("owner_id=?", opt.Uid)
  1215. }
  1216. if !opt.Private {
  1217. sess.And("is_private=?", false)
  1218. }
  1219. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  1220. return repos, err
  1221. }
  1222. // DeleteRepositoryArchives deletes all repositories' archives.
  1223. func DeleteRepositoryArchives() error {
  1224. return x.Where("id > 0").Iterate(new(Repository),
  1225. func(idx int, bean interface{}) error {
  1226. repo := bean.(*Repository)
  1227. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1228. })
  1229. }
  1230. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1231. func DeleteMissingRepositories() error {
  1232. repos := make([]*Repository, 0, 5)
  1233. if err := x.Where("id > 0").Iterate(new(Repository),
  1234. func(idx int, bean interface{}) error {
  1235. repo := bean.(*Repository)
  1236. if !com.IsDir(repo.RepoPath()) {
  1237. repos = append(repos, repo)
  1238. }
  1239. return nil
  1240. }); err != nil {
  1241. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteMissingRepositories: %v", err)); err2 != nil {
  1242. log.Error(4, "CreateRepositoryNotice: %v", err2)
  1243. }
  1244. return nil
  1245. }
  1246. if len(repos) == 0 {
  1247. return nil
  1248. }
  1249. for _, repo := range repos {
  1250. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1251. if err := DeleteRepository(repo.OwnerID, repo.ID); err != nil {
  1252. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1253. log.Error(4, "CreateRepositoryNotice: %v", err2)
  1254. }
  1255. }
  1256. }
  1257. return nil
  1258. }
  1259. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  1260. func RewriteRepositoryUpdateHook() error {
  1261. return x.Where("id > 0").Iterate(new(Repository),
  1262. func(idx int, bean interface{}) error {
  1263. repo := bean.(*Repository)
  1264. return createUpdateHook(repo.RepoPath())
  1265. })
  1266. }
  1267. // statusPool represents a pool of status with true/false.
  1268. type statusPool struct {
  1269. lock sync.RWMutex
  1270. pool map[string]bool
  1271. }
  1272. // Start sets value of given name to true in the pool.
  1273. func (p *statusPool) Start(name string) {
  1274. p.lock.Lock()
  1275. defer p.lock.Unlock()
  1276. p.pool[name] = true
  1277. }
  1278. // Stop sets value of given name to false in the pool.
  1279. func (p *statusPool) Stop(name string) {
  1280. p.lock.Lock()
  1281. defer p.lock.Unlock()
  1282. p.pool[name] = false
  1283. }
  1284. // IsRunning checks if value of given name is set to true in the pool.
  1285. func (p *statusPool) IsRunning(name string) bool {
  1286. p.lock.RLock()
  1287. defer p.lock.RUnlock()
  1288. return p.pool[name]
  1289. }
  1290. // Prevent duplicate running tasks.
  1291. var taskStatusPool = &statusPool{
  1292. pool: make(map[string]bool),
  1293. }
  1294. const (
  1295. _MIRROR_UPDATE = "mirror_update"
  1296. _GIT_FSCK = "git_fsck"
  1297. _CHECK_REPOs = "check_repos"
  1298. )
  1299. // MirrorUpdate checks and updates mirror repositories.
  1300. func MirrorUpdate() {
  1301. if taskStatusPool.IsRunning(_MIRROR_UPDATE) {
  1302. return
  1303. }
  1304. taskStatusPool.Start(_MIRROR_UPDATE)
  1305. defer taskStatusPool.Stop(_MIRROR_UPDATE)
  1306. log.Trace("Doing: MirrorUpdate")
  1307. mirrors := make([]*Mirror, 0, 10)
  1308. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  1309. m := bean.(*Mirror)
  1310. if m.NextUpdate.After(time.Now()) {
  1311. return nil
  1312. }
  1313. if m.Repo == nil {
  1314. log.Error(4, "Disconnected mirror repository found: %d", m.ID)
  1315. return nil
  1316. }
  1317. repoPath := m.Repo.RepoPath()
  1318. if _, stderr, err := process.ExecDir(10*time.Minute,
  1319. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  1320. "git", "remote", "update", "--prune"); err != nil {
  1321. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  1322. log.Error(4, desc)
  1323. if err = CreateRepositoryNotice(desc); err != nil {
  1324. log.Error(4, "CreateRepositoryNotice: %v", err)
  1325. }
  1326. return nil
  1327. }
  1328. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  1329. mirrors = append(mirrors, m)
  1330. return nil
  1331. }); err != nil {
  1332. log.Error(4, "MirrorUpdate: %v", err)
  1333. }
  1334. for i := range mirrors {
  1335. if err := UpdateMirror(mirrors[i]); err != nil {
  1336. log.Error(4, "UpdateMirror[%d]: %v", mirrors[i].ID, err)
  1337. }
  1338. }
  1339. }
  1340. // GitFsck calls 'git fsck' to check repository health.
  1341. func GitFsck() {
  1342. if taskStatusPool.IsRunning(_GIT_FSCK) {
  1343. return
  1344. }
  1345. taskStatusPool.Start(_GIT_FSCK)
  1346. defer taskStatusPool.Stop(_GIT_FSCK)
  1347. log.Trace("Doing: GitFsck")
  1348. if err := x.Where("id>0").Iterate(new(Repository),
  1349. func(idx int, bean interface{}) error {
  1350. repo := bean.(*Repository)
  1351. repoPath := repo.RepoPath()
  1352. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1353. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  1354. log.Warn(desc)
  1355. if err = CreateRepositoryNotice(desc); err != nil {
  1356. log.Error(4, "CreateRepositoryNotice: %v", err)
  1357. }
  1358. }
  1359. return nil
  1360. }); err != nil {
  1361. log.Error(4, "GitFsck: %v", err)
  1362. }
  1363. }
  1364. func GitGcRepos() error {
  1365. args := append([]string{"gc"}, setting.Git.GcArgs...)
  1366. return x.Where("id > 0").Iterate(new(Repository),
  1367. func(idx int, bean interface{}) error {
  1368. repo := bean.(*Repository)
  1369. if err := repo.GetOwner(); err != nil {
  1370. return err
  1371. }
  1372. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  1373. if err != nil {
  1374. return fmt.Errorf("%v: %v", err, stderr)
  1375. }
  1376. return nil
  1377. })
  1378. }
  1379. type repoChecker struct {
  1380. querySQL, correctSQL string
  1381. desc string
  1382. }
  1383. func repoStatsCheck(checker *repoChecker) {
  1384. results, err := x.Query(checker.querySQL)
  1385. if err != nil {
  1386. log.Error(4, "Select %s: %v", checker.desc, err)
  1387. return
  1388. }
  1389. for _, result := range results {
  1390. id := com.StrTo(result["id"]).MustInt64()
  1391. log.Trace("Updating %s: %d", checker.desc, id)
  1392. _, err = x.Exec(checker.correctSQL, id, id)
  1393. if err != nil {
  1394. log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
  1395. }
  1396. }
  1397. }
  1398. func CheckRepoStats() {
  1399. if taskStatusPool.IsRunning(_CHECK_REPOs) {
  1400. return
  1401. }
  1402. taskStatusPool.Start(_CHECK_REPOs)
  1403. defer taskStatusPool.Stop(_CHECK_REPOs)
  1404. log.Trace("Doing: CheckRepoStats")
  1405. checkers := []*repoChecker{
  1406. // Repository.NumWatches
  1407. {
  1408. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1409. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1410. "repository count 'num_watches'",
  1411. },
  1412. // Repository.NumStars
  1413. {
  1414. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1415. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1416. "repository count 'num_stars'",
  1417. },
  1418. // Label.NumIssues
  1419. {
  1420. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1421. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1422. "label count 'num_issues'",
  1423. },
  1424. // User.NumRepos
  1425. {
  1426. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1427. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1428. "user count 'num_repos'",
  1429. },
  1430. // Issue.NumComments
  1431. {
  1432. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1433. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1434. "issue count 'num_comments'",
  1435. },
  1436. }
  1437. for i := range checkers {
  1438. repoStatsCheck(checkers[i])
  1439. }
  1440. // FIXME: use checker when v0.9, stop supporting old fork repo format.
  1441. // ***** START: Repository.NumForks *****
  1442. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1443. if err != nil {
  1444. log.Error(4, "Select repository count 'num_forks': %v", err)
  1445. } else {
  1446. for _, result := range results {
  1447. id := com.StrTo(result["id"]).MustInt64()
  1448. log.Trace("Updating repository count 'num_forks': %d", id)
  1449. repo, err := GetRepositoryByID(id)
  1450. if err != nil {
  1451. log.Error(4, "GetRepositoryByID[%d]: %v", id, err)
  1452. continue
  1453. }
  1454. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1455. if err != nil {
  1456. log.Error(4, "Select count of forks[%d]: %v", repo.ID, err)
  1457. continue
  1458. }
  1459. repo.NumForks = int(parseCountResult(rawResult))
  1460. if err = UpdateRepository(repo, false); err != nil {
  1461. log.Error(4, "UpdateRepository[%d]: %v", id, err)
  1462. continue
  1463. }
  1464. }
  1465. }
  1466. // ***** END: Repository.NumForks *****
  1467. }
  1468. // _________ .__ .__ ___. __ .__
  1469. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  1470. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  1471. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  1472. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  1473. // \/ \/ \/ \/ \/
  1474. // A Collaboration is a relation between an individual and a repository
  1475. type Collaboration struct {
  1476. ID int64 `xorm:"pk autoincr"`
  1477. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1478. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1479. Created time.Time `xorm:"CREATED"`
  1480. }
  1481. // Add collaborator and accompanying access
  1482. func (repo *Repository) AddCollaborator(u *User) error {
  1483. collaboration := &Collaboration{
  1484. RepoID: repo.ID,
  1485. UserID: u.Id,
  1486. }
  1487. has, err := x.Get(collaboration)
  1488. if err != nil {
  1489. return err
  1490. } else if has {
  1491. return nil
  1492. }
  1493. if err = repo.GetOwner(); err != nil {
  1494. return fmt.Errorf("GetOwner: %v", err)
  1495. }
  1496. sess := x.NewSession()
  1497. defer sessionRelease(sess)
  1498. if err = sess.Begin(); err != nil {
  1499. return err
  1500. }
  1501. if _, err = sess.InsertOne(collaboration); err != nil {
  1502. return err
  1503. }
  1504. if repo.Owner.IsOrganization() {
  1505. err = repo.recalculateTeamAccesses(sess, 0)
  1506. } else {
  1507. err = repo.recalculateAccesses(sess)
  1508. }
  1509. if err != nil {
  1510. return fmt.Errorf("recalculateAccesses 'team=%v': %v", repo.Owner.IsOrganization(), err)
  1511. }
  1512. return sess.Commit()
  1513. }
  1514. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  1515. collaborations := make([]*Collaboration, 0)
  1516. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.ID}); err != nil {
  1517. return nil, err
  1518. }
  1519. users := make([]*User, len(collaborations))
  1520. for i, c := range collaborations {
  1521. user, err := getUserByID(e, c.UserID)
  1522. if err != nil {
  1523. return nil, err
  1524. }
  1525. users[i] = user
  1526. }
  1527. return users, nil
  1528. }
  1529. // GetCollaborators returns the collaborators for a repository
  1530. func (repo *Repository) GetCollaborators() ([]*User, error) {
  1531. return repo.getCollaborators(x)
  1532. }
  1533. // Delete collaborator and accompanying access
  1534. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  1535. collaboration := &Collaboration{
  1536. RepoID: repo.ID,
  1537. UserID: u.Id,
  1538. }
  1539. sess := x.NewSession()
  1540. defer sessionRelease(sess)
  1541. if err = sess.Begin(); err != nil {
  1542. return err
  1543. }
  1544. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  1545. return err
  1546. } else if err = repo.recalculateAccesses(sess); err != nil {
  1547. return err
  1548. }
  1549. return sess.Commit()
  1550. }
  1551. // __ __ __ .__
  1552. // / \ / \_____ _/ |_ ____ | |__
  1553. // \ \/\/ /\__ \\ __\/ ___\| | \
  1554. // \ / / __ \| | \ \___| Y \
  1555. // \__/\ / (____ /__| \___ >___| /
  1556. // \/ \/ \/ \/
  1557. // Watch is connection request for receiving repository notification.
  1558. type Watch struct {
  1559. ID int64 `xorm:"pk autoincr"`
  1560. UserID int64 `xorm:"UNIQUE(watch)"`
  1561. RepoID int64 `xorm:"UNIQUE(watch)"`
  1562. }
  1563. func isWatching(e Engine, uid, repoId int64) bool {
  1564. has, _ := e.Get(&Watch{0, uid, repoId})
  1565. return has
  1566. }
  1567. // IsWatching checks if user has watched given repository.
  1568. func IsWatching(uid, repoId int64) bool {
  1569. return isWatching(x, uid, repoId)
  1570. }
  1571. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1572. if watch {
  1573. if isWatching(e, uid, repoId) {
  1574. return nil
  1575. }
  1576. if _, err = e.Insert(&Watch{RepoID: repoId, UserID: uid}); err != nil {
  1577. return err
  1578. }
  1579. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1580. } else {
  1581. if !isWatching(e, uid, repoId) {
  1582. return nil
  1583. }
  1584. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1585. return err
  1586. }
  1587. _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", repoId)
  1588. }
  1589. return err
  1590. }
  1591. // Watch or unwatch repository.
  1592. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1593. return watchRepo(x, uid, repoId, watch)
  1594. }
  1595. func getWatchers(e Engine, repoID int64) ([]*Watch, error) {
  1596. watches := make([]*Watch, 0, 10)
  1597. return watches, e.Find(&watches, &Watch{RepoID: repoID})
  1598. }
  1599. // GetWatchers returns all watchers of given repository.
  1600. func GetWatchers(repoID int64) ([]*Watch, error) {
  1601. return getWatchers(x, repoID)
  1602. }
  1603. // Repository.GetWatchers returns range of users watching given repository.
  1604. func (repo *Repository) GetWatchers(page int) ([]*User, error) {
  1605. users := make([]*User, 0, ItemsPerPage)
  1606. return users, x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  1607. Where("repo_id=?", repo.ID).Join("LEFT", "watch", "user.id=watch.user_id").Find(&users)
  1608. }
  1609. func notifyWatchers(e Engine, act *Action) error {
  1610. // Add feeds for user self and all watchers.
  1611. watches, err := getWatchers(e, act.RepoID)
  1612. if err != nil {
  1613. return fmt.Errorf("get watchers: %v", err)
  1614. }
  1615. // Add feed for actioner.
  1616. act.UserID = act.ActUserID
  1617. if _, err = e.InsertOne(act); err != nil {
  1618. return fmt.Errorf("insert new actioner: %v", err)
  1619. }
  1620. for i := range watches {
  1621. if act.ActUserID == watches[i].UserID {
  1622. continue
  1623. }
  1624. act.ID = 0
  1625. act.UserID = watches[i].UserID
  1626. if _, err = e.InsertOne(act); err != nil {
  1627. return fmt.Errorf("insert new action: %v", err)
  1628. }
  1629. }
  1630. return nil
  1631. }
  1632. // NotifyWatchers creates batch of actions for every watcher.
  1633. func NotifyWatchers(act *Action) error {
  1634. return notifyWatchers(x, act)
  1635. }
  1636. // _________ __
  1637. // / _____// |______ _______
  1638. // \_____ \\ __\__ \\_ __ \
  1639. // / \| | / __ \| | \/
  1640. // /_______ /|__| (____ /__|
  1641. // \/ \/
  1642. type Star struct {
  1643. ID int64 `xorm:"pk autoincr"`
  1644. UID int64 `xorm:"UNIQUE(s)"`
  1645. RepoID int64 `xorm:"UNIQUE(s)"`
  1646. }
  1647. // Star or unstar repository.
  1648. func StarRepo(uid, repoId int64, star bool) (err error) {
  1649. if star {
  1650. if IsStaring(uid, repoId) {
  1651. return nil
  1652. }
  1653. if _, err = x.Insert(&Star{UID: uid, RepoID: repoId}); err != nil {
  1654. return err
  1655. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1656. return err
  1657. }
  1658. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1659. } else {
  1660. if !IsStaring(uid, repoId) {
  1661. return nil
  1662. }
  1663. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1664. return err
  1665. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1666. return err
  1667. }
  1668. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1669. }
  1670. return err
  1671. }
  1672. // IsStaring checks if user has starred given repository.
  1673. func IsStaring(uid, repoId int64) bool {
  1674. has, _ := x.Get(&Star{0, uid, repoId})
  1675. return has
  1676. }
  1677. func (repo *Repository) GetStargazers(page int) ([]*User, error) {
  1678. users := make([]*User, 0, ItemsPerPage)
  1679. return users, x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  1680. Where("repo_id=?", repo.ID).Join("LEFT", "star", "user.id=star.uid").Find(&users)
  1681. }
  1682. // ___________ __
  1683. // \_ _____/__________| | __
  1684. // | __)/ _ \_ __ \ |/ /
  1685. // | \( <_> ) | \/ <
  1686. // \___ / \____/|__| |__|_ \
  1687. // \/ \/
  1688. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1689. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1690. repo := new(Repository)
  1691. has, _ := x.Where("owner_id=? AND fork_id=?", ownerID, repoID).Get(repo)
  1692. return repo, has
  1693. }
  1694. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1695. repo := &Repository{
  1696. OwnerID: u.Id,
  1697. Owner: u,
  1698. Name: name,
  1699. LowerName: strings.ToLower(name),
  1700. Description: desc,
  1701. DefaultBranch: oldRepo.DefaultBranch,
  1702. IsPrivate: oldRepo.IsPrivate,
  1703. IsFork: true,
  1704. ForkID: oldRepo.ID,
  1705. }
  1706. sess := x.NewSession()
  1707. defer sessionRelease(sess)
  1708. if err = sess.Begin(); err != nil {
  1709. return nil, err
  1710. }
  1711. if err = createRepository(sess, u, repo); err != nil {
  1712. return nil, err
  1713. }
  1714. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  1715. return nil, err
  1716. }
  1717. repoPath := RepoPath(u.Name, repo.Name)
  1718. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1719. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1720. "git", "clone", "--bare", oldRepo.RepoPath(), repoPath)
  1721. if err != nil {
  1722. return nil, fmt.Errorf("git clone: %v", stderr)
  1723. }
  1724. _, stderr, err = process.ExecDir(-1,
  1725. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1726. "git", "update-server-info")
  1727. if err != nil {
  1728. return nil, fmt.Errorf("git update-server-info: %v", err)
  1729. }
  1730. if err = createUpdateHook(repoPath); err != nil {
  1731. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1732. }
  1733. return repo, sess.Commit()
  1734. }
  1735. func (repo *Repository) GetForks() ([]*Repository, error) {
  1736. forks := make([]*Repository, 0, repo.NumForks)
  1737. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  1738. }