swift

package
v0.26.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: AGPL-3.0 Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package swift implements the parts of the Swift Package Registry protocol (SE-0292, https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/PackageRegistry/Registry.md) that do not depend on a server: the naming rules of scopes, names and versions, the grammar of registry paths, the Accept negotiation, Link headers, the JSON documents a registry serves and the reading of the source archive a release is published as.

Index

Constants

View Source
const (
	// MediaJSON is the media type of the JSON documents.
	MediaJSON = "application/vnd.swift.registry.v1+json"
	// MediaZip is the media type of the source archive.
	MediaZip = "application/vnd.swift.registry.v1+zip"
	// MediaSwift is the media type of the manifest.
	MediaSwift = "application/vnd.swift.registry.v1+swift"

	// ContentTypeProblem is the media type of an error body (RFC 7807).
	ContentTypeProblem = "application/problem+json"
	// ContentTypeManifest is what a manifest is served as.
	ContentTypeManifest = "text/x-swift"
	// ContentTypeZip is what a source archive is served as.
	ContentTypeZip = "application/zip"
)

Media types of the registry API; the version and the "+json", "+swift" or "+zip" suffix are what a client puts in its Accept header.

View Source
const (
	// MaxManifestBytes is the largest manifest read from a source archive.
	MaxManifestBytes = 1 << 20
	// MaxArchiveEntries is the most entries a source archive may hold.
	MaxArchiveEntries = 200_000
	// MaxManifests is the most manifests (Package.swift and the
	// version-specific ones) read from an archive.
	MaxManifests = 64
)
View Source
const (
	RelCanonical   = "canonical"
	RelAlternate   = "alternate"
	RelLatest      = "latest-version"
	RelSuccessor   = "successor-version"
	RelPredecessor = "predecessor-version"
)

The relations of the Link headers a registry sends.

View Source
const (
	// MaxMetadataBytes is the largest metadata document of a release.
	MaxMetadataBytes = 1 << 20
	// MaxRepositoryURLs is the most repository URLs a release may declare.
	MaxRepositoryURLs = 64
	// MaxURLLen is the longest URL in the metadata.
	MaxURLLen = 2048
)
View Source
const (
	// MaxScopeLen is the longest scope.
	MaxScopeLen = 39
	// MaxNameLen is the longest package name.
	MaxNameLen = 100
	// MaxVersionLen is the longest version.
	MaxVersionLen = 128
	// ContentVersion is the value of the Content-Version header: the version of
	// the registry API a response conforms to.
	ContentVersion = "1"
)
View Source
const (

	// ManifestFile is the name of the package manifest.
	ManifestFile = "Package.swift"
)
View Source
const MaxDocBytes = 32 << 20

MaxDocBytes is the largest registry JSON document a proxy accepts from an upstream.

View Source
const SourceArchive = "source-archive"

SourceArchive is the name of the resource that holds the source archive of a release.

Variables

View Source
var ErrInvalidArchive = errors.New("invalid source archive")

ErrInvalidArchive is wrapped by every error of ReadArchive; its text says what is wrong with the archive.

View Source
var ErrInvalidDoc = errors.New("invalid registry document")

ErrInvalidDoc is wrapped by every error of the Parse functions.

View Source
var ErrInvalidMetadata = errors.New("invalid package metadata")

ErrInvalidMetadata is wrapped by every error of ParseMetadata.

Functions

func CheckAccept

func CheckAccept(values []string) int

CheckAccept judges the Accept header values of a request. A request without one, or with only media types outside the registry family ("*/*", "application/json"), is processed as version 1 (http.StatusOK). Otherwise at least one range must name version 1 (a range without a version means 1): when none does, the answer is http.StatusUnsupportedMediaType if a range named a well-formed other version and http.StatusBadRequest if one was malformed.

func CheckRequest

func CheckRequest(w http.ResponseWriter, r *http.Request) bool

CheckRequest marks the response as version 1 of the registry API (Content-Version) and enforces the request's Accept header: a request for an unknown API version is answered 400 and one for a version that is not supported 415. It returns false after writing the answer.

func Compare

func Compare(a, b string) int

Compare orders two valid versions by semantic-version precedence and breaks ties (versions that differ only in build metadata) by their text, so that the order is total.

func DigestHeader

func DigestHeader(sumHex string) string

DigestHeader is the value of the Digest header of a source archive whose SHA-256 is the hexadecimal sum: "sha-256=" and the base64 of the raw digest.

func ID

func ID(scope, name string) string

ID is the package identity "scope.name" as the registry documents spell it.

func Key

func Key(scope, name string) string

Key is the case-folded identity packages are looked up by: scopes and names are case-insensitive.

func Latest

func Latest(versions []string) string

Latest picks the release a registry names with a "latest-version" link from versions, newest first: the newest one that is not a pre-release, or the newest of all when every one is. It returns "" for no versions.

func ListBody

func ListBody(versions []string, releaseURL func(version string) string) []byte

ListBody renders the release list document of a package: the versions in the order given (newest first), each with the release URL releaseURL returns for it. A nil releaseURL leaves the URLs out, which the protocol allows.

func ManifestName

func ManifestName(swiftVersion string) string

ManifestName is the file name of the manifest for a Swift version, Package.swift for "".

func NormalizeURL

func NormalizeURL(s string) string

NormalizeURL reduces a repository URL to the form two spellings of the same repository share, so "https://github.com/mona/LinkedList.git", "git@github.com:mona/LinkedList" and "ssh://git@github.com/mona/linkedlist/" all become "github.com/mona/linkedlist": no scheme, user or port, no leading "www.", no query, trailing slash or ".git", lower case. A string with no host or no path returns "".

func ParseManifestName

func ParseManifestName(name string) (string, bool)

ParseManifestName returns the Swift version in the name of a version-specific manifest; ok is false for any other name (Package.swift included).

func SortNewestFirst

func SortNewestFirst(vs []string)

SortNewestFirst sorts versions by descending precedence.

func SplitID

func SplitID(id string) (string, string, bool)

SplitID splits "scope.name". Neither part may hold a dot, so the first one is the separator.

func ToolsVersion

func ToolsVersion(src string) string

ToolsVersion returns the swift-tools-version declared on the first line of a manifest, "" when there is none.

func ValidName

func ValidName(s string) bool

ValidName reports whether s is a package name: 1 to MaxNameLen letters, digits, hyphens and underscores, starting and ending with a letter or digit, no two separators in a row.

func ValidPublishVersion

func ValidPublishVersion(v string) bool

ValidPublishVersion reports whether a release may be published as v: a valid version that does not end in ".zip" or ".json", which would make the URL of the release ambiguous with its source archive and its ".json" form.

func ValidSHA256Hex

func ValidSHA256Hex(s string) bool

ValidSHA256Hex reports whether s is 64 lower-case hexadecimal digits.

func ValidScope

func ValidScope(s string) bool

ValidScope reports whether s is a package scope: 1 to MaxScopeLen letters, digits and hyphens, starting and ending with a letter or digit, no two hyphens in a row.

func ValidVersion

func ValidVersion(v string) bool

ValidVersion reports whether v is a semantic version (three numeric parts, optional pre-release and build metadata).

func WriteProblem

func WriteProblem(w http.ResponseWriter, status int, detail string)

WriteProblem answers with an RFC 7807 problem document, the error format of the registry protocol: {"detail": ...} as application/problem+json.

Types

type Kind

type Kind int

Kind says which registry resource a path names.

const (
	// KindList is /{scope}/{name}: the releases of a package.
	KindList Kind = iota + 1
	// KindRelease is /{scope}/{name}/{version}: the metadata of a release.
	KindRelease
	// KindManifest is /{scope}/{name}/{version}/Package.swift.
	KindManifest
	// KindArchive is /{scope}/{name}/{version}.zip: the source archive.
	KindArchive
	// KindIdentifiers is /identifiers: the lookup by repository URL.
	KindIdentifiers
	// KindLogin is /login.
	KindLogin
)

The resources of the registry protocol.

type Link struct {
	URL    string
	Rel    string
	Params map[string]string
}

Link is one link of a Link header (RFC 8288): a target, its relation and the other parameters ("filename", "swift-tools-version").

func ParseLinks(values []string) []Link

ParseLinks parses Link header values. It is tolerant: a link it cannot read is skipped, and a parameter name is lower-cased. Only the first "rel" of a link counts.

func (Link) String

func (l Link) String() string

String renders the link as a Link header value, parameters in name order.

type Manifest

type Manifest struct {
	// Filename is Package.swift or Package@swift-<version>.swift.
	Filename string `json:"filename"`
	// SwiftVersion is the version in the file name, "" for Package.swift.
	SwiftVersion string `json:"swiftVersion,omitempty"` //nolint:tagliatelle // same names as the registry documents
	// ToolsVersion is the swift-tools-version the manifest declares, "" when it
	// declares none.
	ToolsVersion string `json:"toolsVersion,omitempty"` //nolint:tagliatelle // same names as the registry documents
	// Content is the manifest source.
	Content string `json:"content"`
}

Manifest is a manifest of a release.

func ReadArchive

func ReadArchive(ra io.ReaderAt, size int64) ([]Manifest, error)

ReadArchive reads the manifests of a source archive: the Package.swift at its root or in the one top-level directory every entry sits in (as "swift package archive-source" writes it), and the Package@swift-*.swift next to it. Package.swift is the first manifest. It reads nothing else of the archive. An archive that is not a zip, has an entry that escapes the archive, has no manifest, or whose manifest is too large or not UTF-8 text is an ErrInvalidArchive.

type Metadata

type Metadata struct {
	Description             string   `json:"description"`
	LicenseURL              string   `json:"licenseURL"`              //nolint:tagliatelle // package-metadata.json is camelCase (SE-0391)
	OriginalPublicationTime string   `json:"originalPublicationTime"` //nolint:tagliatelle // package-metadata.json is camelCase (SE-0391)
	ReadmeURL               string   `json:"readmeURL"`               //nolint:tagliatelle // package-metadata.json is camelCase (SE-0391)
	RepositoryURLs          []string `json:"repositoryURLs"`          //nolint:tagliatelle // package-metadata.json is camelCase (SE-0391)
}

Metadata is the metadata a release is published with (the "metadata" part of the publish request). The server keeps the document verbatim; these are the fields it reads.

func ParseMetadata

func ParseMetadata(data []byte) (json.RawMessage, Metadata, error)

ParseMetadata validates the metadata document of a release and returns its compact form with the fields read from it. The document must be a JSON object; licenseURL and readmeURL must be absolute http(s) URLs, originalPublicationTime an RFC 3339 time and repositoryURLs a bounded list of non-empty strings. Other fields are kept as sent.

type Path

type Path struct {
	Kind    Kind
	Scope   string
	Name    string
	Version string
}

Path is a parsed registry path.

func ParsePath

func ParsePath(rel string) (Path, bool)

ParsePath classifies a registry path relative to the repository root, with or without a leading slash and with percent-escapes already decoded. The ".json" extension of the list and release resources is dropped. A path that is not one of the resources, or whose scope, name or version is invalid, is not ok.

type Problem

type Problem struct {
	Status int    `json:"status,omitempty"`
	Title  string `json:"title,omitempty"`
	Detail string `json:"detail"`
}

Problem is the RFC 7807 problem details object of a registry response.

type Release

type Release struct {
	ID          string          `json:"id"`
	Version     string          `json:"version"`
	Resources   []Resource      `json:"resources"`
	Metadata    json.RawMessage `json:"metadata,omitempty"`
	PublishedAt string          `json:"publishedAt,omitempty"` //nolint:tagliatelle // Swift Package Registry and stored-document wire format
}

Release is the document of GET /{scope}/{name}/{version}. Metadata is the metadata JSON object the release was published with, verbatim.

func ParseRelease

func ParseRelease(data []byte, id, version string) (Release, error)

ParseRelease reads the release document an upstream sent and checks it describes release id at version: the identity and version match (identities compare case-insensitively) and the source archive has a SHA-256 checksum.

func (Release) Checksum

func (r Release) Checksum() string

Checksum is the lower-case hexadecimal SHA-256 of the source archive, "" when the document has no source-archive resource.

type ReleaseEntry

type ReleaseEntry struct {
	URL     string   `json:"url,omitempty"`
	Problem *Problem `json:"problem,omitempty"`
}

ReleaseEntry is one release of a package in the list document. URL is optional: a client builds it from the version when it is absent.

type ReleaseList

type ReleaseList struct {
	Releases map[string]ReleaseEntry `json:"releases"`
}

ReleaseList is the document of GET /{scope}/{name}.

func ParseReleaseList

func ParseReleaseList(data []byte) (ReleaseList, error)

ParseReleaseList reads the release list an upstream registry sent. Releases under an invalid version are dropped; a document that is not a JSON object with a "releases" object is an error.

func (ReleaseList) Versions

func (l ReleaseList) Versions() []string

Versions returns the versions of the list, newest first (highest precedence first, the order the specification asks for).

type Resource

type Resource struct {
	Name     string   `json:"name"`
	Type     string   `json:"type"`
	Checksum string   `json:"checksum"`
	Signing  *Signing `json:"signing,omitempty"`
}

Resource is one downloadable resource of a release.

type Signing

type Signing struct {
	SignatureBase64Encoded string `json:"signatureBase64Encoded"` //nolint:tagliatelle // Swift Package Registry and stored-document wire format
	SignatureFormat        string `json:"signatureFormat"`        //nolint:tagliatelle // Swift Package Registry and stored-document wire format
}

Signing is the signature of a resource.

type Target

type Target struct {
	Version      string
	Manifest     bool
	SwiftVersion string
}

Target is what a link of a registry response points at within a package: the release Version or, with Manifest, its Package.swift (SwiftVersion names the version-specific manifest, "" the plain one).

func ParseTarget

func ParseTarget(rawURL, scope, name string) (Target, bool)

ParseTarget reads a link target of package scope/name as another registry wrote it: any absolute or relative URL whose path ends with "/{scope}/{name}/{version}" or "/{scope}/{name}/{version}/Package.swift". The URL's own prefix is not looked at, so links of a registry mounted anywhere are understood; scope and name compare case-insensitively. ok is false for every other URL.

Directories

Path Synopsis
Package swifttest builds Swift package source archives for tests.
Package swifttest builds Swift package source archives for tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL