repo.go 68 KB

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