mirror of
https://github.com/go-gitea/gitea.git
synced 2025-11-05 18:32:41 +09:00
Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fcbbc24cc4 | ||
|
|
1454e1b6eb | ||
|
|
d70348836b | ||
|
|
940a930d13 | ||
|
|
45d21a0d5c | ||
|
|
15ad001aef | ||
|
|
ed1828ca92 | ||
|
|
3cfff5af0d | ||
|
|
6f6c66a07d | ||
|
|
d65af69c2b | ||
|
|
12c24c2189 |
14
CHANGELOG.md
14
CHANGELOG.md
@@ -4,6 +4,20 @@ This changelog goes through the changes that have been made in each release
|
||||
without substantial changes to our git log; to see the highlights of what has
|
||||
been added to each release, please refer to the [blog](https://blog.gitea.com).
|
||||
|
||||
## [1.23.1](https://github.com/go-gitea/gitea/releases/tag/v1.23.1) - 2025-01-09
|
||||
|
||||
* ENHANCEMENTS
|
||||
* Move repo size to sidebar (#33155) (#33182)
|
||||
* BUGFIXES
|
||||
* Use updated path to s6-svscan after alpine upgrade (#33185) (#33188)
|
||||
* Fix fuzz test (#33156) (#33158)
|
||||
* Fix raw file API ref handling (#33172) (#33189)
|
||||
* Fix ACME panic (#33178) (#33186)
|
||||
* Fix branch dropdown not display ref name (#33159) (#33183)
|
||||
* Fix assignee list overlapping in Issue sidebar (#33176) (#33181)
|
||||
* Fix sync fork for consistency (#33147) #33192
|
||||
* Fix editor markdown not incrementing in a numbered list (#33187) #33193
|
||||
|
||||
## [1.23.0](https://github.com/go-gitea/gitea/releases/tag/v1.23.0) - 2025-01-08
|
||||
|
||||
* BREAKING
|
||||
|
||||
@@ -54,8 +54,10 @@ func runACME(listenAddr string, m http.Handler) error {
|
||||
altTLSALPNPort = p
|
||||
}
|
||||
|
||||
magic := &certmagic.Default
|
||||
magic.Storage = &certmagic.FileStorage{Path: setting.AcmeLiveDirectory}
|
||||
// FIXME: this path is not right, it uses "AppWorkPath" incorrectly, and writes the data into "AppWorkPath/https"
|
||||
// Ideally it should migrate to AppDataPath write to "AppDataPath/https"
|
||||
certmagic.Default.Storage = &certmagic.FileStorage{Path: setting.AcmeLiveDirectory}
|
||||
magic := certmagic.NewDefault()
|
||||
// Try to use private CA root if provided, otherwise defaults to system's trust
|
||||
var certPool *x509.CertPool
|
||||
if setting.AcmeCARoot != "" {
|
||||
|
||||
@@ -37,5 +37,5 @@ done
|
||||
if [ $# -gt 0 ]; then
|
||||
exec "$@"
|
||||
else
|
||||
exec /bin/s6-svscan /etc/s6
|
||||
exec /usr/bin/s6-svscan /etc/s6
|
||||
fi
|
||||
|
||||
@@ -15,5 +15,5 @@ func TestPamAuth(t *testing.T) {
|
||||
result, err := Auth("gitea", "user1", "false-pwd")
|
||||
assert.Error(t, err)
|
||||
assert.EqualError(t, err, "Authentication failure")
|
||||
assert.Len(t, result)
|
||||
assert.Empty(t, result)
|
||||
}
|
||||
|
||||
@@ -133,3 +133,11 @@ type EditBranchProtectionOption struct {
|
||||
type UpdateBranchProtectionPriories struct {
|
||||
IDs []int64 `json:"ids"`
|
||||
}
|
||||
|
||||
type MergeUpstreamRequest struct {
|
||||
Branch string `json:"branch"`
|
||||
}
|
||||
|
||||
type MergeUpstreamResponse struct {
|
||||
MergeStyle string `json:"merge_type"`
|
||||
}
|
||||
|
||||
@@ -1190,6 +1190,7 @@ func Routes() *web.Router {
|
||||
m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive)
|
||||
m.Combo("/forks").Get(repo.ListForks).
|
||||
Post(reqToken(), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork)
|
||||
m.Post("/merge-upstream", reqToken(), mustNotBeArchived, reqRepoWriter(unit.TypeCode), bind(api.MergeUpstreamRequest{}), repo.MergeUpstream)
|
||||
m.Group("/branches", func() {
|
||||
m.Get("", repo.ListBranches)
|
||||
m.Get("/*", repo.GetBranch)
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/optional"
|
||||
repo_module "code.gitea.io/gitea/modules/repository"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/modules/web"
|
||||
"code.gitea.io/gitea/routers/api/v1/utils"
|
||||
"code.gitea.io/gitea/services/context"
|
||||
@@ -1194,3 +1195,47 @@ func UpdateBranchProtectionPriories(ctx *context.APIContext) {
|
||||
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func MergeUpstream(ctx *context.APIContext) {
|
||||
// swagger:operation POST /repos/{owner}/{repo}/merge-upstream repository repoMergeUpstream
|
||||
// ---
|
||||
// summary: Merge a branch from upstream
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: body
|
||||
// in: body
|
||||
// schema:
|
||||
// "$ref": "#/definitions/MergeUpstreamRequest"
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/MergeUpstreamResponse"
|
||||
// "400":
|
||||
// "$ref": "#/responses/error"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
form := web.GetForm(ctx).(*api.MergeUpstreamRequest)
|
||||
mergeStyle, err := repo_service.MergeUpstream(ctx, ctx.Doer, ctx.Repo.Repository, form.Branch)
|
||||
if err != nil {
|
||||
if errors.Is(err, util.ErrInvalidArgument) {
|
||||
ctx.Error(http.StatusBadRequest, "MergeUpstream", err)
|
||||
return
|
||||
} else if errors.Is(err, util.ErrNotExist) {
|
||||
ctx.Error(http.StatusNotFound, "MergeUpstream", err)
|
||||
return
|
||||
}
|
||||
ctx.Error(http.StatusInternalServerError, "MergeUpstream", err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, &api.MergeUpstreamResponse{MergeStyle: mergeStyle})
|
||||
}
|
||||
|
||||
@@ -448,3 +448,15 @@ type swaggerCompare struct {
|
||||
// in:body
|
||||
Body api.Compare `json:"body"`
|
||||
}
|
||||
|
||||
// swagger:response MergeUpstreamRequest
|
||||
type swaggerMergeUpstreamRequest struct {
|
||||
// in:body
|
||||
Body api.MergeUpstreamRequest `json:"body"`
|
||||
}
|
||||
|
||||
// swagger:response MergeUpstreamResponse
|
||||
type swaggerMergeUpstreamResponse struct {
|
||||
// in:body
|
||||
Body api.MergeUpstreamResponse `json:"body"`
|
||||
}
|
||||
|
||||
@@ -305,8 +305,7 @@ func RepoRefForAPI(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
// NOTICE: the "ref" here for internal usage only (e.g. woodpecker)
|
||||
refName, _ := getRefNameLegacy(ctx.Base, ctx.Repo, ctx.FormTrim("ref"))
|
||||
refName, _ := getRefNameLegacy(ctx.Base, ctx.Repo, ctx.PathParam("*"), ctx.FormTrim("ref"))
|
||||
var err error
|
||||
|
||||
if ctx.Repo.GitRepo.IsBranchExist(refName) {
|
||||
|
||||
@@ -769,35 +769,30 @@ func getRefNameFromPath(repo *Repository, path string, isExist func(string) bool
|
||||
return ""
|
||||
}
|
||||
|
||||
func getRefNameLegacy(ctx *Base, repo *Repository, optionalExtraRef ...string) (string, RepoRefType) {
|
||||
extraRef := util.OptionalArg(optionalExtraRef)
|
||||
reqPath := ctx.PathParam("*")
|
||||
reqPath = path.Join(extraRef, reqPath)
|
||||
|
||||
if refName := getRefName(ctx, repo, RepoRefBranch); refName != "" {
|
||||
func getRefNameLegacy(ctx *Base, repo *Repository, reqPath, extraRef string) (string, RepoRefType) {
|
||||
reqRefPath := path.Join(extraRef, reqPath)
|
||||
reqRefPathParts := strings.Split(reqRefPath, "/")
|
||||
if refName := getRefName(ctx, repo, reqRefPath, RepoRefBranch); refName != "" {
|
||||
return refName, RepoRefBranch
|
||||
}
|
||||
if refName := getRefName(ctx, repo, RepoRefTag); refName != "" {
|
||||
if refName := getRefName(ctx, repo, reqRefPath, RepoRefTag); refName != "" {
|
||||
return refName, RepoRefTag
|
||||
}
|
||||
|
||||
// For legacy support only full commit sha
|
||||
parts := strings.Split(reqPath, "/")
|
||||
if git.IsStringLikelyCommitID(git.ObjectFormatFromName(repo.Repository.ObjectFormatName), parts[0]) {
|
||||
if git.IsStringLikelyCommitID(git.ObjectFormatFromName(repo.Repository.ObjectFormatName), reqRefPathParts[0]) {
|
||||
// FIXME: this logic is different from other types. Ideally, it should also try to GetCommit to check if it exists
|
||||
repo.TreePath = strings.Join(parts[1:], "/")
|
||||
return parts[0], RepoRefCommit
|
||||
repo.TreePath = strings.Join(reqRefPathParts[1:], "/")
|
||||
return reqRefPathParts[0], RepoRefCommit
|
||||
}
|
||||
|
||||
if refName := getRefName(ctx, repo, RepoRefBlob); len(refName) > 0 {
|
||||
if refName := getRefName(ctx, repo, reqPath, RepoRefBlob); refName != "" {
|
||||
return refName, RepoRefBlob
|
||||
}
|
||||
// FIXME: the old code falls back to default branch if "ref" doesn't exist, there could be an edge case:
|
||||
// "README?ref=no-such" would read the README file from the default branch, but the user might expect a 404
|
||||
repo.TreePath = reqPath
|
||||
return repo.Repository.DefaultBranch, RepoRefBranch
|
||||
}
|
||||
|
||||
func getRefName(ctx *Base, repo *Repository, pathType RepoRefType) string {
|
||||
path := ctx.PathParam("*")
|
||||
func getRefName(ctx *Base, repo *Repository, path string, pathType RepoRefType) string {
|
||||
switch pathType {
|
||||
case RepoRefBranch:
|
||||
ref := getRefNameFromPath(repo, path, repo.GitRepo.IsBranchExist)
|
||||
@@ -900,7 +895,8 @@ func RepoRefByType(detectRefType RepoRefType, opts ...RepoRefByTypeOptions) func
|
||||
}
|
||||
|
||||
// Get default branch.
|
||||
if len(ctx.PathParam("*")) == 0 {
|
||||
reqPath := ctx.PathParam("*")
|
||||
if reqPath == "" {
|
||||
refName = ctx.Repo.Repository.DefaultBranch
|
||||
if !ctx.Repo.GitRepo.IsBranchExist(refName) {
|
||||
brs, _, err := ctx.Repo.GitRepo.GetBranches(0, 1)
|
||||
@@ -925,12 +921,12 @@ func RepoRefByType(detectRefType RepoRefType, opts ...RepoRefByTypeOptions) func
|
||||
return cancel
|
||||
}
|
||||
ctx.Repo.IsViewBranch = true
|
||||
} else {
|
||||
} else { // there is a path in request
|
||||
guessLegacyPath := refType == RepoRefUnknown
|
||||
if guessLegacyPath {
|
||||
refName, refType = getRefNameLegacy(ctx.Base, ctx.Repo)
|
||||
refName, refType = getRefNameLegacy(ctx.Base, ctx.Repo, reqPath, "")
|
||||
} else {
|
||||
refName = getRefName(ctx.Base, ctx.Repo, refType)
|
||||
refName = getRefName(ctx.Base, ctx.Repo, reqPath, refType)
|
||||
}
|
||||
ctx.Repo.RefName = refName
|
||||
isRenamedBranch, has := ctx.Data["IsRenamedBranch"].(bool)
|
||||
|
||||
@@ -12,17 +12,19 @@ import (
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
"code.gitea.io/gitea/modules/gitrepo"
|
||||
repo_module "code.gitea.io/gitea/modules/repository"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/services/pull"
|
||||
)
|
||||
|
||||
type UpstreamDivergingInfo struct {
|
||||
BaseIsNewer bool
|
||||
CommitsBehind int
|
||||
CommitsAhead int
|
||||
BaseHasNewCommits bool
|
||||
CommitsBehind int
|
||||
CommitsAhead int
|
||||
}
|
||||
|
||||
// MergeUpstream merges the base repository's default branch into the fork repository's current branch.
|
||||
func MergeUpstream(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, branch string) (mergeStyle string, err error) {
|
||||
if err = repo.MustNotBeArchived(); err != nil {
|
||||
return "", err
|
||||
@@ -32,7 +34,7 @@ func MergeUpstream(ctx context.Context, doer *user_model.User, repo *repo_model.
|
||||
}
|
||||
err = git.Push(ctx, repo.BaseRepo.RepoPath(), git.PushOptions{
|
||||
Remote: repo.RepoPath(),
|
||||
Branch: fmt.Sprintf("%s:%s", branch, branch),
|
||||
Branch: fmt.Sprintf("%s:%s", repo.BaseRepo.DefaultBranch, branch),
|
||||
Env: repo_module.PushingEnvironment(doer, repo),
|
||||
})
|
||||
if err == nil {
|
||||
@@ -64,7 +66,7 @@ func MergeUpstream(ctx context.Context, doer *user_model.User, repo *repo_model.
|
||||
BaseRepoID: repo.BaseRepo.ID,
|
||||
BaseRepo: repo.BaseRepo,
|
||||
HeadBranch: branch, // maybe HeadCommitID is not needed
|
||||
BaseBranch: branch,
|
||||
BaseBranch: repo.BaseRepo.DefaultBranch,
|
||||
}
|
||||
fakeIssue.PullRequest = fakePR
|
||||
err = pull.Update(ctx, fakePR, doer, "merge upstream", false)
|
||||
@@ -74,6 +76,7 @@ func MergeUpstream(ctx context.Context, doer *user_model.User, repo *repo_model.
|
||||
return "merge", nil
|
||||
}
|
||||
|
||||
// GetUpstreamDivergingInfo returns the information about the divergence between the fork repository's branch and the base repository's default branch.
|
||||
func GetUpstreamDivergingInfo(ctx context.Context, repo *repo_model.Repository, branch string) (*UpstreamDivergingInfo, error) {
|
||||
if !repo.IsFork {
|
||||
return nil, util.NewInvalidArgumentErrorf("repo is not a fork")
|
||||
@@ -92,7 +95,7 @@ func GetUpstreamDivergingInfo(ctx context.Context, repo *repo_model.Repository,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
baseBranch, err := git_model.GetBranch(ctx, repo.BaseRepo.ID, branch)
|
||||
baseBranch, err := git_model.GetBranch(ctx, repo.BaseRepo.ID, repo.BaseRepo.DefaultBranch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -102,14 +105,42 @@ func GetUpstreamDivergingInfo(ctx context.Context, repo *repo_model.Repository,
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// TODO: if the fork repo has new commits, this call will fail:
|
||||
// if the fork repo has new commits, this call will fail because they are not in the base repo
|
||||
// exit status 128 - fatal: Invalid symmetric difference expression aaaaaaaaaaaa...bbbbbbbbbbbb
|
||||
// so at the moment, we are not able to handle this case, should be improved in the future
|
||||
// so at the moment, we first check the update time, then check whether the fork branch has base's head
|
||||
diff, err := git.GetDivergingCommits(ctx, repo.BaseRepo.RepoPath(), baseBranch.CommitID, forkBranch.CommitID)
|
||||
if err != nil {
|
||||
info.BaseIsNewer = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix
|
||||
info.BaseHasNewCommits = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix
|
||||
if info.BaseHasNewCommits {
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// if the base's update time is before the fork, check whether the base's head is in the fork
|
||||
baseGitRepo, baseGitRepoCloser, err := gitrepo.RepositoryFromContextOrOpen(ctx, repo.BaseRepo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer baseGitRepoCloser.Close()
|
||||
|
||||
headGitRepo, headGitRepoCloser, err := gitrepo.RepositoryFromContextOrOpen(ctx, repo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer headGitRepoCloser.Close()
|
||||
|
||||
baseCommitID, err := baseGitRepo.ConvertToGitID(baseBranch.CommitID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
headCommit, err := headGitRepo.GetCommit(forkBranch.CommitID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hasPreviousCommit, _ := headCommit.HasPreviousCommit(baseCommitID)
|
||||
info.BaseHasNewCommits = !hasPreviousCommit
|
||||
return info, nil
|
||||
}
|
||||
|
||||
info.CommitsBehind, info.CommitsAhead = diff.Behind, diff.Ahead
|
||||
return info, nil
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{{/* Attributes:
|
||||
* ContainerClasses
|
||||
* Repository
|
||||
* CurrentRefType: eg. "branch", "tag"
|
||||
* CurrentRefShortName: eg. "master", "v1.0"
|
||||
* CurrentRefType: eg. "branch", "tag", "commit"
|
||||
* CurrentRefShortName: eg. "master", "v1.0", "abcdef0123"
|
||||
* CurrentTreePath
|
||||
* RefLinkTemplate: redirect to the link when a branch/tag is selected
|
||||
* RefFormActionTemplate: change the parent form's action when a branch/tag is selected
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{{if and .UpstreamDivergingInfo (or .UpstreamDivergingInfo.BaseIsNewer .UpstreamDivergingInfo.CommitsBehind)}}
|
||||
{{if and .UpstreamDivergingInfo (or .UpstreamDivergingInfo.BaseHasNewCommits .UpstreamDivergingInfo.CommitsBehind)}}
|
||||
<div class="ui message flex-text-block">
|
||||
<div class="tw-flex-1">
|
||||
{{$upstreamLink := printf "%s/src/branch/%s" .Repository.BaseRepo.Link (.BranchName|PathEscapeSegments)}}
|
||||
{{$upstreamHtml := HTMLFormat `<a href="%s">%s:%s</a>` $upstreamLink .Repository.BaseRepo.FullName .BranchName}}
|
||||
{{$upstreamLink := printf "%s/src/branch/%s" .Repository.BaseRepo.Link (.Repository.BaseRepo.DefaultBranch|PathEscapeSegments)}}
|
||||
{{$upstreamHtml := HTMLFormat `<a href="%s">%s:%s</a>` $upstreamLink .Repository.BaseRepo.FullName .Repository.BaseRepo.DefaultBranch}}
|
||||
{{if .UpstreamDivergingInfo.CommitsBehind}}
|
||||
{{ctx.Locale.TrN .UpstreamDivergingInfo.CommitsBehind "repo.pulls.upstream_diverging_prompt_behind_1" "repo.pulls.upstream_diverging_prompt_behind_n" .UpstreamDivergingInfo.CommitsBehind $upstreamHtml}}
|
||||
{{else}}
|
||||
|
||||
@@ -5,14 +5,19 @@
|
||||
{{template "repo/sub_menu" .}}
|
||||
<div class="repo-button-row">
|
||||
<div class="repo-button-row-left">
|
||||
|
||||
{{$branchDropdownCurrentRefType := "branch"}}
|
||||
{{$branchDropdownCurrentRefShortName := .BranchName}}
|
||||
{{if .IsViewTag}}
|
||||
{{$branchDropdownCurrentRefType = "tag"}}
|
||||
{{$branchDropdownCurrentRefShortName = .TagName}}
|
||||
{{end}}
|
||||
{{template "repo/branch_dropdown" dict
|
||||
{{- /* for /owner/repo/commits/branch/the-name */ -}}
|
||||
{{- $branchDropdownCurrentRefType := "branch" -}}
|
||||
{{- $branchDropdownCurrentRefShortName := .BranchName -}}
|
||||
{{- if .IsViewTag -}}
|
||||
{{- /* for /owner/repo/commits/tag/the-name */ -}}
|
||||
{{- $branchDropdownCurrentRefType = "tag" -}}
|
||||
{{- $branchDropdownCurrentRefShortName = .TagName -}}
|
||||
{{- else if .IsViewCommit -}}
|
||||
{{- /* for /owner/repo/commits/commit/000000 */ -}}
|
||||
{{- $branchDropdownCurrentRefType = "commit" -}}
|
||||
{{- $branchDropdownCurrentRefShortName = ShortSha .CommitID -}}
|
||||
{{- end -}}
|
||||
{{- template "repo/branch_dropdown" dict
|
||||
"Repository" .Repository
|
||||
"ShowTabBranches" true
|
||||
"ShowTabTags" true
|
||||
@@ -21,8 +26,7 @@
|
||||
"CurrentTreePath" .TreePath
|
||||
"RefLinkTemplate" "{RepoLink}/commits/{RefType}/{RefShortName}/{TreePath}"
|
||||
"AllowCreateNewRef" .CanCreateBranch
|
||||
}}
|
||||
|
||||
-}}
|
||||
<a href="{{.RepoLink}}/graph" class="ui basic small compact button">
|
||||
{{svg "octicon-git-branch"}}
|
||||
{{ctx.Locale.Tr "repo.commit_graph"}}
|
||||
|
||||
@@ -24,13 +24,19 @@
|
||||
{{template "repo/sub_menu" .}}
|
||||
<div class="repo-button-row">
|
||||
<div class="repo-button-row-left">
|
||||
{{$branchDropdownCurrentRefType := "branch"}}
|
||||
{{$branchDropdownCurrentRefShortName := .BranchName}}
|
||||
{{if .IsViewTag}}
|
||||
{{$branchDropdownCurrentRefType = "tag"}}
|
||||
{{$branchDropdownCurrentRefShortName = .TagName}}
|
||||
{{end}}
|
||||
{{template "repo/branch_dropdown" dict
|
||||
{{- /* for repo home (default branch) and /owner/repo/src/branch/the-name */ -}}
|
||||
{{- $branchDropdownCurrentRefType := "branch" -}}
|
||||
{{- $branchDropdownCurrentRefShortName := .BranchName -}}
|
||||
{{- if .IsViewTag -}}
|
||||
{{- /* for /owner/repo/src/tag/the-name */ -}}
|
||||
{{- $branchDropdownCurrentRefType = "tag" -}}
|
||||
{{- $branchDropdownCurrentRefShortName = .TagName -}}
|
||||
{{- else if .IsViewCommit -}}
|
||||
{{- /* for /owner/repo/src/commit/000000 */ -}}
|
||||
{{- $branchDropdownCurrentRefType = "commit" -}}
|
||||
{{- $branchDropdownCurrentRefShortName = ShortSha .CommitID -}}
|
||||
{{- end -}}
|
||||
{{- template "repo/branch_dropdown" dict
|
||||
"Repository" .Repository
|
||||
"ShowTabBranches" true
|
||||
"ShowTabTags" true
|
||||
@@ -40,7 +46,7 @@
|
||||
"RefLinkTemplate" "{RepoLink}/src/{RefType}/{RefShortName}/{TreePath}"
|
||||
"AllowCreateNewRef" .CanCreateBranch
|
||||
"ShowViewAllRefsEntry" true
|
||||
}}
|
||||
-}}
|
||||
{{if and .CanCompareOrPull .IsViewBranch (not .Repository.IsArchived)}}
|
||||
{{$cmpBranch := ""}}
|
||||
{{if ne .Repository.ID .BaseRepo.ID}}
|
||||
|
||||
@@ -62,6 +62,11 @@
|
||||
{{svg "octicon-cross-reference"}} {{ctx.Locale.Tr "repo.cite_this_repo"}}
|
||||
</a>
|
||||
{{end}}
|
||||
<span class="flex-text-block muted" {{if not (eq .Repository.Size 0)}}data-tooltip-placement="top" data-tooltip-content="{{.Repository.SizeDetailsString}}"{{end}}>
|
||||
{{$fileSizeFormatted := FileSize .Repository.Size}}{{/* the formatted string is always "{val} {unit}" */}}
|
||||
{{$fileSizeFields := StringUtils.Split $fileSizeFormatted " "}}
|
||||
{{svg "octicon-database"}} <b>{{ctx.Locale.PrettyNumber (index $fileSizeFields 0)}}</b> {{index $fileSizeFields 1}}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -16,9 +16,9 @@
|
||||
<input type="text" placeholder="{{ctx.Locale.Tr "repo.issues.filter_assignees"}}">
|
||||
</div>
|
||||
<div class="item clear-selection">{{ctx.Locale.Tr "repo.issues.new.clear_assignees"}}</div>
|
||||
<div class="scrolling menu">
|
||||
<div class="scrolling menu flex-items-block">
|
||||
{{range $data.CandidateAssignees}}
|
||||
<a class="item muted" href="#" data-value="{{.ID}}">
|
||||
<a class="item" href="#" data-value="{{.ID}}">
|
||||
<span class="item-check-mark">{{svg "octicon-check"}}</span>
|
||||
{{ctx.AvatarUtils.Avatar . 20}} {{template "repo/search_name" .}}
|
||||
</a>
|
||||
@@ -26,10 +26,10 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ui list tw-flex tw-flex-row tw-gap-2">
|
||||
<div class="ui list muted-links flex-items-block tw-flex tw-flex-col tw-gap-2">
|
||||
<span class="item empty-list {{if $issueAssignees}}tw-hidden{{end}}">{{ctx.Locale.Tr "repo.issues.new.no_assignees"}}</span>
|
||||
{{range $issueAssignees}}
|
||||
<a class="item muted" href="{{$pageMeta.RepoLink}}/{{if $pageMeta.IsPullRequest}}pulls{{else}}issues{{end}}?assignee={{.ID}}">
|
||||
<a class="item" href="{{$pageMeta.RepoLink}}/{{if $pageMeta.IsPullRequest}}pulls{{else}}issues{{end}}?assignee={{.ID}}">
|
||||
{{ctx.AvatarUtils.Avatar . 20}} {{.GetDisplayName}}
|
||||
</a>
|
||||
{{end}}
|
||||
|
||||
@@ -13,11 +13,6 @@
|
||||
{{svg "octicon-tag"}} <b>{{ctx.Locale.PrettyNumber .NumTags}}</b> {{ctx.Locale.TrN .NumTags "repo.tag" "repo.tags"}}
|
||||
</a>
|
||||
{{end}}
|
||||
<span class="item not-mobile" {{if not (eq .Repository.Size 0)}}data-tooltip-placement="top" data-tooltip-content="{{.Repository.SizeDetailsString}}"{{end}}>
|
||||
{{$fileSizeFormatted := FileSize .Repository.Size}}{{/* the formatted string is always "{val} {unit}" */}}
|
||||
{{$fileSizeFields := StringUtils.Split $fileSizeFormatted " "}}
|
||||
{{svg "octicon-database"}} <b>{{ctx.Locale.PrettyNumber (index $fileSizeFields 0)}}</b> {{index $fileSizeFields 1}}
|
||||
</span>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
78
templates/swagger/v1_json.tmpl
generated
78
templates/swagger/v1_json.tmpl
generated
@@ -10867,6 +10867,52 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/repos/{owner}/{repo}/merge-upstream": {
|
||||
"post": {
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"repository"
|
||||
],
|
||||
"summary": "Merge a branch from upstream",
|
||||
"operationId": "repoMergeUpstream",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "owner of the repo",
|
||||
"name": "owner",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "name of the repo",
|
||||
"name": "repo",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/MergeUpstreamRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/responses/MergeUpstreamResponse"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/responses/error"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/responses/notFound"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/repos/{owner}/{repo}/milestones": {
|
||||
"get": {
|
||||
"produces": [
|
||||
@@ -22827,6 +22873,26 @@
|
||||
"x-go-name": "MergePullRequestForm",
|
||||
"x-go-package": "code.gitea.io/gitea/services/forms"
|
||||
},
|
||||
"MergeUpstreamRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"branch": {
|
||||
"type": "string",
|
||||
"x-go-name": "Branch"
|
||||
}
|
||||
},
|
||||
"x-go-package": "code.gitea.io/gitea/modules/structs"
|
||||
},
|
||||
"MergeUpstreamResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"merge_type": {
|
||||
"type": "string",
|
||||
"x-go-name": "MergeStyle"
|
||||
}
|
||||
},
|
||||
"x-go-package": "code.gitea.io/gitea/modules/structs"
|
||||
},
|
||||
"MigrateRepoOptions": {
|
||||
"description": "MigrateRepoOptions options for migrating repository's\nthis is used to interact with api v1",
|
||||
"type": "object",
|
||||
@@ -26008,6 +26074,18 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"MergeUpstreamRequest": {
|
||||
"description": "",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/MergeUpstreamRequest"
|
||||
}
|
||||
},
|
||||
"MergeUpstreamResponse": {
|
||||
"description": "",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/MergeUpstreamResponse"
|
||||
}
|
||||
},
|
||||
"Milestone": {
|
||||
"description": "Milestone",
|
||||
"schema": {
|
||||
|
||||
@@ -19,6 +19,7 @@ func newFuzzRenderContext() *markup.RenderContext {
|
||||
|
||||
func FuzzMarkdownRenderRaw(f *testing.F) {
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
setting.IsInTesting = true
|
||||
setting.AppURL = "http://localhost:3000/"
|
||||
markdown.RenderRaw(newFuzzRenderContext(), bytes.NewReader(data), io.Discard)
|
||||
})
|
||||
@@ -26,6 +27,7 @@ func FuzzMarkdownRenderRaw(f *testing.F) {
|
||||
|
||||
func FuzzMarkupPostProcess(f *testing.F) {
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
setting.IsInTesting = true
|
||||
setting.AppURL = "http://localhost:3000/"
|
||||
markup.PostProcessDefault(newFuzzRenderContext(), bytes.NewReader(data), io.Discard)
|
||||
})
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
repo_service "code.gitea.io/gitea/services/repository"
|
||||
"code.gitea.io/gitea/tests"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
@@ -168,28 +169,37 @@ func testAPIGetContents(t *testing.T, u *url.URL) {
|
||||
}
|
||||
|
||||
func TestAPIGetContentsRefFormats(t *testing.T) {
|
||||
onGiteaRun(t, func(t *testing.T, u *url.URL) {
|
||||
file := "README.md"
|
||||
sha := "65f1bf27bc3bf70f64657658635e66094edbcb4d"
|
||||
content := "# repo1\n\nDescription for repo1"
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
|
||||
noRef := setting.AppURL + "api/v1/repos/user2/repo1/raw/" + file
|
||||
refInPath := setting.AppURL + "api/v1/repos/user2/repo1/raw/" + sha + "/" + file
|
||||
refInQuery := setting.AppURL + "api/v1/repos/user2/repo1/raw/" + file + "?ref=" + sha
|
||||
file := "README.md"
|
||||
sha := "65f1bf27bc3bf70f64657658635e66094edbcb4d"
|
||||
content := "# repo1\n\nDescription for repo1"
|
||||
|
||||
resp := MakeRequest(t, NewRequest(t, http.MethodGet, noRef), http.StatusOK)
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, content, string(raw))
|
||||
resp := MakeRequest(t, NewRequest(t, http.MethodGet, "/api/v1/repos/user2/repo1/raw/"+file), http.StatusOK)
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, content, string(raw))
|
||||
|
||||
resp = MakeRequest(t, NewRequest(t, http.MethodGet, refInPath), http.StatusOK)
|
||||
raw, err = io.ReadAll(resp.Body)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, content, string(raw))
|
||||
resp = MakeRequest(t, NewRequest(t, http.MethodGet, "/api/v1/repos/user2/repo1/raw/"+sha+"/"+file), http.StatusOK)
|
||||
raw, err = io.ReadAll(resp.Body)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, content, string(raw))
|
||||
|
||||
resp = MakeRequest(t, NewRequest(t, http.MethodGet, refInQuery), http.StatusOK)
|
||||
raw, err = io.ReadAll(resp.Body)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, content, string(raw))
|
||||
})
|
||||
resp = MakeRequest(t, NewRequest(t, http.MethodGet, "/api/v1/repos/user2/repo1/raw/"+file+"?ref="+sha), http.StatusOK)
|
||||
raw, err = io.ReadAll(resp.Body)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, content, string(raw))
|
||||
|
||||
resp = MakeRequest(t, NewRequest(t, http.MethodGet, "/api/v1/repos/user2/repo1/raw/"+file+"?ref=master"), http.StatusOK)
|
||||
raw, err = io.ReadAll(resp.Body)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, content, string(raw))
|
||||
|
||||
_ = MakeRequest(t, NewRequest(t, http.MethodGet, "/api/v1/repos/user2/repo1/raw/docs/README.md?ref=main"), http.StatusNotFound)
|
||||
_ = MakeRequest(t, NewRequest(t, http.MethodGet, "/api/v1/repos/user2/repo1/raw/README.md?ref=main"), http.StatusOK)
|
||||
_ = MakeRequest(t, NewRequest(t, http.MethodGet, "/api/v1/repos/user2/repo1/raw/docs/README.md?ref=sub-home-md-img-check"), http.StatusOK)
|
||||
_ = MakeRequest(t, NewRequest(t, http.MethodGet, "/api/v1/repos/user2/repo1/raw/README.md?ref=sub-home-md-img-check"), http.StatusNotFound)
|
||||
|
||||
// FIXME: this is an incorrect behavior, non-existing branch falls back to default branch
|
||||
_ = MakeRequest(t, NewRequest(t, http.MethodGet, "/api/v1/repos/user2/repo1/raw/README.md?ref=no-such"), http.StatusOK)
|
||||
}
|
||||
|
||||
122
tests/integration/repo_merge_upstream_test.go
Normal file
122
tests/integration/repo_merge_upstream_test.go
Normal file
@@ -0,0 +1,122 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
auth_model "code.gitea.io/gitea/models/auth"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
git_model "code.gitea.io/gitea/models/git"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRepoMergeUpstream(t *testing.T) {
|
||||
onGiteaRun(t, func(*testing.T, *url.URL) {
|
||||
forkUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4})
|
||||
|
||||
baseRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
baseUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: baseRepo.OwnerID})
|
||||
|
||||
checkFileContent := func(branch, exp string) {
|
||||
req := NewRequest(t, "GET", fmt.Sprintf("/%s/test-repo-fork/raw/branch/%s/new-file.txt", forkUser.Name, branch))
|
||||
resp := MakeRequest(t, req, http.StatusOK)
|
||||
require.Equal(t, exp, resp.Body.String())
|
||||
}
|
||||
|
||||
session := loginUser(t, forkUser.Name)
|
||||
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
|
||||
|
||||
// create a fork
|
||||
req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/forks", baseUser.Name, baseRepo.Name), &api.CreateForkOption{
|
||||
Name: util.ToPointer("test-repo-fork"),
|
||||
}).AddTokenAuth(token)
|
||||
MakeRequest(t, req, http.StatusAccepted)
|
||||
forkRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: forkUser.ID, Name: "test-repo-fork"})
|
||||
|
||||
// create fork-branch
|
||||
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/test-repo-fork/branches/_new/branch/master", forkUser.Name), map[string]string{
|
||||
"_csrf": GetUserCSRFToken(t, session),
|
||||
"new_branch_name": "fork-branch",
|
||||
})
|
||||
session.MakeRequest(t, req, http.StatusSeeOther)
|
||||
|
||||
queryMergeUpstreamButtonLink := func(htmlDoc *HTMLDoc) string {
|
||||
return htmlDoc.Find(`button[data-url*="merge-upstream"]`).AttrOr("data-url", "")
|
||||
}
|
||||
|
||||
t.Run("HeadBeforeBase", func(t *testing.T) {
|
||||
// add a file in base repo
|
||||
require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "new-file.txt", "master", "test-content-1"))
|
||||
|
||||
// the repo shows a prompt to "sync fork"
|
||||
var mergeUpstreamLink string
|
||||
require.Eventually(t, func() bool {
|
||||
resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork/src/branch/fork-branch", forkUser.Name), http.StatusOK)
|
||||
htmlDoc := NewHTMLParser(t, resp.Body)
|
||||
mergeUpstreamLink = queryMergeUpstreamButtonLink(htmlDoc)
|
||||
if mergeUpstreamLink == "" {
|
||||
return false
|
||||
}
|
||||
respMsg, _ := htmlDoc.Find(".ui.message:not(.positive)").Html()
|
||||
return strings.Contains(respMsg, `This branch is 1 commit behind <a href="/user2/repo1/src/branch/master">user2/repo1:master</a>`)
|
||||
}, 5*time.Second, 100*time.Millisecond)
|
||||
|
||||
// click the "sync fork" button
|
||||
req = NewRequestWithValues(t, "POST", mergeUpstreamLink, map[string]string{"_csrf": GetUserCSRFToken(t, session)})
|
||||
session.MakeRequest(t, req, http.StatusOK)
|
||||
checkFileContent("fork-branch", "test-content-1")
|
||||
})
|
||||
|
||||
t.Run("BaseChangeAfterHeadChange", func(t *testing.T) {
|
||||
// update the files: base first, head later, and check the prompt
|
||||
require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "new-file.txt", "master", "test-content-2"))
|
||||
require.NoError(t, createOrReplaceFileInBranch(forkUser, forkRepo, "new-file-other.txt", "fork-branch", "test-content-other"))
|
||||
|
||||
// make sure the base branch's update time is before the fork, to make it test the complete logic
|
||||
baseBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: baseRepo.ID, Name: "master"})
|
||||
forkBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: forkRepo.ID, Name: "fork-branch"})
|
||||
_, err := db.GetEngine(db.DefaultContext).ID(forkBranch.ID).Update(&git_model.Branch{UpdatedUnix: baseBranch.UpdatedUnix + 1})
|
||||
require.NoError(t, err)
|
||||
|
||||
// the repo shows a prompt to "sync fork"
|
||||
require.Eventually(t, func() bool {
|
||||
resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork/src/branch/fork-branch", forkUser.Name), http.StatusOK)
|
||||
htmlDoc := NewHTMLParser(t, resp.Body)
|
||||
respMsg, _ := htmlDoc.Find(".ui.message:not(.positive)").Html()
|
||||
return strings.Contains(respMsg, `The base branch <a href="/user2/repo1/src/branch/master">user2/repo1:master</a> has new changes`)
|
||||
}, 5*time.Second, 100*time.Millisecond)
|
||||
|
||||
// and do the merge-upstream by API
|
||||
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/test-repo-fork/merge-upstream", forkUser.Name), &api.MergeUpstreamRequest{
|
||||
Branch: "fork-branch",
|
||||
}).AddTokenAuth(token)
|
||||
resp := MakeRequest(t, req, http.StatusOK)
|
||||
checkFileContent("fork-branch", "test-content-2")
|
||||
|
||||
var mergeResp api.MergeUpstreamResponse
|
||||
DecodeJSON(t, resp, &mergeResp)
|
||||
assert.Equal(t, "merge", mergeResp.MergeStyle)
|
||||
|
||||
// after merge, there should be no "sync fork" button anymore
|
||||
require.Eventually(t, func() bool {
|
||||
resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork/src/branch/fork-branch", forkUser.Name), http.StatusOK)
|
||||
htmlDoc := NewHTMLParser(t, resp.Body)
|
||||
return queryMergeUpstreamButtonLink(htmlDoc) == ""
|
||||
}, 5*time.Second, 100*time.Millisecond)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,4 +1,166 @@
|
||||
import {initTextareaMarkdown} from './EditorMarkdown.ts';
|
||||
import {initTextareaMarkdown, markdownHandleIndention, textareaSplitLines} from './EditorMarkdown.ts';
|
||||
|
||||
test('textareaSplitLines', () => {
|
||||
let ret = textareaSplitLines('a\nbc\nd', 0);
|
||||
expect(ret).toEqual({lines: ['a', 'bc', 'd'], lengthBeforePosLine: 0, posLineIndex: 0, inlinePos: 0});
|
||||
|
||||
ret = textareaSplitLines('a\nbc\nd', 1);
|
||||
expect(ret).toEqual({lines: ['a', 'bc', 'd'], lengthBeforePosLine: 0, posLineIndex: 0, inlinePos: 1});
|
||||
|
||||
ret = textareaSplitLines('a\nbc\nd', 2);
|
||||
expect(ret).toEqual({lines: ['a', 'bc', 'd'], lengthBeforePosLine: 2, posLineIndex: 1, inlinePos: 0});
|
||||
|
||||
ret = textareaSplitLines('a\nbc\nd', 3);
|
||||
expect(ret).toEqual({lines: ['a', 'bc', 'd'], lengthBeforePosLine: 2, posLineIndex: 1, inlinePos: 1});
|
||||
|
||||
ret = textareaSplitLines('a\nbc\nd', 4);
|
||||
expect(ret).toEqual({lines: ['a', 'bc', 'd'], lengthBeforePosLine: 2, posLineIndex: 1, inlinePos: 2});
|
||||
|
||||
ret = textareaSplitLines('a\nbc\nd', 5);
|
||||
expect(ret).toEqual({lines: ['a', 'bc', 'd'], lengthBeforePosLine: 5, posLineIndex: 2, inlinePos: 0});
|
||||
|
||||
ret = textareaSplitLines('a\nbc\nd', 6);
|
||||
expect(ret).toEqual({lines: ['a', 'bc', 'd'], lengthBeforePosLine: 5, posLineIndex: 2, inlinePos: 1});
|
||||
});
|
||||
|
||||
test('markdownHandleIndention', () => {
|
||||
const testInput = (input: string, expected?: string) => {
|
||||
const inputPos = input.indexOf('|');
|
||||
input = input.replace('|', '');
|
||||
const ret = markdownHandleIndention({value: input, selStart: inputPos, selEnd: inputPos});
|
||||
if (expected === null) {
|
||||
expect(ret).toEqual({handled: false});
|
||||
} else {
|
||||
const expectedPos = expected.indexOf('|');
|
||||
expected = expected.replace('|', '');
|
||||
expect(ret).toEqual({
|
||||
handled: true,
|
||||
valueSelection: {value: expected, selStart: expectedPos, selEnd: expectedPos},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
testInput(`
|
||||
a|b
|
||||
`, `
|
||||
a
|
||||
|b
|
||||
`);
|
||||
|
||||
testInput(`
|
||||
1. a
|
||||
2. |
|
||||
`, `
|
||||
1. a
|
||||
|
|
||||
`);
|
||||
|
||||
testInput(`
|
||||
|1. a
|
||||
`, null); // let browser handle it
|
||||
|
||||
testInput(`
|
||||
1. a
|
||||
1. b|c
|
||||
`, `
|
||||
1. a
|
||||
2. b
|
||||
3. |c
|
||||
`);
|
||||
|
||||
testInput(`
|
||||
2. a
|
||||
2. b|
|
||||
|
||||
1. x
|
||||
1. y
|
||||
`, `
|
||||
1. a
|
||||
2. b
|
||||
3. |
|
||||
|
||||
1. x
|
||||
1. y
|
||||
`);
|
||||
|
||||
testInput(`
|
||||
2. a
|
||||
2. b
|
||||
|
||||
1. x|
|
||||
1. y
|
||||
`, `
|
||||
2. a
|
||||
2. b
|
||||
|
||||
1. x
|
||||
2. |
|
||||
3. y
|
||||
`);
|
||||
|
||||
testInput(`
|
||||
1. a
|
||||
2. b|
|
||||
3. c
|
||||
`, `
|
||||
1. a
|
||||
2. b
|
||||
3. |
|
||||
4. c
|
||||
`);
|
||||
|
||||
testInput(`
|
||||
1. a
|
||||
1. b
|
||||
2. b
|
||||
3. b
|
||||
4. b
|
||||
1. c|
|
||||
`, `
|
||||
1. a
|
||||
1. b
|
||||
2. b
|
||||
3. b
|
||||
4. b
|
||||
2. c
|
||||
3. |
|
||||
`);
|
||||
|
||||
testInput(`
|
||||
1. a
|
||||
2. a
|
||||
3. a
|
||||
4. a
|
||||
5. a
|
||||
6. a
|
||||
7. a
|
||||
8. a
|
||||
9. b|c
|
||||
`, `
|
||||
1. a
|
||||
2. a
|
||||
3. a
|
||||
4. a
|
||||
5. a
|
||||
6. a
|
||||
7. a
|
||||
8. a
|
||||
9. b
|
||||
10. |c
|
||||
`);
|
||||
|
||||
// this is a special case, it's difficult to re-format the parent level at the moment, so leave it to the future
|
||||
testInput(`
|
||||
1. a
|
||||
2. b|
|
||||
3. c
|
||||
`, `
|
||||
1. a
|
||||
1. b
|
||||
2. |
|
||||
3. c
|
||||
`);
|
||||
});
|
||||
|
||||
test('EditorMarkdown', () => {
|
||||
const textarea = document.createElement('textarea');
|
||||
@@ -32,10 +194,10 @@ test('EditorMarkdown', () => {
|
||||
testInput({value: '1. \n2. ', pos: 3}, {value: '\n2. ', pos: 0});
|
||||
|
||||
testInput('- x', '- x\n- ');
|
||||
testInput('1. foo', '1. foo\n1. ');
|
||||
testInput({value: '1. a\n2. b\n3. c', pos: 4}, {value: '1. a\n1. \n2. b\n3. c', pos: 8});
|
||||
testInput('1. foo', '1. foo\n2. ');
|
||||
testInput({value: '1. a\n2. b\n3. c', pos: 4}, {value: '1. a\n2. \n3. b\n4. c', pos: 8});
|
||||
testInput('- [ ]', '- [ ]\n- ');
|
||||
testInput('- [ ] foo', '- [ ] foo\n- [ ] ');
|
||||
testInput('* [x] foo', '* [x] foo\n* [ ] ');
|
||||
testInput('1. [x] foo', '1. [x] foo\n1. [ ] ');
|
||||
testInput('1. [x] foo', '1. [x] foo\n2. [ ] ');
|
||||
});
|
||||
|
||||
@@ -14,7 +14,13 @@ export function textareaInsertText(textarea, value) {
|
||||
triggerEditorContentChanged(textarea);
|
||||
}
|
||||
|
||||
function handleIndentSelection(textarea, e) {
|
||||
type TextareaValueSelection = {
|
||||
value: string;
|
||||
selStart: number;
|
||||
selEnd: number;
|
||||
}
|
||||
|
||||
function handleIndentSelection(textarea: HTMLTextAreaElement, e) {
|
||||
const selStart = textarea.selectionStart;
|
||||
const selEnd = textarea.selectionEnd;
|
||||
if (selEnd === selStart) return; // do not process when no selection
|
||||
@@ -56,53 +62,125 @@ function handleIndentSelection(textarea, e) {
|
||||
triggerEditorContentChanged(textarea);
|
||||
}
|
||||
|
||||
function handleNewline(textarea: HTMLTextAreaElement, e: Event) {
|
||||
const selStart = textarea.selectionStart;
|
||||
const selEnd = textarea.selectionEnd;
|
||||
if (selEnd !== selStart) return; // do not process when there is a selection
|
||||
type MarkdownHandleIndentionResult = {
|
||||
handled: boolean;
|
||||
valueSelection?: TextareaValueSelection;
|
||||
}
|
||||
|
||||
const value = textarea.value;
|
||||
type TextLinesBuffer = {
|
||||
lines: string[];
|
||||
lengthBeforePosLine: number;
|
||||
posLineIndex: number;
|
||||
inlinePos: number
|
||||
}
|
||||
|
||||
// find the current line
|
||||
// * if selStart is 0, lastIndexOf(..., -1) is the same as lastIndexOf(..., 0)
|
||||
// * if lastIndexOf reruns -1, lineStart is 0 and it is still correct.
|
||||
const lineStart = value.lastIndexOf('\n', selStart - 1) + 1;
|
||||
let lineEnd = value.indexOf('\n', selStart);
|
||||
lineEnd = lineEnd < 0 ? value.length : lineEnd;
|
||||
let line = value.slice(lineStart, lineEnd);
|
||||
if (!line) return; // if the line is empty, do nothing, let the browser handle it
|
||||
export function textareaSplitLines(value: string, pos: number): TextLinesBuffer {
|
||||
const lines = value.split('\n');
|
||||
let lengthBeforePosLine = 0, inlinePos = 0, posLineIndex = 0;
|
||||
for (; posLineIndex < lines.length; posLineIndex++) {
|
||||
const lineLength = lines[posLineIndex].length + 1;
|
||||
if (lengthBeforePosLine + lineLength > pos) {
|
||||
inlinePos = pos - lengthBeforePosLine;
|
||||
break;
|
||||
}
|
||||
lengthBeforePosLine += lineLength;
|
||||
}
|
||||
return {lines, lengthBeforePosLine, posLineIndex, inlinePos};
|
||||
}
|
||||
|
||||
function markdownReformatListNumbers(linesBuf: TextLinesBuffer, indention: string) {
|
||||
const reDeeperIndention = new RegExp(`^${indention}\\s+`);
|
||||
const reSameLevel = new RegExp(`^${indention}([0-9]+)\\.`);
|
||||
let firstLineIdx: number;
|
||||
for (firstLineIdx = linesBuf.posLineIndex - 1; firstLineIdx >= 0; firstLineIdx--) {
|
||||
const line = linesBuf.lines[firstLineIdx];
|
||||
if (!reDeeperIndention.test(line) && !reSameLevel.test(line)) break;
|
||||
}
|
||||
firstLineIdx++;
|
||||
let num = 1;
|
||||
for (let i = firstLineIdx; i < linesBuf.lines.length; i++) {
|
||||
const oldLine = linesBuf.lines[i];
|
||||
const sameLevel = reSameLevel.test(oldLine);
|
||||
if (!sameLevel && !reDeeperIndention.test(oldLine)) break;
|
||||
if (sameLevel) {
|
||||
const newLine = `${indention}${num}.${oldLine.replace(reSameLevel, '')}`;
|
||||
linesBuf.lines[i] = newLine;
|
||||
num++;
|
||||
if (linesBuf.posLineIndex === i) {
|
||||
// need to correct the cursor inline position if the line length changes
|
||||
linesBuf.inlinePos += newLine.length - oldLine.length;
|
||||
linesBuf.inlinePos = Math.max(0, linesBuf.inlinePos);
|
||||
linesBuf.inlinePos = Math.min(newLine.length, linesBuf.inlinePos);
|
||||
}
|
||||
}
|
||||
}
|
||||
recalculateLengthBeforeLine(linesBuf);
|
||||
}
|
||||
|
||||
function recalculateLengthBeforeLine(linesBuf: TextLinesBuffer) {
|
||||
linesBuf.lengthBeforePosLine = 0;
|
||||
for (let i = 0; i < linesBuf.posLineIndex; i++) {
|
||||
linesBuf.lengthBeforePosLine += linesBuf.lines[i].length + 1;
|
||||
}
|
||||
}
|
||||
|
||||
export function markdownHandleIndention(tvs: TextareaValueSelection): MarkdownHandleIndentionResult {
|
||||
const unhandled: MarkdownHandleIndentionResult = {handled: false};
|
||||
if (tvs.selEnd !== tvs.selStart) return unhandled; // do not process when there is a selection
|
||||
|
||||
const linesBuf = textareaSplitLines(tvs.value, tvs.selStart);
|
||||
const line = linesBuf.lines[linesBuf.posLineIndex] ?? '';
|
||||
if (!line) return unhandled; // if the line is empty, do nothing, let the browser handle it
|
||||
|
||||
// parse the indention
|
||||
const indention = /^\s*/.exec(line)[0];
|
||||
line = line.slice(indention.length);
|
||||
let lineContent = line;
|
||||
const indention = /^\s*/.exec(lineContent)[0];
|
||||
lineContent = lineContent.slice(indention.length);
|
||||
if (linesBuf.inlinePos <= indention.length) return unhandled; // if cursor is at the indention, do nothing, let the browser handle it
|
||||
|
||||
// parse the prefixes: "1. ", "- ", "* ", there could also be " [ ] " or " [x] " for task lists
|
||||
// there must be a space after the prefix because none of "1.foo" / "-foo" is a list item
|
||||
const prefixMatch = /^([0-9]+\.|[-*])(\s\[([ x])\])?\s/.exec(line);
|
||||
const prefixMatch = /^([0-9]+\.|[-*])(\s\[([ x])\])?\s/.exec(lineContent);
|
||||
let prefix = '';
|
||||
if (prefixMatch) {
|
||||
prefix = prefixMatch[0];
|
||||
if (lineStart + prefix.length > selStart) prefix = ''; // do not add new line if cursor is at prefix
|
||||
if (prefix.length > linesBuf.inlinePos) prefix = ''; // do not add new line if cursor is at prefix
|
||||
}
|
||||
|
||||
line = line.slice(prefix.length);
|
||||
if (!indention && !prefix) return; // if no indention and no prefix, do nothing, let the browser handle it
|
||||
lineContent = lineContent.slice(prefix.length);
|
||||
if (!indention && !prefix) return unhandled; // if no indention and no prefix, do nothing, let the browser handle it
|
||||
|
||||
e.preventDefault();
|
||||
if (!line) {
|
||||
if (!lineContent) {
|
||||
// clear current line if we only have i.e. '1. ' and the user presses enter again to finish creating a list
|
||||
textarea.value = value.slice(0, lineStart) + value.slice(lineEnd);
|
||||
textarea.setSelectionRange(selStart - prefix.length, selStart - prefix.length);
|
||||
linesBuf.lines[linesBuf.posLineIndex] = '';
|
||||
linesBuf.inlinePos = 0;
|
||||
} else {
|
||||
// start a new line with the same indention and prefix
|
||||
// start a new line with the same indention
|
||||
let newPrefix = prefix;
|
||||
// a simple approach, otherwise it needs to parse the lines after the current line
|
||||
if (/^\d+\./.test(prefix)) newPrefix = `1. ${newPrefix.slice(newPrefix.indexOf('.') + 2)}`;
|
||||
newPrefix = newPrefix.replace('[x]', '[ ]');
|
||||
const newLine = `\n${indention}${newPrefix}`;
|
||||
textarea.value = value.slice(0, selStart) + newLine + value.slice(selEnd);
|
||||
textarea.setSelectionRange(selStart + newLine.length, selStart + newLine.length);
|
||||
|
||||
const inlinePos = linesBuf.inlinePos;
|
||||
linesBuf.lines[linesBuf.posLineIndex] = line.substring(0, inlinePos);
|
||||
const newLineLeft = `${indention}${newPrefix}`;
|
||||
const newLine = `${newLineLeft}${line.substring(inlinePos)}`;
|
||||
linesBuf.lines.splice(linesBuf.posLineIndex + 1, 0, newLine);
|
||||
linesBuf.posLineIndex++;
|
||||
linesBuf.inlinePos = newLineLeft.length;
|
||||
recalculateLengthBeforeLine(linesBuf);
|
||||
}
|
||||
|
||||
markdownReformatListNumbers(linesBuf, indention);
|
||||
const newPos = linesBuf.lengthBeforePosLine + linesBuf.inlinePos;
|
||||
return {handled: true, valueSelection: {value: linesBuf.lines.join('\n'), selStart: newPos, selEnd: newPos}};
|
||||
}
|
||||
|
||||
function handleNewline(textarea: HTMLTextAreaElement, e: Event) {
|
||||
const ret = markdownHandleIndention({value: textarea.value, selStart: textarea.selectionStart, selEnd: textarea.selectionEnd});
|
||||
if (!ret.handled) return;
|
||||
e.preventDefault();
|
||||
textarea.value = ret.valueSelection.value;
|
||||
textarea.setSelectionRange(ret.valueSelection.selStart, ret.valueSelection.selEnd);
|
||||
triggerEditorContentChanged(textarea);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user