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

repo.go 12 kB

11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
10 years ago
10 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 repo
  5. import (
  6. "fmt"
  7. "os"
  8. "path"
  9. "strings"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/auth"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/context"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/util"
  18. "github.com/Unknwon/com"
  19. )
  20. const (
  21. tplCreate base.TplName = "repo/create"
  22. tplMigrate base.TplName = "repo/migrate"
  23. )
  24. // MustBeNotEmpty render when a repo is a empty git dir
  25. func MustBeNotEmpty(ctx *context.Context) {
  26. if ctx.Repo.Repository.IsEmpty {
  27. ctx.NotFound("MustBeNotEmpty", nil)
  28. }
  29. }
  30. // MustBeEditable check that repo can be edited
  31. func MustBeEditable(ctx *context.Context) {
  32. if !ctx.Repo.Repository.CanEnableEditor() || ctx.Repo.IsViewCommit {
  33. ctx.NotFound("", nil)
  34. return
  35. }
  36. }
  37. // MustBeAbleToUpload check that repo can be uploaded to
  38. func MustBeAbleToUpload(ctx *context.Context) {
  39. if !setting.Repository.Upload.Enabled {
  40. ctx.NotFound("", nil)
  41. }
  42. }
  43. func checkContextUser(ctx *context.Context, uid int64) *models.User {
  44. orgs, err := models.GetOwnedOrgsByUserIDDesc(ctx.User.ID, "updated_unix")
  45. if err != nil {
  46. ctx.ServerError("GetOwnedOrgsByUserIDDesc", err)
  47. return nil
  48. }
  49. ctx.Data["Orgs"] = orgs
  50. // Not equal means current user is an organization.
  51. if uid == ctx.User.ID || uid == 0 {
  52. return ctx.User
  53. }
  54. org, err := models.GetUserByID(uid)
  55. if models.IsErrUserNotExist(err) {
  56. return ctx.User
  57. }
  58. if err != nil {
  59. ctx.ServerError("GetUserByID", fmt.Errorf("[%d]: %v", uid, err))
  60. return nil
  61. }
  62. // Check ownership of organization.
  63. if !org.IsOrganization() {
  64. ctx.Error(403)
  65. return nil
  66. }
  67. if !ctx.User.IsAdmin {
  68. isOwner, err := org.IsOwnedBy(ctx.User.ID)
  69. if err != nil {
  70. ctx.ServerError("IsOwnedBy", err)
  71. return nil
  72. } else if !isOwner {
  73. ctx.Error(403)
  74. return nil
  75. }
  76. }
  77. return org
  78. }
  79. func getRepoPrivate(ctx *context.Context) bool {
  80. switch strings.ToLower(setting.Repository.DefaultPrivate) {
  81. case setting.RepoCreatingLastUserVisibility:
  82. return ctx.User.LastRepoVisibility
  83. case setting.RepoCreatingPrivate:
  84. return true
  85. case setting.RepoCreatingPublic:
  86. return false
  87. default:
  88. return ctx.User.LastRepoVisibility
  89. }
  90. }
  91. // Create render creating repository page
  92. func Create(ctx *context.Context) {
  93. if !ctx.User.CanCreateRepo() {
  94. ctx.RenderWithErr(ctx.Tr("repo.form.reach_limit_of_creation", ctx.User.MaxCreationLimit()), tplCreate, nil)
  95. }
  96. ctx.Data["Title"] = ctx.Tr("new_repo")
  97. // Give default value for template to render.
  98. ctx.Data["Gitignores"] = models.Gitignores
  99. ctx.Data["Licenses"] = models.Licenses
  100. ctx.Data["Readmes"] = models.Readmes
  101. ctx.Data["readme"] = "Default"
  102. ctx.Data["private"] = getRepoPrivate(ctx)
  103. ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
  104. ctxUser := checkContextUser(ctx, ctx.QueryInt64("org"))
  105. if ctx.Written() {
  106. return
  107. }
  108. ctx.Data["ContextUser"] = ctxUser
  109. ctx.HTML(200, tplCreate)
  110. }
  111. func handleCreateError(ctx *context.Context, owner *models.User, err error, name string, tpl base.TplName, form interface{}) {
  112. switch {
  113. case models.IsErrReachLimitOfRepo(err):
  114. ctx.RenderWithErr(ctx.Tr("repo.form.reach_limit_of_creation", owner.MaxCreationLimit()), tpl, form)
  115. case models.IsErrRepoAlreadyExist(err):
  116. ctx.Data["Err_RepoName"] = true
  117. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tpl, form)
  118. case models.IsErrNameReserved(err):
  119. ctx.Data["Err_RepoName"] = true
  120. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form)
  121. case models.IsErrNamePatternNotAllowed(err):
  122. ctx.Data["Err_RepoName"] = true
  123. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form)
  124. default:
  125. ctx.ServerError(name, err)
  126. }
  127. }
  128. // CreatePost response for creating repository
  129. func CreatePost(ctx *context.Context, form auth.CreateRepoForm) {
  130. ctx.Data["Title"] = ctx.Tr("new_repo")
  131. ctx.Data["Gitignores"] = models.Gitignores
  132. ctx.Data["Licenses"] = models.Licenses
  133. ctx.Data["Readmes"] = models.Readmes
  134. ctxUser := checkContextUser(ctx, form.UID)
  135. if ctx.Written() {
  136. return
  137. }
  138. ctx.Data["ContextUser"] = ctxUser
  139. if ctx.HasError() {
  140. ctx.HTML(200, tplCreate)
  141. return
  142. }
  143. repo, err := models.CreateRepository(ctx.User, ctxUser, models.CreateRepoOptions{
  144. Name: form.RepoName,
  145. Description: form.Description,
  146. Gitignores: form.Gitignores,
  147. License: form.License,
  148. Readme: form.Readme,
  149. IsPrivate: form.Private || setting.Repository.ForcePrivate,
  150. AutoInit: form.AutoInit,
  151. })
  152. if err == nil {
  153. log.Trace("Repository created [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name)
  154. ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name)
  155. return
  156. }
  157. if repo != nil {
  158. if errDelete := models.DeleteRepository(ctx.User, ctxUser.ID, repo.ID); errDelete != nil {
  159. log.Error("DeleteRepository: %v", errDelete)
  160. }
  161. }
  162. handleCreateError(ctx, ctxUser, err, "CreatePost", tplCreate, &form)
  163. }
  164. // Migrate render migration of repository page
  165. func Migrate(ctx *context.Context) {
  166. ctx.Data["Title"] = ctx.Tr("new_migrate")
  167. ctx.Data["private"] = getRepoPrivate(ctx)
  168. ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
  169. ctx.Data["mirror"] = ctx.Query("mirror") == "1"
  170. ctx.Data["LFSActive"] = setting.LFS.StartServer
  171. ctxUser := checkContextUser(ctx, ctx.QueryInt64("org"))
  172. if ctx.Written() {
  173. return
  174. }
  175. ctx.Data["ContextUser"] = ctxUser
  176. ctx.HTML(200, tplMigrate)
  177. }
  178. // MigratePost response for migrating from external git repository
  179. func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) {
  180. ctx.Data["Title"] = ctx.Tr("new_migrate")
  181. ctxUser := checkContextUser(ctx, form.UID)
  182. if ctx.Written() {
  183. return
  184. }
  185. ctx.Data["ContextUser"] = ctxUser
  186. if ctx.HasError() {
  187. ctx.HTML(200, tplMigrate)
  188. return
  189. }
  190. remoteAddr, err := form.ParseRemoteAddr(ctx.User)
  191. if err != nil {
  192. if models.IsErrInvalidCloneAddr(err) {
  193. ctx.Data["Err_CloneAddr"] = true
  194. addrErr := err.(models.ErrInvalidCloneAddr)
  195. switch {
  196. case addrErr.IsURLError:
  197. ctx.RenderWithErr(ctx.Tr("form.url_error"), tplMigrate, &form)
  198. case addrErr.IsPermissionDenied:
  199. ctx.RenderWithErr(ctx.Tr("repo.migrate.permission_denied"), tplMigrate, &form)
  200. case addrErr.IsInvalidPath:
  201. ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), tplMigrate, &form)
  202. default:
  203. ctx.ServerError("Unknown error", err)
  204. }
  205. } else {
  206. ctx.ServerError("ParseRemoteAddr", err)
  207. }
  208. return
  209. }
  210. repo, err := models.MigrateRepository(ctx.User, ctxUser, models.MigrateRepoOptions{
  211. Name: form.RepoName,
  212. Description: form.Description,
  213. IsPrivate: form.Private || setting.Repository.ForcePrivate,
  214. IsMirror: form.Mirror,
  215. RemoteAddr: remoteAddr,
  216. })
  217. if err == nil {
  218. log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, form.RepoName)
  219. ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + form.RepoName)
  220. return
  221. }
  222. if models.IsErrRepoAlreadyExist(err) {
  223. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tplMigrate, &form)
  224. return
  225. }
  226. // remoteAddr may contain credentials, so we sanitize it
  227. err = util.URLSanitizedError(err, remoteAddr)
  228. if repo != nil {
  229. if errDelete := models.DeleteRepository(ctx.User, ctxUser.ID, repo.ID); errDelete != nil {
  230. log.Error("DeleteRepository: %v", errDelete)
  231. }
  232. }
  233. if strings.Contains(err.Error(), "Authentication failed") ||
  234. strings.Contains(err.Error(), "could not read Username") {
  235. ctx.Data["Err_Auth"] = true
  236. ctx.RenderWithErr(ctx.Tr("form.auth_failed", err.Error()), tplMigrate, &form)
  237. return
  238. } else if strings.Contains(err.Error(), "fatal:") {
  239. ctx.Data["Err_CloneAddr"] = true
  240. ctx.RenderWithErr(ctx.Tr("repo.migrate.failed", err.Error()), tplMigrate, &form)
  241. return
  242. }
  243. handleCreateError(ctx, ctxUser, err, "MigratePost", tplMigrate, &form)
  244. }
  245. // Action response for actions to a repository
  246. func Action(ctx *context.Context) {
  247. var err error
  248. switch ctx.Params(":action") {
  249. case "watch":
  250. err = models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, true)
  251. case "unwatch":
  252. err = models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, false)
  253. case "star":
  254. err = models.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, true)
  255. case "unstar":
  256. err = models.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, false)
  257. case "desc": // FIXME: this is not used
  258. if !ctx.Repo.IsOwner() {
  259. ctx.Error(404)
  260. return
  261. }
  262. ctx.Repo.Repository.Description = ctx.Query("desc")
  263. ctx.Repo.Repository.Website = ctx.Query("site")
  264. err = models.UpdateRepository(ctx.Repo.Repository, false)
  265. }
  266. if err != nil {
  267. ctx.ServerError(fmt.Sprintf("Action (%s)", ctx.Params(":action")), err)
  268. return
  269. }
  270. ctx.RedirectToFirst(ctx.Query("redirect_to"), ctx.Repo.RepoLink)
  271. }
  272. // RedirectDownload return a file based on the following infos:
  273. func RedirectDownload(ctx *context.Context) {
  274. var (
  275. vTag = ctx.Params("vTag")
  276. fileName = ctx.Params("fileName")
  277. )
  278. tagNames := []string{vTag}
  279. curRepo := ctx.Repo.Repository
  280. releases, err := models.GetReleasesByRepoIDAndNames(curRepo.ID, tagNames)
  281. if err != nil {
  282. if models.IsErrAttachmentNotExist(err) {
  283. ctx.Error(404)
  284. return
  285. }
  286. ctx.ServerError("RedirectDownload", err)
  287. return
  288. }
  289. if len(releases) == 1 {
  290. release := releases[0]
  291. att, err := models.GetAttachmentByReleaseIDFileName(release.ID, fileName)
  292. if err != nil {
  293. ctx.Error(404)
  294. return
  295. }
  296. if att != nil {
  297. ctx.Redirect(setting.AppSubURL + "/attachments/" + att.UUID)
  298. return
  299. }
  300. }
  301. ctx.Error(404)
  302. }
  303. // Download download an archive of a repository
  304. func Download(ctx *context.Context) {
  305. var (
  306. uri = ctx.Params("*")
  307. refName string
  308. ext string
  309. archivePath string
  310. archiveType git.ArchiveType
  311. )
  312. switch {
  313. case strings.HasSuffix(uri, ".zip"):
  314. ext = ".zip"
  315. archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/zip")
  316. archiveType = git.ZIP
  317. case strings.HasSuffix(uri, ".tar.gz"):
  318. ext = ".tar.gz"
  319. archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/targz")
  320. archiveType = git.TARGZ
  321. default:
  322. log.Trace("Unknown format: %s", uri)
  323. ctx.Error(404)
  324. return
  325. }
  326. refName = strings.TrimSuffix(uri, ext)
  327. if !com.IsDir(archivePath) {
  328. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  329. ctx.ServerError("Download -> os.MkdirAll(archivePath)", err)
  330. return
  331. }
  332. }
  333. // Get corresponding commit.
  334. var (
  335. commit *git.Commit
  336. err error
  337. )
  338. gitRepo := ctx.Repo.GitRepo
  339. if gitRepo.IsBranchExist(refName) {
  340. commit, err = gitRepo.GetBranchCommit(refName)
  341. if err != nil {
  342. ctx.ServerError("GetBranchCommit", err)
  343. return
  344. }
  345. } else if gitRepo.IsTagExist(refName) {
  346. commit, err = gitRepo.GetTagCommit(refName)
  347. if err != nil {
  348. ctx.ServerError("GetTagCommit", err)
  349. return
  350. }
  351. } else if len(refName) >= 4 && len(refName) <= 40 {
  352. commit, err = gitRepo.GetCommit(refName)
  353. if err != nil {
  354. ctx.NotFound("GetCommit", nil)
  355. return
  356. }
  357. } else {
  358. ctx.NotFound("Download", nil)
  359. return
  360. }
  361. archivePath = path.Join(archivePath, base.ShortSha(commit.ID.String())+ext)
  362. if !com.IsFile(archivePath) {
  363. if err := commit.CreateArchive(archivePath, archiveType); err != nil {
  364. ctx.ServerError("Download -> CreateArchive "+archivePath, err)
  365. return
  366. }
  367. }
  368. ctx.ServeFile(archivePath, ctx.Repo.Repository.Name+"-"+refName+ext)
  369. }