repo.go 61 KB

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