CodeSampleX

示例

github.com/manifoldco/promptui v0.9.0: SelectTemplates

已验证示例 — golang github.com/manifoldco/promptui v0.9.0: SelectTemplates. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: promptui.SelectTemplates…

sha256:37e4de8ffe67a77250906322fbb0a6085a816df83b72a3f1089b7de0da2d45ca

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 go

验证运行环境

环境 契约 阶段 运行日期
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-28

案例

HOW
目标
verify github.com/manifoldco/promptui.SelectTemplates in pkg:golang/github.com/manifoldco/promptui@v0.9.0
包
符号
  • github.com/manifoldco/promptui.SelectTemplates
创建时间
2026-08-28T00:58:00Z

契约

  1. promptui.SelectTemplates formats Label, Active, Inactive, Selected, and Details templates using promptui.FuncMap ANSI styling functions
  2. promptui.SelectTemplates.FuncMap allows defining and overriding custom template helper functions alongside promptui stylers
  3. promptui.Select validates SelectTemplates syntax during setup and fails early on unclosed or invalid template definitions
  4. promptui.SelectTemplates supports structured data models, multi-line details rendering, and dynamic navigation key formatting

文件

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

下载源代码构件 (tar.gz)

源代码

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify github.com/manifoldco/promptui.SelectTemplates in pkg:golang/github.com/manifoldco/promptui@v0.9.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/manifoldco/promptui@v0.9.0
Demonstrate these symbols/APIs:
  - github.com/manifoldco/promptui.SelectTemplates

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:047a809c284ae8df0f4d2e032d4ad949322bcb8df7bb2651a394323d5512b2d4","contract":["promptui.SelectTemplates formats Label, Active, Inactive, Selected, and Details templates using promptui.FuncMap ANSI styling functions","promptui.SelectTemplates.FuncMap allows defining and overriding custom template helper functions alongside promptui stylers","promptui.Select validates SelectTemplates syntax during setup and fails early on unclosed or invalid template definitions","promptui.SelectTemplates supports structured data models, multi-line details rendering, and dynamic navigation key formatting"],"goal":"verify github.com/manifoldco/promptui.SelectTemplates in pkg:golang/github.com/manifoldco/promptui@v0.9.0","kind":"HOW","packages":["pkg:golang/github.com/manifoldco/promptui@v0.9.0"],"schemaVersion":1,"symbols":["github.com/manifoldco/promptui.SelectTemplates"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/manifoldco/promptui@v0.9.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/manifoldco/promptui@v0.9.0","symbols":["github.com/manifoldco/promptui.SelectTemplates"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22

require github.com/manifoldco/promptui v0.9.0

require (
	github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect
	golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b // indirect
)
go.sum
github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA=
github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b h1:MQE+LT/ABUuuvEZ+YQAMSXindAdUh7slEmAkup74op4=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
main.go
package main

import (
	"bytes"
	"fmt"
	"text/template"

	"github.com/manifoldco/promptui"
)

type ServiceEndpoint struct {
	Name        string
	Protocol    string
	Port        int
	Environment string
	Healthy     bool
}

func main() {
	endpoints := []ServiceEndpoint{
		{Name: "auth-service", Protocol: "HTTPS", Port: 8443, Environment: "production", Healthy: true},
		{Name: "billing-api", Protocol: "HTTPS", Port: 9443, Environment: "production", Healthy: true},
		{Name: "telemetry-collector", Protocol: "gRPC", Port: 50051, Environment: "staging", Healthy: false},
	}

	templates := &promptui.SelectTemplates{
		Label:    "{{ . | cyan }}?",
		Active:   "\U0001F449 {{ .Name | bold | cyan }} ({{ .Protocol }}:{{ .Port | yellow }})",
		Inactive: "   {{ .Name | faint }} ({{ .Protocol }}:{{ .Port }})",
		Selected: "\U0001F389 Selected: {{ .Name | green | bold }} [{{ .Environment }}]",
		Details: `
--------- Service Details ---------
{{ "Name:" | faint }}        {{ .Name }}
{{ "Protocol:" | faint }}    {{ .Protocol }}
{{ "Port:" | faint }}        {{ .Port }}
{{ "Environment:" | faint }} {{ .Environment }}
{{ "Status:" | faint }}      {{ if .Healthy }}{{ "HEALTHY" | green }}{{ else }}{{ "DEGRADED" | red }}{{ end }}`,
		Help: `{{ "Navigation:" | faint }} {{ .NextKey }} {{ .PrevKey }}`,
		FuncMap: template.FuncMap{
			"statusBadge": func(healthy bool) string {
				if healthy {
					return promptui.Styler(promptui.FGBold, promptui.FGGreen)("[OK]")
				}
				return promptui.Styler(promptui.FGBold, promptui.FGRed)("[FAIL]")
			},
		},
	}

	_ = promptui.Select{
		Label:     "Select Target Service",
		Items:     endpoints,
		Templates: templates,
		Size:      5,
	}

	funcs := template.FuncMap{}
	for k, v := range promptui.FuncMap {
		funcs[k] = v
	}
	for k, v := range templates.FuncMap {
		funcs[k] = v
	}

	activeTmpl, err := template.New("active").Funcs(funcs).Parse(templates.Active)
	if err == nil {
		var buf bytes.Buffer
		_ = activeTmpl.Execute(&buf, endpoints[0])
		fmt.Println("Active template preview:", buf.String())
	}
	fmt.Println("promptui.SelectTemplates configured successfully.")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/manifoldco/promptui.SelectTemplates in pkg:golang/github.com/manifoldco/promptui@v0.9.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/manifoldco/promptui@v0.9.0"
  ],
  "symbols": [
    "github.com/manifoldco/promptui.SelectTemplates"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"
	"strings"
	"text/template"

	"github.com/manifoldco/promptui"
)

type ServerConfig struct {
	Hostname string
	Port     int
	Region   string
	Active   bool
}

func main() {
	if err := runContract(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract verification failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All SelectTemplates contract assertions passed successfully.")
}

func runContract() error {
	// Assertion 1: SelectTemplates renders Label, Active, Inactive, Selected, and Details templates with promptui.FuncMap styling
	item := ServerConfig{
		Hostname: "node-us-east-1",
		Port:     8080,
		Region:   "us-east-1",
		Active:   true,
	}

	st := promptui.SelectTemplates{
		Label:    "{{ . }}?",
		Active:   "-> {{ .Hostname | cyan | bold }} ({{ .Port | yellow }})",
		Inactive: "   {{ .Hostname | faint }} ({{ .Port }})",
		Selected: "Selected: {{ .Hostname | green | bold }}",
		Details:  "Host: {{ .Hostname }}\nPort: {{ .Port }}\nRegion: {{ .Region }}",
		Help:     "{{ \"Navigate:\" | faint }} {{ .NextKey }} {{ .PrevKey }}",
	}

	// Render Active template: pipeline evaluates cyan first then bold -> bold(cyan(text))
	activeTmpl, err := template.New("active").Funcs(promptui.FuncMap).Parse(st.Active)
	if err != nil {
		return fmt.Errorf("failed to parse Active template: %w", err)
	}
	var buf bytes.Buffer
	if err := activeTmpl.Execute(&buf, item); err != nil {
		return fmt.Errorf("failed to execute Active template: %w", err)
	}
	expectedActive := "-> \033[1m\033[36mnode-us-east-1\033[0m (\033[33m8080\033[0m)"
	if buf.String() != expectedActive {
		return fmt.Errorf("expected active string %q, got %q", expectedActive, buf.String())
	}

	// Render Inactive template
	inactiveTmpl, err := template.New("inactive").Funcs(promptui.FuncMap).Parse(st.Inactive)
	if err != nil {
		return fmt.Errorf("failed to parse Inactive template: %w", err)
	}
	buf.Reset()
	if err := inactiveTmpl.Execute(&buf, item); err != nil {
		return fmt.Errorf("failed to execute Inactive template: %w", err)
	}
	expectedInactive := "   \033[2mnode-us-east-1\033[0m (8080)"
	if buf.String() != expectedInactive {
		return fmt.Errorf("expected inactive string %q, got %q", expectedInactive, buf.String())
	}

	// Render Selected template: pipeline evaluates green first then bold -> bold(green(text))
	selectedTmpl, err := template.New("selected").Funcs(promptui.FuncMap).Parse(st.Selected)
	if err != nil {
		return fmt.Errorf("failed to parse Selected template: %w", err)
	}
	buf.Reset()
	if err := selectedTmpl.Execute(&buf, item); err != nil {
		return fmt.Errorf("failed to execute Selected template: %w", err)
	}
	expectedSelected := "Selected: \033[1m\033[32mnode-us-east-1\033[0m"
	if buf.String() != expectedSelected {
		return fmt.Errorf("expected selected string %q, got %q", expectedSelected, buf.String())
	}

	// Render Details template
	detailsTmpl, err := template.New("details").Funcs(promptui.FuncMap).Parse(st.Details)
	if err != nil {
		return fmt.Errorf("failed to parse Details template: %w", err)
	}
	buf.Reset()
	if err := detailsTmpl.Execute(&buf, item); err != nil {
		return fmt.Errorf("failed to execute Details template: %w", err)
	}
	expectedDetails := "Host: node-us-east-1\nPort: 8080\nRegion: us-east-1"
	if buf.String() != expectedDetails {
		return fmt.Errorf("expected details string %q, got %q", expectedDetails, buf.String())
	}

	// Assertion 2: SelectTemplates.FuncMap allows custom template helper functions combined with promptui stylers
	customFuncs := template.FuncMap{
		"badge": func(region string) string {
			return promptui.Styler(promptui.FGBold, promptui.FGWhite, promptui.BGBlue)("[" + region + "]")
		},
		"statusIcon": func(active bool) string {
			if active {
				return promptui.Styler(promptui.FGGreen)("ONLINE")
			}
			return promptui.Styler(promptui.FGRed)("OFFLINE")
		},
	}
	mergedFuncs := template.FuncMap{}
	for k, v := range promptui.FuncMap {
		mergedFuncs[k] = v
	}
	for k, v := range customFuncs {
		mergedFuncs[k] = v
	}

	customTmpl, err := template.New("custom").Funcs(mergedFuncs).Parse(`{{ badge .Region }} {{ .Hostname | bold }}: {{ statusIcon .Active }}`)
	if err != nil {
		return fmt.Errorf("failed to parse template with custom FuncMap: %w", err)
	}
	buf.Reset()
	if err := customTmpl.Execute(&buf, item); err != nil {
		return fmt.Errorf("failed to execute custom template: %w", err)
	}
	expectedCustom := "\033[1;37;44m[us-east-1]\033[0m \033[1mnode-us-east-1\033[0m: \033[32mONLINE\033[0m"
	if buf.String() != expectedCustom {
		return fmt.Errorf("expected custom output %q, got %q", expectedCustom, buf.String())
	}

	// Assertion 3: promptui.Select validates SelectTemplates syntax and returns errors for malformed templates
	invalidSelect := promptui.Select{
		Label: "Select Host",
		Items: []ServerConfig{item},
		Templates: &promptui.SelectTemplates{
			Label: "{{ .UnclosedTag",
		},
	}
	_, _, runErr := invalidSelect.Run()
	if runErr == nil {
		return fmt.Errorf("expected Select.Run() to fail with invalid template syntax, but got nil")
	}
	if !strings.Contains(runErr.Error(), "unclosed action") {
		return fmt.Errorf("expected unclosed action template parse error, got: %v", runErr)
	}

	// Assertion 4: SelectTemplates correctly integrates with promptui.Select struct configuration and help templates
	helpKeys := struct {
		NextKey     string
		PrevKey     string
		PageDownKey string
		PageUpKey   string
		SearchKey   string
		Search      bool
	}{
		NextKey:   "↓",
		PrevKey:   "↑",
		SearchKey: "/",
		Search:    true,
	}
	helpTmpl, err := template.New("help").Funcs(promptui.FuncMap).Parse(
		`{{ "Keys:" | faint }} {{ .PrevKey }} {{ .NextKey }}{{ if .Search }} {{ "Search:" | faint }} {{ .SearchKey }}{{ end }}`,
	)
	if err != nil {
		return fmt.Errorf("failed to parse Help template: %w", err)
	}
	buf.Reset()
	if err := helpTmpl.Execute(&buf, helpKeys); err != nil {
		return fmt.Errorf("failed to execute Help template: %w", err)
	}
	expectedHelp := "\033[2mKeys:\033[0m ↑ ↓ \033[2mSearch:\033[0m /"
	if buf.String() != expectedHelp {
		return fmt.Errorf("expected help output %q, got %q", expectedHelp, buf.String())
	}

	return nil
}

原始种子者

匿名