repo.go 56 KB

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