Merge branch 'main' into lunny/add_reviewer_notifier_pr_sync

This commit is contained in:
Lunny Xiao 2025-02-28 13:58:43 -08:00
commit fb1fb03499
59 changed files with 616 additions and 618 deletions

View File

@ -470,7 +470,9 @@ tidy-check: tidy
go-licenses: $(GO_LICENSE_FILE) ## regenerate go licenses
$(GO_LICENSE_FILE): go.mod go.sum
-$(GO) run $(GO_LICENSES_PACKAGE) save . --force --save_path=$(GO_LICENSE_TMP_DIR) 2>/dev/null
@rm -rf $(GO_LICENSE_FILE)
$(GO) install $(GO_LICENSES_PACKAGE)
-GOOS=linux CGO_ENABLED=1 go-licenses save . --force --save_path=$(GO_LICENSE_TMP_DIR) 2>/dev/null
$(GO) run build/generate-go-licenses.go $(GO_LICENSE_TMP_DIR) $(GO_LICENSE_FILE)
@rm -rf $(GO_LICENSE_TMP_DIR)

2
go.mod
View File

@ -24,7 +24,7 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.0
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358
github.com/ProtonMail/go-crypto v1.1.5
github.com/ProtonMail/go-crypto v1.1.6
github.com/PuerkitoBio/goquery v1.10.2
github.com/SaveTheRbtz/zstd-seekable-format-go/pkg v0.7.3
github.com/alecthomas/chroma/v2 v2.15.0

4
go.sum
View File

@ -71,8 +71,8 @@ github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSC
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/ProtonMail/go-crypto v1.1.5 h1:eoAQfK2dwL+tFSFpr7TbOaPNUbPiJj4fLYwwGE1FQO4=
github.com/ProtonMail/go-crypto v1.1.5/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE=
github.com/ProtonMail/go-crypto v1.1.6 h1:ZcV+Ropw6Qn0AX9brlQLAUXfqLBc7Bl+f/DmNxpLfdw=
github.com/ProtonMail/go-crypto v1.1.6/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE=
github.com/PuerkitoBio/goquery v1.10.2 h1:7fh2BdHcG6VFZsK7toXBT/Bh1z5Wmy8Q9MV9HqT2AM8=
github.com/PuerkitoBio/goquery v1.10.2/go.mod h1:0guWGjcLu9AYC7C1GHnpysHy056u9aEkUHwhdnePMCU=
github.com/RoaringBitmap/roaring v0.4.23/go.mod h1:D0gp8kJQgE1A4LQ5wFLggQEyvDi06Mq5mKs52e1TwOo=

View File

@ -5,6 +5,7 @@ package auth
import (
"fmt"
"slices"
"strings"
"code.gitea.io/gitea/models/perm"
@ -14,7 +15,7 @@ import (
type AccessTokenScopeCategory int
const (
AccessTokenScopeCategoryActivityPub = iota
AccessTokenScopeCategoryActivityPub AccessTokenScopeCategory = iota
AccessTokenScopeCategoryAdmin
AccessTokenScopeCategoryMisc // WARN: this is now just a placeholder, don't remove it which will change the following values
AccessTokenScopeCategoryNotification
@ -193,6 +194,14 @@ var accessTokenScopes = map[AccessTokenScopeLevel]map[AccessTokenScopeCategory]A
},
}
func GetAccessTokenCategories() (res []string) {
for _, cat := range accessTokenScopes[Read] {
res = append(res, strings.TrimPrefix(string(cat), "read:"))
}
slices.Sort(res)
return res
}
// GetRequiredScopes gets the specific scopes for a given level and categories
func GetRequiredScopes(level AccessTokenScopeLevel, scopeCategories ...AccessTokenScopeCategory) []AccessTokenScope {
scopes := make([]AccessTokenScope, 0, len(scopeCategories))
@ -270,6 +279,9 @@ func (s AccessTokenScope) parse() (accessTokenScopeBitmap, error) {
// StringSlice returns the AccessTokenScope as a []string
func (s AccessTokenScope) StringSlice() []string {
if s == "" {
return nil
}
return strings.Split(string(s), ",")
}

View File

@ -17,6 +17,7 @@ type scopeTestNormalize struct {
}
func TestAccessTokenScope_Normalize(t *testing.T) {
assert.Equal(t, []string{"activitypub", "admin", "issue", "misc", "notification", "organization", "package", "repository", "user"}, GetAccessTokenCategories())
tests := []scopeTestNormalize{
{"", "", nil},
{"write:misc,write:notification,read:package,write:notification,public-only", "public-only,write:misc,write:notification,read:package", nil},
@ -25,7 +26,7 @@ func TestAccessTokenScope_Normalize(t *testing.T) {
{"write:activitypub,write:admin,write:misc,write:notification,write:organization,write:package,write:issue,write:repository,write:user,public-only", "public-only,all", nil},
}
for _, scope := range []string{"activitypub", "admin", "misc", "notification", "organization", "package", "issue", "repository", "user"} {
for _, scope := range GetAccessTokenCategories() {
tests = append(tests,
scopeTestNormalize{AccessTokenScope(fmt.Sprintf("read:%s", scope)), AccessTokenScope(fmt.Sprintf("read:%s", scope)), nil},
scopeTestNormalize{AccessTokenScope(fmt.Sprintf("write:%s", scope)), AccessTokenScope(fmt.Sprintf("write:%s", scope)), nil},
@ -59,7 +60,7 @@ func TestAccessTokenScope_HasScope(t *testing.T) {
{"public-only", "read:issue", false, nil},
}
for _, scope := range []string{"activitypub", "admin", "misc", "notification", "organization", "package", "issue", "repository", "user"} {
for _, scope := range GetAccessTokenCategories() {
tests = append(tests,
scopeTestHasScope{
AccessTokenScope(fmt.Sprintf("read:%s", scope)),

View File

@ -110,9 +110,12 @@ func GetPackageDescriptor(ctx context.Context, pv *PackageVersion) (*PackageDesc
if err != nil {
return nil, err
}
repository, err := repo_model.GetRepositoryByID(ctx, p.RepoID)
if err != nil && !repo_model.IsErrRepoNotExist(err) {
return nil, err
var repository *repo_model.Repository
if p.RepoID > 0 {
repository, err = repo_model.GetRepositoryByID(ctx, p.RepoID)
if err != nil && !repo_model.IsErrRepoNotExist(err) {
return nil, err
}
}
creator, err := user_model.GetUserByID(ctx, pv.CreatorID)
if err != nil {

View File

@ -911,7 +911,6 @@ delete_token_success=Token byl odstraněn. Aplikace, které jej používají ji
repo_and_org_access=Repozitář a přístup organizace
permissions_public_only=Pouze veřejnost
permissions_access_all=Vše (veřejné, soukromé a omezené)
select_permissions=Vyberte oprávnění
permission_not_set=Není nastaveno
permission_no_access=Bez přístupu
permission_read=Přečtené

View File

@ -910,7 +910,6 @@ delete_token_success=Der Zugriffstoken wurde gelöscht. Anwendungen die diesen T
repo_and_org_access=Repository- und Organisationszugriff
permissions_public_only=Nur öffentlich
permissions_access_all=Alle (öffentlich, privat und begrenzt)
select_permissions=Berechtigungen auswählen
permission_not_set=Nicht festgelegt
permission_no_access=Kein Zugriff
permission_read=Lesen

View File

@ -810,7 +810,6 @@ delete_token_success=Το διακριτικό έχει διαγραφεί. Οι
repo_and_org_access=Πρόσβαση στο Αποθετήριο και Οργανισμό
permissions_public_only=Δημόσια μόνο
permissions_access_all=Όλα (δημόσια, ιδιωτικά, και περιορισμένα)
select_permissions=Επιλέξτε δικαιώματα
permission_no_access=Καμία Πρόσβαση
permission_read=Αναγνωσμένες
permission_write=Ανάγνωση και Εγγραφή

View File

@ -917,7 +917,6 @@ delete_token_success = The token has been deleted. Applications using it no long
repo_and_org_access = Repository and Organization Access
permissions_public_only = Public only
permissions_access_all = All (public, private, and limited)
select_permissions = Select permissions
permission_not_set = Not set
permission_no_access = No Access
permission_read = Read
@ -2595,7 +2594,6 @@ diff.commit = commit
diff.git-notes = Notes
diff.data_not_available = Diff Content Not Available
diff.options_button = Diff Options
diff.show_diff_stats = Show Stats
diff.download_patch = Download Patch File
diff.download_diff = Download Diff File
diff.show_split_view = Split View

View File

@ -806,7 +806,6 @@ delete_token_success=El token ha sido eliminado. Las aplicaciones que lo usen ya
repo_and_org_access=Acceso al Repositorio y a la Organización
permissions_public_only=Sólo público
permissions_access_all=Todo (público, privado y limitado)
select_permissions=Seleccionar permisos
permission_no_access=Sin acceso
permission_read=Leídas
permission_write=Lectura y Escritura

View File

@ -917,7 +917,6 @@ delete_token_success=Ce jeton a été supprimé. Les applications l'utilisant n'
repo_and_org_access=Accès aux Organisations et Dépôts
permissions_public_only=Publique uniquement
permissions_access_all=Tout (public, privé et limité)
select_permissions=Sélectionner les autorisations
permission_not_set=Non défini
permission_no_access=Aucun accès
permission_read=Lecture

View File

@ -917,7 +917,6 @@ delete_token_success=Tá an comhartha scriosta. Níl rochtain ag iarratais a ús
repo_and_org_access=Rochtain Stórála agus Eagraíochta
permissions_public_only=Poiblí amháin
permissions_access_all=Gach (poiblí, príobháideach agus teoranta)
select_permissions=Roghnaigh ceadanna
permission_not_set=Níl leagtha
permission_no_access=Gan rochtain
permission_read=Léigh

View File

@ -917,7 +917,6 @@ delete_token_success=トークンを削除しました。 削除したトーク
repo_and_org_access=リポジトリと組織へのアクセス
permissions_public_only=公開のみ
permissions_access_all=すべて (公開、プライベート、限定)
select_permissions=許可の選択
permission_not_set=設定なし
permission_no_access=アクセス不可
permission_read=読み取り

View File

@ -814,7 +814,6 @@ delete_token_success=Pilnvara tika izdzēsta. Lietojumprogrammām, kas izmantoja
repo_and_org_access=Repozitorija un organizācijas piekļuve
permissions_public_only=Tikai publiskie
permissions_access_all=Visi (publiskie, privātie un ierobežotie)
select_permissions=Norādiet tiesības
permission_no_access=Nav piekļuves
permission_read=Skatīšanās
permission_write=Skatīšanās un raksīšanas

View File

@ -812,7 +812,6 @@ delete_token_success=O token foi excluído. Os aplicativos que o utilizam já n
repo_and_org_access=Acesso ao Repositório e Organização
permissions_public_only=Apenas público
permissions_access_all=Todos (público, privado e limitado)
select_permissions=Selecionar permissões
permission_no_access=Sem acesso
permission_read=Ler
permission_write=Ler e escrever

View File

@ -917,7 +917,6 @@ delete_token_success=O código foi eliminado. Aplicações que o usavam deixaram
repo_and_org_access=Acesso aos repositórios e às organizações
permissions_public_only=Apenas público
permissions_access_all=Tudo (público, privado e limitado)
select_permissions=Escolher permissões
permission_not_set=Não definido
permission_no_access=Sem acesso
permission_read=Lidas

View File

@ -807,7 +807,6 @@ delete_token_success=Токен удалён. Приложения, исполь
repo_and_org_access=Доступ к репозиторию и организации
permissions_public_only=Только публичные
permissions_access_all=Все (публичные, приватные и ограниченные)
select_permissions=Выбрать разрешения
permission_no_access=Нет доступа
permission_read=Прочитанные
permission_write=Чтение и запись

View File

@ -895,7 +895,6 @@ delete_token_success=Jeton silindi. Onu kullanan uygulamalar artık hesabınıza
repo_and_org_access=Depo ve Organizasyon Erişimi
permissions_public_only=Yalnızca herkese açık
permissions_access_all=Tümü (herkese açık, özel ve sınırlı)
select_permissions=İzinleri seçin
permission_not_set=Ayarlanmadı
permission_no_access=Erişim Yok
permission_read=Okunmuş

View File

@ -910,7 +910,6 @@ delete_token_success=令牌已经被删除。使用该令牌的应用将不再
repo_and_org_access=仓库和组织访问权限
permissions_public_only=仅公开
permissions_access_all=全部(公开、私有和受限)
select_permissions=选择权限
permission_not_set=未设置
permission_no_access=无访问权限
permission_read=可读

View File

@ -907,7 +907,6 @@ delete_token_success=已刪除 Token。使用此 Token 的應用程式無法再
repo_and_org_access=儲存庫和組織存取
permissions_public_only=僅公開
permissions_access_all=全部 (公開、私有與受限)
select_permissions=選擇權限
permission_not_set=尚未設定
permission_no_access=沒有權限
permission_read=讀取

View File

@ -66,6 +66,7 @@ type PackageMetadataResponse struct {
}
// PackageVersionMetadata contains package metadata
// https://getcomposer.org/doc/05-repositories.md#package
type PackageVersionMetadata struct {
*composer_module.Metadata
Name string `json:"name"`
@ -73,6 +74,7 @@ type PackageVersionMetadata struct {
Type string `json:"type"`
Created time.Time `json:"time"`
Dist Dist `json:"dist"`
Source Source `json:"source"`
}
// Dist contains package download information
@ -82,6 +84,13 @@ type Dist struct {
Checksum string `json:"shasum"`
}
// Source contains package source information
type Source struct {
URL string `json:"url"`
Type string `json:"type"`
Reference string `json:"reference"`
}
func createPackageMetadataResponse(registryURL string, pds []*packages_model.PackageDescriptor) *PackageMetadataResponse {
versions := make([]*PackageVersionMetadata, 0, len(pds))
@ -94,7 +103,7 @@ func createPackageMetadataResponse(registryURL string, pds []*packages_model.Pac
}
}
versions = append(versions, &PackageVersionMetadata{
pkg := PackageVersionMetadata{
Name: pd.Package.Name,
Version: pd.Version.Version,
Type: packageType,
@ -105,7 +114,16 @@ func createPackageMetadataResponse(registryURL string, pds []*packages_model.Pac
URL: fmt.Sprintf("%s/files/%s/%s/%s", registryURL, url.PathEscape(pd.Package.LowerName), url.PathEscape(pd.Version.LowerVersion), url.PathEscape(pd.Files[0].File.LowerName)),
Checksum: pd.Files[0].Blob.HashSHA1,
},
})
}
if pd.Repository != nil {
pkg.Source = Source{
URL: pd.Repository.HTMLURL(),
Type: "git",
Reference: pd.Version.Version,
}
}
versions = append(versions, &pkg)
}
return &PackageMetadataResponse{

View File

@ -344,18 +344,30 @@ func Diff(ctx *context.Context) {
ctx.Data["Reponame"] = repoName
var parentCommit *git.Commit
var parentCommitID string
if commit.ParentCount() > 0 {
parentCommit, err = gitRepo.GetCommit(parents[0])
if err != nil {
ctx.NotFound(err)
return
}
parentCommitID = parentCommit.ID.String()
}
setCompareContext(ctx, parentCommit, commit, userName, repoName)
ctx.Data["Title"] = commit.Summary() + " · " + base.ShortSha(commitID)
ctx.Data["Commit"] = commit
ctx.Data["Diff"] = diff
if !fileOnly {
diffTree, err := gitdiff.GetDiffTree(ctx, gitRepo, false, parentCommitID, commitID)
if err != nil {
ctx.ServerError("GetDiffTree", err)
return
}
ctx.PageData["DiffFiles"] = transformDiffTreeForUI(diffTree, nil)
}
statuses, _, err := git_model.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, commitID, db.ListOptionsAll)
if err != nil {
log.Error("GetLatestCommitStatus: %v", err)

View File

@ -633,6 +633,16 @@ func PrepareCompareDiff(
ctx.Data["Diff"] = diff
ctx.Data["DiffNotAvailable"] = diff.NumFiles == 0
if !fileOnly {
diffTree, err := gitdiff.GetDiffTree(ctx, ci.HeadGitRepo, false, beforeCommitID, headCommitID)
if err != nil {
ctx.ServerError("GetDiffTree", err)
return false
}
ctx.PageData["DiffFiles"] = transformDiffTreeForUI(diffTree, nil)
}
headCommit, err := ci.HeadGitRepo.GetCommit(headCommitID)
if err != nil {
ctx.ServerError("GetCommit", err)

View File

@ -761,6 +761,7 @@ func viewPullFiles(ctx *context.Context, specifiedStartCommit, specifiedEndCommi
var methodWithError string
var diff *gitdiff.Diff
shouldGetUserSpecificDiff := false
// if we're not logged in or only a single commit (or commit range) is shown we
// have to load only the diff and not get the viewed information
@ -772,6 +773,7 @@ func viewPullFiles(ctx *context.Context, specifiedStartCommit, specifiedEndCommi
} else {
diff, err = gitdiff.SyncAndGetUserSpecificDiff(ctx, ctx.Doer.ID, pull, gitRepo, diffOptions, files...)
methodWithError = "SyncAndGetUserSpecificDiff"
shouldGetUserSpecificDiff = true
}
if err != nil {
ctx.ServerError(methodWithError, err)
@ -816,6 +818,27 @@ func viewPullFiles(ctx *context.Context, specifiedStartCommit, specifiedEndCommi
}
}
if !fileOnly {
// note: use mergeBase is set to false because we already have the merge base from the pull request info
diffTree, err := gitdiff.GetDiffTree(ctx, gitRepo, false, pull.MergeBase, headCommitID)
if err != nil {
ctx.ServerError("GetDiffTree", err)
return
}
filesViewedState := make(map[string]pull_model.ViewedState)
if shouldGetUserSpecificDiff {
// This sort of sucks because we already fetch this when getting the diff
review, err := pull_model.GetNewestReviewState(ctx, ctx.Doer.ID, issue.ID)
if err == nil && review != nil && review.UpdatedFiles != nil {
// If there wasn't an error and we have a review with updated files, use that
filesViewedState = review.UpdatedFiles
}
}
ctx.PageData["DiffFiles"] = transformDiffTreeForUI(diffTree, filesViewedState)
}
ctx.Data["Diff"] = diff
ctx.Data["DiffNotAvailable"] = diff.NumFiles == 0

View File

@ -6,9 +6,11 @@ package repo
import (
"net/http"
pull_model "code.gitea.io/gitea/models/pull"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/services/context"
"code.gitea.io/gitea/services/gitdiff"
"github.com/go-enry/go-enry/v2"
)
@ -52,3 +54,33 @@ func isExcludedEntry(entry *git.TreeEntry) bool {
return false
}
type FileDiffFile struct {
Name string
NameHash string
IsSubmodule bool
IsViewed bool
Status string
}
// transformDiffTreeForUI transforms a DiffTree into a slice of FileDiffFile for UI rendering
// it also takes a map of file names to their viewed state, which is used to mark files as viewed
func transformDiffTreeForUI(diffTree *gitdiff.DiffTree, filesViewedState map[string]pull_model.ViewedState) []FileDiffFile {
files := make([]FileDiffFile, 0, len(diffTree.Files))
for _, file := range diffTree.Files {
nameHash := git.HashFilePathForWebUI(file.HeadPath)
isSubmodule := file.HeadMode == git.EntryModeCommit
isViewed := filesViewedState[file.HeadPath] == pull_model.Viewed
files = append(files, FileDiffFile{
Name: file.HeadPath,
NameHash: nameHash,
IsSubmodule: isSubmodule,
IsViewed: isViewed,
Status: file.Status,
})
}
return files
}

View File

@ -6,12 +6,14 @@ package setting
import (
"net/http"
"strings"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/templates"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/services/context"
"code.gitea.io/gitea/services/forms"
@ -39,18 +41,29 @@ func ApplicationsPost(ctx *context.Context) {
ctx.Data["PageIsSettingsApplications"] = true
ctx.Data["UserDisabledFeatures"] = user_model.DisabledFeaturesWithLoginType(ctx.Doer)
if ctx.HasError() {
loadApplicationsData(ctx)
ctx.HTML(http.StatusOK, tplSettingsApplications)
return
_ = ctx.Req.ParseForm()
var scopeNames []string
for k, v := range ctx.Req.Form {
if strings.HasPrefix(k, "scope-") {
scopeNames = append(scopeNames, v...)
}
}
scope, err := form.GetScope()
scope, err := auth_model.AccessTokenScope(strings.Join(scopeNames, ",")).Normalize()
if err != nil {
ctx.ServerError("GetScope", err)
return
}
if scope == "" || scope == auth_model.AccessTokenScopePublicOnly {
ctx.Flash.Error(ctx.Tr("settings.at_least_one_permission"), true)
}
if ctx.HasError() {
loadApplicationsData(ctx)
ctx.HTML(http.StatusOK, tplSettingsApplications)
return
}
t := &auth_model.AccessToken{
UID: ctx.Doer.ID,
Name: form.Name,
@ -99,7 +112,14 @@ func loadApplicationsData(ctx *context.Context) {
}
ctx.Data["Tokens"] = tokens
ctx.Data["EnableOAuth2"] = setting.OAuth2.Enabled
ctx.Data["IsAdmin"] = ctx.Doer.IsAdmin
// Handle specific ordered token categories for admin or non-admin users
tokenCategoryNames := auth_model.GetAccessTokenCategories()
if !ctx.Doer.IsAdmin {
tokenCategoryNames = util.SliceRemoveAll(tokenCategoryNames, "admin")
}
ctx.Data["TokenCategories"] = tokenCategoryNames
if setting.OAuth2.Enabled {
ctx.Data["Applications"], err = db.Find[auth_model.OAuth2Application](ctx, auth_model.FindOAuth2ApplicationsOptions{
OwnerID: ctx.Doer.ID,

View File

@ -213,13 +213,16 @@ func Contexter() func(next http.Handler) http.Handler {
// Attention: this function changes ctx.Data and ctx.Flash
// If HasError is called, then before Redirect, the error message should be stored by ctx.Flash.Error(ctx.GetErrMsg()) again.
func (ctx *Context) HasError() bool {
hasErr, ok := ctx.Data["HasError"]
if !ok {
hasErr, _ := ctx.Data["HasError"].(bool)
hasErr = hasErr || ctx.Flash.ErrorMsg != ""
if !hasErr {
return false
}
ctx.Flash.ErrorMsg = ctx.GetErrMsg()
if ctx.Flash.ErrorMsg == "" {
ctx.Flash.ErrorMsg = ctx.GetErrMsg()
}
ctx.Data["Flash"] = ctx.Flash
return hasErr.(bool)
return hasErr
}
// GetErrMsg returns error message in form validation.

View File

@ -7,9 +7,7 @@ package forms
import (
"mime/multipart"
"net/http"
"strings"
auth_model "code.gitea.io/gitea/models/auth"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/web/middleware"
@ -347,8 +345,7 @@ func (f *EditVariableForm) Validate(req *http.Request, errs binding.Errors) bind
// NewAccessTokenForm form for creating access token
type NewAccessTokenForm struct {
Name string `binding:"Required;MaxSize(255)" locale:"settings.token_name"`
Scope []string
Name string `binding:"Required;MaxSize(255)" locale:"settings.token_name"`
}
// Validate validates the fields
@ -357,12 +354,6 @@ func (f *NewAccessTokenForm) Validate(req *http.Request, errs binding.Errors) bi
return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
}
func (f *NewAccessTokenForm) GetScope() (auth_model.AccessTokenScope, error) {
scope := strings.Join(f.Scope, ",")
s, err := auth_model.AccessTokenScope(scope).Normalize()
return s, err
}
// EditOAuth2ApplicationForm form for editing oauth2 applications
type EditOAuth2ApplicationForm struct {
Name string `binding:"Required;MaxSize(255)" form:"application_name"`

View File

@ -4,10 +4,8 @@
package forms
import (
"strconv"
"testing"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/modules/setting"
"github.com/gobwas/glob"
@ -104,28 +102,3 @@ func TestRegisterForm_IsDomainAllowed_BlockedEmail(t *testing.T) {
assert.Equal(t, v.valid, form.IsEmailDomainAllowed())
}
}
func TestNewAccessTokenForm_GetScope(t *testing.T) {
tests := []struct {
form NewAccessTokenForm
scope auth_model.AccessTokenScope
expectedErr error
}{
{
form: NewAccessTokenForm{Name: "test", Scope: []string{"read:repository"}},
scope: "read:repository",
},
{
form: NewAccessTokenForm{Name: "test", Scope: []string{"read:repository", "write:user"}},
scope: "read:repository,write:user",
},
}
for i, test := range tests {
t.Run(strconv.Itoa(i), func(t *testing.T) {
scope, err := test.form.GetScope()
assert.Equal(t, test.expectedErr, err)
assert.Equal(t, test.scope, scope)
})
}
}

View File

@ -44,16 +44,17 @@ func UnlinkFromRepository(ctx context.Context, pkg *packages_model.Package, doer
}
repo, err := repo_model.GetRepositoryByID(ctx, pkg.RepoID)
if err != nil {
if err != nil && !repo_model.IsErrRepoNotExist(err) {
return fmt.Errorf("error getting repository %d: %w", pkg.RepoID, err)
}
perms, err := access_model.GetUserRepoPermission(ctx, repo, doer)
if err != nil {
return fmt.Errorf("error getting permissions for user %d on repository %d: %w", doer.ID, repo.ID, err)
}
if !perms.CanWrite(unit.TypePackages) {
return util.ErrPermissionDenied
if err == nil {
perms, err := access_model.GetUserRepoPermission(ctx, repo, doer)
if err != nil {
return fmt.Errorf("error getting permissions for user %d on repository %d: %w", doer.ID, repo.ID, err)
}
if !perms.CanWrite(unit.TypePackages) {
return util.ErrPermissionDenied
}
}
user, err := user_model.GetUserByID(ctx, pkg.OwnerID)

View File

@ -57,32 +57,6 @@
<div>{{ctx.Locale.Tr "repo.pulls.showing_specified_commit_range" (ShortSha .BeforeCommitID) (ShortSha .AfterCommitID)}} - <a href="{{$.Issue.Link}}/files?style={{if $.IsSplitStyle}}split{{else}}unified{{end}}&whitespace={{$.WhitespaceBehavior}}&show-outdated={{$.ShowOutdatedComments}}">{{ctx.Locale.Tr "repo.pulls.show_all_commits"}}</a></div>
</div>
{{end}}
<script id="diff-data-script" type="module">
const diffDataFiles = [{{range $i, $file := .Diff.Files}}{Name:"{{$file.Name}}",NameHash:"{{$file.NameHash}}",Type:{{$file.Type}},IsBin:{{$file.IsBin}},IsSubmodule:{{$file.IsSubmodule}},Addition:{{$file.Addition}},Deletion:{{$file.Deletion}},IsViewed:{{$file.IsViewed}}},{{end}}];
const diffData = {
isIncomplete: {{.Diff.IsIncomplete}},
tooManyFilesMessage: "{{ctx.Locale.Tr "repo.diff.too_many_files"}}",
binaryFileMessage: "{{ctx.Locale.Tr "repo.diff.bin"}}",
showMoreMessage: "{{ctx.Locale.Tr "repo.diff.show_more"}}",
statisticsMessage: "{{ctx.Locale.Tr "repo.diff.stats_desc_file"}}",
linkLoadMore: "?skip-to={{.Diff.End}}&file-only=true",
};
// for first time loading, the diffFileInfo is a plain object
// after the Vue component is mounted, the diffFileInfo is a reactive object
// keep in mind that this script block would be executed many times when loading more files, by "loadMoreFiles"
let diffFileInfo = window.config.pageData.diffFileInfo || {
files:[],
fileTreeIsVisible: false,
fileListIsVisible: false,
isLoadingNewData: false,
selectedItem: '',
};
diffFileInfo = Object.assign(diffFileInfo, diffData);
diffFileInfo.files.push(...diffDataFiles);
window.config.pageData.diffFileInfo = diffFileInfo;
</script>
<div id="diff-file-list"></div>
{{end}}
<div id="diff-container">
{{if $showFileTree}}

View File

@ -1,7 +1,6 @@
<div class="ui dropdown tiny basic button" data-tooltip-content="{{ctx.Locale.Tr "repo.diff.options_button"}}">
{{svg "octicon-kebab-horizontal"}}
<div class="menu">
<a class="item" id="show-file-list-btn">{{ctx.Locale.Tr "repo.diff.show_diff_stats"}}</a>
{{if .Issue.Index}}
<a class="item" href="{{$.RepoLink}}/pulls/{{.Issue.Index}}.patch" download="{{.Issue.Index}}.patch">{{ctx.Locale.Tr "repo.diff.download_patch"}}</a>
<a class="item" href="{{$.RepoLink}}/pulls/{{.Issue.Index}}.diff" download="{{.Issue.Index}}.diff">{{ctx.Locale.Tr "repo.diff.download_diff"}}</a>

View File

@ -50,49 +50,41 @@
</div>
</div>
<div class="ui bottom attached segment">
<h5 class="ui top header">
{{ctx.Locale.Tr "settings.generate_new_token"}}
</h5>
<form id="scoped-access-form" class="ui form ignore-dirty" action="{{.Link}}" method="post">
{{.CsrfTokenHtml}}
<div class="field {{if .Err_Name}}error{{end}}">
<label for="name">{{ctx.Locale.Tr "settings.token_name"}}</label>
<input id="name" name="name" value="{{.name}}" autofocus required maxlength="255">
</div>
<div class="field">
<label>{{ctx.Locale.Tr "settings.repo_and_org_access"}}</label>
<label class="tw-cursor-pointer">
<input class="enable-system tw-mt-1 tw-mr-1" type="radio" name="scope" value="{{$.AccessTokenScopePublicOnly}}">
{{ctx.Locale.Tr "settings.permissions_public_only"}}
</label>
<label class="tw-cursor-pointer">
<input class="enable-system tw-mt-1 tw-mr-1" type="radio" name="scope" value="" checked>
{{ctx.Locale.Tr "settings.permissions_access_all"}}
</label>
</div>
<details class="ui optional field">
<summary class="tw-pb-4 tw-pl-1">
{{ctx.Locale.Tr "settings.select_permissions"}}
</summary>
<p class="activity meta">
<i>{{ctx.Locale.Tr "settings.access_token_desc" (HTMLFormat `href="%s/api/swagger" target="_blank"` AppSubUrl) (`href="https://docs.gitea.com/development/oauth2-provider#scopes" target="_blank"`|SafeHTML)}}</i>
</p>
<div id="scoped-access-token-selector"
data-is-admin="{{if .IsAdmin}}true{{else}}false{{end}}"
data-no-access-label="{{ctx.Locale.Tr "settings.permission_no_access"}}"
data-read-label="{{ctx.Locale.Tr "settings.permission_read"}}"
data-write-label="{{ctx.Locale.Tr "settings.permission_write"}}"
data-locale-component-failed-to-load="{{ctx.Locale.Tr "graphs.component_failed_to_load"}}"
>
<details {{if or .name (not .Tokens)}}open{{end}}>
<summary><h4 class="ui header tw-inline-block tw-my-2">{{ctx.Locale.Tr "settings.generate_new_token"}}</h4></summary>
<form class="ui form ignore-dirty" action="{{.Link}}" method="post">
{{.CsrfTokenHtml}}
<div class="field {{if .Err_Name}}error{{end}}">
<label for="name">{{ctx.Locale.Tr "settings.token_name"}}</label>
<input id="name" name="name" value="{{.name}}" required maxlength="255">
</div>
</details>
<button id="scoped-access-submit" class="ui primary button">
{{ctx.Locale.Tr "settings.generate_token"}}
</button>
</form>{{/* Fomantic ".ui.form .warning.message" is hidden by default, so put the warning message out of the form*/}}
<div id="scoped-access-warning" class="ui warning message center tw-hidden">
{{ctx.Locale.Tr "settings.at_least_one_permission"}}
</div>
<div class="field">
<div class="tw-my-2">{{ctx.Locale.Tr "settings.repo_and_org_access"}}</div>
<label class="gt-checkbox">
<input type="radio" name="scope-public-only" value="{{$.AccessTokenScopePublicOnly}}"> {{ctx.Locale.Tr "settings.permissions_public_only"}}
</label>
<label class="gt-checkbox">
<input type="radio" name="scope-public-only" value="" checked> {{ctx.Locale.Tr "settings.permissions_access_all"}}
</label>
</div>
<div>
<div class="tw-my-2">{{ctx.Locale.Tr "settings.access_token_desc" (HTMLFormat `href="%s/api/swagger" target="_blank"` AppSubUrl) (`href="https://docs.gitea.com/development/oauth2-provider#scopes" target="_blank"`|SafeHTML)}}</div>
<table class="ui table unstackable tw-my-2">
{{range $category := .TokenCategories}}
<tr>
<td>{{$category}}</td>
<td><label class="gt-checkbox"><input type="radio" name="scope-{{$category}}" value="" checked> {{ctx.Locale.Tr "settings.permission_no_access"}}</label></td>
<td><label class="gt-checkbox"><input type="radio" name="scope-{{$category}}" value="read:{{$category}}"> {{ctx.Locale.Tr "settings.permission_read"}}</label></td>
<td><label class="gt-checkbox"><input type="radio" name="scope-{{$category}}" value="write:{{$category}}"> {{ctx.Locale.Tr "settings.permission_write"}}</label></td>
</tr>
{{end}}
</table>
</div>
<button class="ui primary button">
{{ctx.Locale.Tr "settings.generate_token"}}
</button>
</form>
</details>
</div>
{{if .EnableOAuth2}}

View File

@ -48,33 +48,33 @@
</div>
<div class="ui bottom attached segment">
<h5 class="ui top header">
{{ctx.Locale.Tr "settings.create_oauth2_application"}}
</h5>
<form class="ui form ignore-dirty" action="{{.Link}}/oauth2" method="post">
{{.CsrfTokenHtml}}
<div class="field {{if .Err_AppName}}error{{end}}">
<label for="application-name">{{ctx.Locale.Tr "settings.oauth2_application_name"}}</label>
<input id="application-name" name="application_name" value="{{.application_name}}" required maxlength="255">
</div>
<div class="field {{if .Err_RedirectURI}}error{{end}}">
<label for="redirect-uris">{{ctx.Locale.Tr "settings.oauth2_redirect_uris"}}</label>
<textarea name="redirect_uris" id="redirect-uris"></textarea>
</div>
<div class="field {{if .Err_ConfidentialClient}}error{{end}}">
<div class="ui checkbox">
<label>{{ctx.Locale.Tr "settings.oauth2_confidential_client"}}</label>
<input class="disable-setting" type="checkbox" name="confidential_client" data-target="#skip-secondary-authorization" checked>
<details {{if .application_name}}open{{end}}>
<summary><h4 class="ui header tw-inline-block tw-my-2">{{ctx.Locale.Tr "settings.create_oauth2_application"}}</h4></summary>
<form class="ui form ignore-dirty" action="{{.Link}}/oauth2" method="post">
{{.CsrfTokenHtml}}
<div class="field {{if .Err_AppName}}error{{end}}">
<label for="application-name">{{ctx.Locale.Tr "settings.oauth2_application_name"}}</label>
<input id="application-name" name="application_name" value="{{.application_name}}" required maxlength="255">
</div>
</div>
<div class="field {{if .Err_SkipSecondaryAuthorization}}error{{end}} disabled" id="skip-secondary-authorization">
<div class="ui checkbox">
<label>{{ctx.Locale.Tr "settings.oauth2_skip_secondary_authorization"}}</label>
<input type="checkbox" name="skip_secondary_authorization">
<div class="field {{if .Err_RedirectURI}}error{{end}}">
<label for="redirect-uris">{{ctx.Locale.Tr "settings.oauth2_redirect_uris"}}</label>
<textarea name="redirect_uris" id="redirect-uris"></textarea>
</div>
</div>
<button class="ui primary button">
{{ctx.Locale.Tr "settings.create_oauth2_application_button"}}
</button>
</form>
<div class="field {{if .Err_ConfidentialClient}}error{{end}}">
<div class="ui checkbox">
<label>{{ctx.Locale.Tr "settings.oauth2_confidential_client"}}</label>
<input class="disable-setting" type="checkbox" name="confidential_client" data-target="#skip-secondary-authorization" checked>
</div>
</div>
<div class="field {{if .Err_SkipSecondaryAuthorization}}error{{end}} disabled" id="skip-secondary-authorization">
<div class="ui checkbox">
<label>{{ctx.Locale.Tr "settings.oauth2_skip_secondary_authorization"}}</label>
<input type="checkbox" name="skip_secondary_authorization">
</div>
</div>
<button class="ui primary button">
{{ctx.Locale.Tr "settings.create_oauth2_application_button"}}
</button>
</form>
</details>
</div>

View File

@ -76,7 +76,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) {
defer tests.PrepareTestEnv(t)()
nonAdminUsername := "user2"
session := loginUser(t, nonAdminUsername)
token := getTokenForLoggedInUser(t, session)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAll)
org := api.CreateOrgOption{
UserName: "user2_org",
FullName: "User2's organization",

View File

@ -76,7 +76,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) {
var newPublicKey api.PublicKey
DecodeJSON(t, resp, &newPublicKey)
token = getUserToken(t, normalUsername)
token = getUserToken(t, normalUsername, auth_model.AccessTokenScopeAll)
req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d", adminUsername, newPublicKey.ID).
AddTokenAuth(token)
MakeRequest(t, req, http.StatusForbidden)
@ -139,7 +139,7 @@ func TestAPIListUsersNotLoggedIn(t *testing.T) {
func TestAPIListUsersNonAdmin(t *testing.T) {
defer tests.PrepareTestEnv(t)()
nonAdminUsername := "user2"
token := getUserToken(t, nonAdminUsername)
token := getUserToken(t, nonAdminUsername, auth_model.AccessTokenScopeAll)
req := NewRequest(t, "GET", "/api/v1/admin/users").
AddTokenAuth(token)
MakeRequest(t, req, http.StatusForbidden)

View File

@ -33,6 +33,10 @@ type APITestContext struct {
func NewAPITestContext(t *testing.T, username, reponame string, scope ...auth.AccessTokenScope) APITestContext {
session := loginUser(t, username)
if len(scope) == 0 {
// FIXME: legacy logic: no scope means all
scope = []auth.AccessTokenScope{auth.AccessTokenScopeAll}
}
token := getTokenForLoggedInUser(t, session, scope...)
return APITestContext{
Session: session,

View File

@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/packages"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
composer_module "code.gitea.io/gitea/modules/packages/composer"
@ -217,5 +218,39 @@ func TestPackageComposer(t *testing.T) {
assert.Equal(t, "4f5fa464c3cb808a1df191dbf6cb75363f8b7072", pkgs[0].Dist.Checksum)
assert.Len(t, pkgs[0].Bin, 1)
assert.Equal(t, packageBin, pkgs[0].Bin[0])
// Test package linked to repository
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
userPkgs, err := packages.GetPackagesByType(db.DefaultContext, user.ID, packages.TypeComposer)
assert.NoError(t, err)
assert.Len(t, userPkgs, 1)
assert.EqualValues(t, 0, userPkgs[0].RepoID)
err = packages.SetRepositoryLink(db.DefaultContext, userPkgs[0].ID, repo1.ID)
assert.NoError(t, err)
req = NewRequest(t, "GET", fmt.Sprintf("%s/p2/%s/%s.json", url, vendorName, projectName)).
AddBasicAuth(user.Name)
resp = MakeRequest(t, req, http.StatusOK)
result = composer.PackageMetadataResponse{}
DecodeJSON(t, resp, &result)
assert.Contains(t, result.Packages, packageName)
pkgs = result.Packages[packageName]
assert.Len(t, pkgs, 1)
assert.Equal(t, packageName, pkgs[0].Name)
assert.Equal(t, packageVersion, pkgs[0].Version)
assert.Equal(t, packageType, pkgs[0].Type)
assert.Equal(t, packageDescription, pkgs[0].Description)
assert.Len(t, pkgs[0].Authors, 1)
assert.Equal(t, packageAuthor, pkgs[0].Authors[0].Name)
assert.Equal(t, "zip", pkgs[0].Dist.Type)
assert.Equal(t, "4f5fa464c3cb808a1df191dbf6cb75363f8b7072", pkgs[0].Dist.Checksum)
assert.Len(t, pkgs[0].Bin, 1)
assert.Equal(t, packageBin, pkgs[0].Bin[0])
assert.Equal(t, repo1.HTMLURL(), pkgs[0].Source.URL)
assert.Equal(t, "git", pkgs[0].Source.Type)
assert.Equal(t, packageVersion, pkgs[0].Source.Reference)
})
}

View File

@ -72,7 +72,7 @@ func TestAPIReposGitBlobs(t *testing.T) {
// Login as User4.
session = loginUser(t, user4.Name)
token4 := getTokenForLoggedInUser(t, session)
token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAll)
// Test using org repo "org3/repo3" where user4 is a NOT collaborator
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/d56a3073c1dbb7b15963110a049d50cdb5db99fc?access=%s", org3.Name, repo3.Name, token4)

View File

@ -69,7 +69,7 @@ func TestAPIReposGitTrees(t *testing.T) {
// Login as User4.
session = loginUser(t, user4.Name)
token4 := getTokenForLoggedInUser(t, session)
token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAll)
// Test using org repo "org3/repo3" where user4 is a NOT collaborator
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/d56a3073c1dbb7b15963110a049d50cdb5db99fc?access=%s", org3.Name, repo3.Name, token4)

View File

@ -249,55 +249,19 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession
// token has to be unique this counter take care of
var tokenCounter int64
// getTokenForLoggedInUser returns a token for a logged in user.
// The scope is an optional list of snake_case strings like the frontend form fields,
// but without the "scope_" prefix.
// getTokenForLoggedInUser returns a token for a logged-in user.
func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...auth.AccessTokenScope) string {
t.Helper()
var token string
req := NewRequest(t, "GET", "/user/settings/applications")
resp := session.MakeRequest(t, req, http.StatusOK)
var csrf string
for _, cookie := range resp.Result().Cookies() {
if cookie.Name != "_csrf" {
continue
}
csrf = cookie.Value
break
}
if csrf == "" {
doc := NewHTMLParser(t, resp.Body)
csrf = doc.GetCSRF()
}
assert.NotEmpty(t, csrf)
urlValues := url.Values{}
urlValues.Add("_csrf", csrf)
urlValues.Add("_csrf", GetUserCSRFToken(t, session))
urlValues.Add("name", fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1)))
for _, scope := range scopes {
urlValues.Add("scope", string(scope))
urlValues.Add("scope-dummy", string(scope)) // it only needs to start with "scope-" to be accepted
}
req = NewRequestWithURLValues(t, "POST", "/user/settings/applications", urlValues)
resp = session.MakeRequest(t, req, http.StatusSeeOther)
// Log the flash values on failure
if !assert.Equal(t, []string{"/user/settings/applications"}, resp.Result().Header["Location"]) {
for _, cookie := range resp.Result().Cookies() {
if cookie.Name != gitea_context.CookieNameFlash {
continue
}
flash, _ := url.ParseQuery(cookie.Value)
for key, value := range flash {
t.Logf("Flash %q: %q", key, value)
}
}
}
req = NewRequest(t, "GET", "/user/settings/applications")
resp = session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
token = htmlDoc.doc.Find(".ui.info p").Text()
assert.NotEmpty(t, token)
return token
req := NewRequestWithURLValues(t, "POST", "/user/settings/applications", urlValues)
session.MakeRequest(t, req, http.StatusSeeOther)
flashes := session.GetCookieFlashMessage()
return flashes.InfoMsg
}
type RequestWrapper struct {

View File

@ -19,7 +19,6 @@
@import "./modules/dimmer.css";
@import "./modules/modal.css";
@import "./modules/select.css";
@import "./modules/tippy.css";
@import "./modules/breadcrumb.css";
@import "./modules/comment.css";

View File

@ -119,3 +119,13 @@ input[type="radio"] {
.ui.toggle.checkbox input:focus:checked ~ label::before {
background: var(--color-primary) !important;
}
label.gt-checkbox {
display: inline-flex;
align-items: center;
gap: 0.25em;
}
.ui.form .field > label.gt-checkbox {
display: flex;
}

View File

@ -1,25 +0,0 @@
.gitea-select {
position: relative;
}
.gitea-select select {
appearance: none; /* hide default triangle */
}
/* ::before and ::after pseudo elements don't work on select elements,
so we need to put it on the parent. */
.gitea-select::after {
position: absolute;
top: 12px;
right: 8px;
pointer-events: none;
content: "";
width: 14px;
height: 14px;
mask-size: cover;
-webkit-mask-size: cover;
mask-image: var(--octicon-chevron-right);
-webkit-mask-image: var(--octicon-chevron-right);
transform: rotate(90deg); /* point the chevron down */
background: currentcolor;
}

View File

@ -1,60 +0,0 @@
<script lang="ts" setup>
import {onMounted, onUnmounted} from 'vue';
import {loadMoreFiles} from '../features/repo-diff.ts';
import {diffTreeStore} from '../modules/stores.ts';
const store = diffTreeStore();
onMounted(() => {
document.querySelector('#show-file-list-btn').addEventListener('click', toggleFileList);
});
onUnmounted(() => {
document.querySelector('#show-file-list-btn').removeEventListener('click', toggleFileList);
});
function toggleFileList() {
store.fileListIsVisible = !store.fileListIsVisible;
}
function diffTypeToString(pType: number) {
const diffTypes: Record<string, string> = {
'1': 'add',
'2': 'modify',
'3': 'del',
'4': 'rename',
'5': 'copy',
};
return diffTypes[String(pType)];
}
function diffStatsWidth(adds: number, dels: number) {
return `${adds / (adds + dels) * 100}%`;
}
function loadMoreData() {
loadMoreFiles(store.linkLoadMore);
}
</script>
<template>
<ol class="diff-stats tw-m-0" ref="root" v-if="store.fileListIsVisible">
<li v-for="file in store.files" :key="file.NameHash">
<div class="tw-font-semibold tw-flex tw-items-center pull-right">
<span v-if="file.IsBin" class="tw-ml-0.5 tw-mr-2">{{ store.binaryFileMessage }}</span>
{{ file.IsBin ? '' : file.Addition + file.Deletion }}
<span v-if="!file.IsBin" class="diff-stats-bar tw-mx-2" :data-tooltip-content="store.statisticsMessage.replace('%d', (file.Addition + file.Deletion)).replace('%d', file.Addition).replace('%d', file.Deletion)">
<div class="diff-stats-add-bar" :style="{ 'width': diffStatsWidth(file.Addition, file.Deletion) }"/>
</span>
</div>
<!-- todo finish all file status, now modify, add, delete and rename -->
<span :class="['status', diffTypeToString(file.Type)]" :data-tooltip-content="diffTypeToString(file.Type)">&nbsp;</span>
<a class="file tw-font-mono" :href="'#diff-' + file.NameHash">{{ file.Name }}</a>
</li>
<li v-if="store.isIncomplete" class="tw-pt-1">
<span class="file tw-flex tw-items-center tw-justify-between">{{ store.tooManyFilesMessage }}
<a :class="['ui', 'basic', 'tiny', 'button', store.isLoadingNewData ? 'disabled' : '']" @click.stop="loadMoreData">{{ store.showMoreMessage }}</a>
</span>
</li>
</ol>
</template>

View File

@ -1,75 +1,18 @@
<script lang="ts" setup>
import DiffFileTreeItem, {type Item} from './DiffFileTreeItem.vue';
import {loadMoreFiles} from '../features/repo-diff.ts';
import DiffFileTreeItem from './DiffFileTreeItem.vue';
import {toggleElem} from '../utils/dom.ts';
import {diffTreeStore} from '../modules/stores.ts';
import {setFileFolding} from '../features/file-fold.ts';
import {computed, onMounted, onUnmounted} from 'vue';
import {pathListToTree, mergeChildIfOnlyOneDir} from '../utils/filetree.ts';
const LOCAL_STORAGE_KEY = 'diff_file_tree_visible';
const store = diffTreeStore();
const fileTree = computed(() => {
const result: Array<Item> = [];
for (const file of store.files) {
// Split file into directories
const splits = file.Name.split('/');
let index = 0;
let parent = null;
let isFile = false;
for (const split of splits) {
index += 1;
// reached the end
if (index === splits.length) {
isFile = true;
}
let newParent: Item = {
name: split,
children: [],
isFile,
};
if (isFile === true) {
newParent.file = file;
}
if (parent) {
// check if the folder already exists
const existingFolder = parent.children.find(
(x) => x.name === split,
);
if (existingFolder) {
newParent = existingFolder;
} else {
parent.children.push(newParent);
}
} else {
const existingFolder = result.find((x) => x.name === split);
if (existingFolder) {
newParent = existingFolder;
} else {
result.push(newParent);
}
}
parent = newParent;
}
}
const mergeChildIfOnlyOneDir = (entries: Array<Record<string, any>>) => {
for (const entry of entries) {
if (entry.children) {
mergeChildIfOnlyOneDir(entry.children);
}
if (entry.children.length === 1 && entry.children[0].isFile === false) {
// Merge it to the parent
entry.name = `${entry.name}/${entry.children[0].name}`;
entry.children = entry.children[0].children;
}
}
};
// Merge folders with just a folder as children in order to
// reduce the depth of our tree.
mergeChildIfOnlyOneDir(result);
const result = pathListToTree(store.files);
mergeChildIfOnlyOneDir(result); // mutation
return result;
});
@ -121,19 +64,12 @@ function updateState(visible: boolean) {
toggleElem(toShow, !visible);
toggleElem(toHide, visible);
}
function loadMoreData() {
loadMoreFiles(store.linkLoadMore);
}
</script>
<template>
<div v-if="store.fileTreeIsVisible" class="diff-file-tree-items">
<!-- only render the tree if we're visible. in many cases this is something that doesn't change very often -->
<DiffFileTreeItem v-for="item in fileTree" :key="item.name" :item="item"/>
<div v-if="store.isIncomplete" class="tw-pt-1">
<a :class="['ui', 'basic', 'tiny', 'button', store.isLoadingNewData ? 'disabled' : '']" @click.stop="loadMoreData">{{ store.showMoreMessage }}</a>
</div>
</div>
</template>

View File

@ -2,21 +2,7 @@
import {SvgIcon, type SvgName} from '../svg.ts';
import {diffTreeStore} from '../modules/stores.ts';
import {ref} from 'vue';
type File = {
Name: string;
NameHash: string;
Type: number;
IsViewed: boolean;
IsSubmodule: boolean;
}
export type Item = {
name: string;
isFile: boolean;
file?: File;
children?: Item[];
};
import type {Item, File, FileStatus} from '../utils/filetree.ts';
defineProps<{
item: Item,
@ -25,15 +11,16 @@ defineProps<{
const store = diffTreeStore();
const collapsed = ref(false);
function getIconForDiffType(pType: number) {
const diffTypes: Record<string, {name: SvgName, classes: Array<string>}> = {
'1': {name: 'octicon-diff-added', classes: ['text', 'green']},
'2': {name: 'octicon-diff-modified', classes: ['text', 'yellow']},
'3': {name: 'octicon-diff-removed', classes: ['text', 'red']},
'4': {name: 'octicon-diff-renamed', classes: ['text', 'teal']},
'5': {name: 'octicon-diff-renamed', classes: ['text', 'green']}, // there is no octicon for copied, so renamed should be ok
function getIconForDiffStatus(pType: FileStatus) {
const diffTypes: Record<FileStatus, { name: SvgName, classes: Array<string> }> = {
'added': {name: 'octicon-diff-added', classes: ['text', 'green']},
'modified': {name: 'octicon-diff-modified', classes: ['text', 'yellow']},
'deleted': {name: 'octicon-diff-removed', classes: ['text', 'red']},
'renamed': {name: 'octicon-diff-renamed', classes: ['text', 'teal']},
'copied': {name: 'octicon-diff-renamed', classes: ['text', 'green']},
'typechange': {name: 'octicon-diff-modified', classes: ['text', 'green']}, // there is no octicon for copied, so renamed should be ok
};
return diffTypes[String(pType)];
return diffTypes[pType];
}
function fileIcon(file: File) {
@ -48,27 +35,37 @@ function fileIcon(file: File) {
<!--title instead of tooltip above as the tooltip needs too much work with the current methods, i.e. not being loaded or staying open for "too long"-->
<a
v-if="item.isFile" class="item-file"
:class="{'selected': store.selectedItem === '#diff-' + item.file.NameHash, 'viewed': item.file.IsViewed}"
:class="{ 'selected': store.selectedItem === '#diff-' + item.file.NameHash, 'viewed': item.file.IsViewed }"
:title="item.name" :href="'#diff-' + item.file.NameHash"
>
<!-- file -->
<SvgIcon :name="fileIcon(item.file)"/>
<span class="gt-ellipsis tw-flex-1">{{ item.name }}</span>
<SvgIcon :name="getIconForDiffType(item.file.Type).name" :class="getIconForDiffType(item.file.Type).classes"/>
<SvgIcon
:name="getIconForDiffStatus(item.file.Status).name"
:class="getIconForDiffStatus(item.file.Status).classes"
/>
</a>
<div v-else class="item-directory" :title="item.name" @click.stop="collapsed = !collapsed">
<!-- directory -->
<SvgIcon :name="collapsed ? 'octicon-chevron-right' : 'octicon-chevron-down'"/>
<SvgIcon class="text primary" :name="collapsed ? 'octicon-file-directory-fill' : 'octicon-file-directory-open-fill'"/>
<span class="gt-ellipsis">{{ item.name }}</span>
</div>
<div v-if="item.children?.length" v-show="!collapsed" class="sub-items">
<DiffFileTreeItem v-for="childItem in item.children" :key="childItem.name" :item="childItem"/>
</div>
<template v-else-if="item.isFile === false">
<div class="item-directory" :title="item.name" @click.stop="collapsed = !collapsed">
<!-- directory -->
<SvgIcon :name="collapsed ? 'octicon-chevron-right' : 'octicon-chevron-down'"/>
<SvgIcon
class="text primary"
:name="collapsed ? 'octicon-file-directory-fill' : 'octicon-file-directory-open-fill'"
/>
<span class="gt-ellipsis">{{ item.name }}</span>
</div>
<div v-show="!collapsed" class="sub-items">
<DiffFileTreeItem v-for="childItem in item.children" :key="childItem.name" :item="childItem"/>
</div>
</template>
</template>
<style scoped>
a, a:hover {
a,
a:hover {
text-decoration: none;
color: var(--color-text);
}

View File

@ -1,81 +0,0 @@
<script lang="ts" setup>
import {computed, onMounted, onUnmounted} from 'vue';
import {hideElem, showElem} from '../utils/dom.ts';
const props = defineProps<{
isAdmin: boolean;
noAccessLabel: string;
readLabel: string;
writeLabel: string;
}>();
const categories = computed(() => {
const categories = [
'activitypub',
];
if (props.isAdmin) {
categories.push('admin');
}
categories.push(
'issue',
'misc',
'notification',
'organization',
'package',
'repository',
'user');
return categories;
});
onMounted(() => {
document.querySelector('#scoped-access-submit').addEventListener('click', onClickSubmit);
});
onUnmounted(() => {
document.querySelector('#scoped-access-submit').removeEventListener('click', onClickSubmit);
});
function onClickSubmit(e: Event) {
e.preventDefault();
const warningEl = document.querySelector('#scoped-access-warning');
// check that at least one scope has been selected
for (const el of document.querySelectorAll<HTMLInputElement>('.access-token-select')) {
if (el.value) {
// Hide the error if it was visible from previous attempt.
hideElem(warningEl);
// Submit the form.
document.querySelector<HTMLFormElement>('#scoped-access-form').submit();
// Don't show the warning.
return;
}
}
// no scopes selected, show validation error
showElem(warningEl);
}
</script>
<template>
<div v-for="category in categories" :key="category" class="field tw-pl-1 tw-pb-1 access-token-category">
<label class="category-label" :for="'access-token-scope-' + category">
{{ category }}
</label>
<div class="gitea-select">
<select
class="ui selection access-token-select"
name="scope"
:id="'access-token-scope-' + category"
>
<option value="">
{{ noAccessLabel }}
</option>
<option :value="'read:' + category">
{{ readLabel }}
</option>
<option :value="'write:' + category">
{{ writeLabel }}
</option>
</select>
</div>
</div>
</template>

View File

@ -1,6 +1,5 @@
import {createApp} from 'vue';
import DiffFileTree from '../components/DiffFileTree.vue';
import DiffFileList from '../components/DiffFileList.vue';
export function initDiffFileTree() {
const el = document.querySelector('#diff-file-tree');
@ -9,11 +8,3 @@ export function initDiffFileTree() {
const fileTreeView = createApp(DiffFileTree);
fileTreeView.mount(el);
}
export function initDiffFileList() {
const fileListElement = document.querySelector('#diff-file-list');
if (!fileListElement) return;
const fileListView = createApp(DiffFileList);
fileListView.mount(fileListElement);
}

View File

@ -1,41 +1,33 @@
import $ from 'jquery';
import {initCompReactionSelector} from './comp/ReactionSelector.ts';
import {initRepoIssueContentHistory} from './repo-issue-content.ts';
import {initDiffFileTree, initDiffFileList} from './repo-diff-filetree.ts';
import {initDiffFileTree} from './repo-diff-filetree.ts';
import {initDiffCommitSelect} from './repo-diff-commitselect.ts';
import {validateTextareaNonEmpty} from './comp/ComboMarkdownEditor.ts';
import {initViewedCheckboxListenerFor, countAndUpdateViewedFiles, initExpandAndCollapseFilesButton} from './pull-view-file.ts';
import {initImageDiff} from './imagediff.ts';
import {showErrorToast} from '../modules/toast.ts';
import {
submitEventSubmitter,
queryElemSiblings,
hideElem,
showElem,
animateOnce,
addDelegatedEventListener,
createElementFromHTML,
} from '../utils/dom.ts';
import {submitEventSubmitter, queryElemSiblings, hideElem, showElem, animateOnce, addDelegatedEventListener, createElementFromHTML, queryElems} from '../utils/dom.ts';
import {POST, GET} from '../modules/fetch.ts';
import {fomanticQuery} from '../modules/fomantic/base.ts';
import {createTippy} from '../modules/tippy.ts';
import {invertFileFolding} from './file-fold.ts';
import {parseDom} from '../utils.ts';
const {pageData, i18n} = window.config;
const {i18n} = window.config;
function initRepoDiffFileViewToggle() {
$('.file-view-toggle').on('click', function () {
for (const el of queryElemSiblings(this)) {
el.classList.remove('active');
}
this.classList.add('active');
// switch between "rendered" and "source", for image and CSV files
// FIXME: this event listener is not correctly added to "load more files"
queryElems(document, '.file-view-toggle', (btn) => btn.addEventListener('click', () => {
queryElemSiblings(btn, '.file-view-toggle', (el) => el.classList.remove('active'));
btn.classList.add('active');
const target = document.querySelector(this.getAttribute('data-toggle-selector'));
if (!target) return;
const target = document.querySelector(btn.getAttribute('data-toggle-selector'));
if (!target) throw new Error('Target element not found');
hideElem(queryElemSiblings(target));
showElem(target);
});
}));
}
function initRepoDiffConversationForm() {
@ -103,22 +95,23 @@ function initRepoDiffConversationForm() {
}
});
$(document).on('click', '.resolve-conversation', async function (e) {
addDelegatedEventListener(document, 'click', '.resolve-conversation', async (el, e) => {
e.preventDefault();
const comment_id = $(this).data('comment-id');
const origin = $(this).data('origin');
const action = $(this).data('action');
const url = $(this).data('update-url');
const comment_id = el.getAttribute('data-comment-id');
const origin = el.getAttribute('data-origin');
const action = el.getAttribute('data-action');
const url = el.getAttribute('data-update-url');
try {
const response = await POST(url, {data: new URLSearchParams({origin, action, comment_id})});
const data = await response.text();
if ($(this).closest('.conversation-holder').length) {
const $conversation = $(data);
$(this).closest('.conversation-holder').replaceWith($conversation);
$conversation.find('.dropdown').dropdown();
initCompReactionSelector($conversation[0]);
const elConversationHolder = el.closest('.conversation-holder');
if (elConversationHolder) {
const elNewConversation = createElementFromHTML(data);
elConversationHolder.replaceWith(elNewConversation);
queryElems(elConversationHolder, '.ui.dropdown:not(.custom)', (el) => fomanticQuery(el).dropdown());
initCompReactionSelector(elNewConversation);
} else {
window.location.reload();
}
@ -128,24 +121,19 @@ function initRepoDiffConversationForm() {
});
}
export function initRepoDiffConversationNav() {
function initRepoDiffConversationNav() {
// Previous/Next code review conversation
$(document).on('click', '.previous-conversation', (e) => {
const $conversation = $(e.currentTarget).closest('.comment-code-cloud');
const $conversations = $('.comment-code-cloud:not(.tw-hidden)');
const index = $conversations.index($conversation);
const previousIndex = index > 0 ? index - 1 : $conversations.length - 1;
const $previousConversation = $conversations.eq(previousIndex);
const anchor = $previousConversation.find('.comment').first()[0].getAttribute('id');
window.location.href = `#${anchor}`;
});
$(document).on('click', '.next-conversation', (e) => {
const $conversation = $(e.currentTarget).closest('.comment-code-cloud');
const $conversations = $('.comment-code-cloud:not(.tw-hidden)');
const index = $conversations.index($conversation);
const nextIndex = index < $conversations.length - 1 ? index + 1 : 0;
const $nextConversation = $conversations.eq(nextIndex);
const anchor = $nextConversation.find('.comment').first()[0].getAttribute('id');
addDelegatedEventListener(document, 'click', '.previous-conversation, .next-conversation', (el, e) => {
e.preventDefault();
const isPrevious = el.matches('.previous-conversation');
const elCurConversation = el.closest('.comment-code-cloud');
const elAllConversations = document.querySelectorAll('.comment-code-cloud:not(.tw-hidden)');
const index = Array.from(elAllConversations).indexOf(elCurConversation);
const previousIndex = index > 0 ? index - 1 : elAllConversations.length - 1;
const nextIndex = index < elAllConversations.length - 1 ? index + 1 : 0;
const navIndex = isPrevious ? previousIndex : nextIndex;
const elNavConversation = elAllConversations[navIndex];
const anchor = elNavConversation.querySelector('.comment').id;
window.location.href = `#${anchor}`;
});
}
@ -161,6 +149,7 @@ function initDiffHeaderPopup() {
// Will be called when the show more (files) button has been pressed
function onShowMoreFiles() {
// FIXME: here the init calls are incomplete: at least it misses dropdown & initCompReactionSelector & initRepoDiffFileViewToggle
initRepoIssueContentHistory();
initViewedCheckboxListenerFor();
countAndUpdateViewedFiles();
@ -168,83 +157,108 @@ function onShowMoreFiles() {
initDiffHeaderPopup();
}
export async function loadMoreFiles(url: string) {
const target = document.querySelector('a#diff-show-more-files');
if (target?.classList.contains('disabled') || pageData.diffFileInfo.isLoadingNewData) {
return;
async function loadMoreFiles(btn: Element): Promise<boolean> {
if (btn.classList.contains('disabled')) {
return false;
}
pageData.diffFileInfo.isLoadingNewData = true;
target?.classList.add('disabled');
btn.classList.add('disabled');
const url = btn.getAttribute('data-href');
try {
const response = await GET(url);
const resp = await response.text();
const $resp = $(resp);
const respDoc = parseDom(resp, 'text/html');
const respFileBoxes = respDoc.querySelector('#diff-file-boxes');
// the response is a full HTML page, we need to extract the relevant contents:
// 1. append the newly loaded file list items to the existing list
$('#diff-incomplete').replaceWith($resp.find('#diff-file-boxes').children());
// 2. re-execute the script to append the newly loaded items to the JS variables to refresh the DiffFileTree
$('body').append($resp.find('script#diff-data-script'));
// * append the newly loaded file list items to the existing list
document.querySelector('#diff-incomplete').replaceWith(...Array.from(respFileBoxes.children));
onShowMoreFiles();
return true;
} catch (error) {
console.error('Error:', error);
showErrorToast('An error occurred while loading more files.');
} finally {
target?.classList.remove('disabled');
pageData.diffFileInfo.isLoadingNewData = false;
btn.classList.remove('disabled');
}
return false;
}
function initRepoDiffShowMore() {
$(document).on('click', 'a#diff-show-more-files', (e) => {
addDelegatedEventListener(document, 'click', 'a#diff-show-more-files', (el, e) => {
e.preventDefault();
const linkLoadMore = e.target.getAttribute('data-href');
loadMoreFiles(linkLoadMore);
loadMoreFiles(el);
});
$(document).on('click', 'a.diff-load-button', async (e) => {
addDelegatedEventListener(document, 'click', 'a.diff-load-button', async (el, e) => {
e.preventDefault();
const $target = $(e.target);
if (el.classList.contains('disabled')) return;
if (e.target.classList.contains('disabled')) {
return;
}
e.target.classList.add('disabled');
const url = $target.data('href');
el.classList.add('disabled');
const url = el.getAttribute('data-href');
try {
const response = await GET(url);
const resp = await response.text();
if (!resp) {
return;
}
$target.parent().replaceWith($(resp).find('#diff-file-boxes .diff-file-body .file-body').children());
const respDoc = parseDom(resp, 'text/html');
const respFileBody = respDoc.querySelector('#diff-file-boxes .diff-file-body .file-body');
el.parentElement.replaceWith(...Array.from(respFileBody.children));
// FIXME: calling onShowMoreFiles is not quite right here.
// But since onShowMoreFiles mixes "init diff box" and "init diff body" together,
// so it still needs to call it to make the "ImageDiff" and something similar work.
onShowMoreFiles();
} catch (error) {
console.error('Error:', error);
} finally {
e.target.classList.remove('disabled');
el.classList.remove('disabled');
}
});
}
async function loadUntilFound() {
const hashTargetSelector = window.location.hash;
if (!hashTargetSelector.startsWith('#diff-') && !hashTargetSelector.startsWith('#issuecomment-')) {
return;
}
while (true) {
// use getElementById to avoid querySelector throws an error when the hash is invalid
// eslint-disable-next-line unicorn/prefer-query-selector
const targetElement = document.getElementById(hashTargetSelector.substring(1));
if (targetElement) {
targetElement.scrollIntoView();
return;
}
// the button will be refreshed after each "load more", so query it every time
const showMoreButton = document.querySelector('#diff-show-more-files');
if (!showMoreButton) {
return; // nothing more to load
}
// Load more files, await ensures we don't block progress
const ok = await loadMoreFiles(showMoreButton);
if (!ok) return; // failed to load more files
}
}
function initRepoDiffHashChangeListener() {
window.addEventListener('hashchange', loadUntilFound);
loadUntilFound();
}
export function initRepoDiffView() {
initRepoDiffConversationForm();
if (!$('#diff-file-list').length) return;
initRepoDiffConversationForm(); // such form appears on the "conversation" page and "diff" page
if (!document.querySelector('#diff-file-boxes')) return;
initRepoDiffConversationNav(); // "previous" and "next" buttons only appear on "diff" page
initDiffFileTree();
initDiffFileList();
initDiffCommitSelect();
initRepoDiffShowMore();
initDiffHeaderPopup();
initRepoDiffFileViewToggle();
initViewedCheckboxListenerFor();
initExpandAndCollapseFilesButton();
initRepoDiffHashChangeListener();
addDelegatedEventListener(document, 'click', '.fold-file', (el) => {
invertFileFolding(el.closest('.file-content'), el);

View File

@ -9,7 +9,6 @@ import {initUnicodeEscapeButton} from './repo-unicode-escape.ts';
import {initRepoCloneButtons} from './repo-common.ts';
import {initCitationFileCopyContent} from './citation.ts';
import {initCompLabelEdit} from './comp/LabelEdit.ts';
import {initRepoDiffConversationNav} from './repo-diff.ts';
import {initCompReactionSelector} from './comp/ReactionSelector.ts';
import {initRepoSettings} from './repo-settings.ts';
import {initRepoPullRequestMergeForm} from './repo-issue-pr-form.ts';
@ -64,7 +63,6 @@ export function initRepository() {
initRepoIssueWipToggle();
initRepoIssueComments();
initRepoDiffConversationNav();
initRepoIssueReferenceIssue();
initRepoIssueCommentDelete();

View File

@ -1,20 +0,0 @@
import {createApp} from 'vue';
export async function initScopedAccessTokenCategories() {
const el = document.querySelector('#scoped-access-token-selector');
if (!el) return;
const {default: ScopedAccessTokenSelector} = await import(/* webpackChunkName: "scoped-access-token-selector" */'../components/ScopedAccessTokenSelector.vue');
try {
const View = createApp(ScopedAccessTokenSelector, {
isAdmin: JSON.parse(el.getAttribute('data-is-admin')),
noAccessLabel: el.getAttribute('data-no-access-label'),
readLabel: el.getAttribute('data-read-label'),
writeLabel: el.getAttribute('data-write-label'),
});
View.mount(el);
} catch (err) {
console.error('ScopedAccessTokenSelector failed to load', err);
el.textContent = el.getAttribute('data-locale-component-failed-to-load');
}
}

View File

@ -68,7 +68,6 @@ import {initColorPickers} from './features/colorpicker.ts';
import {initAdminSelfCheck} from './features/admin/selfcheck.ts';
import {initOAuth2SettingsDisableCheckbox} from './features/oauth2-settings.ts';
import {initGlobalFetchAction} from './features/common-fetch-action.ts';
import {initScopedAccessTokenCategories} from './features/scoped-access-token.ts';
import {
initFootLanguageMenu,
initGlobalDropdown,
@ -209,7 +208,6 @@ onDomReady(() => {
initUserSettings,
initRepoDiffView,
initPdfViewer,
initScopedAccessTokenCategories,
initColorPickers,
initOAuth2SettingsDisableCheckbox,

View File

@ -1,11 +1,16 @@
import {reactive} from 'vue';
import type {Reactive} from 'vue';
const {pageData} = window.config;
let diffTreeStoreReactive: Reactive<Record<string, any>>;
export function diffTreeStore() {
if (!diffTreeStoreReactive) {
diffTreeStoreReactive = reactive(window.config.pageData.diffFileInfo);
window.config.pageData.diffFileInfo = diffTreeStoreReactive;
diffTreeStoreReactive = reactive({
files: pageData.DiffFiles,
fileTreeIsVisible: false,
selectedItem: '',
});
}
return diffTreeStoreReactive;
}

View File

@ -1,9 +1,15 @@
import {
basename, extname, isObject, stripTags, parseIssueHref,
dirname, basename, extname, isObject, stripTags, parseIssueHref,
parseUrl, translateMonth, translateDay, blobToDataURI,
toAbsoluteUrl, encodeURLEncodedBase64, decodeURLEncodedBase64, isImageFile, isVideoFile, parseRepoOwnerPathInfo,
} from './utils.ts';
test('dirname', () => {
expect(dirname('/path/to/file.js')).toEqual('/path/to');
expect(dirname('/path/to')).toEqual('/path');
expect(dirname('file.js')).toEqual('');
});
test('basename', () => {
expect(basename('/path/to/file.js')).toEqual('file.js');
expect(basename('/path/to/file')).toEqual('file');

View File

@ -1,6 +1,12 @@
import {decode, encode} from 'uint8-to-base64';
import type {IssuePageInfo, IssuePathInfo, RepoOwnerPathInfo} from './types.ts';
// transform /path/to/file.ext to /path/to
export function dirname(path: string): string {
const lastSlashIndex = path.lastIndexOf('/');
return lastSlashIndex < 0 ? '' : path.substring(0, lastSlashIndex);
}
// transform /path/to/file.ext to file.ext
export function basename(path: string): string {
const lastSlashIndex = path.lastIndexOf('/');

View File

@ -0,0 +1,86 @@
import {mergeChildIfOnlyOneDir, pathListToTree, type File} from './filetree.ts';
const emptyList: File[] = [];
const singleFile = [{Name: 'file1'}] as File[];
const singleDir = [{Name: 'dir1/file1'}] as File[];
const nestedDir = [{Name: 'dir1/dir2/file1'}] as File[];
const multiplePathsDisjoint = [{Name: 'dir1/dir2/file1'}, {Name: 'dir3/file2'}] as File[];
const multiplePathsShared = [{Name: 'dir1/dir2/dir3/file1'}, {Name: 'dir1/file2'}] as File[];
test('pathListToTree', () => {
expect(pathListToTree(emptyList)).toEqual([]);
expect(pathListToTree(singleFile)).toEqual([
{isFile: true, name: 'file1', path: 'file1', file: {Name: 'file1'}},
]);
expect(pathListToTree(singleDir)).toEqual([
{isFile: false, name: 'dir1', path: 'dir1', children: [
{isFile: true, name: 'file1', path: 'dir1/file1', file: {Name: 'dir1/file1'}},
]},
]);
expect(pathListToTree(nestedDir)).toEqual([
{isFile: false, name: 'dir1', path: 'dir1', children: [
{isFile: false, name: 'dir2', path: 'dir1/dir2', children: [
{isFile: true, name: 'file1', path: 'dir1/dir2/file1', file: {Name: 'dir1/dir2/file1'}},
]},
]},
]);
expect(pathListToTree(multiplePathsDisjoint)).toEqual([
{isFile: false, name: 'dir1', path: 'dir1', children: [
{isFile: false, name: 'dir2', path: 'dir1/dir2', children: [
{isFile: true, name: 'file1', path: 'dir1/dir2/file1', file: {Name: 'dir1/dir2/file1'}},
]},
]},
{isFile: false, name: 'dir3', path: 'dir3', children: [
{isFile: true, name: 'file2', path: 'dir3/file2', file: {Name: 'dir3/file2'}},
]},
]);
expect(pathListToTree(multiplePathsShared)).toEqual([
{isFile: false, name: 'dir1', path: 'dir1', children: [
{isFile: false, name: 'dir2', path: 'dir1/dir2', children: [
{isFile: false, name: 'dir3', path: 'dir1/dir2/dir3', children: [
{isFile: true, name: 'file1', path: 'dir1/dir2/dir3/file1', file: {Name: 'dir1/dir2/dir3/file1'}},
]},
]},
{isFile: true, name: 'file2', path: 'dir1/file2', file: {Name: 'dir1/file2'}},
]},
]);
});
const mergeChildWrapper = (testCase: File[]) => {
const tree = pathListToTree(testCase);
mergeChildIfOnlyOneDir(tree);
return tree;
};
test('mergeChildIfOnlyOneDir', () => {
expect(mergeChildWrapper(emptyList)).toEqual([]);
expect(mergeChildWrapper(singleFile)).toEqual([
{isFile: true, name: 'file1', path: 'file1', file: {Name: 'file1'}},
]);
expect(mergeChildWrapper(singleDir)).toEqual([
{isFile: false, name: 'dir1', path: 'dir1', children: [
{isFile: true, name: 'file1', path: 'dir1/file1', file: {Name: 'dir1/file1'}},
]},
]);
expect(mergeChildWrapper(nestedDir)).toEqual([
{isFile: false, name: 'dir1/dir2', path: 'dir1/dir2', children: [
{isFile: true, name: 'file1', path: 'dir1/dir2/file1', file: {Name: 'dir1/dir2/file1'}},
]},
]);
expect(mergeChildWrapper(multiplePathsDisjoint)).toEqual([
{isFile: false, name: 'dir1/dir2', path: 'dir1/dir2', children: [
{isFile: true, name: 'file1', path: 'dir1/dir2/file1', file: {Name: 'dir1/dir2/file1'}},
]},
{isFile: false, name: 'dir3', path: 'dir3', children: [
{isFile: true, name: 'file2', path: 'dir3/file2', file: {Name: 'dir3/file2'}},
]},
]);
expect(mergeChildWrapper(multiplePathsShared)).toEqual([
{isFile: false, name: 'dir1', path: 'dir1', children: [
{isFile: false, name: 'dir2/dir3', path: 'dir1/dir2/dir3', children: [
{isFile: true, name: 'file1', path: 'dir1/dir2/dir3/file1', file: {Name: 'dir1/dir2/dir3/file1'}},
]},
{isFile: true, name: 'file2', path: 'dir1/file2', file: {Name: 'dir1/file2'}},
]},
]);
});

View File

@ -0,0 +1,85 @@
import {dirname, basename} from '../utils.ts';
export type FileStatus = 'added' | 'modified' | 'deleted' | 'renamed' | 'copied' | 'typechange';
export type File = {
Name: string;
NameHash: string;
Status: FileStatus;
IsViewed: boolean;
IsSubmodule: boolean;
}
type DirItem = {
isFile: false;
name: string;
path: string;
children: Item[];
}
type FileItem = {
isFile: true;
name: string;
path: string;
file: File;
}
export type Item = DirItem | FileItem;
export function pathListToTree(fileEntries: File[]): Item[] {
const pathToItem = new Map<string, DirItem>();
// init root node
const root: DirItem = {name: '', path: '', isFile: false, children: []};
pathToItem.set('', root);
for (const fileEntry of fileEntries) {
const [parentPath, fileName] = [dirname(fileEntry.Name), basename(fileEntry.Name)];
let parentItem = pathToItem.get(parentPath);
if (!parentItem) {
parentItem = constructParents(pathToItem, parentPath);
}
const fileItem: FileItem = {name: fileName, path: fileEntry.Name, isFile: true, file: fileEntry};
parentItem.children.push(fileItem);
}
return root.children;
}
function constructParents(pathToItem: Map<string, DirItem>, dirPath: string): DirItem {
const [dirParentPath, dirName] = [dirname(dirPath), basename(dirPath)];
let parentItem = pathToItem.get(dirParentPath);
if (!parentItem) {
// if the parent node does not exist, create it
parentItem = constructParents(pathToItem, dirParentPath);
}
const dirItem: DirItem = {name: dirName, path: dirPath, isFile: false, children: []};
parentItem.children.push(dirItem);
pathToItem.set(dirPath, dirItem);
return dirItem;
}
export function mergeChildIfOnlyOneDir(nodes: Item[]): void {
for (const node of nodes) {
if (node.isFile) {
continue;
}
const dir = node as DirItem;
mergeChildIfOnlyOneDir(dir.children);
if (dir.children.length === 1 && dir.children[0].isFile === false) {
const child = dir.children[0];
dir.name = `${dir.name}/${child.name}`;
dir.path = child.path;
dir.children = child.children;
}
}
}