repo.go 61 KB

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