You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 56 kB

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