repo.go 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466
  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 db
  5. import (
  6. "bytes"
  7. "fmt"
  8. "image"
  9. _ "image/jpeg"
  10. "image/png"
  11. "io/ioutil"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "sort"
  17. "strings"
  18. "time"
  19. "github.com/mcuadros/go-version"
  20. "github.com/nfnt/resize"
  21. "github.com/unknwon/cae/zip"
  22. "github.com/unknwon/com"
  23. log "gopkg.in/clog.v1"
  24. "gopkg.in/ini.v1"
  25. "xorm.io/xorm"
  26. "github.com/gogs/git-module"
  27. api "github.com/gogs/go-gogs-client"
  28. "gogs.io/gogs/internal/assets/conf"
  29. "gogs.io/gogs/internal/avatar"
  30. "gogs.io/gogs/internal/db/errors"
  31. "gogs.io/gogs/internal/markup"
  32. "gogs.io/gogs/internal/osutil"
  33. "gogs.io/gogs/internal/process"
  34. "gogs.io/gogs/internal/setting"
  35. "gogs.io/gogs/internal/sync"
  36. )
  37. // REPO_AVATAR_URL_PREFIX is used to identify a URL is to access repository avatar.
  38. const REPO_AVATAR_URL_PREFIX = "repo-avatars"
  39. var repoWorkingPool = sync.NewExclusivePool()
  40. var (
  41. Gitignores, Licenses, Readmes, LabelTemplates []string
  42. // Maximum items per page in forks, watchers and stars of a repo
  43. ItemsPerPage = 40
  44. )
  45. func LoadRepoConfig() {
  46. // Load .gitignore and license files and readme templates.
  47. types := []string{"gitignore", "license", "readme", "label"}
  48. typeFiles := make([][]string, 4)
  49. for i, t := range types {
  50. files, err := conf.AssetDir("conf/" + t)
  51. if err != nil {
  52. log.Fatal(4, "Fail to get %s files: %v", t, err)
  53. }
  54. customPath := path.Join(setting.CustomPath, "conf", t)
  55. if com.IsDir(customPath) {
  56. customFiles, err := com.StatDir(customPath)
  57. if err != nil {
  58. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  59. }
  60. for _, f := range customFiles {
  61. if !com.IsSliceContainsStr(files, f) {
  62. files = append(files, f)
  63. }
  64. }
  65. }
  66. typeFiles[i] = files
  67. }
  68. Gitignores = typeFiles[0]
  69. Licenses = typeFiles[1]
  70. Readmes = typeFiles[2]
  71. LabelTemplates = typeFiles[3]
  72. sort.Strings(Gitignores)
  73. sort.Strings(Licenses)
  74. sort.Strings(Readmes)
  75. sort.Strings(LabelTemplates)
  76. // Filter out invalid names and promote preferred licenses.
  77. sortedLicenses := make([]string, 0, len(Licenses))
  78. for _, name := range setting.Repository.PreferredLicenses {
  79. if com.IsSliceContainsStr(Licenses, name) {
  80. sortedLicenses = append(sortedLicenses, name)
  81. }
  82. }
  83. for _, name := range Licenses {
  84. if !com.IsSliceContainsStr(setting.Repository.PreferredLicenses, name) {
  85. sortedLicenses = append(sortedLicenses, name)
  86. }
  87. }
  88. Licenses = sortedLicenses
  89. }
  90. func NewRepoContext() {
  91. zip.Verbose = false
  92. // Check Git installation.
  93. if _, err := exec.LookPath("git"); err != nil {
  94. log.Fatal(2, "Failed to test 'git' command: %v (forgotten install?)", err)
  95. }
  96. // Check Git version.
  97. var err error
  98. setting.Git.Version, err = git.BinVersion()
  99. if err != nil {
  100. log.Fatal(2, "Failed to get Git version: %v", err)
  101. }
  102. log.Info("Git version: %s", setting.Git.Version)
  103. if version.Compare("1.8.3", setting.Git.Version, ">") {
  104. log.Fatal(2, "Gogs requires Git version greater or equal to 1.8.3")
  105. }
  106. git.HookDir = "custom_hooks"
  107. git.HookSampleDir = "hooks"
  108. git.DefaultCommitsPageSize = setting.UI.User.CommitsPagingNum
  109. // Git requires setting user.name and user.email in order to commit changes.
  110. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogs@fake.local"} {
  111. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  112. // ExitError indicates this config is not set
  113. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  114. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  115. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  116. }
  117. log.Info("Git config %s set to %s", configKey, defaultValue)
  118. } else {
  119. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  120. }
  121. }
  122. }
  123. // Set git some configurations.
  124. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  125. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  126. log.Fatal(2, "Fail to execute 'git config --global core.quotepath false': %v - %s", err, stderr)
  127. }
  128. RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp"))
  129. }
  130. // Repository contains information of a repository.
  131. type Repository struct {
  132. ID int64
  133. OwnerID int64 `xorm:"UNIQUE(s)"`
  134. Owner *User `xorm:"-" json:"-"`
  135. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  136. Name string `xorm:"INDEX NOT NULL"`
  137. Description string `xorm:"VARCHAR(512)"`
  138. Website string
  139. DefaultBranch string
  140. Size int64 `xorm:"NOT NULL DEFAULT 0"`
  141. UseCustomAvatar bool
  142. // Counters
  143. NumWatches int
  144. NumStars int
  145. NumForks int
  146. NumIssues int
  147. NumClosedIssues int
  148. NumOpenIssues int `xorm:"-" json:"-"`
  149. NumPulls int
  150. NumClosedPulls int
  151. NumOpenPulls int `xorm:"-" json:"-"`
  152. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  153. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  154. NumOpenMilestones int `xorm:"-" json:"-"`
  155. NumTags int `xorm:"-" json:"-"`
  156. IsPrivate bool
  157. IsBare bool
  158. IsMirror bool
  159. *Mirror `xorm:"-" json:"-"`
  160. // Advanced settings
  161. EnableWiki bool `xorm:"NOT NULL DEFAULT true"`
  162. AllowPublicWiki bool
  163. EnableExternalWiki bool
  164. ExternalWikiURL string
  165. EnableIssues bool `xorm:"NOT NULL DEFAULT true"`
  166. AllowPublicIssues bool
  167. EnableExternalTracker bool
  168. ExternalTrackerURL string
  169. ExternalTrackerFormat string
  170. ExternalTrackerStyle string
  171. ExternalMetas map[string]string `xorm:"-" json:"-"`
  172. EnablePulls bool `xorm:"NOT NULL DEFAULT true"`
  173. PullsIgnoreWhitespace bool `xorm:"NOT NULL DEFAULT false"`
  174. PullsAllowRebase bool `xorm:"NOT NULL DEFAULT false"`
  175. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  176. ForkID int64
  177. BaseRepo *Repository `xorm:"-" json:"-"`
  178. Created time.Time `xorm:"-" json:"-"`
  179. CreatedUnix int64
  180. Updated time.Time `xorm:"-" json:"-"`
  181. UpdatedUnix int64
  182. }
  183. func (repo *Repository) BeforeInsert() {
  184. repo.CreatedUnix = time.Now().Unix()
  185. repo.UpdatedUnix = repo.CreatedUnix
  186. }
  187. func (repo *Repository) BeforeUpdate() {
  188. repo.UpdatedUnix = time.Now().Unix()
  189. }
  190. func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
  191. switch colName {
  192. case "default_branch":
  193. // FIXME: use db migration to solve all at once.
  194. if len(repo.DefaultBranch) == 0 {
  195. repo.DefaultBranch = "master"
  196. }
  197. case "num_closed_issues":
  198. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  199. case "num_closed_pulls":
  200. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  201. case "num_closed_milestones":
  202. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  203. case "external_tracker_style":
  204. if len(repo.ExternalTrackerStyle) == 0 {
  205. repo.ExternalTrackerStyle = markup.ISSUE_NAME_STYLE_NUMERIC
  206. }
  207. case "created_unix":
  208. repo.Created = time.Unix(repo.CreatedUnix, 0).Local()
  209. case "updated_unix":
  210. repo.Updated = time.Unix(repo.UpdatedUnix, 0)
  211. }
  212. }
  213. func (repo *Repository) loadAttributes(e Engine) (err error) {
  214. if repo.Owner == nil {
  215. repo.Owner, err = getUserByID(e, repo.OwnerID)
  216. if err != nil {
  217. return fmt.Errorf("getUserByID [%d]: %v", repo.OwnerID, err)
  218. }
  219. }
  220. if repo.IsFork && repo.BaseRepo == nil {
  221. repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID)
  222. if err != nil {
  223. if errors.IsRepoNotExist(err) {
  224. repo.IsFork = false
  225. repo.ForkID = 0
  226. } else {
  227. return fmt.Errorf("getRepositoryByID [%d]: %v", repo.ForkID, err)
  228. }
  229. }
  230. }
  231. return nil
  232. }
  233. func (repo *Repository) LoadAttributes() error {
  234. return repo.loadAttributes(x)
  235. }
  236. // IsPartialPublic returns true if repository is public or allow public access to wiki or issues.
  237. func (repo *Repository) IsPartialPublic() bool {
  238. return !repo.IsPrivate || repo.AllowPublicWiki || repo.AllowPublicIssues
  239. }
  240. func (repo *Repository) CanGuestViewWiki() bool {
  241. return repo.EnableWiki && !repo.EnableExternalWiki && repo.AllowPublicWiki
  242. }
  243. func (repo *Repository) CanGuestViewIssues() bool {
  244. return repo.EnableIssues && !repo.EnableExternalTracker && repo.AllowPublicIssues
  245. }
  246. // MustOwner always returns a valid *User object to avoid conceptually impossible error handling.
  247. // It creates a fake object that contains error deftail when error occurs.
  248. func (repo *Repository) MustOwner() *User {
  249. return repo.mustOwner(x)
  250. }
  251. func (repo *Repository) FullName() string {
  252. return repo.MustOwner().Name + "/" + repo.Name
  253. }
  254. func (repo *Repository) HTMLURL() string {
  255. return setting.AppURL + repo.FullName()
  256. }
  257. // CustomAvatarPath returns repository custom avatar file path.
  258. func (repo *Repository) CustomAvatarPath() string {
  259. return filepath.Join(setting.RepositoryAvatarUploadPath, com.ToStr(repo.ID))
  260. }
  261. // RelAvatarLink returns relative avatar link to the site domain,
  262. // which includes app sub-url as prefix.
  263. // Since Gravatar support not needed here - just check for image path.
  264. func (repo *Repository) RelAvatarLink() string {
  265. defaultImgUrl := ""
  266. if !com.IsExist(repo.CustomAvatarPath()) {
  267. return defaultImgUrl
  268. }
  269. return fmt.Sprintf("%s/%s/%d", setting.AppSubURL, REPO_AVATAR_URL_PREFIX, repo.ID)
  270. }
  271. // AvatarLink returns repository avatar absolute link.
  272. func (repo *Repository) AvatarLink() string {
  273. link := repo.RelAvatarLink()
  274. if link[0] == '/' && link[1] != '/' {
  275. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  276. }
  277. return link
  278. }
  279. // UploadAvatar saves custom avatar for repository.
  280. // FIXME: split uploads to different subdirs in case we have massive number of repositories.
  281. func (repo *Repository) UploadAvatar(data []byte) error {
  282. img, _, err := image.Decode(bytes.NewReader(data))
  283. if err != nil {
  284. return fmt.Errorf("decode image: %v", err)
  285. }
  286. os.MkdirAll(setting.RepositoryAvatarUploadPath, os.ModePerm)
  287. fw, err := os.Create(repo.CustomAvatarPath())
  288. if err != nil {
  289. return fmt.Errorf("create custom avatar directory: %v", err)
  290. }
  291. defer fw.Close()
  292. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  293. if err = png.Encode(fw, m); err != nil {
  294. return fmt.Errorf("encode image: %v", err)
  295. }
  296. return nil
  297. }
  298. // DeleteAvatar deletes the repository custom avatar.
  299. func (repo *Repository) DeleteAvatar() error {
  300. log.Trace("DeleteAvatar [%d]: %s", repo.ID, repo.CustomAvatarPath())
  301. if err := os.Remove(repo.CustomAvatarPath()); err != nil {
  302. return err
  303. }
  304. repo.UseCustomAvatar = false
  305. return UpdateRepository(repo, false)
  306. }
  307. // This method assumes following fields have been assigned with valid values:
  308. // Required - BaseRepo (if fork)
  309. // Arguments that are allowed to be nil: permission
  310. func (repo *Repository) APIFormat(permission *api.Permission, user ...*User) *api.Repository {
  311. cloneLink := repo.CloneLink()
  312. apiRepo := &api.Repository{
  313. ID: repo.ID,
  314. Owner: repo.Owner.APIFormat(),
  315. Name: repo.Name,
  316. FullName: repo.FullName(),
  317. Description: repo.Description,
  318. Private: repo.IsPrivate,
  319. Fork: repo.IsFork,
  320. Empty: repo.IsBare,
  321. Mirror: repo.IsMirror,
  322. Size: repo.Size,
  323. HTMLURL: repo.HTMLURL(),
  324. SSHURL: cloneLink.SSH,
  325. CloneURL: cloneLink.HTTPS,
  326. Website: repo.Website,
  327. Stars: repo.NumStars,
  328. Forks: repo.NumForks,
  329. Watchers: repo.NumWatches,
  330. OpenIssues: repo.NumOpenIssues,
  331. DefaultBranch: repo.DefaultBranch,
  332. Created: repo.Created,
  333. Updated: repo.Updated,
  334. Permissions: permission,
  335. // Reserved for go-gogs-client change
  336. // AvatarUrl: repo.AvatarLink(),
  337. }
  338. if repo.IsFork {
  339. p := &api.Permission{Pull: true}
  340. if len(user) != 0 {
  341. p.Admin = user[0].IsAdminOfRepo(repo)
  342. p.Push = user[0].IsWriterOfRepo(repo)
  343. }
  344. apiRepo.Parent = repo.BaseRepo.APIFormat(p)
  345. }
  346. return apiRepo
  347. }
  348. func (repo *Repository) getOwner(e Engine) (err error) {
  349. if repo.Owner != nil {
  350. return nil
  351. }
  352. repo.Owner, err = getUserByID(e, repo.OwnerID)
  353. return err
  354. }
  355. func (repo *Repository) GetOwner() error {
  356. return repo.getOwner(x)
  357. }
  358. func (repo *Repository) mustOwner(e Engine) *User {
  359. if err := repo.getOwner(e); err != nil {
  360. return &User{
  361. Name: "error",
  362. FullName: err.Error(),
  363. }
  364. }
  365. return repo.Owner
  366. }
  367. func (repo *Repository) UpdateSize() error {
  368. countObject, err := git.GetRepoSize(repo.RepoPath())
  369. if err != nil {
  370. return fmt.Errorf("GetRepoSize: %v", err)
  371. }
  372. repo.Size = countObject.Size + countObject.SizePack
  373. if _, err = x.Id(repo.ID).Cols("size").Update(repo); err != nil {
  374. return fmt.Errorf("update size: %v", err)
  375. }
  376. return nil
  377. }
  378. // ComposeMetas composes a map of metas for rendering external issue tracker URL.
  379. func (repo *Repository) ComposeMetas() map[string]string {
  380. if !repo.EnableExternalTracker {
  381. return nil
  382. } else if repo.ExternalMetas == nil {
  383. repo.ExternalMetas = map[string]string{
  384. "format": repo.ExternalTrackerFormat,
  385. "user": repo.MustOwner().Name,
  386. "repo": repo.Name,
  387. }
  388. switch repo.ExternalTrackerStyle {
  389. case markup.ISSUE_NAME_STYLE_ALPHANUMERIC:
  390. repo.ExternalMetas["style"] = markup.ISSUE_NAME_STYLE_ALPHANUMERIC
  391. default:
  392. repo.ExternalMetas["style"] = markup.ISSUE_NAME_STYLE_NUMERIC
  393. }
  394. }
  395. return repo.ExternalMetas
  396. }
  397. // DeleteWiki removes the actual and local copy of repository wiki.
  398. func (repo *Repository) DeleteWiki() {
  399. wikiPaths := []string{repo.WikiPath(), repo.LocalWikiPath()}
  400. for _, wikiPath := range wikiPaths {
  401. RemoveAllWithNotice("Delete repository wiki", wikiPath)
  402. }
  403. }
  404. // getUsersWithAccesMode returns users that have at least given access mode to the repository.
  405. func (repo *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*User, err error) {
  406. if err = repo.getOwner(e); err != nil {
  407. return nil, err
  408. }
  409. accesses := make([]*Access, 0, 10)
  410. if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil {
  411. return nil, err
  412. }
  413. // Leave a seat for owner itself to append later, but if owner is an organization
  414. // and just waste 1 unit is cheaper than re-allocate memory once.
  415. users := make([]*User, 0, len(accesses)+1)
  416. if len(accesses) > 0 {
  417. userIDs := make([]int64, len(accesses))
  418. for i := 0; i < len(accesses); i++ {
  419. userIDs[i] = accesses[i].UserID
  420. }
  421. if err = e.In("id", userIDs).Find(&users); err != nil {
  422. return nil, err
  423. }
  424. }
  425. if !repo.Owner.IsOrganization() {
  426. users = append(users, repo.Owner)
  427. }
  428. return users, nil
  429. }
  430. // getAssignees returns a list of users who can be assigned to issues in this repository.
  431. func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
  432. return repo.getUsersWithAccesMode(e, ACCESS_MODE_READ)
  433. }
  434. // GetAssignees returns all users that have read access and can be assigned to issues
  435. // of the repository,
  436. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  437. return repo.getAssignees(x)
  438. }
  439. // GetAssigneeByID returns the user that has write access of repository by given ID.
  440. func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
  441. return GetAssigneeByID(repo, userID)
  442. }
  443. // GetWriters returns all users that have write access to the repository.
  444. func (repo *Repository) GetWriters() (_ []*User, err error) {
  445. return repo.getUsersWithAccesMode(x, ACCESS_MODE_WRITE)
  446. }
  447. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  448. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  449. return GetMilestoneByRepoID(repo.ID, milestoneID)
  450. }
  451. // IssueStats returns number of open and closed repository issues by given filter mode.
  452. func (repo *Repository) IssueStats(userID int64, filterMode FilterMode, isPull bool) (int64, int64) {
  453. return GetRepoIssueStats(repo.ID, userID, filterMode, isPull)
  454. }
  455. func (repo *Repository) GetMirror() (err error) {
  456. repo.Mirror, err = GetMirrorByRepoID(repo.ID)
  457. return err
  458. }
  459. func (repo *Repository) repoPath(e Engine) string {
  460. return RepoPath(repo.mustOwner(e).Name, repo.Name)
  461. }
  462. func (repo *Repository) RepoPath() string {
  463. return repo.repoPath(x)
  464. }
  465. func (repo *Repository) GitConfigPath() string {
  466. return filepath.Join(repo.RepoPath(), "config")
  467. }
  468. func (repo *Repository) RelLink() string {
  469. return "/" + repo.FullName()
  470. }
  471. func (repo *Repository) Link() string {
  472. return setting.AppSubURL + "/" + repo.FullName()
  473. }
  474. func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
  475. return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
  476. }
  477. func (repo *Repository) HasAccess(userID int64) bool {
  478. has, _ := HasAccess(userID, repo, ACCESS_MODE_READ)
  479. return has
  480. }
  481. func (repo *Repository) IsOwnedBy(userID int64) bool {
  482. return repo.OwnerID == userID
  483. }
  484. // CanBeForked returns true if repository meets the requirements of being forked.
  485. func (repo *Repository) CanBeForked() bool {
  486. return !repo.IsBare
  487. }
  488. // CanEnablePulls returns true if repository meets the requirements of accepting pulls.
  489. func (repo *Repository) CanEnablePulls() bool {
  490. return !repo.IsMirror && !repo.IsBare
  491. }
  492. // AllowPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
  493. func (repo *Repository) AllowsPulls() bool {
  494. return repo.CanEnablePulls() && repo.EnablePulls
  495. }
  496. func (repo *Repository) IsBranchRequirePullRequest(name string) bool {
  497. return IsBranchOfRepoRequirePullRequest(repo.ID, name)
  498. }
  499. // CanEnableEditor returns true if repository meets the requirements of web editor.
  500. func (repo *Repository) CanEnableEditor() bool {
  501. return !repo.IsMirror
  502. }
  503. // FIXME: should have a mutex to prevent producing same index for two issues that are created
  504. // closely enough.
  505. func (repo *Repository) NextIssueIndex() int64 {
  506. return int64(repo.NumIssues+repo.NumPulls) + 1
  507. }
  508. func (repo *Repository) LocalCopyPath() string {
  509. return path.Join(setting.AppDataPath, "tmp/local-repo", com.ToStr(repo.ID))
  510. }
  511. // UpdateLocalCopy fetches latest changes of given branch from repoPath to localPath.
  512. // It creates a new clone if local copy does not exist, but does not checks out to a
  513. // specific branch if the local copy belongs to a wiki.
  514. // For existing local copy, it checks out to target branch by default, and safe to
  515. // assume subsequent operations are against target branch when caller has confidence
  516. // about no race condition.
  517. func UpdateLocalCopyBranch(repoPath, localPath, branch string, isWiki bool) (err error) {
  518. if !com.IsExist(localPath) {
  519. // Checkout to a specific branch fails when wiki is an empty repository.
  520. if isWiki {
  521. branch = ""
  522. }
  523. if err = git.Clone(repoPath, localPath, git.CloneRepoOptions{
  524. Timeout: time.Duration(setting.Git.Timeout.Clone) * time.Second,
  525. Branch: branch,
  526. }); err != nil {
  527. return fmt.Errorf("git clone %s: %v", branch, err)
  528. }
  529. } else {
  530. if err = git.Fetch(localPath, git.FetchRemoteOptions{
  531. Prune: true,
  532. }); err != nil {
  533. return fmt.Errorf("git fetch: %v", err)
  534. }
  535. if err = git.Checkout(localPath, git.CheckoutOptions{
  536. Branch: branch,
  537. }); err != nil {
  538. return fmt.Errorf("git checkout %s: %v", branch, err)
  539. }
  540. // Reset to align with remote in case of force push.
  541. if err = git.ResetHEAD(localPath, true, "origin/"+branch); err != nil {
  542. return fmt.Errorf("git reset --hard origin/%s: %v", branch, err)
  543. }
  544. }
  545. return nil
  546. }
  547. // UpdateLocalCopyBranch makes sure local copy of repository in given branch is up-to-date.
  548. func (repo *Repository) UpdateLocalCopyBranch(branch string) error {
  549. return UpdateLocalCopyBranch(repo.RepoPath(), repo.LocalCopyPath(), branch, false)
  550. }
  551. // PatchPath returns corresponding patch file path of repository by given issue ID.
  552. func (repo *Repository) PatchPath(index int64) (string, error) {
  553. if err := repo.GetOwner(); err != nil {
  554. return "", err
  555. }
  556. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  557. }
  558. // SavePatch saves patch data to corresponding location by given issue ID.
  559. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  560. patchPath, err := repo.PatchPath(index)
  561. if err != nil {
  562. return fmt.Errorf("PatchPath: %v", err)
  563. }
  564. os.MkdirAll(filepath.Dir(patchPath), os.ModePerm)
  565. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  566. return fmt.Errorf("WriteFile: %v", err)
  567. }
  568. return nil
  569. }
  570. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  571. has, err := e.Get(&Repository{
  572. OwnerID: u.ID,
  573. LowerName: strings.ToLower(repoName),
  574. })
  575. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  576. }
  577. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  578. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  579. return isRepositoryExist(x, u, repoName)
  580. }
  581. // CloneLink represents different types of clone URLs of repository.
  582. type CloneLink struct {
  583. SSH string
  584. HTTPS string
  585. Git string
  586. }
  587. // ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name.
  588. func ComposeHTTPSCloneURL(owner, repo string) string {
  589. return fmt.Sprintf("%s%s/%s.git", setting.AppURL, owner, repo)
  590. }
  591. func (repo *Repository) cloneLink(isWiki bool) *CloneLink {
  592. repoName := repo.Name
  593. if isWiki {
  594. repoName += ".wiki"
  595. }
  596. repo.Owner = repo.MustOwner()
  597. cl := new(CloneLink)
  598. if setting.SSH.Port != 22 {
  599. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.SSH.Domain, setting.SSH.Port, repo.Owner.Name, repoName)
  600. } else {
  601. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  602. }
  603. cl.HTTPS = ComposeHTTPSCloneURL(repo.Owner.Name, repoName)
  604. return cl
  605. }
  606. // CloneLink returns clone URLs of repository.
  607. func (repo *Repository) CloneLink() (cl *CloneLink) {
  608. return repo.cloneLink(false)
  609. }
  610. type MigrateRepoOptions struct {
  611. Name string
  612. Description string
  613. IsPrivate bool
  614. IsMirror bool
  615. RemoteAddr string
  616. }
  617. /*
  618. GitHub, GitLab, Gogs: *.wiki.git
  619. BitBucket: *.git/wiki
  620. */
  621. var commonWikiURLSuffixes = []string{".wiki.git", ".git/wiki"}
  622. // wikiRemoteURL returns accessible repository URL for wiki if exists.
  623. // Otherwise, it returns an empty string.
  624. func wikiRemoteURL(remote string) string {
  625. remote = strings.TrimSuffix(remote, ".git")
  626. for _, suffix := range commonWikiURLSuffixes {
  627. wikiURL := remote + suffix
  628. if git.IsRepoURLAccessible(git.NetworkOptions{
  629. URL: wikiURL,
  630. }) {
  631. return wikiURL
  632. }
  633. }
  634. return ""
  635. }
  636. // MigrateRepository migrates a existing repository from other project hosting.
  637. func MigrateRepository(doer, owner *User, opts MigrateRepoOptions) (*Repository, error) {
  638. repo, err := CreateRepository(doer, owner, CreateRepoOptions{
  639. Name: opts.Name,
  640. Description: opts.Description,
  641. IsPrivate: opts.IsPrivate,
  642. IsMirror: opts.IsMirror,
  643. })
  644. if err != nil {
  645. return nil, err
  646. }
  647. repoPath := RepoPath(owner.Name, opts.Name)
  648. wikiPath := WikiPath(owner.Name, opts.Name)
  649. if owner.IsOrganization() {
  650. t, err := owner.GetOwnerTeam()
  651. if err != nil {
  652. return nil, err
  653. }
  654. repo.NumWatches = t.NumMembers
  655. } else {
  656. repo.NumWatches = 1
  657. }
  658. migrateTimeout := time.Duration(setting.Git.Timeout.Migrate) * time.Second
  659. RemoveAllWithNotice("Repository path erase before creation", repoPath)
  660. if err = git.Clone(opts.RemoteAddr, repoPath, git.CloneRepoOptions{
  661. Mirror: true,
  662. Quiet: true,
  663. Timeout: migrateTimeout,
  664. }); err != nil {
  665. return repo, fmt.Errorf("Clone: %v", err)
  666. }
  667. wikiRemotePath := wikiRemoteURL(opts.RemoteAddr)
  668. if len(wikiRemotePath) > 0 {
  669. RemoveAllWithNotice("Repository wiki path erase before creation", wikiPath)
  670. if err = git.Clone(wikiRemotePath, wikiPath, git.CloneRepoOptions{
  671. Mirror: true,
  672. Quiet: true,
  673. Timeout: migrateTimeout,
  674. }); err != nil {
  675. log.Trace("Fail to clone wiki: %v", err)
  676. RemoveAllWithNotice("Delete repository wiki for initialization failure", wikiPath)
  677. }
  678. }
  679. // Check if repository is empty.
  680. _, stderr, err := com.ExecCmdDir(repoPath, "git", "log", "-1")
  681. if err != nil {
  682. if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
  683. repo.IsBare = true
  684. } else {
  685. return repo, fmt.Errorf("check bare: %v - %s", err, stderr)
  686. }
  687. }
  688. if !repo.IsBare {
  689. // Try to get HEAD branch and set it as default branch.
  690. gitRepo, err := git.OpenRepository(repoPath)
  691. if err != nil {
  692. return repo, fmt.Errorf("OpenRepository: %v", err)
  693. }
  694. headBranch, err := gitRepo.GetHEADBranch()
  695. if err != nil {
  696. return repo, fmt.Errorf("GetHEADBranch: %v", err)
  697. }
  698. if headBranch != nil {
  699. repo.DefaultBranch = headBranch.Name
  700. }
  701. if err = repo.UpdateSize(); err != nil {
  702. log.Error(2, "UpdateSize [repo_id: %d]: %v", repo.ID, err)
  703. }
  704. }
  705. if opts.IsMirror {
  706. if _, err = x.InsertOne(&Mirror{
  707. RepoID: repo.ID,
  708. Interval: setting.Mirror.DefaultInterval,
  709. EnablePrune: true,
  710. NextSync: time.Now().Add(time.Duration(setting.Mirror.DefaultInterval) * time.Hour),
  711. }); err != nil {
  712. return repo, fmt.Errorf("InsertOne: %v", err)
  713. }
  714. repo.IsMirror = true
  715. return repo, UpdateRepository(repo, false)
  716. }
  717. return CleanUpMigrateInfo(repo)
  718. }
  719. // cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
  720. // This also removes possible user credentials.
  721. func cleanUpMigrateGitConfig(configPath string) error {
  722. cfg, err := ini.Load(configPath)
  723. if err != nil {
  724. return fmt.Errorf("open config file: %v", err)
  725. }
  726. cfg.DeleteSection("remote \"origin\"")
  727. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  728. return fmt.Errorf("save config file: %v", err)
  729. }
  730. return nil
  731. }
  732. var hooksTpls = map[string]string{
  733. "pre-receive": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n",
  734. "update": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n",
  735. "post-receive": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n",
  736. }
  737. func createDelegateHooks(repoPath string) (err error) {
  738. for _, name := range git.HookNames {
  739. hookPath := filepath.Join(repoPath, "hooks", name)
  740. if err = ioutil.WriteFile(hookPath,
  741. []byte(fmt.Sprintf(hooksTpls[name], setting.ScriptType, setting.AppPath, setting.CustomConf)),
  742. os.ModePerm); err != nil {
  743. return fmt.Errorf("create delegate hook '%s': %v", hookPath, err)
  744. }
  745. }
  746. return nil
  747. }
  748. // Finish migrating repository and/or wiki with things that don't need to be done for mirrors.
  749. func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
  750. repoPath := repo.RepoPath()
  751. if err := createDelegateHooks(repoPath); err != nil {
  752. return repo, fmt.Errorf("createDelegateHooks: %v", err)
  753. }
  754. if repo.HasWiki() {
  755. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  756. return repo, fmt.Errorf("createDelegateHooks.(wiki): %v", err)
  757. }
  758. }
  759. if err := cleanUpMigrateGitConfig(repo.GitConfigPath()); err != nil {
  760. return repo, fmt.Errorf("cleanUpMigrateGitConfig: %v", err)
  761. }
  762. if repo.HasWiki() {
  763. if err := cleanUpMigrateGitConfig(path.Join(repo.WikiPath(), "config")); err != nil {
  764. return repo, fmt.Errorf("cleanUpMigrateGitConfig.(wiki): %v", err)
  765. }
  766. }
  767. return repo, UpdateRepository(repo, false)
  768. }
  769. // initRepoCommit temporarily changes with work directory.
  770. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  771. var stderr string
  772. if _, stderr, err = process.ExecDir(-1,
  773. tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
  774. "git", "add", "--all"); err != nil {
  775. return fmt.Errorf("git add: %s", stderr)
  776. }
  777. if _, stderr, err = process.ExecDir(-1,
  778. tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
  779. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  780. "-m", "Initial commit"); err != nil {
  781. return fmt.Errorf("git commit: %s", stderr)
  782. }
  783. if _, stderr, err = process.ExecDir(-1,
  784. tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
  785. "git", "push", "origin", "master"); err != nil {
  786. return fmt.Errorf("git push: %s", stderr)
  787. }
  788. return nil
  789. }
  790. type CreateRepoOptions struct {
  791. Name string
  792. Description string
  793. Gitignores string
  794. License string
  795. Readme string
  796. IsPrivate bool
  797. IsMirror bool
  798. AutoInit bool
  799. }
  800. func getRepoInitFile(tp, name string) ([]byte, error) {
  801. relPath := path.Join("conf", tp, strings.TrimLeft(path.Clean("/"+name), "/"))
  802. // Use custom file when available.
  803. customPath := path.Join(setting.CustomPath, relPath)
  804. if osutil.IsFile(customPath) {
  805. return ioutil.ReadFile(customPath)
  806. }
  807. return conf.Asset(relPath)
  808. }
  809. func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  810. // Clone to temprory path and do the init commit.
  811. _, stderr, err := process.Exec(
  812. fmt.Sprintf("initRepository(git clone): %s", repoPath), "git", "clone", repoPath, tmpDir)
  813. if err != nil {
  814. return fmt.Errorf("git clone: %v - %s", err, stderr)
  815. }
  816. // README
  817. data, err := getRepoInitFile("readme", opts.Readme)
  818. if err != nil {
  819. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  820. }
  821. cloneLink := repo.CloneLink()
  822. match := map[string]string{
  823. "Name": repo.Name,
  824. "Description": repo.Description,
  825. "CloneURL.SSH": cloneLink.SSH,
  826. "CloneURL.HTTPS": cloneLink.HTTPS,
  827. }
  828. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  829. []byte(com.Expand(string(data), match)), 0644); err != nil {
  830. return fmt.Errorf("write README.md: %v", err)
  831. }
  832. // .gitignore
  833. if len(opts.Gitignores) > 0 {
  834. var buf bytes.Buffer
  835. names := strings.Split(opts.Gitignores, ",")
  836. for _, name := range names {
  837. data, err = getRepoInitFile("gitignore", name)
  838. if err != nil {
  839. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  840. }
  841. buf.WriteString("# ---> " + name + "\n")
  842. buf.Write(data)
  843. buf.WriteString("\n")
  844. }
  845. if buf.Len() > 0 {
  846. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  847. return fmt.Errorf("write .gitignore: %v", err)
  848. }
  849. }
  850. }
  851. // LICENSE
  852. if len(opts.License) > 0 {
  853. data, err = getRepoInitFile("license", opts.License)
  854. if err != nil {
  855. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  856. }
  857. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  858. return fmt.Errorf("write LICENSE: %v", err)
  859. }
  860. }
  861. return nil
  862. }
  863. // initRepository performs initial commit with chosen setup files on behave of doer.
  864. func initRepository(e Engine, repoPath string, doer *User, repo *Repository, opts CreateRepoOptions) (err error) {
  865. // Somehow the directory could exist.
  866. if com.IsExist(repoPath) {
  867. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  868. }
  869. // Init bare new repository.
  870. if err = git.InitRepository(repoPath, true); err != nil {
  871. return fmt.Errorf("InitRepository: %v", err)
  872. } else if err = createDelegateHooks(repoPath); err != nil {
  873. return fmt.Errorf("createDelegateHooks: %v", err)
  874. }
  875. tmpDir := filepath.Join(os.TempDir(), "gogs-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  876. // Initialize repository according to user's choice.
  877. if opts.AutoInit {
  878. os.MkdirAll(tmpDir, os.ModePerm)
  879. defer RemoveAllWithNotice("Delete repository for auto-initialization", tmpDir)
  880. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  881. return fmt.Errorf("prepareRepoCommit: %v", err)
  882. }
  883. // Apply changes and commit.
  884. if err = initRepoCommit(tmpDir, doer.NewGitSig()); err != nil {
  885. return fmt.Errorf("initRepoCommit: %v", err)
  886. }
  887. }
  888. // Re-fetch the repository from database before updating it (else it would
  889. // override changes that were done earlier with sql)
  890. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  891. return fmt.Errorf("getRepositoryByID: %v", err)
  892. }
  893. if !opts.AutoInit {
  894. repo.IsBare = true
  895. }
  896. repo.DefaultBranch = "master"
  897. if err = updateRepository(e, repo, false); err != nil {
  898. return fmt.Errorf("updateRepository: %v", err)
  899. }
  900. return nil
  901. }
  902. var (
  903. reservedRepoNames = []string{".", ".."}
  904. reservedRepoPatterns = []string{"*.git", "*.wiki"}
  905. )
  906. // IsUsableRepoName return an error if given name is a reserved name or pattern.
  907. func IsUsableRepoName(name string) error {
  908. return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
  909. }
  910. func createRepository(e *xorm.Session, doer, owner *User, repo *Repository) (err error) {
  911. if err = IsUsableRepoName(repo.Name); err != nil {
  912. return err
  913. }
  914. has, err := isRepositoryExist(e, owner, repo.Name)
  915. if err != nil {
  916. return fmt.Errorf("IsRepositoryExist: %v", err)
  917. } else if has {
  918. return ErrRepoAlreadyExist{owner.Name, repo.Name}
  919. }
  920. if _, err = e.Insert(repo); err != nil {
  921. return err
  922. }
  923. owner.NumRepos++
  924. // Remember visibility preference.
  925. owner.LastRepoVisibility = repo.IsPrivate
  926. if err = updateUser(e, owner); err != nil {
  927. return fmt.Errorf("updateUser: %v", err)
  928. }
  929. // Give access to all members in owner team.
  930. if owner.IsOrganization() {
  931. t, err := owner.getOwnerTeam(e)
  932. if err != nil {
  933. return fmt.Errorf("getOwnerTeam: %v", err)
  934. } else if err = t.addRepository(e, repo); err != nil {
  935. return fmt.Errorf("addRepository: %v", err)
  936. }
  937. } else {
  938. // Organization automatically called this in addRepository method.
  939. if err = repo.recalculateAccesses(e); err != nil {
  940. return fmt.Errorf("recalculateAccesses: %v", err)
  941. }
  942. }
  943. if err = watchRepo(e, owner.ID, repo.ID, true); err != nil {
  944. return fmt.Errorf("watchRepo: %v", err)
  945. } else if err = newRepoAction(e, doer, owner, repo); err != nil {
  946. return fmt.Errorf("newRepoAction: %v", err)
  947. }
  948. return repo.loadAttributes(e)
  949. }
  950. // CreateRepository creates a repository for given user or organization.
  951. func CreateRepository(doer, owner *User, opts CreateRepoOptions) (_ *Repository, err error) {
  952. if !owner.CanCreateRepo() {
  953. return nil, errors.ReachLimitOfRepo{owner.RepoCreationNum()}
  954. }
  955. repo := &Repository{
  956. OwnerID: owner.ID,
  957. Owner: owner,
  958. Name: opts.Name,
  959. LowerName: strings.ToLower(opts.Name),
  960. Description: opts.Description,
  961. IsPrivate: opts.IsPrivate,
  962. EnableWiki: true,
  963. EnableIssues: true,
  964. EnablePulls: true,
  965. }
  966. sess := x.NewSession()
  967. defer sess.Close()
  968. if err = sess.Begin(); err != nil {
  969. return nil, err
  970. }
  971. if err = createRepository(sess, doer, owner, repo); err != nil {
  972. return nil, err
  973. }
  974. // No need for init mirror.
  975. if !opts.IsMirror {
  976. repoPath := RepoPath(owner.Name, repo.Name)
  977. if err = initRepository(sess, repoPath, doer, repo, opts); err != nil {
  978. RemoveAllWithNotice("Delete repository for initialization failure", repoPath)
  979. return nil, fmt.Errorf("initRepository: %v", err)
  980. }
  981. _, stderr, err := process.ExecDir(-1,
  982. repoPath, fmt.Sprintf("CreateRepository 'git update-server-info': %s", repoPath),
  983. "git", "update-server-info")
  984. if err != nil {
  985. return nil, fmt.Errorf("CreateRepository 'git update-server-info': %s", stderr)
  986. }
  987. }
  988. return repo, sess.Commit()
  989. }
  990. func countRepositories(userID int64, private bool) int64 {
  991. sess := x.Where("id > 0")
  992. if userID > 0 {
  993. sess.And("owner_id = ?", userID)
  994. }
  995. if !private {
  996. sess.And("is_private=?", false)
  997. }
  998. count, err := sess.Count(new(Repository))
  999. if err != nil {
  1000. log.Error(4, "countRepositories: %v", err)
  1001. }
  1002. return count
  1003. }
  1004. // CountRepositories returns number of repositories.
  1005. // Argument private only takes effect when it is false,
  1006. // set it true to count all repositories.
  1007. func CountRepositories(private bool) int64 {
  1008. return countRepositories(-1, private)
  1009. }
  1010. // CountUserRepositories returns number of repositories user owns.
  1011. // Argument private only takes effect when it is false,
  1012. // set it true to count all repositories.
  1013. func CountUserRepositories(userID int64, private bool) int64 {
  1014. return countRepositories(userID, private)
  1015. }
  1016. func Repositories(page, pageSize int) (_ []*Repository, err error) {
  1017. repos := make([]*Repository, 0, pageSize)
  1018. return repos, x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos)
  1019. }
  1020. // RepositoriesWithUsers returns number of repos in given page.
  1021. func RepositoriesWithUsers(page, pageSize int) (_ []*Repository, err error) {
  1022. repos, err := Repositories(page, pageSize)
  1023. if err != nil {
  1024. return nil, fmt.Errorf("Repositories: %v", err)
  1025. }
  1026. for i := range repos {
  1027. if err = repos[i].GetOwner(); err != nil {
  1028. return nil, err
  1029. }
  1030. }
  1031. return repos, nil
  1032. }
  1033. // FilterRepositoryWithIssues selects repositories that are using interal issue tracker
  1034. // and has disabled external tracker from given set.
  1035. // It returns nil if result set is empty.
  1036. func FilterRepositoryWithIssues(repoIDs []int64) ([]int64, error) {
  1037. if len(repoIDs) == 0 {
  1038. return nil, nil
  1039. }
  1040. repos := make([]*Repository, 0, len(repoIDs))
  1041. if err := x.Where("enable_issues=?", true).
  1042. And("enable_external_tracker=?", false).
  1043. In("id", repoIDs).
  1044. Cols("id").
  1045. Find(&repos); err != nil {
  1046. return nil, fmt.Errorf("filter valid repositories %v: %v", repoIDs, err)
  1047. }
  1048. if len(repos) == 0 {
  1049. return nil, nil
  1050. }
  1051. repoIDs = make([]int64, len(repos))
  1052. for i := range repos {
  1053. repoIDs[i] = repos[i].ID
  1054. }
  1055. return repoIDs, nil
  1056. }
  1057. // RepoPath returns repository path by given user and repository name.
  1058. func RepoPath(userName, repoName string) string {
  1059. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  1060. }
  1061. // TransferOwnership transfers all corresponding setting from old user to new one.
  1062. func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
  1063. newOwner, err := GetUserByName(newOwnerName)
  1064. if err != nil {
  1065. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  1066. }
  1067. // Check if new owner has repository with same name.
  1068. has, err := IsRepositoryExist(newOwner, repo.Name)
  1069. if err != nil {
  1070. return fmt.Errorf("IsRepositoryExist: %v", err)
  1071. } else if has {
  1072. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  1073. }
  1074. sess := x.NewSession()
  1075. defer sess.Close()
  1076. if err = sess.Begin(); err != nil {
  1077. return fmt.Errorf("sess.Begin: %v", err)
  1078. }
  1079. owner := repo.Owner
  1080. // Note: we have to set value here to make sure recalculate accesses is based on
  1081. // new owner.
  1082. repo.OwnerID = newOwner.ID
  1083. repo.Owner = newOwner
  1084. // Update repository.
  1085. if _, err := sess.ID(repo.ID).Update(repo); err != nil {
  1086. return fmt.Errorf("update owner: %v", err)
  1087. }
  1088. // Remove redundant collaborators.
  1089. collaborators, err := repo.getCollaborators(sess)
  1090. if err != nil {
  1091. return fmt.Errorf("getCollaborators: %v", err)
  1092. }
  1093. // Dummy object.
  1094. collaboration := &Collaboration{RepoID: repo.ID}
  1095. for _, c := range collaborators {
  1096. collaboration.UserID = c.ID
  1097. if c.ID == newOwner.ID || newOwner.IsOrgMember(c.ID) {
  1098. if _, err = sess.Delete(collaboration); err != nil {
  1099. return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
  1100. }
  1101. }
  1102. }
  1103. // Remove old team-repository relations.
  1104. if owner.IsOrganization() {
  1105. if err = owner.getTeams(sess); err != nil {
  1106. return fmt.Errorf("getTeams: %v", err)
  1107. }
  1108. for _, t := range owner.Teams {
  1109. if !t.hasRepository(sess, repo.ID) {
  1110. continue
  1111. }
  1112. t.NumRepos--
  1113. if _, err := sess.ID(t.ID).AllCols().Update(t); err != nil {
  1114. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  1115. }
  1116. }
  1117. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  1118. return fmt.Errorf("removeOrgRepo: %v", err)
  1119. }
  1120. }
  1121. if newOwner.IsOrganization() {
  1122. t, err := newOwner.getOwnerTeam(sess)
  1123. if err != nil {
  1124. return fmt.Errorf("getOwnerTeam: %v", err)
  1125. } else if err = t.addRepository(sess, repo); err != nil {
  1126. return fmt.Errorf("add to owner team: %v", err)
  1127. }
  1128. } else {
  1129. // Organization called this in addRepository method.
  1130. if err = repo.recalculateAccesses(sess); err != nil {
  1131. return fmt.Errorf("recalculateAccesses: %v", err)
  1132. }
  1133. }
  1134. // Update repository count.
  1135. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
  1136. return fmt.Errorf("increase new owner repository count: %v", err)
  1137. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.ID); err != nil {
  1138. return fmt.Errorf("decrease old owner repository count: %v", err)
  1139. }
  1140. if err = watchRepo(sess, newOwner.ID, repo.ID, true); err != nil {
  1141. return fmt.Errorf("watchRepo: %v", err)
  1142. } else if err = transferRepoAction(sess, doer, owner, repo); err != nil {
  1143. return fmt.Errorf("transferRepoAction: %v", err)
  1144. }
  1145. // Rename remote repository to new path and delete local copy.
  1146. os.MkdirAll(UserPath(newOwner.Name), os.ModePerm)
  1147. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  1148. return fmt.Errorf("rename repository directory: %v", err)
  1149. }
  1150. deleteRepoLocalCopy(repo)
  1151. // Rename remote wiki repository to new path and delete local copy.
  1152. wikiPath := WikiPath(owner.Name, repo.Name)
  1153. if com.IsExist(wikiPath) {
  1154. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1155. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  1156. return fmt.Errorf("rename repository wiki: %v", err)
  1157. }
  1158. }
  1159. return sess.Commit()
  1160. }
  1161. func deleteRepoLocalCopy(repo *Repository) {
  1162. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  1163. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  1164. RemoveAllWithNotice("Delete repository local copy", repo.LocalCopyPath())
  1165. }
  1166. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  1167. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  1168. oldRepoName = strings.ToLower(oldRepoName)
  1169. newRepoName = strings.ToLower(newRepoName)
  1170. if err = IsUsableRepoName(newRepoName); err != nil {
  1171. return err
  1172. }
  1173. has, err := IsRepositoryExist(u, newRepoName)
  1174. if err != nil {
  1175. return fmt.Errorf("IsRepositoryExist: %v", err)
  1176. } else if has {
  1177. return ErrRepoAlreadyExist{u.Name, newRepoName}
  1178. }
  1179. repo, err := GetRepositoryByName(u.ID, oldRepoName)
  1180. if err != nil {
  1181. return fmt.Errorf("GetRepositoryByName: %v", err)
  1182. }
  1183. // Change repository directory name
  1184. if err = os.Rename(repo.RepoPath(), RepoPath(u.Name, newRepoName)); err != nil {
  1185. return fmt.Errorf("rename repository directory: %v", err)
  1186. }
  1187. wikiPath := repo.WikiPath()
  1188. if com.IsExist(wikiPath) {
  1189. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  1190. return fmt.Errorf("rename repository wiki: %v", err)
  1191. }
  1192. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1193. }
  1194. deleteRepoLocalCopy(repo)
  1195. return nil
  1196. }
  1197. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  1198. repos := make([]*Repository, 0, 10)
  1199. return repos, e.Where("fork_id=?", forkID).Find(&repos)
  1200. }
  1201. // GetRepositoriesByForkID returns all repositories with given fork ID.
  1202. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  1203. return getRepositoriesByForkID(x, forkID)
  1204. }
  1205. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  1206. repo.LowerName = strings.ToLower(repo.Name)
  1207. if len(repo.Description) > 512 {
  1208. repo.Description = repo.Description[:512]
  1209. }
  1210. if len(repo.Website) > 255 {
  1211. repo.Website = repo.Website[:255]
  1212. }
  1213. if _, err = e.ID(repo.ID).AllCols().Update(repo); err != nil {
  1214. return fmt.Errorf("update: %v", err)
  1215. }
  1216. if visibilityChanged {
  1217. if err = repo.getOwner(e); err != nil {
  1218. return fmt.Errorf("getOwner: %v", err)
  1219. }
  1220. if repo.Owner.IsOrganization() {
  1221. // Organization repository need to recalculate access table when visivility is changed
  1222. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  1223. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  1224. }
  1225. }
  1226. // Create/Remove git-daemon-export-ok for git-daemon
  1227. daemonExportFile := path.Join(repo.RepoPath(), "git-daemon-export-ok")
  1228. if repo.IsPrivate && com.IsExist(daemonExportFile) {
  1229. if err = os.Remove(daemonExportFile); err != nil {
  1230. log.Error(4, "Failed to remove %s: %v", daemonExportFile, err)
  1231. }
  1232. } else if !repo.IsPrivate && !com.IsExist(daemonExportFile) {
  1233. if f, err := os.Create(daemonExportFile); err != nil {
  1234. log.Error(4, "Failed to create %s: %v", daemonExportFile, err)
  1235. } else {
  1236. f.Close()
  1237. }
  1238. }
  1239. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1240. if err != nil {
  1241. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1242. }
  1243. for i := range forkRepos {
  1244. forkRepos[i].IsPrivate = repo.IsPrivate
  1245. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1246. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1247. }
  1248. }
  1249. // Change visibility of generated actions
  1250. if _, err = e.Where("repo_id = ?", repo.ID).Cols("is_private").Update(&Action{IsPrivate: repo.IsPrivate}); err != nil {
  1251. return fmt.Errorf("change action visibility of repository: %v", err)
  1252. }
  1253. }
  1254. return nil
  1255. }
  1256. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1257. sess := x.NewSession()
  1258. defer sess.Close()
  1259. if err = sess.Begin(); err != nil {
  1260. return err
  1261. }
  1262. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  1263. return fmt.Errorf("updateRepository: %v", err)
  1264. }
  1265. return sess.Commit()
  1266. }
  1267. // DeleteRepository deletes a repository for a user or organization.
  1268. func DeleteRepository(uid, repoID int64) error {
  1269. repo := &Repository{ID: repoID, OwnerID: uid}
  1270. has, err := x.Get(repo)
  1271. if err != nil {
  1272. return err
  1273. } else if !has {
  1274. return errors.RepoNotExist{repoID, uid, ""}
  1275. }
  1276. // In case is a organization.
  1277. org, err := GetUserByID(uid)
  1278. if err != nil {
  1279. return err
  1280. }
  1281. if org.IsOrganization() {
  1282. if err = org.GetTeams(); err != nil {
  1283. return err
  1284. }
  1285. }
  1286. sess := x.NewSession()
  1287. defer sess.Close()
  1288. if err = sess.Begin(); err != nil {
  1289. return err
  1290. }
  1291. if org.IsOrganization() {
  1292. for _, t := range org.Teams {
  1293. if !t.hasRepository(sess, repoID) {
  1294. continue
  1295. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1296. return err
  1297. }
  1298. }
  1299. }
  1300. if err = deleteBeans(sess,
  1301. &Repository{ID: repoID},
  1302. &Access{RepoID: repo.ID},
  1303. &Action{RepoID: repo.ID},
  1304. &Watch{RepoID: repoID},
  1305. &Star{RepoID: repoID},
  1306. &Mirror{RepoID: repoID},
  1307. &IssueUser{RepoID: repoID},
  1308. &Milestone{RepoID: repoID},
  1309. &Release{RepoID: repoID},
  1310. &Collaboration{RepoID: repoID},
  1311. &PullRequest{BaseRepoID: repoID},
  1312. &ProtectBranch{RepoID: repoID},
  1313. &ProtectBranchWhitelist{RepoID: repoID},
  1314. &Webhook{RepoID: repoID},
  1315. &HookTask{RepoID: repoID},
  1316. ); err != nil {
  1317. return fmt.Errorf("deleteBeans: %v", err)
  1318. }
  1319. // Delete comments and attachments.
  1320. issues := make([]*Issue, 0, 25)
  1321. attachmentPaths := make([]string, 0, len(issues))
  1322. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  1323. return err
  1324. }
  1325. for i := range issues {
  1326. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  1327. return err
  1328. }
  1329. attachments := make([]*Attachment, 0, 5)
  1330. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  1331. return err
  1332. }
  1333. for j := range attachments {
  1334. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1335. }
  1336. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  1337. return err
  1338. }
  1339. }
  1340. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1341. return err
  1342. }
  1343. if repo.IsFork {
  1344. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1345. return fmt.Errorf("decrease fork count: %v", err)
  1346. }
  1347. }
  1348. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1349. return err
  1350. }
  1351. if err = sess.Commit(); err != nil {
  1352. return fmt.Errorf("Commit: %v", err)
  1353. }
  1354. // Remove repository files.
  1355. repoPath := repo.RepoPath()
  1356. RemoveAllWithNotice("Delete repository files", repoPath)
  1357. repo.DeleteWiki()
  1358. // Remove attachment files.
  1359. for i := range attachmentPaths {
  1360. RemoveAllWithNotice("Delete attachment", attachmentPaths[i])
  1361. }
  1362. if repo.NumForks > 0 {
  1363. if _, err = x.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1364. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  1365. }
  1366. }
  1367. return nil
  1368. }
  1369. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  1370. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  1371. func GetRepositoryByRef(ref string) (*Repository, error) {
  1372. n := strings.IndexByte(ref, byte('/'))
  1373. if n < 2 {
  1374. return nil, errors.InvalidRepoReference{ref}
  1375. }
  1376. userName, repoName := ref[:n], ref[n+1:]
  1377. user, err := GetUserByName(userName)
  1378. if err != nil {
  1379. return nil, err
  1380. }
  1381. return GetRepositoryByName(user.ID, repoName)
  1382. }
  1383. // GetRepositoryByName returns the repository by given name under user if exists.
  1384. func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
  1385. repo := &Repository{
  1386. OwnerID: ownerID,
  1387. LowerName: strings.ToLower(name),
  1388. }
  1389. has, err := x.Get(repo)
  1390. if err != nil {
  1391. return nil, err
  1392. } else if !has {
  1393. return nil, errors.RepoNotExist{0, ownerID, name}
  1394. }
  1395. return repo, repo.LoadAttributes()
  1396. }
  1397. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1398. repo := new(Repository)
  1399. has, err := e.ID(id).Get(repo)
  1400. if err != nil {
  1401. return nil, err
  1402. } else if !has {
  1403. return nil, errors.RepoNotExist{id, 0, ""}
  1404. }
  1405. return repo, repo.loadAttributes(e)
  1406. }
  1407. // GetRepositoryByID returns the repository by given id if exists.
  1408. func GetRepositoryByID(id int64) (*Repository, error) {
  1409. return getRepositoryByID(x, id)
  1410. }
  1411. type UserRepoOptions struct {
  1412. UserID int64
  1413. Private bool
  1414. Page int
  1415. PageSize int
  1416. }
  1417. // GetUserRepositories returns a list of repositories of given user.
  1418. func GetUserRepositories(opts *UserRepoOptions) ([]*Repository, error) {
  1419. sess := x.Where("owner_id=?", opts.UserID).Desc("updated_unix")
  1420. if !opts.Private {
  1421. sess.And("is_private=?", false)
  1422. }
  1423. if opts.Page <= 0 {
  1424. opts.Page = 1
  1425. }
  1426. sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1427. repos := make([]*Repository, 0, opts.PageSize)
  1428. return repos, sess.Find(&repos)
  1429. }
  1430. // GetUserRepositories returns a list of mirror repositories of given user.
  1431. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1432. repos := make([]*Repository, 0, 10)
  1433. return repos, x.Where("owner_id = ?", userID).And("is_mirror = ?", true).Find(&repos)
  1434. }
  1435. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  1436. func GetRecentUpdatedRepositories(page, pageSize int) (repos []*Repository, err error) {
  1437. return repos, x.Limit(pageSize, (page-1)*pageSize).
  1438. Where("is_private=?", false).Limit(pageSize).Desc("updated_unix").Find(&repos)
  1439. }
  1440. // GetUserAndCollaborativeRepositories returns list of repositories the user owns and collaborates.
  1441. func GetUserAndCollaborativeRepositories(userID int64) ([]*Repository, error) {
  1442. repos := make([]*Repository, 0, 10)
  1443. if err := x.Alias("repo").
  1444. Join("INNER", "collaboration", "collaboration.repo_id = repo.id").
  1445. Where("collaboration.user_id = ?", userID).
  1446. Find(&repos); err != nil {
  1447. return nil, fmt.Errorf("select collaborative repositories: %v", err)
  1448. }
  1449. ownRepos := make([]*Repository, 0, 10)
  1450. if err := x.Where("owner_id = ?", userID).Find(&ownRepos); err != nil {
  1451. return nil, fmt.Errorf("select own repositories: %v", err)
  1452. }
  1453. return append(repos, ownRepos...), nil
  1454. }
  1455. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1456. return x.Count(&Repository{OwnerID: u.ID})
  1457. }
  1458. // GetRepositoryCount returns the total number of repositories of user.
  1459. func GetRepositoryCount(u *User) (int64, error) {
  1460. return getRepositoryCount(x, u)
  1461. }
  1462. type SearchRepoOptions struct {
  1463. Keyword string
  1464. OwnerID int64
  1465. UserID int64 // When set results will contain all public/private repositories user has access to
  1466. OrderBy string
  1467. Private bool // Include private repositories in results
  1468. Page int
  1469. PageSize int // Can be smaller than or equal to setting.ExplorePagingNum
  1470. }
  1471. // SearchRepositoryByName takes keyword and part of repository name to search,
  1472. // it returns results in given range and number of total results.
  1473. func SearchRepositoryByName(opts *SearchRepoOptions) (repos []*Repository, count int64, err error) {
  1474. if opts.Page <= 0 {
  1475. opts.Page = 1
  1476. }
  1477. repos = make([]*Repository, 0, opts.PageSize)
  1478. sess := x.Alias("repo")
  1479. // Attempt to find repositories that opts.UserID has access to,
  1480. // this does not include other people's private repositories even if opts.UserID is an admin.
  1481. if !opts.Private && opts.UserID > 0 {
  1482. sess.Join("LEFT", "access", "access.repo_id = repo.id").
  1483. Where("repo.owner_id = ? OR access.user_id = ? OR repo.is_private = ? OR (repo.is_private = ? AND (repo.allow_public_wiki = ? OR repo.allow_public_issues = ?))", opts.UserID, opts.UserID, false, true, true, true)
  1484. } else {
  1485. // Only return public repositories if opts.Private is not set
  1486. if !opts.Private {
  1487. sess.And("repo.is_private = ? OR (repo.is_private = ? AND (repo.allow_public_wiki = ? OR repo.allow_public_issues = ?))", false, true, true, true)
  1488. }
  1489. }
  1490. if len(opts.Keyword) > 0 {
  1491. sess.And("repo.lower_name LIKE ? OR repo.description LIKE ?", "%"+strings.ToLower(opts.Keyword)+"%", "%"+strings.ToLower(opts.Keyword)+"%")
  1492. }
  1493. if opts.OwnerID > 0 {
  1494. sess.And("repo.owner_id = ?", opts.OwnerID)
  1495. }
  1496. // We need all fields (repo.*) in final list but only ID (repo.id) is good enough for counting.
  1497. count, err = sess.Clone().Distinct("repo.id").Count(new(Repository))
  1498. if err != nil {
  1499. return nil, 0, fmt.Errorf("Count: %v", err)
  1500. }
  1501. if len(opts.OrderBy) > 0 {
  1502. sess.OrderBy("repo." + opts.OrderBy)
  1503. }
  1504. return repos, count, sess.Distinct("repo.*").Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&repos)
  1505. }
  1506. func DeleteOldRepositoryArchives() {
  1507. if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
  1508. return
  1509. }
  1510. taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
  1511. defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
  1512. log.Trace("Doing: DeleteOldRepositoryArchives")
  1513. formats := []string{"zip", "targz"}
  1514. oldestTime := time.Now().Add(-setting.Cron.RepoArchiveCleanup.OlderThan)
  1515. if err := x.Where("id > 0").Iterate(new(Repository),
  1516. func(idx int, bean interface{}) error {
  1517. repo := bean.(*Repository)
  1518. basePath := filepath.Join(repo.RepoPath(), "archives")
  1519. for _, format := range formats {
  1520. dirPath := filepath.Join(basePath, format)
  1521. if !com.IsDir(dirPath) {
  1522. continue
  1523. }
  1524. dir, err := os.Open(dirPath)
  1525. if err != nil {
  1526. log.Error(3, "Fail to open directory '%s': %v", dirPath, err)
  1527. continue
  1528. }
  1529. fis, err := dir.Readdir(0)
  1530. dir.Close()
  1531. if err != nil {
  1532. log.Error(3, "Fail to read directory '%s': %v", dirPath, err)
  1533. continue
  1534. }
  1535. for _, fi := range fis {
  1536. if fi.IsDir() || fi.ModTime().After(oldestTime) {
  1537. continue
  1538. }
  1539. archivePath := filepath.Join(dirPath, fi.Name())
  1540. if err = os.Remove(archivePath); err != nil {
  1541. desc := fmt.Sprintf("Fail to health delete archive '%s': %v", archivePath, err)
  1542. log.Warn(desc)
  1543. if err = CreateRepositoryNotice(desc); err != nil {
  1544. log.Error(3, "CreateRepositoryNotice: %v", err)
  1545. }
  1546. }
  1547. }
  1548. }
  1549. return nil
  1550. }); err != nil {
  1551. log.Error(2, "DeleteOldRepositoryArchives: %v", err)
  1552. }
  1553. }
  1554. // DeleteRepositoryArchives deletes all repositories' archives.
  1555. func DeleteRepositoryArchives() error {
  1556. if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
  1557. return nil
  1558. }
  1559. taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
  1560. defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
  1561. return x.Where("id > 0").Iterate(new(Repository),
  1562. func(idx int, bean interface{}) error {
  1563. repo := bean.(*Repository)
  1564. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1565. })
  1566. }
  1567. func gatherMissingRepoRecords() ([]*Repository, error) {
  1568. repos := make([]*Repository, 0, 10)
  1569. if err := x.Where("id > 0").Iterate(new(Repository),
  1570. func(idx int, bean interface{}) error {
  1571. repo := bean.(*Repository)
  1572. if !com.IsDir(repo.RepoPath()) {
  1573. repos = append(repos, repo)
  1574. }
  1575. return nil
  1576. }); err != nil {
  1577. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1578. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1579. }
  1580. }
  1581. return repos, nil
  1582. }
  1583. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1584. func DeleteMissingRepositories() error {
  1585. repos, err := gatherMissingRepoRecords()
  1586. if err != nil {
  1587. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1588. }
  1589. if len(repos) == 0 {
  1590. return nil
  1591. }
  1592. for _, repo := range repos {
  1593. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1594. if err := DeleteRepository(repo.OwnerID, repo.ID); err != nil {
  1595. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1596. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1597. }
  1598. }
  1599. }
  1600. return nil
  1601. }
  1602. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1603. func ReinitMissingRepositories() error {
  1604. repos, err := gatherMissingRepoRecords()
  1605. if err != nil {
  1606. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1607. }
  1608. if len(repos) == 0 {
  1609. return nil
  1610. }
  1611. for _, repo := range repos {
  1612. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1613. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  1614. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1615. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1616. }
  1617. }
  1618. }
  1619. return nil
  1620. }
  1621. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  1622. // to make sure the binary and custom conf path are up-to-date.
  1623. func SyncRepositoryHooks() error {
  1624. return x.Where("id > 0").Iterate(new(Repository),
  1625. func(idx int, bean interface{}) error {
  1626. repo := bean.(*Repository)
  1627. if err := createDelegateHooks(repo.RepoPath()); err != nil {
  1628. return err
  1629. }
  1630. if repo.HasWiki() {
  1631. return createDelegateHooks(repo.WikiPath())
  1632. }
  1633. return nil
  1634. })
  1635. }
  1636. // Prevent duplicate running tasks.
  1637. var taskStatusTable = sync.NewStatusTable()
  1638. const (
  1639. _MIRROR_UPDATE = "mirror_update"
  1640. _GIT_FSCK = "git_fsck"
  1641. _CHECK_REPO_STATS = "check_repos_stats"
  1642. _CLEAN_OLD_ARCHIVES = "clean_old_archives"
  1643. )
  1644. // GitFsck calls 'git fsck' to check repository health.
  1645. func GitFsck() {
  1646. if taskStatusTable.IsRunning(_GIT_FSCK) {
  1647. return
  1648. }
  1649. taskStatusTable.Start(_GIT_FSCK)
  1650. defer taskStatusTable.Stop(_GIT_FSCK)
  1651. log.Trace("Doing: GitFsck")
  1652. if err := x.Where("id>0").Iterate(new(Repository),
  1653. func(idx int, bean interface{}) error {
  1654. repo := bean.(*Repository)
  1655. repoPath := repo.RepoPath()
  1656. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1657. desc := fmt.Sprintf("Failed to perform health check on repository '%s': %v", repoPath, err)
  1658. log.Warn(desc)
  1659. if err = CreateRepositoryNotice(desc); err != nil {
  1660. log.Error(3, "CreateRepositoryNotice: %v", err)
  1661. }
  1662. }
  1663. return nil
  1664. }); err != nil {
  1665. log.Error(2, "GitFsck: %v", err)
  1666. }
  1667. }
  1668. func GitGcRepos() error {
  1669. args := append([]string{"gc"}, setting.Git.GCArgs...)
  1670. return x.Where("id > 0").Iterate(new(Repository),
  1671. func(idx int, bean interface{}) error {
  1672. repo := bean.(*Repository)
  1673. if err := repo.GetOwner(); err != nil {
  1674. return err
  1675. }
  1676. _, stderr, err := process.ExecDir(
  1677. time.Duration(setting.Git.Timeout.GC)*time.Second,
  1678. RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection",
  1679. "git", args...)
  1680. if err != nil {
  1681. return fmt.Errorf("%v: %v", err, stderr)
  1682. }
  1683. return nil
  1684. })
  1685. }
  1686. type repoChecker struct {
  1687. querySQL, correctSQL string
  1688. desc string
  1689. }
  1690. func repoStatsCheck(checker *repoChecker) {
  1691. results, err := x.Query(checker.querySQL)
  1692. if err != nil {
  1693. log.Error(2, "Select %s: %v", checker.desc, err)
  1694. return
  1695. }
  1696. for _, result := range results {
  1697. id := com.StrTo(result["id"]).MustInt64()
  1698. log.Trace("Updating %s: %d", checker.desc, id)
  1699. _, err = x.Exec(checker.correctSQL, id, id)
  1700. if err != nil {
  1701. log.Error(2, "Update %s[%d]: %v", checker.desc, id, err)
  1702. }
  1703. }
  1704. }
  1705. func CheckRepoStats() {
  1706. if taskStatusTable.IsRunning(_CHECK_REPO_STATS) {
  1707. return
  1708. }
  1709. taskStatusTable.Start(_CHECK_REPO_STATS)
  1710. defer taskStatusTable.Stop(_CHECK_REPO_STATS)
  1711. log.Trace("Doing: CheckRepoStats")
  1712. checkers := []*repoChecker{
  1713. // Repository.NumWatches
  1714. {
  1715. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1716. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1717. "repository count 'num_watches'",
  1718. },
  1719. // Repository.NumStars
  1720. {
  1721. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1722. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1723. "repository count 'num_stars'",
  1724. },
  1725. // Label.NumIssues
  1726. {
  1727. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1728. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1729. "label count 'num_issues'",
  1730. },
  1731. // User.NumRepos
  1732. {
  1733. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1734. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1735. "user count 'num_repos'",
  1736. },
  1737. // Issue.NumComments
  1738. {
  1739. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1740. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1741. "issue count 'num_comments'",
  1742. },
  1743. }
  1744. for i := range checkers {
  1745. repoStatsCheck(checkers[i])
  1746. }
  1747. // ***** START: Repository.NumClosedIssues *****
  1748. desc := "repository count 'num_closed_issues'"
  1749. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false)
  1750. if err != nil {
  1751. log.Error(2, "Select %s: %v", desc, err)
  1752. } else {
  1753. for _, result := range results {
  1754. id := com.StrTo(result["id"]).MustInt64()
  1755. log.Trace("Updating %s: %d", desc, id)
  1756. _, err = x.Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id)
  1757. if err != nil {
  1758. log.Error(2, "Update %s[%d]: %v", desc, id, err)
  1759. }
  1760. }
  1761. }
  1762. // ***** END: Repository.NumClosedIssues *****
  1763. // FIXME: use checker when stop supporting old fork repo format.
  1764. // ***** START: Repository.NumForks *****
  1765. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1766. if err != nil {
  1767. log.Error(2, "Select repository count 'num_forks': %v", err)
  1768. } else {
  1769. for _, result := range results {
  1770. id := com.StrTo(result["id"]).MustInt64()
  1771. log.Trace("Updating repository count 'num_forks': %d", id)
  1772. repo, err := GetRepositoryByID(id)
  1773. if err != nil {
  1774. log.Error(2, "GetRepositoryByID[%d]: %v", id, err)
  1775. continue
  1776. }
  1777. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1778. if err != nil {
  1779. log.Error(2, "Select count of forks[%d]: %v", repo.ID, err)
  1780. continue
  1781. }
  1782. repo.NumForks = int(parseCountResult(rawResult))
  1783. if err = UpdateRepository(repo, false); err != nil {
  1784. log.Error(2, "UpdateRepository[%d]: %v", id, err)
  1785. continue
  1786. }
  1787. }
  1788. }
  1789. // ***** END: Repository.NumForks *****
  1790. }
  1791. type RepositoryList []*Repository
  1792. func (repos RepositoryList) loadAttributes(e Engine) error {
  1793. if len(repos) == 0 {
  1794. return nil
  1795. }
  1796. // Load owners
  1797. userSet := make(map[int64]*User)
  1798. for i := range repos {
  1799. userSet[repos[i].OwnerID] = nil
  1800. }
  1801. userIDs := make([]int64, 0, len(userSet))
  1802. for userID := range userSet {
  1803. userIDs = append(userIDs, userID)
  1804. }
  1805. users := make([]*User, 0, len(userIDs))
  1806. if err := e.Where("id > 0").In("id", userIDs).Find(&users); err != nil {
  1807. return fmt.Errorf("find users: %v", err)
  1808. }
  1809. for i := range users {
  1810. userSet[users[i].ID] = users[i]
  1811. }
  1812. for i := range repos {
  1813. repos[i].Owner = userSet[repos[i].OwnerID]
  1814. }
  1815. // Load base repositories
  1816. repoSet := make(map[int64]*Repository)
  1817. for i := range repos {
  1818. if repos[i].IsFork {
  1819. repoSet[repos[i].ForkID] = nil
  1820. }
  1821. }
  1822. baseIDs := make([]int64, 0, len(repoSet))
  1823. for baseID := range repoSet {
  1824. baseIDs = append(baseIDs, baseID)
  1825. }
  1826. baseRepos := make([]*Repository, 0, len(baseIDs))
  1827. if err := e.Where("id > 0").In("id", baseIDs).Find(&baseRepos); err != nil {
  1828. return fmt.Errorf("find base repositories: %v", err)
  1829. }
  1830. for i := range baseRepos {
  1831. repoSet[baseRepos[i].ID] = baseRepos[i]
  1832. }
  1833. for i := range repos {
  1834. if repos[i].IsFork {
  1835. repos[i].BaseRepo = repoSet[repos[i].ForkID]
  1836. }
  1837. }
  1838. return nil
  1839. }
  1840. func (repos RepositoryList) LoadAttributes() error {
  1841. return repos.loadAttributes(x)
  1842. }
  1843. type MirrorRepositoryList []*Repository
  1844. func (repos MirrorRepositoryList) loadAttributes(e Engine) error {
  1845. if len(repos) == 0 {
  1846. return nil
  1847. }
  1848. // Load mirrors.
  1849. repoIDs := make([]int64, 0, len(repos))
  1850. for i := range repos {
  1851. if !repos[i].IsMirror {
  1852. continue
  1853. }
  1854. repoIDs = append(repoIDs, repos[i].ID)
  1855. }
  1856. mirrors := make([]*Mirror, 0, len(repoIDs))
  1857. if err := e.Where("id > 0").In("repo_id", repoIDs).Find(&mirrors); err != nil {
  1858. return fmt.Errorf("find mirrors: %v", err)
  1859. }
  1860. set := make(map[int64]*Mirror)
  1861. for i := range mirrors {
  1862. set[mirrors[i].RepoID] = mirrors[i]
  1863. }
  1864. for i := range repos {
  1865. repos[i].Mirror = set[repos[i].ID]
  1866. }
  1867. return nil
  1868. }
  1869. func (repos MirrorRepositoryList) LoadAttributes() error {
  1870. return repos.loadAttributes(x)
  1871. }
  1872. // __ __ __ .__
  1873. // / \ / \_____ _/ |_ ____ | |__
  1874. // \ \/\/ /\__ \\ __\/ ___\| | \
  1875. // \ / / __ \| | \ \___| Y \
  1876. // \__/\ / (____ /__| \___ >___| /
  1877. // \/ \/ \/ \/
  1878. // Watch is connection request for receiving repository notification.
  1879. type Watch struct {
  1880. ID int64
  1881. UserID int64 `xorm:"UNIQUE(watch)"`
  1882. RepoID int64 `xorm:"UNIQUE(watch)"`
  1883. }
  1884. func isWatching(e Engine, userID, repoID int64) bool {
  1885. has, _ := e.Get(&Watch{0, userID, repoID})
  1886. return has
  1887. }
  1888. // IsWatching checks if user has watched given repository.
  1889. func IsWatching(userID, repoID int64) bool {
  1890. return isWatching(x, userID, repoID)
  1891. }
  1892. func watchRepo(e Engine, userID, repoID int64, watch bool) (err error) {
  1893. if watch {
  1894. if isWatching(e, userID, repoID) {
  1895. return nil
  1896. }
  1897. if _, err = e.Insert(&Watch{RepoID: repoID, UserID: userID}); err != nil {
  1898. return err
  1899. }
  1900. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoID)
  1901. } else {
  1902. if !isWatching(e, userID, repoID) {
  1903. return nil
  1904. }
  1905. if _, err = e.Delete(&Watch{0, userID, repoID}); err != nil {
  1906. return err
  1907. }
  1908. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoID)
  1909. }
  1910. return err
  1911. }
  1912. // Watch or unwatch repository.
  1913. func WatchRepo(userID, repoID int64, watch bool) (err error) {
  1914. return watchRepo(x, userID, repoID, watch)
  1915. }
  1916. func getWatchers(e Engine, repoID int64) ([]*Watch, error) {
  1917. watches := make([]*Watch, 0, 10)
  1918. return watches, e.Find(&watches, &Watch{RepoID: repoID})
  1919. }
  1920. // GetWatchers returns all watchers of given repository.
  1921. func GetWatchers(repoID int64) ([]*Watch, error) {
  1922. return getWatchers(x, repoID)
  1923. }
  1924. // Repository.GetWatchers returns range of users watching given repository.
  1925. func (repo *Repository) GetWatchers(page int) ([]*User, error) {
  1926. users := make([]*User, 0, ItemsPerPage)
  1927. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("watch.repo_id=?", repo.ID)
  1928. if setting.UsePostgreSQL {
  1929. sess = sess.Join("LEFT", "watch", `"user".id=watch.user_id`)
  1930. } else {
  1931. sess = sess.Join("LEFT", "watch", "user.id=watch.user_id")
  1932. }
  1933. return users, sess.Find(&users)
  1934. }
  1935. func notifyWatchers(e Engine, act *Action) error {
  1936. // Add feeds for user self and all watchers.
  1937. watchers, err := getWatchers(e, act.RepoID)
  1938. if err != nil {
  1939. return fmt.Errorf("getWatchers: %v", err)
  1940. }
  1941. // Reset ID to reuse Action object
  1942. act.ID = 0
  1943. // Add feed for actioner.
  1944. act.UserID = act.ActUserID
  1945. if _, err = e.Insert(act); err != nil {
  1946. return fmt.Errorf("insert new action: %v", err)
  1947. }
  1948. for i := range watchers {
  1949. if act.ActUserID == watchers[i].UserID {
  1950. continue
  1951. }
  1952. act.ID = 0
  1953. act.UserID = watchers[i].UserID
  1954. if _, err = e.Insert(act); err != nil {
  1955. return fmt.Errorf("insert new action: %v", err)
  1956. }
  1957. }
  1958. return nil
  1959. }
  1960. // NotifyWatchers creates batch of actions for every watcher.
  1961. func NotifyWatchers(act *Action) error {
  1962. return notifyWatchers(x, act)
  1963. }
  1964. // _________ __
  1965. // / _____// |______ _______
  1966. // \_____ \\ __\__ \\_ __ \
  1967. // / \| | / __ \| | \/
  1968. // /_______ /|__| (____ /__|
  1969. // \/ \/
  1970. type Star struct {
  1971. ID int64
  1972. UID int64 `xorm:"UNIQUE(s)"`
  1973. RepoID int64 `xorm:"UNIQUE(s)"`
  1974. }
  1975. // Star or unstar repository.
  1976. func StarRepo(userID, repoID int64, star bool) (err error) {
  1977. if star {
  1978. if IsStaring(userID, repoID) {
  1979. return nil
  1980. }
  1981. if _, err = x.Insert(&Star{UID: userID, RepoID: repoID}); err != nil {
  1982. return err
  1983. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoID); err != nil {
  1984. return err
  1985. }
  1986. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", userID)
  1987. } else {
  1988. if !IsStaring(userID, repoID) {
  1989. return nil
  1990. }
  1991. if _, err = x.Delete(&Star{0, userID, repoID}); err != nil {
  1992. return err
  1993. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoID); err != nil {
  1994. return err
  1995. }
  1996. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", userID)
  1997. }
  1998. return err
  1999. }
  2000. // IsStaring checks if user has starred given repository.
  2001. func IsStaring(userID, repoID int64) bool {
  2002. has, _ := x.Get(&Star{0, userID, repoID})
  2003. return has
  2004. }
  2005. func (repo *Repository) GetStargazers(page int) ([]*User, error) {
  2006. users := make([]*User, 0, ItemsPerPage)
  2007. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("star.repo_id=?", repo.ID)
  2008. if setting.UsePostgreSQL {
  2009. sess = sess.Join("LEFT", "star", `"user".id=star.uid`)
  2010. } else {
  2011. sess = sess.Join("LEFT", "star", "user.id=star.uid")
  2012. }
  2013. return users, sess.Find(&users)
  2014. }
  2015. // ___________ __
  2016. // \_ _____/__________| | __
  2017. // | __)/ _ \_ __ \ |/ /
  2018. // | \( <_> ) | \/ <
  2019. // \___ / \____/|__| |__|_ \
  2020. // \/ \/
  2021. // HasForkedRepo checks if given user has already forked a repository.
  2022. // When user has already forked, it returns true along with the repository.
  2023. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool, error) {
  2024. repo := new(Repository)
  2025. has, err := x.Where("owner_id = ? AND fork_id = ?", ownerID, repoID).Get(repo)
  2026. if err != nil {
  2027. return nil, false, err
  2028. } else if !has {
  2029. return nil, false, nil
  2030. }
  2031. return repo, true, repo.LoadAttributes()
  2032. }
  2033. // ForkRepository creates a fork of target repository under another user domain.
  2034. func ForkRepository(doer, owner *User, baseRepo *Repository, name, desc string) (_ *Repository, err error) {
  2035. if !owner.CanCreateRepo() {
  2036. return nil, errors.ReachLimitOfRepo{owner.RepoCreationNum()}
  2037. }
  2038. repo := &Repository{
  2039. OwnerID: owner.ID,
  2040. Owner: owner,
  2041. Name: name,
  2042. LowerName: strings.ToLower(name),
  2043. Description: desc,
  2044. DefaultBranch: baseRepo.DefaultBranch,
  2045. IsPrivate: baseRepo.IsPrivate,
  2046. IsFork: true,
  2047. ForkID: baseRepo.ID,
  2048. }
  2049. sess := x.NewSession()
  2050. defer sess.Close()
  2051. if err = sess.Begin(); err != nil {
  2052. return nil, err
  2053. }
  2054. if err = createRepository(sess, doer, owner, repo); err != nil {
  2055. return nil, err
  2056. } else if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", baseRepo.ID); err != nil {
  2057. return nil, err
  2058. }
  2059. repoPath := repo.repoPath(sess)
  2060. RemoveAllWithNotice("Repository path erase before creation", repoPath)
  2061. _, stderr, err := process.ExecTimeout(10*time.Minute,
  2062. fmt.Sprintf("ForkRepository 'git clone': %s/%s", owner.Name, repo.Name),
  2063. "git", "clone", "--bare", baseRepo.RepoPath(), repoPath)
  2064. if err != nil {
  2065. return nil, fmt.Errorf("git clone: %v", stderr)
  2066. }
  2067. _, stderr, err = process.ExecDir(-1,
  2068. repoPath, fmt.Sprintf("ForkRepository 'git update-server-info': %s", repoPath),
  2069. "git", "update-server-info")
  2070. if err != nil {
  2071. return nil, fmt.Errorf("git update-server-info: %v", err)
  2072. }
  2073. if err = createDelegateHooks(repoPath); err != nil {
  2074. return nil, fmt.Errorf("createDelegateHooks: %v", err)
  2075. }
  2076. if err = sess.Commit(); err != nil {
  2077. return nil, fmt.Errorf("Commit: %v", err)
  2078. }
  2079. if err = repo.UpdateSize(); err != nil {
  2080. log.Error(2, "UpdateSize [repo_id: %d]: %v", repo.ID, err)
  2081. }
  2082. if err = PrepareWebhooks(baseRepo, HOOK_EVENT_FORK, &api.ForkPayload{
  2083. Forkee: repo.APIFormat(nil),
  2084. Repo: baseRepo.APIFormat(nil),
  2085. Sender: doer.APIFormat(),
  2086. }); err != nil {
  2087. log.Error(2, "PrepareWebhooks [repo_id: %d]: %v", baseRepo.ID, err)
  2088. }
  2089. return repo, nil
  2090. }
  2091. func (repo *Repository) GetForks() ([]*Repository, error) {
  2092. forks := make([]*Repository, 0, repo.NumForks)
  2093. if err := x.Find(&forks, &Repository{ForkID: repo.ID}); err != nil {
  2094. return nil, err
  2095. }
  2096. for _, fork := range forks {
  2097. fork.BaseRepo = repo
  2098. }
  2099. return forks, nil
  2100. }
  2101. // __________ .__
  2102. // \______ \____________ ____ ____ | |__
  2103. // | | _/\_ __ \__ \ / \_/ ___\| | \
  2104. // | | \ | | \// __ \| | \ \___| Y \
  2105. // |______ / |__| (____ /___| /\___ >___| /
  2106. // \/ \/ \/ \/ \/
  2107. //
  2108. func (repo *Repository) CreateNewBranch(doer *User, oldBranchName, branchName string) (err error) {
  2109. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  2110. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  2111. localPath := repo.LocalCopyPath()
  2112. if err = discardLocalRepoBranchChanges(localPath, oldBranchName); err != nil {
  2113. return fmt.Errorf("discardLocalRepoChanges: %v", err)
  2114. } else if err = repo.UpdateLocalCopyBranch(oldBranchName); err != nil {
  2115. return fmt.Errorf("UpdateLocalCopyBranch: %v", err)
  2116. }
  2117. if err = repo.CheckoutNewBranch(oldBranchName, branchName); err != nil {
  2118. return fmt.Errorf("CreateNewBranch: %v", err)
  2119. }
  2120. if err = git.Push(localPath, "origin", branchName); err != nil {
  2121. return fmt.Errorf("Push: %v", err)
  2122. }
  2123. return nil
  2124. }