repo.go 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040
  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. if !u.CanCreateRepo() {
  768. return nil, ErrReachLimitOfRepo{u.MaxRepoCreation}
  769. }
  770. repo := &Repository{
  771. OwnerID: u.Id,
  772. Owner: u,
  773. Name: opts.Name,
  774. LowerName: strings.ToLower(opts.Name),
  775. Description: opts.Description,
  776. IsPrivate: opts.IsPrivate,
  777. EnableWiki: true,
  778. EnableIssues: true,
  779. EnablePulls: true,
  780. }
  781. sess := x.NewSession()
  782. defer sessionRelease(sess)
  783. if err = sess.Begin(); err != nil {
  784. return nil, err
  785. }
  786. if err = createRepository(sess, u, repo); err != nil {
  787. return nil, err
  788. }
  789. // No need for init mirror.
  790. if !opts.IsMirror {
  791. repoPath := RepoPath(u.Name, repo.Name)
  792. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  793. if err2 := os.RemoveAll(repoPath); err2 != nil {
  794. log.Error(4, "initRepository: %v", err)
  795. return nil, fmt.Errorf(
  796. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  797. }
  798. return nil, fmt.Errorf("initRepository: %v", err)
  799. }
  800. _, stderr, err := process.ExecDir(-1,
  801. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  802. "git", "update-server-info")
  803. if err != nil {
  804. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  805. }
  806. }
  807. return repo, sess.Commit()
  808. }
  809. func countRepositories(showPrivate bool) int64 {
  810. sess := x.NewSession()
  811. if !showPrivate {
  812. sess.Where("is_private=", false)
  813. }
  814. count, _ := sess.Count(new(Repository))
  815. return count
  816. }
  817. // CountRepositories returns number of repositories.
  818. func CountRepositories() int64 {
  819. return countRepositories(true)
  820. }
  821. // CountPublicRepositories returns number of public repositories.
  822. func CountPublicRepositories() int64 {
  823. return countRepositories(false)
  824. }
  825. // RepositoriesWithUsers returns number of repos in given page.
  826. func RepositoriesWithUsers(page, pageSize int) (_ []*Repository, err error) {
  827. repos := make([]*Repository, 0, pageSize)
  828. if err = x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos); err != nil {
  829. return nil, err
  830. }
  831. for i := range repos {
  832. if err = repos[i].GetOwner(); err != nil {
  833. return nil, err
  834. }
  835. }
  836. return repos, nil
  837. }
  838. // RepoPath returns repository path by given user and repository name.
  839. func RepoPath(userName, repoName string) string {
  840. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  841. }
  842. // TransferOwnership transfers all corresponding setting from old user to new one.
  843. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  844. newOwner, err := GetUserByName(newOwnerName)
  845. if err != nil {
  846. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  847. }
  848. // Check if new owner has repository with same name.
  849. has, err := IsRepositoryExist(newOwner, repo.Name)
  850. if err != nil {
  851. return fmt.Errorf("IsRepositoryExist: %v", err)
  852. } else if has {
  853. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  854. }
  855. sess := x.NewSession()
  856. defer sessionRelease(sess)
  857. if err = sess.Begin(); err != nil {
  858. return fmt.Errorf("sess.Begin: %v", err)
  859. }
  860. owner := repo.Owner
  861. // Note: we have to set value here to make sure recalculate accesses is based on
  862. // new owner.
  863. repo.OwnerID = newOwner.Id
  864. repo.Owner = newOwner
  865. // Update repository.
  866. if _, err := sess.Id(repo.ID).Update(repo); err != nil {
  867. return fmt.Errorf("update owner: %v", err)
  868. }
  869. // Remove redundant collaborators.
  870. collaborators, err := repo.getCollaborators(sess)
  871. if err != nil {
  872. return fmt.Errorf("getCollaborators: %v", err)
  873. }
  874. // Dummy object.
  875. collaboration := &Collaboration{RepoID: repo.ID}
  876. for _, c := range collaborators {
  877. collaboration.UserID = c.Id
  878. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  879. if _, err = sess.Delete(collaboration); err != nil {
  880. return fmt.Errorf("remove collaborator '%d': %v", c.Id, err)
  881. }
  882. }
  883. }
  884. // Remove old team-repository relations.
  885. if owner.IsOrganization() {
  886. if err = owner.getTeams(sess); err != nil {
  887. return fmt.Errorf("getTeams: %v", err)
  888. }
  889. for _, t := range owner.Teams {
  890. if !t.hasRepository(sess, repo.ID) {
  891. continue
  892. }
  893. t.NumRepos--
  894. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  895. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  896. }
  897. }
  898. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  899. return fmt.Errorf("removeOrgRepo: %v", err)
  900. }
  901. }
  902. if newOwner.IsOrganization() {
  903. t, err := newOwner.getOwnerTeam(sess)
  904. if err != nil {
  905. return fmt.Errorf("getOwnerTeam: %v", err)
  906. } else if err = t.addRepository(sess, repo); err != nil {
  907. return fmt.Errorf("add to owner team: %v", err)
  908. }
  909. } else {
  910. // Organization called this in addRepository method.
  911. if err = repo.recalculateAccesses(sess); err != nil {
  912. return fmt.Errorf("recalculateAccesses: %v", err)
  913. }
  914. }
  915. // Update repository count.
  916. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.Id); err != nil {
  917. return fmt.Errorf("increase new owner repository count: %v", err)
  918. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.Id); err != nil {
  919. return fmt.Errorf("decrease old owner repository count: %v", err)
  920. }
  921. if err = watchRepo(sess, newOwner.Id, repo.ID, true); err != nil {
  922. return fmt.Errorf("watchRepo: %v", err)
  923. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  924. return fmt.Errorf("transferRepoAction: %v", err)
  925. }
  926. // Change repository directory name.
  927. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  928. return fmt.Errorf("rename repository directory: %v", err)
  929. }
  930. wikiPath := WikiPath(owner.Name, repo.Name)
  931. if com.IsExist(wikiPath) {
  932. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  933. return fmt.Errorf("rename repository wiki: %v", err)
  934. }
  935. }
  936. return sess.Commit()
  937. }
  938. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  939. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  940. oldRepoName = strings.ToLower(oldRepoName)
  941. newRepoName = strings.ToLower(newRepoName)
  942. if err = IsUsableName(newRepoName); err != nil {
  943. return err
  944. }
  945. has, err := IsRepositoryExist(u, newRepoName)
  946. if err != nil {
  947. return fmt.Errorf("IsRepositoryExist: %v", err)
  948. } else if has {
  949. return ErrRepoAlreadyExist{u.Name, newRepoName}
  950. }
  951. // Change repository directory name.
  952. if err = os.Rename(RepoPath(u.Name, oldRepoName), RepoPath(u.Name, newRepoName)); err != nil {
  953. return fmt.Errorf("rename repository directory: %v", err)
  954. }
  955. wikiPath := WikiPath(u.Name, oldRepoName)
  956. if com.IsExist(wikiPath) {
  957. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  958. return fmt.Errorf("rename repository wiki: %v", err)
  959. }
  960. }
  961. return nil
  962. }
  963. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  964. repos := make([]*Repository, 0, 10)
  965. return repos, e.Where("fork_id=?", forkID).Find(&repos)
  966. }
  967. // GetRepositoriesByForkID returns all repositories with given fork ID.
  968. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  969. return getRepositoriesByForkID(x, forkID)
  970. }
  971. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  972. repo.LowerName = strings.ToLower(repo.Name)
  973. if len(repo.Description) > 255 {
  974. repo.Description = repo.Description[:255]
  975. }
  976. if len(repo.Website) > 255 {
  977. repo.Website = repo.Website[:255]
  978. }
  979. if _, err = e.Id(repo.ID).AllCols().Update(repo); err != nil {
  980. return fmt.Errorf("update: %v", err)
  981. }
  982. if visibilityChanged {
  983. if err = repo.getOwner(e); err != nil {
  984. return fmt.Errorf("getOwner: %v", err)
  985. }
  986. if repo.Owner.IsOrganization() {
  987. // Organization repository need to recalculate access table when visivility is changed.
  988. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  989. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  990. }
  991. }
  992. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  993. if err != nil {
  994. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  995. }
  996. for i := range forkRepos {
  997. forkRepos[i].IsPrivate = repo.IsPrivate
  998. if err = updateRepository(e, forkRepos[i], true); err != nil {
  999. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1000. }
  1001. }
  1002. }
  1003. return nil
  1004. }
  1005. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1006. sess := x.NewSession()
  1007. defer sessionRelease(sess)
  1008. if err = sess.Begin(); err != nil {
  1009. return err
  1010. }
  1011. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  1012. return fmt.Errorf("updateRepository: %v", err)
  1013. }
  1014. return sess.Commit()
  1015. }
  1016. // DeleteRepository deletes a repository for a user or organization.
  1017. func DeleteRepository(uid, repoID int64) error {
  1018. repo := &Repository{ID: repoID, OwnerID: uid}
  1019. has, err := x.Get(repo)
  1020. if err != nil {
  1021. return err
  1022. } else if !has {
  1023. return ErrRepoNotExist{repoID, uid, ""}
  1024. }
  1025. // In case is a organization.
  1026. org, err := GetUserByID(uid)
  1027. if err != nil {
  1028. return err
  1029. }
  1030. if org.IsOrganization() {
  1031. if err = org.GetTeams(); err != nil {
  1032. return err
  1033. }
  1034. }
  1035. sess := x.NewSession()
  1036. defer sessionRelease(sess)
  1037. if err = sess.Begin(); err != nil {
  1038. return err
  1039. }
  1040. if org.IsOrganization() {
  1041. for _, t := range org.Teams {
  1042. if !t.hasRepository(sess, repoID) {
  1043. continue
  1044. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1045. return err
  1046. }
  1047. }
  1048. }
  1049. if err = deleteBeans(sess,
  1050. &Repository{ID: repoID},
  1051. &Access{RepoID: repo.ID},
  1052. &Action{RepoID: repo.ID},
  1053. &Watch{RepoID: repoID},
  1054. &Star{RepoID: repoID},
  1055. &Mirror{RepoID: repoID},
  1056. &IssueUser{RepoID: repoID},
  1057. &Milestone{RepoID: repoID},
  1058. &Release{RepoID: repoID},
  1059. &Collaboration{RepoID: repoID},
  1060. &PullRequest{BaseRepoID: repoID},
  1061. ); err != nil {
  1062. return fmt.Errorf("deleteBeans: %v", err)
  1063. }
  1064. // Delete comments and attachments.
  1065. issues := make([]*Issue, 0, 25)
  1066. attachmentPaths := make([]string, 0, len(issues))
  1067. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  1068. return err
  1069. }
  1070. for i := range issues {
  1071. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  1072. return err
  1073. }
  1074. attachments := make([]*Attachment, 0, 5)
  1075. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  1076. return err
  1077. }
  1078. for j := range attachments {
  1079. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1080. }
  1081. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  1082. return err
  1083. }
  1084. }
  1085. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1086. return err
  1087. }
  1088. if repo.IsFork {
  1089. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1090. return fmt.Errorf("decrease fork count: %v", err)
  1091. }
  1092. }
  1093. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1094. return err
  1095. }
  1096. // Remove repository files.
  1097. repoPath := repo.repoPath(sess)
  1098. if err = os.RemoveAll(repoPath); err != nil {
  1099. desc := fmt.Sprintf("delete repository files [%s]: %v", repoPath, err)
  1100. log.Warn(desc)
  1101. if err = CreateRepositoryNotice(desc); err != nil {
  1102. log.Error(4, "CreateRepositoryNotice: %v", err)
  1103. }
  1104. }
  1105. wikiPath := repo.WikiPath()
  1106. if err = os.RemoveAll(wikiPath); err != nil {
  1107. desc := fmt.Sprintf("delete repository wiki [%s]: %v", wikiPath, err)
  1108. log.Warn(desc)
  1109. if err = CreateRepositoryNotice(desc); err != nil {
  1110. log.Error(4, "CreateRepositoryNotice: %v", err)
  1111. }
  1112. }
  1113. // Remove attachment files.
  1114. for i := range attachmentPaths {
  1115. if err = os.Remove(attachmentPaths[i]); err != nil {
  1116. log.Warn("delete attachment: %v", err)
  1117. }
  1118. }
  1119. if err = sess.Commit(); err != nil {
  1120. return fmt.Errorf("Commit: %v", err)
  1121. }
  1122. if repo.NumForks > 0 {
  1123. if repo.IsPrivate {
  1124. forkRepos, err := GetRepositoriesByForkID(repo.ID)
  1125. if err != nil {
  1126. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1127. }
  1128. for i := range forkRepos {
  1129. if err = DeleteRepository(forkRepos[i].OwnerID, forkRepos[i].ID); err != nil {
  1130. log.Error(4, "updateRepository[%d]: %v", forkRepos[i].ID, err)
  1131. }
  1132. }
  1133. } else {
  1134. if _, err = x.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1135. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  1136. }
  1137. }
  1138. }
  1139. return nil
  1140. }
  1141. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  1142. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  1143. func GetRepositoryByRef(ref string) (*Repository, error) {
  1144. n := strings.IndexByte(ref, byte('/'))
  1145. if n < 2 {
  1146. return nil, ErrInvalidReference
  1147. }
  1148. userName, repoName := ref[:n], ref[n+1:]
  1149. user, err := GetUserByName(userName)
  1150. if err != nil {
  1151. return nil, err
  1152. }
  1153. return GetRepositoryByName(user.Id, repoName)
  1154. }
  1155. // GetRepositoryByName returns the repository by given name under user if exists.
  1156. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  1157. repo := &Repository{
  1158. OwnerID: uid,
  1159. LowerName: strings.ToLower(repoName),
  1160. }
  1161. has, err := x.Get(repo)
  1162. if err != nil {
  1163. return nil, err
  1164. } else if !has {
  1165. return nil, ErrRepoNotExist{0, uid, repoName}
  1166. }
  1167. return repo, err
  1168. }
  1169. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1170. repo := new(Repository)
  1171. has, err := e.Id(id).Get(repo)
  1172. if err != nil {
  1173. return nil, err
  1174. } else if !has {
  1175. return nil, ErrRepoNotExist{id, 0, ""}
  1176. }
  1177. return repo, nil
  1178. }
  1179. // GetRepositoryByID returns the repository by given id if exists.
  1180. func GetRepositoryByID(id int64) (*Repository, error) {
  1181. return getRepositoryByID(x, id)
  1182. }
  1183. // GetRepositories returns a list of repositories of given user.
  1184. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  1185. repos := make([]*Repository, 0, 10)
  1186. sess := x.Desc("updated")
  1187. if !private {
  1188. sess.Where("is_private=?", false)
  1189. }
  1190. return repos, sess.Find(&repos, &Repository{OwnerID: uid})
  1191. }
  1192. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  1193. func GetRecentUpdatedRepositories(page int) (repos []*Repository, err error) {
  1194. return repos, x.Limit(setting.ExplorePagingNum, (page-1)*setting.ExplorePagingNum).
  1195. Where("is_private=?", false).Limit(setting.ExplorePagingNum).Desc("updated").Find(&repos)
  1196. }
  1197. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1198. return x.Count(&Repository{OwnerID: u.Id})
  1199. }
  1200. // GetRepositoryCount returns the total number of repositories of user.
  1201. func GetRepositoryCount(u *User) (int64, error) {
  1202. return getRepositoryCount(x, u)
  1203. }
  1204. type SearchOption struct {
  1205. Keyword string
  1206. Uid int64
  1207. Limit int
  1208. Private bool
  1209. }
  1210. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  1211. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  1212. if len(opt.Keyword) == 0 {
  1213. return repos, nil
  1214. }
  1215. opt.Keyword = strings.ToLower(opt.Keyword)
  1216. repos = make([]*Repository, 0, opt.Limit)
  1217. // Append conditions.
  1218. sess := x.Limit(opt.Limit)
  1219. if opt.Uid > 0 {
  1220. sess.Where("owner_id=?", opt.Uid)
  1221. }
  1222. if !opt.Private {
  1223. sess.And("is_private=?", false)
  1224. }
  1225. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  1226. return repos, err
  1227. }
  1228. // DeleteRepositoryArchives deletes all repositories' archives.
  1229. func DeleteRepositoryArchives() error {
  1230. return x.Where("id > 0").Iterate(new(Repository),
  1231. func(idx int, bean interface{}) error {
  1232. repo := bean.(*Repository)
  1233. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1234. })
  1235. }
  1236. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1237. func DeleteMissingRepositories() error {
  1238. repos := make([]*Repository, 0, 5)
  1239. if err := x.Where("id > 0").Iterate(new(Repository),
  1240. func(idx int, bean interface{}) error {
  1241. repo := bean.(*Repository)
  1242. if !com.IsDir(repo.RepoPath()) {
  1243. repos = append(repos, repo)
  1244. }
  1245. return nil
  1246. }); err != nil {
  1247. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteMissingRepositories: %v", err)); err2 != nil {
  1248. log.Error(4, "CreateRepositoryNotice: %v", err2)
  1249. }
  1250. return nil
  1251. }
  1252. if len(repos) == 0 {
  1253. return nil
  1254. }
  1255. for _, repo := range repos {
  1256. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1257. if err := DeleteRepository(repo.OwnerID, repo.ID); err != nil {
  1258. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1259. log.Error(4, "CreateRepositoryNotice: %v", err2)
  1260. }
  1261. }
  1262. }
  1263. return nil
  1264. }
  1265. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  1266. func RewriteRepositoryUpdateHook() error {
  1267. return x.Where("id > 0").Iterate(new(Repository),
  1268. func(idx int, bean interface{}) error {
  1269. repo := bean.(*Repository)
  1270. return createUpdateHook(repo.RepoPath())
  1271. })
  1272. }
  1273. // statusPool represents a pool of status with true/false.
  1274. type statusPool struct {
  1275. lock sync.RWMutex
  1276. pool map[string]bool
  1277. }
  1278. // Start sets value of given name to true in the pool.
  1279. func (p *statusPool) Start(name string) {
  1280. p.lock.Lock()
  1281. defer p.lock.Unlock()
  1282. p.pool[name] = true
  1283. }
  1284. // Stop sets value of given name to false in the pool.
  1285. func (p *statusPool) Stop(name string) {
  1286. p.lock.Lock()
  1287. defer p.lock.Unlock()
  1288. p.pool[name] = false
  1289. }
  1290. // IsRunning checks if value of given name is set to true in the pool.
  1291. func (p *statusPool) IsRunning(name string) bool {
  1292. p.lock.RLock()
  1293. defer p.lock.RUnlock()
  1294. return p.pool[name]
  1295. }
  1296. // Prevent duplicate running tasks.
  1297. var taskStatusPool = &statusPool{
  1298. pool: make(map[string]bool),
  1299. }
  1300. const (
  1301. _MIRROR_UPDATE = "mirror_update"
  1302. _GIT_FSCK = "git_fsck"
  1303. _CHECK_REPOs = "check_repos"
  1304. )
  1305. // MirrorUpdate checks and updates mirror repositories.
  1306. func MirrorUpdate() {
  1307. if taskStatusPool.IsRunning(_MIRROR_UPDATE) {
  1308. return
  1309. }
  1310. taskStatusPool.Start(_MIRROR_UPDATE)
  1311. defer taskStatusPool.Stop(_MIRROR_UPDATE)
  1312. log.Trace("Doing: MirrorUpdate")
  1313. mirrors := make([]*Mirror, 0, 10)
  1314. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  1315. m := bean.(*Mirror)
  1316. if m.NextUpdate.After(time.Now()) {
  1317. return nil
  1318. }
  1319. if m.Repo == nil {
  1320. log.Error(4, "Disconnected mirror repository found: %d", m.ID)
  1321. return nil
  1322. }
  1323. repoPath := m.Repo.RepoPath()
  1324. if _, stderr, err := process.ExecDir(10*time.Minute,
  1325. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  1326. "git", "remote", "update", "--prune"); err != nil {
  1327. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  1328. log.Error(4, desc)
  1329. if err = CreateRepositoryNotice(desc); err != nil {
  1330. log.Error(4, "CreateRepositoryNotice: %v", err)
  1331. }
  1332. return nil
  1333. }
  1334. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  1335. mirrors = append(mirrors, m)
  1336. return nil
  1337. }); err != nil {
  1338. log.Error(4, "MirrorUpdate: %v", err)
  1339. }
  1340. for i := range mirrors {
  1341. if err := UpdateMirror(mirrors[i]); err != nil {
  1342. log.Error(4, "UpdateMirror[%d]: %v", mirrors[i].ID, err)
  1343. }
  1344. }
  1345. }
  1346. // GitFsck calls 'git fsck' to check repository health.
  1347. func GitFsck() {
  1348. if taskStatusPool.IsRunning(_GIT_FSCK) {
  1349. return
  1350. }
  1351. taskStatusPool.Start(_GIT_FSCK)
  1352. defer taskStatusPool.Stop(_GIT_FSCK)
  1353. log.Trace("Doing: GitFsck")
  1354. if err := x.Where("id>0").Iterate(new(Repository),
  1355. func(idx int, bean interface{}) error {
  1356. repo := bean.(*Repository)
  1357. repoPath := repo.RepoPath()
  1358. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1359. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  1360. log.Warn(desc)
  1361. if err = CreateRepositoryNotice(desc); err != nil {
  1362. log.Error(4, "CreateRepositoryNotice: %v", err)
  1363. }
  1364. }
  1365. return nil
  1366. }); err != nil {
  1367. log.Error(4, "GitFsck: %v", err)
  1368. }
  1369. }
  1370. func GitGcRepos() error {
  1371. args := append([]string{"gc"}, setting.Git.GcArgs...)
  1372. return x.Where("id > 0").Iterate(new(Repository),
  1373. func(idx int, bean interface{}) error {
  1374. repo := bean.(*Repository)
  1375. if err := repo.GetOwner(); err != nil {
  1376. return err
  1377. }
  1378. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  1379. if err != nil {
  1380. return fmt.Errorf("%v: %v", err, stderr)
  1381. }
  1382. return nil
  1383. })
  1384. }
  1385. type repoChecker struct {
  1386. querySQL, correctSQL string
  1387. desc string
  1388. }
  1389. func repoStatsCheck(checker *repoChecker) {
  1390. results, err := x.Query(checker.querySQL)
  1391. if err != nil {
  1392. log.Error(4, "Select %s: %v", checker.desc, err)
  1393. return
  1394. }
  1395. for _, result := range results {
  1396. id := com.StrTo(result["id"]).MustInt64()
  1397. log.Trace("Updating %s: %d", checker.desc, id)
  1398. _, err = x.Exec(checker.correctSQL, id, id)
  1399. if err != nil {
  1400. log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
  1401. }
  1402. }
  1403. }
  1404. func CheckRepoStats() {
  1405. if taskStatusPool.IsRunning(_CHECK_REPOs) {
  1406. return
  1407. }
  1408. taskStatusPool.Start(_CHECK_REPOs)
  1409. defer taskStatusPool.Stop(_CHECK_REPOs)
  1410. log.Trace("Doing: CheckRepoStats")
  1411. checkers := []*repoChecker{
  1412. // Repository.NumWatches
  1413. {
  1414. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1415. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1416. "repository count 'num_watches'",
  1417. },
  1418. // Repository.NumStars
  1419. {
  1420. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1421. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1422. "repository count 'num_stars'",
  1423. },
  1424. // Label.NumIssues
  1425. {
  1426. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1427. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1428. "label count 'num_issues'",
  1429. },
  1430. // User.NumRepos
  1431. {
  1432. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1433. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1434. "user count 'num_repos'",
  1435. },
  1436. // Issue.NumComments
  1437. {
  1438. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1439. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1440. "issue count 'num_comments'",
  1441. },
  1442. }
  1443. for i := range checkers {
  1444. repoStatsCheck(checkers[i])
  1445. }
  1446. // FIXME: use checker when v0.9, stop supporting old fork repo format.
  1447. // ***** START: Repository.NumForks *****
  1448. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1449. if err != nil {
  1450. log.Error(4, "Select repository count 'num_forks': %v", err)
  1451. } else {
  1452. for _, result := range results {
  1453. id := com.StrTo(result["id"]).MustInt64()
  1454. log.Trace("Updating repository count 'num_forks': %d", id)
  1455. repo, err := GetRepositoryByID(id)
  1456. if err != nil {
  1457. log.Error(4, "GetRepositoryByID[%d]: %v", id, err)
  1458. continue
  1459. }
  1460. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1461. if err != nil {
  1462. log.Error(4, "Select count of forks[%d]: %v", repo.ID, err)
  1463. continue
  1464. }
  1465. repo.NumForks = int(parseCountResult(rawResult))
  1466. if err = UpdateRepository(repo, false); err != nil {
  1467. log.Error(4, "UpdateRepository[%d]: %v", id, err)
  1468. continue
  1469. }
  1470. }
  1471. }
  1472. // ***** END: Repository.NumForks *****
  1473. }
  1474. // _________ .__ .__ ___. __ .__
  1475. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  1476. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  1477. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  1478. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  1479. // \/ \/ \/ \/ \/
  1480. // A Collaboration is a relation between an individual and a repository
  1481. type Collaboration struct {
  1482. ID int64 `xorm:"pk autoincr"`
  1483. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1484. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1485. Created time.Time `xorm:"CREATED"`
  1486. }
  1487. // Add collaborator and accompanying access
  1488. func (repo *Repository) AddCollaborator(u *User) error {
  1489. collaboration := &Collaboration{
  1490. RepoID: repo.ID,
  1491. UserID: u.Id,
  1492. }
  1493. has, err := x.Get(collaboration)
  1494. if err != nil {
  1495. return err
  1496. } else if has {
  1497. return nil
  1498. }
  1499. if err = repo.GetOwner(); err != nil {
  1500. return fmt.Errorf("GetOwner: %v", err)
  1501. }
  1502. sess := x.NewSession()
  1503. defer sessionRelease(sess)
  1504. if err = sess.Begin(); err != nil {
  1505. return err
  1506. }
  1507. if _, err = sess.InsertOne(collaboration); err != nil {
  1508. return err
  1509. }
  1510. if repo.Owner.IsOrganization() {
  1511. err = repo.recalculateTeamAccesses(sess, 0)
  1512. } else {
  1513. err = repo.recalculateAccesses(sess)
  1514. }
  1515. if err != nil {
  1516. return fmt.Errorf("recalculateAccesses 'team=%v': %v", repo.Owner.IsOrganization(), err)
  1517. }
  1518. return sess.Commit()
  1519. }
  1520. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  1521. collaborations := make([]*Collaboration, 0)
  1522. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.ID}); err != nil {
  1523. return nil, err
  1524. }
  1525. users := make([]*User, len(collaborations))
  1526. for i, c := range collaborations {
  1527. user, err := getUserByID(e, c.UserID)
  1528. if err != nil {
  1529. return nil, err
  1530. }
  1531. users[i] = user
  1532. }
  1533. return users, nil
  1534. }
  1535. // GetCollaborators returns the collaborators for a repository
  1536. func (repo *Repository) GetCollaborators() ([]*User, error) {
  1537. return repo.getCollaborators(x)
  1538. }
  1539. // Delete collaborator and accompanying access
  1540. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  1541. collaboration := &Collaboration{
  1542. RepoID: repo.ID,
  1543. UserID: u.Id,
  1544. }
  1545. sess := x.NewSession()
  1546. defer sessionRelease(sess)
  1547. if err = sess.Begin(); err != nil {
  1548. return err
  1549. }
  1550. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  1551. return err
  1552. } else if err = repo.recalculateAccesses(sess); err != nil {
  1553. return err
  1554. }
  1555. return sess.Commit()
  1556. }
  1557. // __ __ __ .__
  1558. // / \ / \_____ _/ |_ ____ | |__
  1559. // \ \/\/ /\__ \\ __\/ ___\| | \
  1560. // \ / / __ \| | \ \___| Y \
  1561. // \__/\ / (____ /__| \___ >___| /
  1562. // \/ \/ \/ \/
  1563. // Watch is connection request for receiving repository notification.
  1564. type Watch struct {
  1565. ID int64 `xorm:"pk autoincr"`
  1566. UserID int64 `xorm:"UNIQUE(watch)"`
  1567. RepoID int64 `xorm:"UNIQUE(watch)"`
  1568. }
  1569. func isWatching(e Engine, uid, repoId int64) bool {
  1570. has, _ := e.Get(&Watch{0, uid, repoId})
  1571. return has
  1572. }
  1573. // IsWatching checks if user has watched given repository.
  1574. func IsWatching(uid, repoId int64) bool {
  1575. return isWatching(x, uid, repoId)
  1576. }
  1577. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1578. if watch {
  1579. if isWatching(e, uid, repoId) {
  1580. return nil
  1581. }
  1582. if _, err = e.Insert(&Watch{RepoID: repoId, UserID: uid}); err != nil {
  1583. return err
  1584. }
  1585. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1586. } else {
  1587. if !isWatching(e, uid, repoId) {
  1588. return nil
  1589. }
  1590. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1591. return err
  1592. }
  1593. _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", repoId)
  1594. }
  1595. return err
  1596. }
  1597. // Watch or unwatch repository.
  1598. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1599. return watchRepo(x, uid, repoId, watch)
  1600. }
  1601. func getWatchers(e Engine, repoID int64) ([]*Watch, error) {
  1602. watches := make([]*Watch, 0, 10)
  1603. return watches, e.Find(&watches, &Watch{RepoID: repoID})
  1604. }
  1605. // GetWatchers returns all watchers of given repository.
  1606. func GetWatchers(repoID int64) ([]*Watch, error) {
  1607. return getWatchers(x, repoID)
  1608. }
  1609. // Repository.GetWatchers returns range of users watching given repository.
  1610. func (repo *Repository) GetWatchers(page int) ([]*User, error) {
  1611. users := make([]*User, 0, ItemsPerPage)
  1612. return users, x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  1613. Where("repo_id=?", repo.ID).Join("LEFT", "watch", "user.id=watch.user_id").Find(&users)
  1614. }
  1615. func notifyWatchers(e Engine, act *Action) error {
  1616. // Add feeds for user self and all watchers.
  1617. watches, err := getWatchers(e, act.RepoID)
  1618. if err != nil {
  1619. return fmt.Errorf("get watchers: %v", err)
  1620. }
  1621. // Add feed for actioner.
  1622. act.UserID = act.ActUserID
  1623. if _, err = e.InsertOne(act); err != nil {
  1624. return fmt.Errorf("insert new actioner: %v", err)
  1625. }
  1626. for i := range watches {
  1627. if act.ActUserID == watches[i].UserID {
  1628. continue
  1629. }
  1630. act.ID = 0
  1631. act.UserID = watches[i].UserID
  1632. if _, err = e.InsertOne(act); err != nil {
  1633. return fmt.Errorf("insert new action: %v", err)
  1634. }
  1635. }
  1636. return nil
  1637. }
  1638. // NotifyWatchers creates batch of actions for every watcher.
  1639. func NotifyWatchers(act *Action) error {
  1640. return notifyWatchers(x, act)
  1641. }
  1642. // _________ __
  1643. // / _____// |______ _______
  1644. // \_____ \\ __\__ \\_ __ \
  1645. // / \| | / __ \| | \/
  1646. // /_______ /|__| (____ /__|
  1647. // \/ \/
  1648. type Star struct {
  1649. ID int64 `xorm:"pk autoincr"`
  1650. UID int64 `xorm:"UNIQUE(s)"`
  1651. RepoID int64 `xorm:"UNIQUE(s)"`
  1652. }
  1653. // Star or unstar repository.
  1654. func StarRepo(uid, repoId int64, star bool) (err error) {
  1655. if star {
  1656. if IsStaring(uid, repoId) {
  1657. return nil
  1658. }
  1659. if _, err = x.Insert(&Star{UID: uid, RepoID: repoId}); err != nil {
  1660. return err
  1661. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1662. return err
  1663. }
  1664. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1665. } else {
  1666. if !IsStaring(uid, repoId) {
  1667. return nil
  1668. }
  1669. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1670. return err
  1671. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1672. return err
  1673. }
  1674. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1675. }
  1676. return err
  1677. }
  1678. // IsStaring checks if user has starred given repository.
  1679. func IsStaring(uid, repoId int64) bool {
  1680. has, _ := x.Get(&Star{0, uid, repoId})
  1681. return has
  1682. }
  1683. func (repo *Repository) GetStargazers(page int) ([]*User, error) {
  1684. users := make([]*User, 0, ItemsPerPage)
  1685. return users, x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  1686. Where("repo_id=?", repo.ID).Join("LEFT", "star", "user.id=star.uid").Find(&users)
  1687. }
  1688. // ___________ __
  1689. // \_ _____/__________| | __
  1690. // | __)/ _ \_ __ \ |/ /
  1691. // | \( <_> ) | \/ <
  1692. // \___ / \____/|__| |__|_ \
  1693. // \/ \/
  1694. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1695. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1696. repo := new(Repository)
  1697. has, _ := x.Where("owner_id=? AND fork_id=?", ownerID, repoID).Get(repo)
  1698. return repo, has
  1699. }
  1700. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1701. repo := &Repository{
  1702. OwnerID: u.Id,
  1703. Owner: u,
  1704. Name: name,
  1705. LowerName: strings.ToLower(name),
  1706. Description: desc,
  1707. DefaultBranch: oldRepo.DefaultBranch,
  1708. IsPrivate: oldRepo.IsPrivate,
  1709. IsFork: true,
  1710. ForkID: oldRepo.ID,
  1711. }
  1712. sess := x.NewSession()
  1713. defer sessionRelease(sess)
  1714. if err = sess.Begin(); err != nil {
  1715. return nil, err
  1716. }
  1717. if err = createRepository(sess, u, repo); err != nil {
  1718. return nil, err
  1719. }
  1720. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  1721. return nil, err
  1722. }
  1723. repoPath := RepoPath(u.Name, repo.Name)
  1724. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1725. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1726. "git", "clone", "--bare", oldRepo.RepoPath(), repoPath)
  1727. if err != nil {
  1728. return nil, fmt.Errorf("git clone: %v", stderr)
  1729. }
  1730. _, stderr, err = process.ExecDir(-1,
  1731. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1732. "git", "update-server-info")
  1733. if err != nil {
  1734. return nil, fmt.Errorf("git update-server-info: %v", err)
  1735. }
  1736. if err = createUpdateHook(repoPath); err != nil {
  1737. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1738. }
  1739. return repo, sess.Commit()
  1740. }
  1741. func (repo *Repository) GetForks() ([]*Repository, error) {
  1742. forks := make([]*Repository, 0, repo.NumForks)
  1743. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  1744. }