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

repo.go 59KB

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