repo.go 56 KB

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