repo.go 60 KB

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