You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 56 kB

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