CodeSampleX

샘플

golang.org/x/net v0.61.0: html.ParseFragment

검증된 샘플 — golang golang.org/x/net v0.61.0: html.ParseFragment. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: html.ParseFragment parses HTML…

sha256:78e4beedc9c1092d1a9cb29e2b7a65424ee8b11003245aa56abc26b91cf89ef7

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-10-11

케이스

HOW
목표
verify golang.org/x/net/html.ParseFragment in pkg:golang/golang.org/x/net@v0.61.0
패키지
심벌
  • golang.org/x/net/html.ParseFragment
생성일
2026-10-11T22:47:59Z

컨트랙트

  1. html.ParseFragment parses HTML fragment without context into a root html element containing head and body
  2. html.ParseFragment parses child elements directly when provided an element context like body
  3. html.ParseFragment wraps table rows in an implicit tbody when parsed with a table context
  4. html.ParseFragment parses option elements and preserves attributes when given a select context
  5. html.ParseFragment handles malformed fragment markup by performing HTML5 error recovery without failing

파일

  • PROMPT.md
  • csx.json
  • fragment.go
  • go.mod
  • go.sum
  • 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 golang.org/x/net/html.ParseFragment in pkg:golang/golang.org/x/net@v0.61.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/net@v0.61.0
Demonstrate these symbols/APIs:
  - golang.org/x/net/html.ParseFragment

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:fce9ad77ab9f6c961772a63a78ea86ed0d1bb4e9e1082936a80267ae1a357cbd","contract":["html.ParseFragment parses HTML fragment without context into a root html element containing head and body","html.ParseFragment parses child elements directly when provided an element context like body","html.ParseFragment wraps table rows in an implicit tbody when parsed with a table context","html.ParseFragment parses option elements and preserves attributes when given a select context","html.ParseFragment handles malformed fragment markup by performing HTML5 error recovery without failing"],"goal":"verify golang.org/x/net/html.ParseFragment in pkg:golang/golang.org/x/net@v0.61.0","kind":"HOW","packages":["pkg:golang/golang.org/x/net@v0.61.0"],"schemaVersion":1,"symbols":["golang.org/x/net/html.ParseFragment"]},"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/golang.org/x/net@v0.61.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/net@v0.61.0","symbols":["golang.org/x/net/html.ParseFragment"],"verifierAdapter":"golang@1"}
fragment.go
package sample

import (
	"io"
	"strings"

	"golang.org/x/net/html"
)

// ParseFragment parses an HTML fragment with the given context element.
// If context is nil, it parses within the default context.
func ParseFragment(r io.Reader, context *html.Node) ([]*html.Node, error) {
	return html.ParseFragment(r, context)
}

// ParseFragmentString parses an HTML string fragment with the given context element.
func ParseFragmentString(fragment string, context *html.Node) ([]*html.Node, error) {
	return html.ParseFragment(strings.NewReader(fragment), context)
}

// FindFirstElement searches depth-first for the first element node with the specified tag name.
func FindFirstElement(nodes []*html.Node, tagName string) *html.Node {
	for _, n := range nodes {
		if found := findInTree(n, tagName); found != nil {
			return found
		}
	}
	return nil
}

func findInTree(n *html.Node, tagName string) *html.Node {
	if n == nil {
		return nil
	}
	if n.Type == html.ElementNode && n.Data == tagName {
		return n
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if found := findInTree(c, tagName); found != nil {
			return found
		}
	}
	return nil
}

// GetAttr returns the value of the attribute with the given key, and whether it was found.
func GetAttr(n *html.Node, key string) (string, bool) {
	if n == nil {
		return "", false
	}
	for _, attr := range n.Attr {
		if attr.Key == key {
			return attr.Val, true
		}
	}
	return "", false
}
go.mod
module sample

go 1.26.6

require golang.org/x/net v0.61.0
go.sum
golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/net/html.ParseFragment in pkg:golang/golang.org/x/net@v0.61.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/net@v0.61.0"
  ],
  "symbols": [
    "golang.org/x/net/html.ParseFragment"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"

	"golang.org/x/net/html"
	"golang.org/x/net/html/atom"
	"sample"
)

func main() {
	// Assertion 1: html.ParseFragment parses HTML fragment without context into a root html element containing head and body
	nodes1, err := sample.ParseFragmentString("<p>Paragraph</p>", nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 1 failed: parse error: %v\n", err)
		os.Exit(1)
	}
	if len(nodes1) != 1 || nodes1[0].Type != html.ElementNode || nodes1[0].Data != "html" {
		fmt.Fprintf(os.Stderr, "Assertion 1 failed: expected 1 root html node, got %v\n", nodes1)
		os.Exit(1)
	}
	headNode := sample.FindFirstElement(nodes1, "head")
	bodyNode := sample.FindFirstElement(nodes1, "body")
	pNode := sample.FindFirstElement(nodes1, "p")
	if headNode == nil || bodyNode == nil || pNode == nil {
		fmt.Fprintf(os.Stderr, "Assertion 1 failed: missing head, body, or p element\n")
		os.Exit(1)
	}
	if pNode.FirstChild == nil || pNode.FirstChild.Data != "Paragraph" {
		fmt.Fprintf(os.Stderr, "Assertion 1 failed: p content mismatch\n")
		os.Exit(1)
	}

	// Assertion 2: html.ParseFragment parses child elements directly when provided an element context like body
	bodyContext := &html.Node{
		Type:     html.ElementNode,
		Data:     "body",
		DataAtom: atom.Body,
	}
	nodes2, err := sample.ParseFragmentString("<h2>Heading</h2><span>Details</span>", bodyContext)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 2 failed: parse error: %v\n", err)
		os.Exit(1)
	}
	if len(nodes2) != 2 {
		fmt.Fprintf(os.Stderr, "Assertion 2 failed: expected 2 top-level nodes, got %d\n", len(nodes2))
		os.Exit(1)
	}
	if nodes2[0].Data != "h2" || nodes2[1].Data != "span" {
		fmt.Fprintf(os.Stderr, "Assertion 2 failed: unexpected tags %q, %q\n", nodes2[0].Data, nodes2[1].Data)
		os.Exit(1)
	}
	if nodes2[0].FirstChild == nil || nodes2[0].FirstChild.Data != "Heading" ||
		nodes2[1].FirstChild == nil || nodes2[1].FirstChild.Data != "Details" {
		fmt.Fprintf(os.Stderr, "Assertion 2 failed: inner text mismatch\n")
		os.Exit(1)
	}

	// Assertion 3: html.ParseFragment wraps table rows in an implicit tbody when parsed with a table context
	tableContext := &html.Node{
		Type:     html.ElementNode,
		Data:     "table",
		DataAtom: atom.Table,
	}
	nodes3, err := sample.ParseFragmentString("<tr><td>RowItem</td></tr>", tableContext)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 3 failed: parse error: %v\n", err)
		os.Exit(1)
	}
	if len(nodes3) != 1 || nodes3[0].Data != "tbody" {
		fmt.Fprintf(os.Stderr, "Assertion 3 failed: expected implicit tbody root, got %v\n", nodes3)
		os.Exit(1)
	}
	trNode := sample.FindFirstElement(nodes3, "tr")
	tdNode := sample.FindFirstElement(nodes3, "td")
	if trNode == nil || tdNode == nil {
		fmt.Fprintf(os.Stderr, "Assertion 3 failed: expected tr and td nodes within tbody\n")
		os.Exit(1)
	}
	if tdNode.FirstChild == nil || tdNode.FirstChild.Data != "RowItem" {
		fmt.Fprintf(os.Stderr, "Assertion 3 failed: td text mismatch\n")
		os.Exit(1)
	}

	// Assertion 4: html.ParseFragment parses option elements and preserves attributes when given a select context
	selectContext := &html.Node{
		Type:     html.ElementNode,
		Data:     "select",
		DataAtom: atom.Select,
	}
	optsHTML := `<option value="first">First Choice</option><option value="second" selected>Second Choice</option>`
	nodes4, err := sample.ParseFragmentString(optsHTML, selectContext)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 4 failed: parse error: %v\n", err)
		os.Exit(1)
	}
	if len(nodes4) != 2 {
		fmt.Fprintf(os.Stderr, "Assertion 4 failed: expected 2 option nodes, got %d\n", len(nodes4))
		os.Exit(1)
	}
	val1, ok1 := sample.GetAttr(nodes4[0], "value")
	if !ok1 || val1 != "first" {
		fmt.Fprintf(os.Stderr, "Assertion 4 failed: option 1 value mismatch: %q (found: %v)\n", val1, ok1)
		os.Exit(1)
	}
	val2, ok2 := sample.GetAttr(nodes4[1], "value")
	if !ok2 || val2 != "second" {
		fmt.Fprintf(os.Stderr, "Assertion 4 failed: option 2 value mismatch: %q (found: %v)\n", val2, ok2)
		os.Exit(1)
	}
	_, hasSelected := sample.GetAttr(nodes4[1], "selected")
	if !hasSelected {
		fmt.Fprintf(os.Stderr, "Assertion 4 failed: option 2 missing selected attribute\n")
		os.Exit(1)
	}

	// Assertion 5: html.ParseFragment handles malformed fragment markup by performing HTML5 error recovery without failing
	malformedHTML := `<div><p>Unclosed paragraph<span>Unclosed span</div>`
	nodes5, err := sample.ParseFragment(strings.NewReader(malformedHTML), nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 5 failed: expected graceful parse of malformed fragment, got error: %v\n", err)
		os.Exit(1)
	}
	divNode := sample.FindFirstElement(nodes5, "div")
	if divNode == nil {
		fmt.Fprintf(os.Stderr, "Assertion 5 failed: expected div element to be recovered\n")
		os.Exit(1)
	}
	pRecovered := sample.FindFirstElement([]*html.Node{divNode}, "p")
	spanRecovered := sample.FindFirstElement([]*html.Node{divNode}, "span")
	if pRecovered == nil || spanRecovered == nil {
		fmt.Fprintf(os.Stderr, "Assertion 5 failed: expected child p and span elements to be recovered\n")
		os.Exit(1)
	}

	fmt.Println("All html.ParseFragment contract assertions passed.")
}

오리진 시더

익명