enhance: user-friendly packages setup manual (#38946)

* replace #35564
* fix #36992
This commit is contained in:
wxiaoguang
2026-08-17 17:43:34 +00:00
committed by GitHub
parent 596b7f7a25
commit dea71bb8ba
16 changed files with 205 additions and 46 deletions
+1 -1
View File
@@ -149,7 +149,7 @@ func (b *HTMLBuilder) WriteHTML(s template.HTML) *HTMLBuilder {
return b
}
func (b *HTMLBuilder) WriteFormat(fmt template.HTML, args ...any) *HTMLBuilder {
func (b *HTMLBuilder) WriteFormatf(fmt template.HTML, args ...any) *HTMLBuilder {
_, _ = HTMLPrintf(&b.sb, fmt, args...)
return b
}
+1 -1
View File
@@ -26,7 +26,7 @@ func TestHTMLFormat(t *testing.T) {
func TestHTMLBuilder(t *testing.T) {
b := &HTMLBuilder{}
b.WriteString("<").WriteHTML("<hr>").WriteFormat("<span>%s%s</span>", ">", EscapeString(">"))
b.WriteString("<").WriteHTML("<hr>").WriteFormatf("<span>%s%s</span>", ">", EscapeString(">"))
assert.Equal(t, "&lt;<hr><span>&gt;&gt;</span>", b.String())
assert.Equal(t, template.HTML("&lt;<hr><span>&gt;&gt;</span>"), b.HTMLString())
}
+6 -6
View File
@@ -227,7 +227,7 @@ func (ut *RenderUtils) RenderLabels(labels []*issues_model.Label, repoLink strin
if label == nil {
continue
}
htmlCode.WriteFormat(`<a class="item" href="%s?labels=%d">`, baseLink, label.ID)
htmlCode.WriteFormatf(`<a class="item" href="%s?labels=%d">`, baseLink, label.ID)
htmlCode.WriteHTML(ut.RenderLabel(label))
htmlCode.WriteHTML("</a>")
}
@@ -347,7 +347,7 @@ func (ut *RenderUtils) AvatarStack(data *user_model.AvatarStackData) template.HT
var b htmlutil.HTMLBuilder
b.WriteHTML(`<span class="avatar-stack">`)
if overflow > 0 {
b.WriteFormat(`<span class="avatar-stack-overflow-chip tw-text-xs" aria-label="+%d more">+%d</span>`, overflow, overflow)
b.WriteFormatf(`<span class="avatar-stack-overflow-chip tw-text-xs" aria-label="+%d more">+%d</span>`, overflow, overflow)
}
// FIXME: such "backward" breaks a11y like screen readers
@@ -361,9 +361,9 @@ func (ut *RenderUtils) AvatarStack(data *user_model.AvatarStackData) template.HT
func (ut *RenderUtils) writeAvatarStackItem(b *htmlutil.HTMLBuilder, data *user_model.AvatarStackData, participant *user_model.CommitParticipant) {
avatar := ut.participantAvatar(participant)
if href := ut.participantHref(data, participant); href != "" {
b.WriteFormat(`<a href="%s">%s</a>`, href, avatar)
b.WriteFormatf(`<a href="%s">%s</a>`, href, avatar)
} else {
b.WriteFormat(`<span>%s</span>`, avatar)
b.WriteFormatf(`<span>%s</span>`, avatar)
}
}
@@ -392,10 +392,10 @@ func (ut *RenderUtils) AvatarStackWithNames(data *user_model.AvatarStackData) te
b.WriteHTML(ut.participantNameLink(data, participants[0]))
case 2:
b.WriteHTML(ut.participantNameLink(data, participants[0]))
b.WriteFormat(`<span>%s</span>`, locale.Tr("repo.commits.avatar_stack_and"))
b.WriteFormatf(`<span>%s</span>`, locale.Tr("repo.commits.avatar_stack_and"))
b.WriteHTML(ut.participantNameLink(data, participants[1]))
default:
b.WriteFormat(`<button type="button" class="avatar-stack-popup-trigger" data-global-init="initAvatarStackPopup">%s</button>`,
b.WriteFormatf(`<button type="button" class="avatar-stack-popup-trigger" data-global-init="initAvatarStackPopup">%s</button>`,
locale.Tr("repo.commits.avatar_stack_people", len(participants)))
b.WriteHTML(`<div class="tippy-target"><div class="avatar-stack-popup">`)
for _, participant := range participants {
-1
View File
@@ -3600,7 +3600,6 @@
"packages.cran.registry": "Set up this registry in your <code>Rprofile.site</code> file:",
"packages.cran.install": "To install the package, run the following command:",
"packages.debian.registry": "Set up this registry from the command line:",
"packages.debian.registry.info": "Choose $distribution and $component from the list below.",
"packages.debian.install": "To install the package, run the following command:",
"packages.debian.repository": "Repository Info",
"packages.debian.repository.distributions": "Distributions",
+4 -23
View File
@@ -23,7 +23,6 @@ import (
alpine_module "gitea.dev/modules/packages/alpine"
arch_module "gitea.dev/modules/packages/arch"
container_module "gitea.dev/modules/packages/container"
debian_module "gitea.dev/modules/packages/debian"
rpm_module "gitea.dev/modules/packages/rpm"
terraform_module "gitea.dev/modules/packages/terraform"
"gitea.dev/modules/setting"
@@ -245,27 +244,6 @@ func ViewPackageVersion(ctx *context.Context) {
ctx.Data["Repositories"] = util.Sorted(repositories.Values())
ctx.Data["Architectures"] = util.Sorted(architectures.Values())
case packages_model.TypeDebian:
distributions := make(container.Set[string])
components := make(container.Set[string])
architectures := make(container.Set[string])
for _, f := range pd.Files {
for _, pp := range f.Properties {
switch pp.Name {
case debian_module.PropertyDistribution:
distributions.Add(pp.Value)
case debian_module.PropertyComponent:
components.Add(pp.Value)
case debian_module.PropertyArchitecture:
architectures.Add(pp.Value)
}
}
}
ctx.Data["Distributions"] = util.Sorted(distributions.Values())
ctx.Data["Components"] = util.Sorted(components.Values())
ctx.Data["Architectures"] = util.Sorted(architectures.Values())
case packages_model.TypeRpm:
groups := make(container.Set[string])
architectures := make(container.Set[string])
@@ -318,12 +296,15 @@ func ViewPackageVersion(ctx *context.Context) {
}
ctx.Data["LatestVersions"] = pvs
ctx.Data["TotalVersionCount"] = pvsTotal
ctx.Data["PackageVersionViewData"], err = packages_service.GetSpecManager().Get(pd.Package.Type).GetViewPackageVersionData(ctx, pd)
pkgSpec := packages_service.GetSpecManager().Get(pd.Package.Type)
viewData, err := pkgSpec.GetViewPackageVersionData(ctx, pd)
if err != nil {
ctx.ServerError("GetViewPackageVersionData", err)
return
}
ctx.Data["PackageVersionViewData"] = viewData
ctx.Data["PackageVersionSetupManual"] = pkgSpec.RenderSetupManual(ctx, pd, viewData)
ctx.Data["CanWritePackages"] = ctx.Package.AccessMode >= perm.AccessModeWrite || ctx.IsUserSiteAdmin()
hasRepositoryAccess := false
+87
View File
@@ -0,0 +1,87 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package debian
import (
"context"
"html/template"
"strings"
packages_model "gitea.dev/models/packages"
"gitea.dev/modules/container"
"gitea.dev/modules/htmlutil"
"gitea.dev/modules/httplib"
debian_module "gitea.dev/modules/packages/debian"
"gitea.dev/modules/util"
packages_service "gitea.dev/services/packages"
)
type Specialization struct {
packages_service.SpecOnBeforeRemovePackageAll
packages_service.SpecOnBeforeRemovePackageVersion
}
var _ packages_service.Specialization = (*Specialization)(nil)
type debianViewData struct {
Distributions []string
Components []string
Architectures []string
}
func (s Specialization) GetViewPackageVersionData(ctx context.Context, pd *packages_model.PackageDescriptor) (any, error) {
distributions := make(container.Set[string])
components := make(container.Set[string])
architectures := make(container.Set[string])
for _, f := range pd.Files {
for _, pp := range f.Properties {
switch pp.Name {
case debian_module.PropertyDistribution:
distributions.Add(pp.Value)
case debian_module.PropertyComponent:
components.Add(pp.Value)
case debian_module.PropertyArchitecture:
architectures.Add(pp.Value)
}
}
}
viewData := debianViewData{
Distributions: util.Sorted(distributions.Values()),
Components: util.Sorted(components.Values()),
Architectures: util.Sorted(architectures.Values()),
}
return viewData, nil
}
func writeVarSelect(w *htmlutil.HTMLBuilder, varName string, varItems []string) {
w.WriteFormatf(`<div>%s=<select data-code-var="%s">`, varName, varName)
for _, v := range varItems {
w.WriteFormatf(`<option value="%s">%s</option>`, v, v)
}
w.WriteHTML("</select></div>")
}
func (s Specialization) RenderSetupManual(ctx context.Context, pkg *packages_model.PackageDescriptor, viewDataAny any) template.HTML {
viewData := viewDataAny.(debianViewData) //nolint:forcetypeassert // must be valid
const nl = "\n"
appFullLink := strings.TrimSuffix(httplib.GuessCurrentAppURL(ctx), "/")
w := &htmlutil.HTMLBuilder{}
w.WriteHTML(`<div data-global-init="initPackagesManualVars">`)
{
w.WriteHTML(`<div class="package-manual-vars">`)
writeVarSelect(w, "distribution", viewData.Distributions)
writeVarSelect(w, "component", viewData.Components)
w.WriteHTML(`</div>`)
}
{
w.WriteHTML(`<div class="markup"><pre class="code-block"><code>`)
w.WriteFormatf(`sudo curl %s/api/packages/%s/debian/repository.key -o /etc/apt/keyrings/gitea-%s.asc`+nl+nl, appFullLink, pkg.Owner.Name, pkg.Owner.Name)
w.WriteFormatf(`echo "deb [signed-by=/etc/apt/keyrings/gitea-%s.asc] %s/api/packages/%s/debian <span>$distribution</span> <span>$component</span>" | sudo tee -a /etc/apt/sources.list.d/gitea.list`+nl+nl, pkg.Owner.Name, appFullLink, pkg.Owner.Name)
w.WriteHTML(`sudo apt update` + nl)
w.WriteHTML(`</code></pre></div>`)
}
w.WriteHTML(`</div>`)
return w.HTMLString()
}
+2
View File
@@ -8,6 +8,7 @@ import (
"encoding/hex"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"net/url"
@@ -37,6 +38,7 @@ type Specialization interface {
OnBeforeRemovePackageAll(ctx context.Context, doer *user_model.User, pkg *packages_model.Package, pds []*packages_model.PackageDescriptor) error
OnBeforeRemovePackageVersion(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) error
GetViewPackageVersionData(ctx context.Context, pd *packages_model.PackageDescriptor) (any, error)
RenderSetupManual(ctx context.Context, pkg *packages_model.PackageDescriptor, viewData any) template.HTML
}
// PackageInfo describes a package
+2
View File
@@ -6,11 +6,13 @@ package pkgspec
import (
packages_model "gitea.dev/models/packages"
packages_service "gitea.dev/services/packages"
"gitea.dev/services/packages/debian"
"gitea.dev/services/packages/terraform"
)
func InitManager() error {
mgr := packages_service.GetSpecManager()
mgr.Add(packages_model.TypeDebian, &debian.Specialization{})
mgr.Add(packages_model.TypeTerraformState, &terraform.Specialization{})
// TODO: add more in the future, refactor the existing code to use this approach
return nil
+28 -6
View File
@@ -5,27 +5,49 @@ package packages
import (
"context"
"html/template"
"sync"
packages_model "gitea.dev/models/packages"
user_model "gitea.dev/models/user"
)
type nop struct{}
type SpecGetViewPackageVersionData struct{}
func (n *nop) GetViewPackageVersionData(ctx context.Context, pd *packages_model.PackageDescriptor) (any, error) {
func (*SpecGetViewPackageVersionData) GetViewPackageVersionData(ctx context.Context, pd *packages_model.PackageDescriptor) (any, error) {
return nil, nil //nolint:nilnil // no data, no error
}
func (n *nop) OnBeforeRemovePackageAll(ctx context.Context, doer *user_model.User, pkg *packages_model.Package, pds []*packages_model.PackageDescriptor) error {
type SpecOnBeforeRemovePackageAll struct{}
func (*SpecOnBeforeRemovePackageAll) OnBeforeRemovePackageAll(ctx context.Context, doer *user_model.User, pkg *packages_model.Package, pds []*packages_model.PackageDescriptor) error {
return nil
}
func (n *nop) OnBeforeRemovePackageVersion(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) error {
type SpecOnBeforeRemovePackageVersion struct{}
func (*SpecOnBeforeRemovePackageVersion) OnBeforeRemovePackageVersion(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) error {
return nil
}
var _ Specialization = (*nop)(nil)
type SpecRenderUsageManual struct{}
func (*SpecRenderUsageManual) RenderSetupManual(ctx context.Context, pkg *packages_model.PackageDescriptor, viewData any) template.HTML {
return ""
}
type specDefault struct {
SpecGetViewPackageVersionData
SpecOnBeforeRemovePackageAll
SpecOnBeforeRemovePackageVersion
SpecRenderUsageManual
}
func (n *specDefault) OnBeforeRemovePackageVersion(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) error {
return nil
}
var _ Specialization = (*specDefault)(nil)
type SpecManagerType struct {
specMap map[packages_model.Type]Specialization
@@ -41,7 +63,7 @@ func (m *SpecManagerType) Get(t packages_model.Type) Specialization {
}
spec := m.specMap[t]
if spec == nil {
return &nop{}
return &specDefault{}
}
return spec
}
+3 -1
View File
@@ -14,7 +14,9 @@ import (
packages_service "gitea.dev/services/packages"
)
type Specialization struct{}
type Specialization struct {
packages_service.SpecRenderUsageManual
}
var _ packages_service.Specialization = (*Specialization)(nil)
+5 -7
View File
@@ -4,10 +4,7 @@
<div class="ui form">
<div class="field">
<label>{{svg "octicon-terminal"}} {{ctx.Locale.Tr "packages.debian.registry"}}</label>
<div class="markup"><pre class="code-block"><code>sudo curl {{ctx.AppFullLink}}/api/packages/{{$.PackageDescriptor.Owner.Name}}/debian/repository.key -o /etc/apt/keyrings/gitea-{{$.PackageDescriptor.Owner.Name}}.asc
echo "deb [signed-by=/etc/apt/keyrings/gitea-{{$.PackageDescriptor.Owner.Name}}.asc] {{ctx.AppFullLink}}/api/packages/{{$.PackageDescriptor.Owner.Name}}/debian $distribution $component" | sudo tee -a /etc/apt/sources.list.d/gitea.list
sudo apt update</code></pre></div>
<p>{{ctx.Locale.Tr "packages.debian.registry.info"}}</p>
{{$.PackageVersionSetupManual}}
</div>
<div class="field">
<label>{{svg "octicon-terminal"}} {{ctx.Locale.Tr "packages.debian.install"}}</label>
@@ -21,21 +18,22 @@ sudo apt update</code></pre></div>
</div>
</div>
{{$viewData := $.PackageVersionViewData}}
<h4 class="ui top attached header">{{ctx.Locale.Tr "packages.debian.repository"}}</h4>
<div class="ui attached segment">
<table class="ui single line very basic table">
<tbody>
<tr>
<td class="collapsing"><h5>{{ctx.Locale.Tr "packages.debian.repository.distributions"}}</h5></td>
<td>{{StringUtils.Join .Distributions ", "}}</td>
<td>{{StringUtils.Join $viewData.Distributions ", "}}</td>
</tr>
<tr>
<td class="collapsing"><h5>{{ctx.Locale.Tr "packages.debian.repository.components"}}</h5></td>
<td>{{StringUtils.Join .Components ", "}}</td>
<td>{{StringUtils.Join $viewData.Components ", "}}</td>
</tr>
<tr>
<td class="collapsing"><h5>{{ctx.Locale.Tr "packages.debian.repository.architectures"}}</h5></td>
<td>{{StringUtils.Join .Architectures ", "}}</td>
<td>{{StringUtils.Join $viewData.Architectures ", "}}</td>
</tr>
</tbody>
</table>
@@ -58,6 +58,10 @@ func TestPackageDebian(t *testing.T) {
}
aw.WriteHeader(hdr)
aw.Write(cbuf.Bytes())
// if you'd like to do some tests manually, uncomment the WriteFile line, then you will get some "deb" package files:
// OWNER= PASS= DIST= COMP= ; curl -X PUT "http://$OWNER:$PASS@localhost:3000/api/packages/$OWNER/debian/pool/$DIST/$COMP/upload" -T /tmp/gitea_test_debian_gitea_1.0.3_amd64.deb
// _ = os.WriteFile("/tmp/gitea_test_debian_"+name+"_"+version+"_"+architecture+".deb", buf.Bytes(), 0o644)
return &buf
}
+18
View File
@@ -9,6 +9,24 @@
width: calc(100% - 250px - 16px);
}
.packages-content-left .markup {
margin: var(--gap-block) 0;
}
.packages-content-left .markup pre.code-block {
margin: 0;
}
.package-manual-vars {
display: flex;
gap: 1em;
flex-wrap: wrap;
}
.package-manual-vars select {
border-radius: var(--border-radius);
}
.packages-content-right {
margin: 0 !important;
width: 250px;
+18
View File
@@ -0,0 +1,18 @@
import {initPackagesManualVars} from './packages.ts';
import {createElementFromHTML} from '../utils/dom.ts';
test('initPackagesManualVars', () => {
const el = createElementFromHTML<HTMLElement>(`
<div>
<select data-code-var="foo"><option value="v1"></option><option value="v2"></option></select>
<span>$foo</span>
</div>
`);
initPackagesManualVars(el);
const elSelect = el.querySelector<HTMLSelectElement>('select')!;
const elSpan = el.querySelector('span')!;
expect(elSpan.textContent).toBe('v1');
elSelect.value = 'v2';
elSelect.dispatchEvent(new Event('change'));
expect(elSpan.textContent).toBe('v2');
});
+24
View File
@@ -0,0 +1,24 @@
import {registerGlobalInitFunc} from '../modules/observer.ts';
import {queryElems} from '../utils/dom.ts';
export function initPackagesManualVars(el: HTMLElement) {
queryElems(el, 'span', (elSpan: HTMLElement) => {
const text = elSpan.textContent;
if (!text.startsWith('$')) return;
elSpan.setAttribute('data-code-var', text.substring(1));
});
const syncVar = (elSelect: HTMLSelectElement) => {
const varName = elSelect.getAttribute('data-code-var')!;
const elSpans = el.querySelectorAll(`span[data-code-var="${CSS.escape(varName)}"]`);
if (elSpans.length === 0) throw new Error(`No span found for variable ${varName}`);
for (const elSpan of elSpans) elSpan.textContent = elSelect.value;
};
queryElems(el, 'select[data-code-var]', (elSelect: HTMLSelectElement) => {
syncVar(elSelect);
elSelect.addEventListener('change', () => syncVar(elSelect));
});
}
export function initPackagesView() {
registerGlobalInitFunc('initPackagesManualVars', initPackagesManualVars);
}
+2
View File
@@ -66,6 +66,7 @@ import {initRefIssueContextPopup} from './features/ref-issue.ts';
import {initGlobalShortcut} from './modules/shortcut.ts';
import {initDevtest} from './modules/devtest.ts';
import {initRepoWatch} from './features/repo-watch.ts';
import {initPackagesView} from './features/packages.ts';
const initStartTime = performance.now();
const initPerformanceTracer = callInitFunctions([
@@ -103,6 +104,7 @@ const initPerformanceTracer = callInitFunctions([
initTableSort,
initRepoFileSearch,
initCopyContent,
initPackagesView,
initAdminCommon,
initAdminUserListSearchForm,