mirror of
https://github.com/clearlinux/rkt.git
synced 2026-11-25 13:34:53 +00:00
*: vendor appc spec
Take two at getting the spec vendored into Rocket with Godep. Since actool is used during the construction of the stage1.aci, it really needs to be vendored too to prevent any unexpected divergence between whatever version the user happens to have in their PATH. Thus, we introduce a silly dummy package (stage1/dummy.go) to coerce Godep into vendoring actool. This also requires a slight rearrangement of the appc repo, moving some functionality from actool itself into the aci package.
This commit is contained in:
Generated
+29
@@ -10,6 +10,31 @@
|
||||
"Comment": "null-12",
|
||||
"Rev": "7dda39b2e7d5e265014674c5af696ba4186679e9"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/appc/spec/aci",
|
||||
"Comment": "v0.2.0-44-g2fee340e9314",
|
||||
"Rev": "2fee340e9314b9f0f53cbf0e929d158a09930a5f"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/appc/spec/actool",
|
||||
"Comment": "v0.2.0-44-g2fee340e9314",
|
||||
"Rev": "2fee340e9314b9f0f53cbf0e929d158a09930a5f"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/appc/spec/discovery",
|
||||
"Comment": "v0.2.0-44-g2fee340e9314",
|
||||
"Rev": "2fee340e9314b9f0f53cbf0e929d158a09930a5f"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/appc/spec/pkg/tarheader",
|
||||
"Comment": "v0.2.0-44-g2fee340e9314",
|
||||
"Rev": "2fee340e9314b9f0f53cbf0e929d158a09930a5f"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/appc/spec/schema",
|
||||
"Comment": "v0.2.0-44-g2fee340e9314",
|
||||
"Rev": "2fee340e9314b9f0f53cbf0e929d158a09930a5f"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/coreos/go-semver/semver",
|
||||
"Rev": "6fe83ccda8fb9b7549c9ab4ba47f47858bc950aa"
|
||||
@@ -50,6 +75,10 @@
|
||||
{
|
||||
"ImportPath": "golang.org/x/crypto/openpgp",
|
||||
"Rev": "a7ead6ddf06233883deca151dffaef2effbf498f"
|
||||
},
|
||||
{
|
||||
"ImportPath": "golang.org/x/net/html",
|
||||
"Rev": "1dfe7915deaf3f80b962c163b918868d8a6d8974"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package aci
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/pkg/tarheader"
|
||||
)
|
||||
|
||||
// BuildWalker creates a filepath.WalkFunc that walks over the given root
|
||||
// (which should represent an ACI layout on disk) and adds the files in the
|
||||
// rootfs/ subdirectory to the given ArchiveWriter
|
||||
func BuildWalker(root string, aw ArchiveWriter) filepath.WalkFunc {
|
||||
// cache of inode -> filepath, used to leverage hard links in the archive
|
||||
inos := map[uint64]string{}
|
||||
return func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
relpath, err := filepath.Rel(root, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if relpath == "." {
|
||||
return nil
|
||||
}
|
||||
if relpath == ManifestFile {
|
||||
// ignore; this will be written by the archive writer
|
||||
// TODO(jonboulle): does this make sense? maybe just remove from archivewriter?
|
||||
return nil
|
||||
}
|
||||
|
||||
link := ""
|
||||
var r io.Reader
|
||||
switch info.Mode() & os.ModeType {
|
||||
case os.ModeCharDevice:
|
||||
case os.ModeDevice:
|
||||
case os.ModeDir:
|
||||
case os.ModeSymlink:
|
||||
target, err := os.Readlink(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
link = target
|
||||
default:
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
r = file
|
||||
}
|
||||
|
||||
hdr, err := tar.FileInfoHeader(info, link)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// Because os.FileInfo's Name method returns only the base
|
||||
// name of the file it describes, it may be necessary to
|
||||
// modify the Name field of the returned header to provide the
|
||||
// full path name of the file.
|
||||
hdr.Name = relpath
|
||||
tarheader.Populate(hdr, info, inos)
|
||||
// If the file is a hard link to a file we've already seen, we
|
||||
// don't need the contents
|
||||
if hdr.Typeflag == tar.TypeLink {
|
||||
hdr.Size = 0
|
||||
r = nil
|
||||
}
|
||||
if err := aw.AddFile(hdr, r); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
// Package aci contains various functions for working with App Container Images.
|
||||
package aci
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
package aci
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/bzip2"
|
||||
"compress/gzip"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
|
||||
)
|
||||
|
||||
type FileType string
|
||||
|
||||
const (
|
||||
TypeGzip = FileType("gz")
|
||||
TypeBzip2 = FileType("bz2")
|
||||
TypeXz = FileType("xz")
|
||||
TypeTar = FileType("tar")
|
||||
TypeText = FileType("text")
|
||||
TypeUnknown = FileType("unknown")
|
||||
|
||||
readLen = 512 // max bytes to sniff
|
||||
|
||||
hexHdrGzip = "1f8b"
|
||||
hexHdrBzip2 = "425a68"
|
||||
hexHdrXz = "fd377a585a00"
|
||||
hexSigTar = "7573746172"
|
||||
|
||||
tarOffset = 257
|
||||
|
||||
textMime = "text/plain; charset=utf-8"
|
||||
)
|
||||
|
||||
var (
|
||||
hdrGzip []byte
|
||||
hdrBzip2 []byte
|
||||
hdrXz []byte
|
||||
sigTar []byte
|
||||
tarEnd int
|
||||
)
|
||||
|
||||
func mustDecodeHex(s string) []byte {
|
||||
b, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func init() {
|
||||
hdrGzip = mustDecodeHex(hexHdrGzip)
|
||||
hdrBzip2 = mustDecodeHex(hexHdrBzip2)
|
||||
hdrXz = mustDecodeHex(hexHdrXz)
|
||||
sigTar = mustDecodeHex(hexSigTar)
|
||||
tarEnd = tarOffset + len(sigTar)
|
||||
}
|
||||
|
||||
// DetectFileType attempts to detect the type of file that the given reader
|
||||
// represents by comparing it against known file signatures (magic numbers)
|
||||
func DetectFileType(r io.Reader) (FileType, error) {
|
||||
var b bytes.Buffer
|
||||
n, err := io.CopyN(&b, r, readLen)
|
||||
if err != nil && err != io.EOF {
|
||||
return TypeUnknown, err
|
||||
}
|
||||
bs := b.Bytes()
|
||||
switch {
|
||||
case bytes.HasPrefix(bs, hdrGzip):
|
||||
return TypeGzip, nil
|
||||
case bytes.HasPrefix(bs, hdrBzip2):
|
||||
return TypeBzip2, nil
|
||||
case bytes.HasPrefix(bs, hdrXz):
|
||||
return TypeXz, nil
|
||||
case n > int64(tarEnd) && bytes.Equal(bs[tarOffset:tarEnd], sigTar):
|
||||
return TypeTar, nil
|
||||
case http.DetectContentType(bs) == textMime:
|
||||
return TypeText, nil
|
||||
default:
|
||||
return TypeUnknown, nil
|
||||
}
|
||||
}
|
||||
|
||||
// XzReader shells out to a command line xz executable (if
|
||||
// available) to decompress the given io.Reader using the xz
|
||||
// compression format
|
||||
func XzReader(r io.Reader) io.ReadCloser {
|
||||
rpipe, wpipe := io.Pipe()
|
||||
ex, err := exec.LookPath("xz")
|
||||
if err != nil {
|
||||
log.Fatalf("couldn't find xz executable: %v", err)
|
||||
}
|
||||
cmd := exec.Command(ex, "--decompress", "--stdout")
|
||||
cmd.Stdin = r
|
||||
cmd.Stdout = wpipe
|
||||
|
||||
go func() {
|
||||
err := cmd.Run()
|
||||
wpipe.CloseWithError(err)
|
||||
}()
|
||||
|
||||
return rpipe
|
||||
}
|
||||
|
||||
// ManifestFromImage extracts a new schema.ImageManifest from the given ACI image.
|
||||
func ManifestFromImage(rs io.ReadSeeker) (*schema.ImageManifest, error) {
|
||||
var im schema.ImageManifest
|
||||
manifestFound := false
|
||||
|
||||
tr, err := NewCompressedTarReader(rs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for {
|
||||
hdr, err := tr.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if hdr.Name == "manifest" {
|
||||
data, err := ioutil.ReadAll(tr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := im.UnmarshalJSON(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
manifestFound = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !manifestFound {
|
||||
return nil, errors.New("error: missing manifest")
|
||||
}
|
||||
return &im, nil
|
||||
}
|
||||
|
||||
// NewCompressedTarReader creates a new tar.Reader reading from the given ACI image.
|
||||
func NewCompressedTarReader(rs io.ReadSeeker) (*tar.Reader, error) {
|
||||
cr, err := NewCompressedReader(rs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tar.NewReader(cr), nil
|
||||
}
|
||||
|
||||
// NewCompressedReader creates a new io.Reader from the given ACI image.
|
||||
func NewCompressedReader(rs io.ReadSeeker) (io.Reader, error) {
|
||||
|
||||
var (
|
||||
dr io.Reader
|
||||
err error
|
||||
)
|
||||
|
||||
_, err = rs.Seek(0, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ftype, err := DetectFileType(rs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = rs.Seek(0, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch ftype {
|
||||
case TypeGzip:
|
||||
dr, err = gzip.NewReader(rs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case TypeBzip2:
|
||||
dr = bzip2.NewReader(rs)
|
||||
case TypeXz:
|
||||
dr = XzReader(rs)
|
||||
case TypeTar:
|
||||
dr = rs
|
||||
case TypeUnknown:
|
||||
return nil, errors.New("error: unknown image filetype")
|
||||
default:
|
||||
return nil, errors.New("no type returned from DetectFileType?")
|
||||
}
|
||||
return dr, nil
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package aci
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newTestACI() (*os.File, error) {
|
||||
tf, err := ioutil.TempFile("", "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
manifestBody := `{"acKind":"ImageManifest","acVersion":"0.2.0","name":"example.com/app"}`
|
||||
|
||||
gw := gzip.NewWriter(tf)
|
||||
tw := tar.NewWriter(gw)
|
||||
|
||||
hdr := &tar.Header{
|
||||
Name: "manifest",
|
||||
Size: int64(len(manifestBody)),
|
||||
}
|
||||
if err := tw.WriteHeader(hdr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := tw.Write([]byte(manifestBody)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := gw.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tf, nil
|
||||
}
|
||||
|
||||
func newEmptyTestACI() (*os.File, error) {
|
||||
tf, err := ioutil.TempFile("", "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gw := gzip.NewWriter(tf)
|
||||
tw := tar.NewWriter(gw)
|
||||
if err := tw.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := gw.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tf, nil
|
||||
}
|
||||
|
||||
func TestManifestFromImage(t *testing.T) {
|
||||
img, err := newTestACI()
|
||||
if err != nil {
|
||||
t.Fatalf("newTestACI: unexpected error %v", err)
|
||||
}
|
||||
defer img.Close()
|
||||
defer os.Remove(img.Name())
|
||||
|
||||
im, err := ManifestFromImage(img)
|
||||
if err != nil {
|
||||
t.Fatalf("ManifestFromImage: unexpected error %v", err)
|
||||
}
|
||||
if im.Name.String() != "example.com/app" {
|
||||
t.Errorf("expected %s, got %s", "example.com/app", im.Name.String())
|
||||
}
|
||||
|
||||
emptyImg, err := newEmptyTestACI()
|
||||
if err != nil {
|
||||
t.Fatalf("newEmptyTestACI: unexpected error %v", err)
|
||||
}
|
||||
defer emptyImg.Close()
|
||||
defer os.Remove(emptyImg.Name())
|
||||
|
||||
im, err = ManifestFromImage(emptyImg)
|
||||
if err == nil {
|
||||
t.Fatalf("ManifestFromImage: expected error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCompressedTarReader(t *testing.T) {
|
||||
img, err := newTestACI()
|
||||
if err != nil {
|
||||
t.Fatalf("newTestACI: unexpected error %v", err)
|
||||
}
|
||||
defer img.Close()
|
||||
defer os.Remove(img.Name())
|
||||
|
||||
cr, err := NewCompressedTarReader(img)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCompressedTarReader: unexpected error %v", err)
|
||||
}
|
||||
|
||||
ftype, err := DetectFileType(cr)
|
||||
if err != nil {
|
||||
t.Fatalf("DetectFileType: unexpected error %v", err)
|
||||
}
|
||||
|
||||
if ftype != TypeText {
|
||||
t.Errorf("expected %v, got %v", TypeText, ftype)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCompressedReader(t *testing.T) {
|
||||
img, err := newTestACI()
|
||||
if err != nil {
|
||||
t.Fatalf("newTestACI: unexpected error %v", err)
|
||||
}
|
||||
defer img.Close()
|
||||
defer os.Remove(img.Name())
|
||||
|
||||
cr, err := NewCompressedReader(img)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCompressedReader: unexpected error %v", err)
|
||||
}
|
||||
|
||||
ftype, err := DetectFileType(cr)
|
||||
if err != nil {
|
||||
t.Fatalf("DetectFileType: unexpected error %v", err)
|
||||
}
|
||||
|
||||
if ftype != TypeTar {
|
||||
t.Errorf("expected %v, got %v", TypeTar, ftype)
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package aci
|
||||
|
||||
/*
|
||||
|
||||
Image Layout
|
||||
|
||||
The on-disk layout of an app container is straightforward.
|
||||
It includes a rootfs with all of the files that will exist in the root of the app and a manifest describing the image.
|
||||
The layout MUST contain an image manifest.
|
||||
|
||||
/manifest
|
||||
/rootfs/
|
||||
/rootfs/usr/bin/mysql
|
||||
|
||||
*/
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
|
||||
)
|
||||
|
||||
const (
|
||||
// Path to manifest file inside the layout
|
||||
ManifestFile = "manifest"
|
||||
// Path to rootfs directory inside the layout
|
||||
RootfsDir = "rootfs"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNoRootFS = errors.New("no rootfs found in layout")
|
||||
ErrNoManifest = errors.New("no image manifest found in layout")
|
||||
)
|
||||
|
||||
// ValidateLayout takes a directory and validates that the layout of the directory
|
||||
// matches that expected by the Application Container Image format.
|
||||
// If any errors are encountered during the validation, it will abort and
|
||||
// return the first one.
|
||||
func ValidateLayout(dir string) error {
|
||||
fi, err := os.Stat(dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error accessing layout: %v", err)
|
||||
}
|
||||
if !fi.IsDir() {
|
||||
return fmt.Errorf("given path %q is not a directory", dir)
|
||||
}
|
||||
var flist []string
|
||||
var imOK, rfsOK bool
|
||||
var im io.Reader
|
||||
walkLayout := func(fpath string, fi os.FileInfo, err error) error {
|
||||
rpath, err := filepath.Rel(dir, fpath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := filepath.Base(rpath)
|
||||
switch name {
|
||||
case ".":
|
||||
case ManifestFile:
|
||||
im, err = os.Open(fpath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
imOK = true
|
||||
case RootfsDir:
|
||||
if !fi.IsDir() {
|
||||
return errors.New("rootfs is not a directory")
|
||||
}
|
||||
rfsOK = true
|
||||
default:
|
||||
flist = append(flist, rpath)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := filepath.Walk(dir, walkLayout); err != nil {
|
||||
return err
|
||||
}
|
||||
return validate(imOK, im, rfsOK, flist)
|
||||
}
|
||||
|
||||
// ValidateLayout takes a *tar.Reader and validates that the layout of the
|
||||
// filesystem the reader encapsulates matches that expected by the
|
||||
// Application Container Image format. If any errors are encountered during
|
||||
// the validation, it will abort and return the first one.
|
||||
func ValidateArchive(tr *tar.Reader) error {
|
||||
var flist []string
|
||||
var imOK, rfsOK bool
|
||||
var im bytes.Buffer
|
||||
Tar:
|
||||
for {
|
||||
hdr, err := tr.Next()
|
||||
switch {
|
||||
case err == nil:
|
||||
case err == io.EOF:
|
||||
break Tar
|
||||
default:
|
||||
return err
|
||||
}
|
||||
name := filepath.Clean(hdr.Name)
|
||||
switch name {
|
||||
case ".":
|
||||
case ManifestFile:
|
||||
_, err := io.Copy(&im, tr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
imOK = true
|
||||
case RootfsDir:
|
||||
if !hdr.FileInfo().IsDir() {
|
||||
return fmt.Errorf("rootfs is not a directory")
|
||||
}
|
||||
rfsOK = true
|
||||
default:
|
||||
flist = append(flist, name)
|
||||
}
|
||||
}
|
||||
return validate(imOK, &im, rfsOK, flist)
|
||||
}
|
||||
|
||||
func validate(imOK bool, im io.Reader, rfsOK bool, files []string) error {
|
||||
defer func() {
|
||||
if rc, ok := im.(io.Closer); ok {
|
||||
rc.Close()
|
||||
}
|
||||
}()
|
||||
if !imOK {
|
||||
return ErrNoManifest
|
||||
}
|
||||
if !rfsOK {
|
||||
return ErrNoRootFS
|
||||
}
|
||||
b, err := ioutil.ReadAll(im)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error reading image manifest: %v", err)
|
||||
}
|
||||
var a schema.ImageManifest
|
||||
if err := a.UnmarshalJSON(b); err != nil {
|
||||
return fmt.Errorf("image manifest validation failed: %v", err)
|
||||
}
|
||||
for _, f := range files {
|
||||
if !strings.HasPrefix(f, "rootfs") {
|
||||
return fmt.Errorf("unrecognized file path in layout: %q", f)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package aci
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
|
||||
)
|
||||
|
||||
// ArchiveWriter writes App Container Images. Users wanting to create an ACI or
|
||||
// should create an ArchiveWriter and add files to it; the ACI will be written
|
||||
// to the underlying tar.Writer
|
||||
type ArchiveWriter interface {
|
||||
AddFile(hdr *tar.Header, r io.Reader) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
type imageArchiveWriter struct {
|
||||
*tar.Writer
|
||||
am *schema.ImageManifest
|
||||
}
|
||||
|
||||
// NewImageWriter creates a new ArchiveWriter which will generate an App
|
||||
// Container Image based on the given manifest and write it to the given
|
||||
// tar.Writer
|
||||
func NewImageWriter(am schema.ImageManifest, w *tar.Writer) ArchiveWriter {
|
||||
aw := &imageArchiveWriter{
|
||||
w,
|
||||
&am,
|
||||
}
|
||||
return aw
|
||||
}
|
||||
|
||||
func (aw *imageArchiveWriter) AddFile(hdr *tar.Header, r io.Reader) error {
|
||||
err := aw.Writer.WriteHeader(hdr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
_, err := io.Copy(aw.Writer, r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (aw *imageArchiveWriter) addFileNow(path string, contents []byte) error {
|
||||
buf := bytes.NewBuffer(contents)
|
||||
now := time.Now()
|
||||
hdr := tar.Header{
|
||||
Name: path,
|
||||
Mode: 0644,
|
||||
Uid: 0,
|
||||
Gid: 0,
|
||||
Size: int64(buf.Len()),
|
||||
ModTime: now,
|
||||
Typeflag: tar.TypeReg,
|
||||
Uname: "root",
|
||||
Gname: "root",
|
||||
ChangeTime: now,
|
||||
}
|
||||
return aw.AddFile(&hdr, buf)
|
||||
}
|
||||
|
||||
func (aw *imageArchiveWriter) addManifest(name string, m json.Marshaler) error {
|
||||
out, err := m.MarshalJSON()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return aw.addFileNow(name, out)
|
||||
}
|
||||
|
||||
func (aw *imageArchiveWriter) Close() error {
|
||||
if err := aw.addManifest(ManifestFile, aw.am); err != nil {
|
||||
return err
|
||||
}
|
||||
return aw.Writer.Close()
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
)
|
||||
|
||||
const (
|
||||
cliName = "actool"
|
||||
cliDescription = "actool, the application container tool"
|
||||
)
|
||||
|
||||
var (
|
||||
globalFlagset = flag.NewFlagSet(cliName, flag.ExitOnError)
|
||||
out *tabwriter.Writer
|
||||
commands []*Command
|
||||
globalFlags = struct {
|
||||
Dir string
|
||||
Debug bool
|
||||
Help bool
|
||||
}{}
|
||||
transportFlags = struct {
|
||||
Insecure bool
|
||||
}{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
globalFlagset.BoolVar(&globalFlags.Help, "help", false, "Print usage information and exit")
|
||||
globalFlagset.BoolVar(&globalFlags.Debug, "debug", false, "Print verbose (debug) output")
|
||||
}
|
||||
|
||||
type Command struct {
|
||||
Name string // Name of the Command and the string to use to invoke it
|
||||
Summary string // One-sentence summary of what the Command does
|
||||
Usage string // Usage options/arguments
|
||||
Description string // Detailed description of command
|
||||
Flags flag.FlagSet // Set of flags associated with this command
|
||||
|
||||
Run func(args []string) int // Run a command with the given arguments, return exit status
|
||||
}
|
||||
|
||||
func init() {
|
||||
out = new(tabwriter.Writer)
|
||||
out.Init(os.Stdout, 0, 8, 1, '\t', 0)
|
||||
commands = []*Command{
|
||||
cmdBuild,
|
||||
cmdDiscover,
|
||||
cmdHelp,
|
||||
cmdValidate,
|
||||
cmdVersion,
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// parse global arguments
|
||||
globalFlagset.Parse(os.Args[1:])
|
||||
args := globalFlagset.Args()
|
||||
if len(args) < 1 || globalFlags.Help {
|
||||
args = []string{"help"}
|
||||
}
|
||||
|
||||
var cmd *Command
|
||||
|
||||
// determine which Command should be run
|
||||
for _, c := range commands {
|
||||
if c.Name == args[0] {
|
||||
cmd = c
|
||||
if err := c.Flags.Parse(args[1:]); err != nil {
|
||||
stderr("%v", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if cmd == nil {
|
||||
stderr("%v: unknown subcommand: %q", cliName, args[0])
|
||||
stderr("Run '%v help' for usage.", cliName)
|
||||
os.Exit(2)
|
||||
}
|
||||
os.Exit(cmd.Run(cmd.Flags.Args()))
|
||||
}
|
||||
|
||||
func getAllFlags() (flags []*flag.Flag) {
|
||||
return getFlags(globalFlagset)
|
||||
}
|
||||
|
||||
func getFlags(flagset *flag.FlagSet) (flags []*flag.Flag) {
|
||||
flags = make([]*flag.Flag, 0)
|
||||
flagset.VisitAll(func(f *flag.Flag) {
|
||||
flags = append(flags, f)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func stderr(format string, a ...interface{}) {
|
||||
out := fmt.Sprintf(format, a...)
|
||||
fmt.Fprintln(os.Stderr, strings.TrimSuffix(out, "\n"))
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/aci"
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
|
||||
)
|
||||
|
||||
var (
|
||||
buildNocompress bool
|
||||
buildOverwrite bool
|
||||
cmdBuild = &Command{
|
||||
Name: "build",
|
||||
Description: `Build an ACI from a given directory. The directory should
|
||||
contain an Image Layout. The Image Layout will be validated
|
||||
before the ACI is created. The produced ACI will be
|
||||
gzip-compressed by default.`,
|
||||
Summary: "Build an ACI from an Image Layout (experimental)",
|
||||
Usage: `[--overwrite] [--no-compression] DIRECTORY OUTPUT_FILE`,
|
||||
Run: runBuild,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
cmdBuild.Flags.BoolVar(&buildOverwrite, "overwrite", false, "Overwrite target file if it already exists")
|
||||
cmdBuild.Flags.BoolVar(&buildNocompress, "no-compression", false, "Do not gzip-compress the produced ACI")
|
||||
}
|
||||
|
||||
func runBuild(args []string) (exit int) {
|
||||
if len(args) != 2 {
|
||||
stderr("build: Must provide directory and output file")
|
||||
return 1
|
||||
}
|
||||
|
||||
root := args[0]
|
||||
tgt := args[1]
|
||||
ext := filepath.Ext(tgt)
|
||||
if ext != schema.ACIExtension {
|
||||
stderr("build: Extension must be %s (given %s)", schema.ACIExtension, ext)
|
||||
return 1
|
||||
}
|
||||
|
||||
mode := os.O_CREATE | os.O_WRONLY
|
||||
if buildOverwrite {
|
||||
mode |= os.O_TRUNC
|
||||
} else {
|
||||
mode |= os.O_EXCL
|
||||
}
|
||||
fh, err := os.OpenFile(tgt, mode, 0644)
|
||||
if err != nil {
|
||||
if os.IsExist(err) {
|
||||
stderr("build: Target file exists (try --overwrite)")
|
||||
} else {
|
||||
stderr("build: Unable to open target %s: %v", tgt, err)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
var gw *gzip.Writer
|
||||
var r io.WriteCloser = fh
|
||||
if !buildNocompress {
|
||||
gw = gzip.NewWriter(fh)
|
||||
r = gw
|
||||
}
|
||||
tr := tar.NewWriter(r)
|
||||
|
||||
defer func() {
|
||||
tr.Close()
|
||||
if !buildNocompress {
|
||||
gw.Close()
|
||||
}
|
||||
fh.Close()
|
||||
if exit != 0 && !buildOverwrite {
|
||||
os.Remove(tgt)
|
||||
}
|
||||
}()
|
||||
|
||||
// TODO(jonboulle): stream the validation so we don't have to walk the rootfs twice
|
||||
if err := aci.ValidateLayout(root); err != nil {
|
||||
stderr("build: Layout failed validation: %v", err)
|
||||
return 1
|
||||
}
|
||||
mpath := filepath.Join(root, aci.ManifestFile)
|
||||
b, err := ioutil.ReadFile(mpath)
|
||||
if err != nil {
|
||||
stderr("build: Unable to read Image Manifest: %v", err)
|
||||
return 1
|
||||
}
|
||||
var im schema.ImageManifest
|
||||
if err := im.UnmarshalJSON(b); err != nil {
|
||||
stderr("build: Unable to load Image Manifest: %v", err)
|
||||
return 1
|
||||
}
|
||||
iw := aci.NewImageWriter(im, tr)
|
||||
|
||||
err = filepath.Walk(root, aci.BuildWalker(root, iw))
|
||||
if err != nil {
|
||||
stderr("build: Error walking rootfs: %v", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
err = iw.Close()
|
||||
if err != nil {
|
||||
stderr("build: Unable to close image %s: %v", tgt, err)
|
||||
return 1
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/discovery"
|
||||
)
|
||||
|
||||
var (
|
||||
cmdDiscover = &Command{
|
||||
Name: "discover",
|
||||
Description: "Discover the download URLs for an app",
|
||||
Summary: "Discover the download URLs for one or more app container images",
|
||||
Usage: "APP...",
|
||||
Run: runDiscover,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
cmdDiscover.Flags.BoolVar(&transportFlags.Insecure, "insecure", false,
|
||||
"Allow insecure non-TLS downloads over http")
|
||||
}
|
||||
|
||||
func runDiscover(args []string) (exit int) {
|
||||
if len(args) < 1 {
|
||||
stderr("discover: at least one name required")
|
||||
}
|
||||
|
||||
for _, name := range args {
|
||||
app, err := discovery.NewAppFromString(name)
|
||||
if err != nil {
|
||||
stderr("%s: %s", name, err)
|
||||
return 1
|
||||
}
|
||||
eps, err := discovery.DiscoverEndpoints(*app, transportFlags.Insecure)
|
||||
if err != nil {
|
||||
stderr("error fetching %s: %s", name, err)
|
||||
return 1
|
||||
}
|
||||
for _, aciEndpoint := range eps.ACIEndpoints {
|
||||
fmt.Println("ACI: %s, Sig: %s\n", aciEndpoint.ACI, aciEndpoint.Sig)
|
||||
}
|
||||
if len(eps.Keys) > 0 {
|
||||
fmt.Println("Keys: " + strings.Join(eps.Keys, ","))
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
// Package main contains a tool for building and validating images and
|
||||
// manifests that meet the App Container specifications.
|
||||
package main
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
|
||||
)
|
||||
|
||||
var (
|
||||
cmdHelp = &Command{
|
||||
Name: "help",
|
||||
Summary: "Show a list of commands or help for one command",
|
||||
Usage: "[COMMAND]",
|
||||
Description: "Show a list of commands or detailed help for one command",
|
||||
Run: runHelp,
|
||||
}
|
||||
|
||||
globalUsageTemplate *template.Template
|
||||
commandUsageTemplate *template.Template
|
||||
templFuncs = template.FuncMap{
|
||||
"descToLines": func(s string) []string {
|
||||
// trim leading/trailing whitespace and split into slice of lines
|
||||
return strings.Split(strings.Trim(s, "\n\t "), "\n")
|
||||
},
|
||||
"printOption": func(name, defvalue, usage string) string {
|
||||
prefix := "--"
|
||||
if len(name) == 1 {
|
||||
prefix = "-"
|
||||
}
|
||||
return fmt.Sprintf("\t%s%s=%s\t%s", prefix, name, defvalue, usage)
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
globalUsageTemplate = template.Must(template.New("global_usage").Funcs(templFuncs).Parse(`
|
||||
NAME:
|
||||
{{printf "\t%s - %s" .Executable .Description}}
|
||||
|
||||
USAGE:
|
||||
{{printf "\t%s" .Executable}} [global options] <command> [command options] [arguments...]
|
||||
|
||||
VERSION:
|
||||
{{printf "\t%s" .Version}}
|
||||
|
||||
COMMANDS:{{range .Commands}}
|
||||
{{printf "\t%s\t%s" .Name .Summary}}{{end}}
|
||||
|
||||
GLOBAL OPTIONS:{{range .Flags}}
|
||||
{{printOption .Name .DefValue .Usage}}{{end}}
|
||||
|
||||
Run "{{.Executable}} help <command>" for more details on a specific command.
|
||||
`[1:]))
|
||||
commandUsageTemplate = template.Must(template.New("command_usage").Funcs(templFuncs).Parse(`
|
||||
NAME:
|
||||
{{printf "\t%s - %s" .Cmd.Name .Cmd.Summary}}
|
||||
|
||||
USAGE:
|
||||
{{printf "\t%s %s %s" .Executable .Cmd.Name .Cmd.Usage}}
|
||||
|
||||
DESCRIPTION:
|
||||
{{range $line := descToLines .Cmd.Description}}{{printf "\t%s" $line}}
|
||||
{{end}}
|
||||
{{if .CmdFlags}}OPTIONS:{{range .CmdFlags}}
|
||||
{{printOption .Name .DefValue .Usage}}{{end}}
|
||||
|
||||
{{end}}For help on global options run "{{.Executable}} help"
|
||||
`[1:]))
|
||||
}
|
||||
|
||||
func runHelp(args []string) (exit int) {
|
||||
if len(args) < 1 {
|
||||
printGlobalUsage()
|
||||
return
|
||||
}
|
||||
|
||||
var cmd *Command
|
||||
|
||||
for _, c := range commands {
|
||||
if c.Name == args[0] {
|
||||
cmd = c
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if cmd == nil {
|
||||
stderr("Unrecognized command: %s", args[0])
|
||||
return 1
|
||||
}
|
||||
|
||||
printCommandUsage(cmd)
|
||||
return
|
||||
}
|
||||
|
||||
func printGlobalUsage() {
|
||||
globalUsageTemplate.Execute(out, struct {
|
||||
Executable string
|
||||
Commands []*Command
|
||||
Flags []*flag.Flag
|
||||
Description string
|
||||
Version string
|
||||
}{
|
||||
cliName,
|
||||
commands,
|
||||
getAllFlags(),
|
||||
cliDescription,
|
||||
schema.AppContainerVersion.String(),
|
||||
})
|
||||
out.Flush()
|
||||
}
|
||||
|
||||
func printCommandUsage(cmd *Command) {
|
||||
commandUsageTemplate.Execute(out, struct {
|
||||
Executable string
|
||||
Cmd *Command
|
||||
CmdFlags []*flag.Flag
|
||||
}{
|
||||
cliName,
|
||||
cmd,
|
||||
getFlags(&cmd.Flags),
|
||||
})
|
||||
out.Flush()
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/bzip2"
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/aci"
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
|
||||
)
|
||||
|
||||
const (
|
||||
typeAppImage = "appimage"
|
||||
typeImageLayout = "layout"
|
||||
typeManifest = "manifest"
|
||||
)
|
||||
|
||||
var (
|
||||
valType string
|
||||
cmdValidate = &Command{
|
||||
Name: "validate",
|
||||
Description: "Validate one or more AppContainer files",
|
||||
Summary: "Validate that one or more images or manifests meet the AppContainer specification",
|
||||
Usage: "[--type=TYPE] FILE...",
|
||||
Run: runValidate,
|
||||
}
|
||||
types = []string{
|
||||
typeAppImage,
|
||||
typeImageLayout,
|
||||
typeManifest,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
cmdValidate.Flags.StringVar(&valType, "type", "",
|
||||
fmt.Sprintf(`Type of file to validate. If unset, actool will try to detect the type. One of "%s"`, strings.Join(types, ",")))
|
||||
}
|
||||
|
||||
func runValidate(args []string) (exit int) {
|
||||
if len(args) < 1 {
|
||||
stderr("must pass one or more files")
|
||||
return 1
|
||||
}
|
||||
|
||||
for _, path := range args {
|
||||
vt := valType
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
stderr("unable to access %s: %v", path, err)
|
||||
return 1
|
||||
}
|
||||
var fh *os.File
|
||||
if fi.IsDir() {
|
||||
switch vt {
|
||||
case typeImageLayout:
|
||||
case "":
|
||||
vt = typeImageLayout
|
||||
case typeManifest, typeAppImage:
|
||||
stderr("%s is a directory (wrong --type?)", path)
|
||||
return 1
|
||||
default:
|
||||
// should never happen
|
||||
panic(fmt.Sprintf("unexpected type: %v", vt))
|
||||
}
|
||||
} else {
|
||||
fh, err = os.Open(path)
|
||||
if err != nil {
|
||||
stderr("%s: unable to open: %v", path, err)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
if vt == "" {
|
||||
vt, err = detectValType(fh)
|
||||
if err != nil {
|
||||
stderr("%s: error detecting file type: %v", path, err)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
switch vt {
|
||||
case typeImageLayout:
|
||||
err = aci.ValidateLayout(path)
|
||||
if err != nil {
|
||||
stderr("%s: invalid image layout: %v", path, err)
|
||||
exit = 1
|
||||
} else if globalFlags.Debug {
|
||||
stderr("%s: valid image layout", path)
|
||||
}
|
||||
case typeAppImage:
|
||||
fr, err := maybeDecompress(fh)
|
||||
if err != nil {
|
||||
stderr("%s: error decompressing file: %v", path, err)
|
||||
return 1
|
||||
}
|
||||
tr := tar.NewReader(fr)
|
||||
err = aci.ValidateArchive(tr)
|
||||
fh.Close()
|
||||
if err != nil {
|
||||
stderr("%s: error validating: %v", path, err)
|
||||
exit = 1
|
||||
} else if globalFlags.Debug {
|
||||
stderr("%s: valid app container image", path)
|
||||
}
|
||||
case typeManifest:
|
||||
b, err := ioutil.ReadAll(fh)
|
||||
fh.Close()
|
||||
if err != nil {
|
||||
stderr("%s: unable to read file %s", path, err)
|
||||
return 1
|
||||
}
|
||||
k := schema.Kind{}
|
||||
if err := k.UnmarshalJSON(b); err != nil {
|
||||
stderr("%s: error unmarshaling manifest: %v", path, err)
|
||||
return 1
|
||||
}
|
||||
switch k.ACKind {
|
||||
case "ImageManifest":
|
||||
m := schema.ImageManifest{}
|
||||
err = m.UnmarshalJSON(b)
|
||||
case "ContainerRuntimeManifest":
|
||||
m := schema.ContainerRuntimeManifest{}
|
||||
err = m.UnmarshalJSON(b)
|
||||
default:
|
||||
// Should not get here; schema.Kind unmarshal should fail
|
||||
panic("bad ACKind")
|
||||
}
|
||||
if err != nil {
|
||||
stderr("%s: invalid %s: %v", path, k.ACKind, err)
|
||||
exit = 1
|
||||
} else if globalFlags.Debug {
|
||||
stderr("%s: valid %s", path, k.ACKind)
|
||||
}
|
||||
default:
|
||||
stderr("%s: unable to detect filetype (try --type)", path)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func detectValType(file *os.File) (string, error) {
|
||||
typ, err := aci.DetectFileType(file)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := file.Seek(0, 0); err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch typ {
|
||||
case aci.TypeXz, aci.TypeGzip, aci.TypeBzip2, aci.TypeTar:
|
||||
return typeAppImage, nil
|
||||
case aci.TypeText:
|
||||
return typeManifest, nil
|
||||
default:
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
|
||||
func maybeDecompress(rs io.ReadSeeker) (io.Reader, error) {
|
||||
// TODO(jonboulle): this is a bit redundant with detectValType
|
||||
typ, err := aci.DetectFileType(rs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := rs.Seek(0, 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r io.Reader
|
||||
switch typ {
|
||||
case aci.TypeGzip:
|
||||
r, err = gzip.NewReader(rs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error reading gzip: %v", err)
|
||||
}
|
||||
case aci.TypeBzip2:
|
||||
r = bzip2.NewReader(rs)
|
||||
case aci.TypeXz:
|
||||
r = aci.XzReader(rs)
|
||||
case aci.TypeTar:
|
||||
r = rs
|
||||
case aci.TypeUnknown:
|
||||
return nil, errors.New("unknown filetype")
|
||||
default:
|
||||
// should never happen
|
||||
panic(fmt.Sprintf("bad type returned from DetectFileType: %v", typ))
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
|
||||
)
|
||||
|
||||
var cmdVersion = &Command{
|
||||
Name: "version",
|
||||
Description: "Print the version and exit",
|
||||
Summary: "Print the version and exit",
|
||||
Run: runVersion,
|
||||
}
|
||||
|
||||
func runVersion(args []string) (exit int) {
|
||||
fmt.Printf("actool version %s\n", schema.AppContainerVersion.String())
|
||||
return
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/golang.org/x/net/html"
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/golang.org/x/net/html/atom"
|
||||
)
|
||||
|
||||
type acMeta struct {
|
||||
name string
|
||||
prefix string
|
||||
uri string
|
||||
}
|
||||
|
||||
type ACIEndpoint struct {
|
||||
ACI string
|
||||
Sig string
|
||||
}
|
||||
|
||||
type Endpoints struct {
|
||||
ACIEndpoints []ACIEndpoint
|
||||
Keys []string
|
||||
}
|
||||
|
||||
const (
|
||||
defaultVersion = "latest"
|
||||
)
|
||||
|
||||
var (
|
||||
templateExpression = regexp.MustCompile(`{.*?}`)
|
||||
)
|
||||
|
||||
func appendMeta(meta []acMeta, attrs []html.Attribute) []acMeta {
|
||||
m := acMeta{}
|
||||
|
||||
for _, a := range attrs {
|
||||
if a.Namespace != "" {
|
||||
continue
|
||||
}
|
||||
|
||||
switch a.Key {
|
||||
case "name":
|
||||
m.name = a.Val
|
||||
|
||||
case "content":
|
||||
parts := strings.SplitN(strings.TrimSpace(a.Val), " ", 2)
|
||||
if len(parts) < 2 {
|
||||
break
|
||||
}
|
||||
m.prefix = parts[0]
|
||||
m.uri = strings.TrimSpace(parts[1])
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(eyakubovich): should prefix be optional?
|
||||
if !strings.HasPrefix(m.name, "ac-") || m.prefix == "" || m.uri == "" {
|
||||
return meta
|
||||
}
|
||||
|
||||
return append(meta, m)
|
||||
}
|
||||
|
||||
func extractACMeta(r io.Reader) []acMeta {
|
||||
var meta []acMeta
|
||||
|
||||
z := html.NewTokenizer(r)
|
||||
|
||||
for {
|
||||
switch z.Next() {
|
||||
case html.ErrorToken:
|
||||
return meta
|
||||
|
||||
case html.StartTagToken, html.SelfClosingTagToken:
|
||||
tok := z.Token()
|
||||
if tok.DataAtom == atom.Meta {
|
||||
meta = appendMeta(meta, tok.Attr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func renderTemplate(tpl string, kvs ...string) (string, bool) {
|
||||
for i := 0; i < len(kvs); i += 2 {
|
||||
k := kvs[i]
|
||||
v := kvs[i+1]
|
||||
tpl = strings.Replace(tpl, k, v, -1)
|
||||
}
|
||||
return tpl, !templateExpression.MatchString(tpl)
|
||||
}
|
||||
|
||||
func createTemplateVars(app App) []string {
|
||||
tplVars := []string{"{name}", app.Name.String()}
|
||||
// If a label is called "name", it will be ignored as it appears after
|
||||
// in the slice
|
||||
for n, v := range app.Labels {
|
||||
tplVars = append(tplVars, fmt.Sprintf("{%s}", n), v)
|
||||
}
|
||||
return tplVars
|
||||
}
|
||||
|
||||
func doDiscover(app App, pre string, insecure bool) (*Endpoints, error) {
|
||||
if app.Labels["version"] == "" {
|
||||
app.Labels["version"] = defaultVersion
|
||||
}
|
||||
|
||||
_, body, err := httpsOrHTTP(pre, insecure)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
meta := extractACMeta(body)
|
||||
|
||||
tplVars := createTemplateVars(app)
|
||||
|
||||
de := &Endpoints{}
|
||||
|
||||
for _, m := range meta {
|
||||
if !strings.HasPrefix(app.Name.String(), m.prefix) {
|
||||
continue
|
||||
}
|
||||
|
||||
switch m.name {
|
||||
case "ac-discovery":
|
||||
// Ignore not handled variables as {ext} isn't already rendered.
|
||||
uri, _ := renderTemplate(m.uri, tplVars...)
|
||||
sig, ok := renderTemplate(uri, "{ext}", "sig")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
aci, ok := renderTemplate(uri, "{ext}", "aci")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
de.ACIEndpoints = append(de.ACIEndpoints, ACIEndpoint{ACI: aci, Sig: sig})
|
||||
|
||||
case "ac-discovery-pubkeys":
|
||||
de.Keys = append(de.Keys, m.uri)
|
||||
}
|
||||
}
|
||||
|
||||
if len(de.ACIEndpoints) == 0 {
|
||||
return nil, fmt.Errorf("found no ACI meta tags")
|
||||
}
|
||||
|
||||
return de, nil
|
||||
}
|
||||
|
||||
// DiscoverEndpoints will make HTTPS requests to find the ac-discovery meta
|
||||
// tags and optionally will use HTTP if insecure is set. Based on the app
|
||||
// passed the discovery templates will be filled out and returned in eps.
|
||||
func DiscoverEndpoints(app App, insecure bool) (eps *Endpoints, err error) {
|
||||
parts := strings.Split(string(app.Name), "/")
|
||||
for i := range parts {
|
||||
end := len(parts) - i
|
||||
pre := strings.Join(parts[:end], "/")
|
||||
eps, err = doDiscover(app, pre, insecure)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func fakeHTTPGet(filename string, failures int) func(uri string) (*http.Response, error) {
|
||||
attempts := 0
|
||||
return func(uri string) (*http.Response, error) {
|
||||
f, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp *http.Response
|
||||
|
||||
switch {
|
||||
case attempts < failures:
|
||||
resp = &http.Response{
|
||||
Status: "404 Not Found",
|
||||
StatusCode: http.StatusNotFound,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: http.Header{
|
||||
"Content-Type": []string{"text/html"},
|
||||
},
|
||||
Body: ioutil.NopCloser(bytes.NewBufferString("")),
|
||||
}
|
||||
default:
|
||||
resp = &http.Response{
|
||||
Status: "200 OK",
|
||||
StatusCode: http.StatusOK,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: http.Header{
|
||||
"Content-Type": []string{"text/html"},
|
||||
},
|
||||
Body: f,
|
||||
}
|
||||
}
|
||||
|
||||
attempts = attempts + 1
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
type httpgetter func(uri string) (*http.Response, error)
|
||||
|
||||
func TestDiscoverEndpoints(t *testing.T) {
|
||||
tests := []struct {
|
||||
get httpgetter
|
||||
expectDiscoverySuccess bool
|
||||
app App
|
||||
expectedACIEndpoints []ACIEndpoint
|
||||
expectedKeys []string
|
||||
}{
|
||||
{
|
||||
fakeHTTPGet("myapp.html", 0),
|
||||
true,
|
||||
App{
|
||||
Name: "example.com/myapp",
|
||||
Labels: map[string]string{
|
||||
"version": "1.0.0",
|
||||
"os": "linux",
|
||||
"arch": "amd64",
|
||||
},
|
||||
},
|
||||
[]ACIEndpoint{
|
||||
ACIEndpoint{
|
||||
ACI: "https://storage.example.com/example.com/myapp-1.0.0.aci?torrent",
|
||||
Sig: "https://storage.example.com/example.com/myapp-1.0.0.sig?torrent",
|
||||
},
|
||||
ACIEndpoint{
|
||||
ACI: "hdfs://storage.example.com/example.com/myapp-1.0.0.aci",
|
||||
Sig: "hdfs://storage.example.com/example.com/myapp-1.0.0.sig",
|
||||
},
|
||||
},
|
||||
[]string{"https://example.com/pubkeys.gpg"},
|
||||
},
|
||||
{
|
||||
fakeHTTPGet("myapp.html", 1),
|
||||
true,
|
||||
App{
|
||||
Name: "example.com/myapp/foobar",
|
||||
Labels: map[string]string{
|
||||
"version": "1.0.0",
|
||||
"os": "linux",
|
||||
"arch": "amd64",
|
||||
},
|
||||
},
|
||||
[]ACIEndpoint{
|
||||
ACIEndpoint{
|
||||
ACI: "https://storage.example.com/example.com/myapp/foobar-1.0.0.aci?torrent",
|
||||
Sig: "https://storage.example.com/example.com/myapp/foobar-1.0.0.sig?torrent",
|
||||
},
|
||||
ACIEndpoint{
|
||||
ACI: "hdfs://storage.example.com/example.com/myapp/foobar-1.0.0.aci",
|
||||
Sig: "hdfs://storage.example.com/example.com/myapp/foobar-1.0.0.sig",
|
||||
},
|
||||
},
|
||||
[]string{"https://example.com/pubkeys.gpg"},
|
||||
},
|
||||
{
|
||||
fakeHTTPGet("myapp.html", 20),
|
||||
false,
|
||||
App{
|
||||
Name: "example.com/myapp/foobar/bazzer",
|
||||
Labels: map[string]string{
|
||||
"version": "1.0.0",
|
||||
"os": "linux",
|
||||
"arch": "amd64",
|
||||
},
|
||||
},
|
||||
[]ACIEndpoint{},
|
||||
[]string{},
|
||||
},
|
||||
// Test missing label. Only one ac-discovery template should be
|
||||
// returned as the other one cannot be completely rendered due to
|
||||
// missing labels.
|
||||
{
|
||||
fakeHTTPGet("myapp2.html", 0),
|
||||
true,
|
||||
App{
|
||||
Name: "example.com/myapp",
|
||||
Labels: map[string]string{
|
||||
"version": "1.0.0",
|
||||
},
|
||||
},
|
||||
[]ACIEndpoint{
|
||||
ACIEndpoint{
|
||||
ACI: "https://storage.example.com/example.com/myapp-1.0.0.aci",
|
||||
Sig: "https://storage.example.com/example.com/myapp-1.0.0.sig",
|
||||
},
|
||||
},
|
||||
[]string{"https://example.com/pubkeys.gpg"},
|
||||
},
|
||||
// Test missing labels. version label should default to
|
||||
// "latest" and the first template should be rendered
|
||||
{
|
||||
fakeHTTPGet("myapp2.html", 0),
|
||||
false,
|
||||
App{
|
||||
Name: "example.com/myapp",
|
||||
Labels: map[string]string{},
|
||||
},
|
||||
[]ACIEndpoint{
|
||||
ACIEndpoint{
|
||||
ACI: "https://storage.example.com/example.com/myapp-latest.aci",
|
||||
Sig: "https://storage.example.com/example.com/myapp-latest.sig",
|
||||
},
|
||||
},
|
||||
[]string{"https://example.com/pubkeys.gpg"},
|
||||
},
|
||||
// Test with a label called "name". It should be ignored.
|
||||
{
|
||||
fakeHTTPGet("myapp2.html", 0),
|
||||
false,
|
||||
App{
|
||||
Name: "example.com/myapp",
|
||||
Labels: map[string]string{
|
||||
"name": "labelcalledname",
|
||||
"version": "1.0.0",
|
||||
},
|
||||
},
|
||||
[]ACIEndpoint{
|
||||
ACIEndpoint{
|
||||
ACI: "https://storage.example.com/example.com/myapp-1.0.0.aci",
|
||||
Sig: "https://storage.example.com/example.com/myapp-1.0.0.sig",
|
||||
},
|
||||
},
|
||||
[]string{"https://example.com/pubkeys.gpg"},
|
||||
},
|
||||
}
|
||||
|
||||
for i, tt := range tests {
|
||||
httpGet = tt.get
|
||||
de, err := DiscoverEndpoints(tt.app, true)
|
||||
if err != nil && !tt.expectDiscoverySuccess {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("#%d DiscoverEndpoints failed: %v", i, err)
|
||||
}
|
||||
|
||||
if len(de.ACIEndpoints) != len(tt.expectedACIEndpoints) {
|
||||
t.Errorf("ACIEndpoints array is wrong length want %d got %d", len(tt.expectedACIEndpoints), len(de.ACIEndpoints))
|
||||
} else {
|
||||
for n, _ := range de.ACIEndpoints {
|
||||
if de.ACIEndpoints[n] != tt.expectedACIEndpoints[n] {
|
||||
t.Errorf("#%d ACIEndpoints[%d] mismatch: want %v got %v", i, n, tt.expectedACIEndpoints[n], de.ACIEndpoints[n])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(de.Keys) != len(tt.expectedKeys) {
|
||||
t.Errorf("Keys array is wrong length want %d got %d", len(tt.expectedKeys), len(de.Keys))
|
||||
} else {
|
||||
for n, _ := range de.Keys {
|
||||
if de.Keys[n] != tt.expectedKeys[n] {
|
||||
t.Errorf("#%d sig[%d] mismatch: want %v got %v", i, n, tt.expectedKeys[n], de.Keys[n])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
// Package discovery contains an experimental implementation of the Image
|
||||
// Discovery section of the appc specification.
|
||||
package discovery
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultDialTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
// httpGet is the function used by discovery to retrieve URLs; it is
|
||||
// defined here so it can be overridden for testing
|
||||
httpGet func(url string) (resp *http.Response, err error)
|
||||
)
|
||||
|
||||
func init() {
|
||||
t := &http.Transport{
|
||||
Dial: func(n, a string) (net.Conn, error) {
|
||||
return net.DialTimeout(n, a, defaultDialTimeout)
|
||||
},
|
||||
}
|
||||
c := &http.Client{
|
||||
Transport: t,
|
||||
}
|
||||
httpGet = c.Get
|
||||
}
|
||||
|
||||
func httpsOrHTTP(name string, insecure bool) (urlStr string, body io.ReadCloser, err error) {
|
||||
fetch := func(scheme string) (urlStr string, res *http.Response, err error) {
|
||||
u, err := url.Parse(scheme + "://" + name)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
u.RawQuery = "ac-discovery=1"
|
||||
urlStr = u.String()
|
||||
res, err = httpGet(urlStr)
|
||||
return
|
||||
}
|
||||
closeBody := func(res *http.Response) {
|
||||
if res != nil {
|
||||
res.Body.Close()
|
||||
}
|
||||
}
|
||||
urlStr, res, err := fetch("https")
|
||||
if err != nil || res.StatusCode != http.StatusOK {
|
||||
if insecure {
|
||||
closeBody(res)
|
||||
urlStr, res, err = fetch("http")
|
||||
}
|
||||
}
|
||||
|
||||
if res != nil && res.StatusCode != http.StatusOK {
|
||||
err = fmt.Errorf("expected a 200 OK got %d", res.StatusCode)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
closeBody(res)
|
||||
return "", nil, err
|
||||
}
|
||||
return urlStr, res.Body, nil
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func fakeHttpOrHttpsGet(filename string, httpSuccess bool, httpsSuccess bool, httpErrorCode int) func(uri string) (*http.Response, error) {
|
||||
return func(uri string) (*http.Response, error) {
|
||||
f, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp *http.Response
|
||||
|
||||
switch {
|
||||
case strings.HasPrefix(uri, "https://") && httpsSuccess:
|
||||
fallthrough
|
||||
case strings.HasPrefix(uri, "http://") && httpSuccess:
|
||||
resp = &http.Response{
|
||||
Status: "200 OK",
|
||||
StatusCode: http.StatusOK,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: http.Header{
|
||||
"Content-Type": []string{"text/html"},
|
||||
},
|
||||
Body: f,
|
||||
}
|
||||
case httpErrorCode > 0:
|
||||
resp = &http.Response{
|
||||
Status: "Error",
|
||||
StatusCode: httpErrorCode,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: http.Header{
|
||||
"Content-Type": []string{"text/html"},
|
||||
},
|
||||
Body: ioutil.NopCloser(bytes.NewBufferString("")),
|
||||
}
|
||||
default:
|
||||
err = errors.New("fakeHttpOrHttpsGet failed as requested")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestHttpsOrHTTP(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
insecure bool
|
||||
get httpgetter
|
||||
expectUrlStr string
|
||||
expectSuccess bool
|
||||
}{
|
||||
{
|
||||
"good-server",
|
||||
false,
|
||||
fakeHttpOrHttpsGet("myapp.html", true, true, 0),
|
||||
"https://good-server?ac-discovery=1",
|
||||
true,
|
||||
},
|
||||
{
|
||||
"file-not-found",
|
||||
false,
|
||||
fakeHttpOrHttpsGet("myapp.html", false, false, 404),
|
||||
"",
|
||||
false,
|
||||
},
|
||||
{
|
||||
"completely-broken-server",
|
||||
false,
|
||||
fakeHttpOrHttpsGet("myapp.html", false, false, 0),
|
||||
"",
|
||||
false,
|
||||
},
|
||||
{
|
||||
"file-only-on-http",
|
||||
false, // do not accept fallback on http
|
||||
fakeHttpOrHttpsGet("myapp.html", true, false, 404),
|
||||
"",
|
||||
false,
|
||||
},
|
||||
{
|
||||
"file-only-on-http",
|
||||
true, // accept fallback on http
|
||||
fakeHttpOrHttpsGet("myapp.html", true, false, 404),
|
||||
"http://file-only-on-http?ac-discovery=1",
|
||||
true,
|
||||
},
|
||||
{
|
||||
"https-server-is-down",
|
||||
true, // accept fallback on http
|
||||
fakeHttpOrHttpsGet("myapp.html", true, false, 0),
|
||||
"http://https-server-is-down?ac-discovery=1",
|
||||
true,
|
||||
},
|
||||
}
|
||||
|
||||
for i, tt := range tests {
|
||||
httpGet = tt.get
|
||||
urlStr, body, err := httpsOrHTTP(tt.name, tt.insecure)
|
||||
if tt.expectSuccess {
|
||||
if err != nil {
|
||||
t.Fatalf("#%d httpsOrHTTP failed: %v", i, err)
|
||||
}
|
||||
if urlStr == "" {
|
||||
t.Fatalf("#%d httpsOrHTTP didn't return a urlStr", i)
|
||||
}
|
||||
if urlStr != tt.expectUrlStr {
|
||||
t.Fatalf("#%d httpsOrHTTP urlStr mismatch: want %s got %s",
|
||||
i, tt.expectUrlStr, urlStr)
|
||||
}
|
||||
if body == nil {
|
||||
t.Fatalf("#%d httpsOrHTTP didn't return a body", i)
|
||||
}
|
||||
} else {
|
||||
if err == nil {
|
||||
t.Fatalf("#%d httpsOrHTTP should have failed", i)
|
||||
}
|
||||
if urlStr != "" {
|
||||
t.Fatalf("#%d httpsOrHTTP should not have returned a urlStr", i)
|
||||
}
|
||||
if body != nil {
|
||||
t.Fatalf("#%d httpsOrHTTP should not have returned a body", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>My app</title>
|
||||
<meta name="ac-discovery" content="example.com https://storage.example.com/{name}-{version}.{ext}?torrent">
|
||||
<meta name="ac-discovery" content="example.com hdfs://storage.example.com/{name}-{version}.{ext}">
|
||||
<meta name="ac-discovery-cas-prefix" content="example.com https://storage.example.com/cas/">
|
||||
<meta name="ac-discovery-pubkeys" content="example.com https://example.com/pubkeys.gpg">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>My App</h1>
|
||||
</body>
|
||||
</html>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>My app</title>
|
||||
<meta name="ac-discovery" content="example.com https://storage.example.com/{name}-{version}-{os}-{arch}.{ext}">
|
||||
<meta name="ac-discovery" content="example.com https://storage.example.com/{name}-{version}.{ext}">
|
||||
<meta name="ac-discovery-cas-prefix" content="example.com https://storage.example.com/cas/">
|
||||
<meta name="ac-discovery-pubkeys" content="example.com https://example.com/pubkeys.gpg">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>My App</h1>
|
||||
</body>
|
||||
</html>
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
Name types.ACName
|
||||
Labels map[string]string
|
||||
}
|
||||
|
||||
func NewApp(name string, labels map[string]string) (*App, error) {
|
||||
if labels == nil {
|
||||
labels = make(map[string]string, 0)
|
||||
}
|
||||
acn, err := types.NewACName(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &App{
|
||||
Name: *acn,
|
||||
Labels: labels,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NewAppFromString takes a command line app parameter and returns a map of labels.
|
||||
//
|
||||
// Example app parameters:
|
||||
// example.com/reduce-worker:1.0.0
|
||||
// example.com/reduce-worker,channel=alpha,label=value
|
||||
func NewAppFromString(app string) (*App, error) {
|
||||
var (
|
||||
name string
|
||||
labels map[string]string
|
||||
)
|
||||
|
||||
app = strings.Replace(app, ":", ",version=", -1)
|
||||
app = "name=" + app
|
||||
v, err := url.ParseQuery(strings.Replace(app, ",", "&", -1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
labels = make(map[string]string, 0)
|
||||
for key, val := range v {
|
||||
if len(val) > 1 {
|
||||
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
|
||||
}
|
||||
if key == "name" {
|
||||
name = val[0]
|
||||
continue
|
||||
}
|
||||
labels[key] = val[0]
|
||||
}
|
||||
a, err := NewApp(name, labels)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewAppFromString(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
|
||||
w *App
|
||||
werr bool
|
||||
}{
|
||||
{
|
||||
"example.com/reduce-worker:1.0.0",
|
||||
|
||||
&App{
|
||||
Name: "example.com/reduce-worker",
|
||||
Labels: map[string]string{
|
||||
"version": "1.0.0",
|
||||
},
|
||||
},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"example.com/reduce-worker,channel=alpha,label=value",
|
||||
|
||||
&App{
|
||||
Name: "example.com/reduce-worker",
|
||||
Labels: map[string]string{
|
||||
"channel": "alpha",
|
||||
"label": "value",
|
||||
},
|
||||
},
|
||||
|
||||
false,
|
||||
},
|
||||
|
||||
// bad AC name for app
|
||||
{
|
||||
"not an app name",
|
||||
|
||||
nil,
|
||||
true,
|
||||
},
|
||||
|
||||
// bad URL escape (bad query)
|
||||
{
|
||||
"example.com/garbage%8 939",
|
||||
|
||||
nil,
|
||||
true,
|
||||
},
|
||||
|
||||
// multi-value labels
|
||||
{
|
||||
"foo.com/bar,channel=alpha,dog=woof,channel=beta",
|
||||
|
||||
nil,
|
||||
true,
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
g, err := NewAppFromString(tt.in)
|
||||
gerr := (err != nil)
|
||||
if !reflect.DeepEqual(g, tt.w) {
|
||||
t.Errorf("#%d: got %v, want %v", i, g, tt.w)
|
||||
}
|
||||
if gerr != tt.werr {
|
||||
t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
// Package tarheader contains a simple abstraction to accurately create
|
||||
// tar.Headers on different operating systems.
|
||||
package tarheader
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
//+build darwin
|
||||
|
||||
package tarheader
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
populateHeaderStat = append(populateHeaderStat, populateHeaderCtime)
|
||||
}
|
||||
|
||||
func populateHeaderCtime(h *tar.Header, fi os.FileInfo, _ map[uint64]string) {
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
sec, nsec := st.Ctimespec.Unix()
|
||||
ctime := time.Unix(sec, nsec)
|
||||
h.ChangeTime = ctime
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package tarheader
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
populateHeaderStat = append(populateHeaderStat, populateHeaderCtime)
|
||||
}
|
||||
|
||||
func populateHeaderCtime(h *tar.Header, fi os.FileInfo, _ map[uint64]string) {
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
sec, nsec := st.Ctim.Unix()
|
||||
ctime := time.Unix(sec, nsec)
|
||||
h.ChangeTime = ctime
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package tarheader
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func init() {
|
||||
populateHeaderStat = append(populateHeaderStat, populateHeaderUnix)
|
||||
}
|
||||
|
||||
func populateHeaderUnix(h *tar.Header, fi os.FileInfo, seen map[uint64]string) {
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.Uid = int(st.Uid)
|
||||
h.Gid = int(st.Gid)
|
||||
// If we have already seen this inode, generate a hardlink
|
||||
p, ok := seen[uint64(st.Ino)]
|
||||
if ok {
|
||||
h.Linkname = p
|
||||
h.Typeflag = tar.TypeLink
|
||||
} else {
|
||||
seen[uint64(st.Ino)] = h.Name
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package tarheader
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"os"
|
||||
)
|
||||
|
||||
var populateHeaderStat []func(h *tar.Header, fi os.FileInfo, seen map[uint64]string)
|
||||
|
||||
func Populate(h *tar.Header, fi os.FileInfo, seen map[uint64]string) {
|
||||
for _, pop := range populateHeaderStat {
|
||||
pop(h, fi, seen)
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
|
||||
)
|
||||
|
||||
type ContainerRuntimeManifest struct {
|
||||
ACVersion types.SemVer `json:"acVersion"`
|
||||
ACKind types.ACKind `json:"acKind"`
|
||||
UUID types.UUID `json:"uuid"`
|
||||
Apps AppList `json:"apps"`
|
||||
Volumes []types.Volume `json:"volumes"`
|
||||
Isolators []types.Isolator `json:"isolators"`
|
||||
Annotations types.Annotations `json:"annotations"`
|
||||
}
|
||||
|
||||
// containerRuntimeManifest is a model to facilitate extra validation during the
|
||||
// unmarshalling of the ContainerRuntimeManifest
|
||||
type containerRuntimeManifest ContainerRuntimeManifest
|
||||
|
||||
func (cm *ContainerRuntimeManifest) UnmarshalJSON(data []byte) error {
|
||||
c := containerRuntimeManifest{}
|
||||
err := json.Unmarshal(data, &c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ncm := ContainerRuntimeManifest(c)
|
||||
if err := ncm.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
*cm = ncm
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cm ContainerRuntimeManifest) MarshalJSON() ([]byte, error) {
|
||||
if err := cm.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(containerRuntimeManifest(cm))
|
||||
}
|
||||
|
||||
// assertValid performs extra assertions on an ContainerRuntimeManifest to
|
||||
// ensure that fields are set appropriately, etc. It is used exclusively when
|
||||
// marshalling and unmarshalling an ContainerRuntimeManifest. Most
|
||||
// field-specific validation is performed through the individual types being
|
||||
// marshalled; assertValid() should only deal with higher-level validation.
|
||||
func (cm *ContainerRuntimeManifest) assertValid() error {
|
||||
if cm.ACKind != "ContainerRuntimeManifest" {
|
||||
return types.ACKindError(`missing or bad ACKind (must be "ContainerRuntimeManifest")`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type AppList []RuntimeApp
|
||||
|
||||
// Get retrieves an app by the specified name from the AppList; if there is
|
||||
// no such app, nil is returned. The returned *RuntimeApp MUST be considered
|
||||
// read-only.
|
||||
func (al AppList) Get(name types.ACName) *RuntimeApp {
|
||||
for _, a := range al {
|
||||
if name.Equals(a.Name) {
|
||||
aa := a
|
||||
return &aa
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Mount describes the mapping between a volume and an apps
|
||||
// MountPoint that will be fulfilled at runtime.
|
||||
type Mount struct {
|
||||
Volume types.ACName `json:"volume"`
|
||||
MountPoint types.ACName `json:"mountPoint"`
|
||||
}
|
||||
|
||||
func (r Mount) assertValid() error {
|
||||
if r.Volume.Empty() {
|
||||
return errors.New("volume must be set")
|
||||
}
|
||||
if r.MountPoint.Empty() {
|
||||
return errors.New("mountPoint must be set")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RuntimeApp describes an application referenced in a ContainerRuntimeManifest
|
||||
type RuntimeApp struct {
|
||||
Name types.ACName `json:"name"`
|
||||
ImageID types.Hash `json:"imageID"`
|
||||
Mounts []Mount `json:"mounts"`
|
||||
Isolators []types.Isolator `json:"isolators"`
|
||||
Annotations types.Annotations `json:"annotations"`
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
// Package schema provides definitions for the JSON schema of the different
|
||||
// manifests in the App Container Specification. The manifests are canonically
|
||||
// represented in their respective structs:
|
||||
// - `ImageManifest`
|
||||
// - `ContainerRuntimeManifest`
|
||||
//
|
||||
// Validation is performed through serialization: if a blob of JSON data will
|
||||
// unmarshal to one of the *Manifests, it is considered a valid implementation
|
||||
// of the standard. Similarly, if a constructed *Manifest struct marshals
|
||||
// successfully to JSON, it must be valid.
|
||||
package schema
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
|
||||
)
|
||||
|
||||
const (
|
||||
ACIExtension = ".aci"
|
||||
)
|
||||
|
||||
type ImageManifest struct {
|
||||
ACKind types.ACKind `json:"acKind"`
|
||||
ACVersion types.SemVer `json:"acVersion"`
|
||||
Name types.ACName `json:"name"`
|
||||
Labels types.Labels `json:"labels,omitempty"`
|
||||
App *types.App `json:"app,omitempty"`
|
||||
Annotations types.Annotations `json:"annotations,omitempty"`
|
||||
Dependencies types.Dependencies `json:"dependencies,omitempty"`
|
||||
PathWhitelist []string `json:"pathWhitelist,omitempty"`
|
||||
}
|
||||
|
||||
// imageManifest is a model to facilitate extra validation during the
|
||||
// unmarshalling of the ImageManifest
|
||||
type imageManifest ImageManifest
|
||||
|
||||
func (im *ImageManifest) UnmarshalJSON(data []byte) error {
|
||||
a := imageManifest{}
|
||||
err := json.Unmarshal(data, &a)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nim := ImageManifest(a)
|
||||
if err := nim.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
*im = nim
|
||||
return nil
|
||||
}
|
||||
|
||||
func (im ImageManifest) MarshalJSON() ([]byte, error) {
|
||||
if err := im.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(imageManifest(im))
|
||||
}
|
||||
|
||||
// assertValid performs extra assertions on an ImageManifest to ensure that
|
||||
// fields are set appropriately, etc. It is used exclusively when marshalling
|
||||
// and unmarshalling an ImageManifest. Most field-specific validation is
|
||||
// performed through the individual types being marshalled; assertValid()
|
||||
// should only deal with higher-level validation.
|
||||
func (im *ImageManifest) assertValid() error {
|
||||
if im.ACKind != "ImageManifest" {
|
||||
return types.ACKindError(`missing or bad ACKind (must be "ImageManifest")`)
|
||||
}
|
||||
if im.ACVersion.Empty() {
|
||||
return errors.New(`acVersion must be set`)
|
||||
}
|
||||
if im.Name.Empty() {
|
||||
return errors.New(`name must be set`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (im *ImageManifest) GetLabel(name string) (val string, ok bool) {
|
||||
return im.Labels.Get(name)
|
||||
}
|
||||
|
||||
func (im *ImageManifest) GetAnnotation(name string) (val string, ok bool) {
|
||||
return im.Annotations.Get(name)
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package schema
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEmptyApp(t *testing.T) {
|
||||
imj := `
|
||||
{
|
||||
"acKind": "ImageManifest",
|
||||
"acVersion": "0.2.0",
|
||||
"name": "example.com/test"
|
||||
}
|
||||
`
|
||||
|
||||
var im ImageManifest
|
||||
|
||||
err := im.UnmarshalJSON([]byte(imj))
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Marshal and Unmarshal to verify that no "app": {} is generated on
|
||||
// Marshal and converted to empty struct on Unmarshal
|
||||
buf, err := im.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
err = im.UnmarshalJSON(buf)
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
|
||||
)
|
||||
|
||||
type Kind struct {
|
||||
ACVersion types.SemVer `json:"acVersion"`
|
||||
ACKind types.ACKind `json:"acKind"`
|
||||
}
|
||||
|
||||
type kind Kind
|
||||
|
||||
func (k *Kind) UnmarshalJSON(data []byte) error {
|
||||
nk := kind{}
|
||||
err := json.Unmarshal(data, &nk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*k = Kind(nk)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (k Kind) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(kind(k))
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNoACKind = ACKindError("ACKind must be set")
|
||||
)
|
||||
|
||||
// ACKind wraps a string to define a field which must be set with one of
|
||||
// several ACKind values. If it is unset, or has an invalid value, the field
|
||||
// will refuse to marshal/unmarshal.
|
||||
type ACKind string
|
||||
|
||||
func (a ACKind) String() string {
|
||||
return string(a)
|
||||
}
|
||||
|
||||
func (a ACKind) assertValid() error {
|
||||
s := a.String()
|
||||
switch s {
|
||||
case "ImageManifest", "ContainerRuntimeManifest":
|
||||
return nil
|
||||
case "":
|
||||
return ErrNoACKind
|
||||
default:
|
||||
msg := fmt.Sprintf("bad ACKind: %s", s)
|
||||
return ACKindError(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func (a ACKind) MarshalJSON() ([]byte, error) {
|
||||
if err := a.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(a.String())
|
||||
}
|
||||
|
||||
func (a *ACKind) UnmarshalJSON(data []byte) error {
|
||||
var s string
|
||||
err := json.Unmarshal(data, &s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
na := ACKind(s)
|
||||
if err := na.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
*a = na
|
||||
return nil
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestACKindMarshalBad(t *testing.T) {
|
||||
tests := map[string]error{
|
||||
"Foo": ACKindError("bad ACKind: Foo"),
|
||||
"ApplicationManifest": ACKindError("bad ACKind: ApplicationManifest"),
|
||||
"": ErrNoACKind,
|
||||
}
|
||||
for in, werr := range tests {
|
||||
a := ACKind(in)
|
||||
b, gerr := json.Marshal(a)
|
||||
if b != nil {
|
||||
t.Errorf("ACKind(%q): want b=nil, got %v", in, b)
|
||||
}
|
||||
if jerr, ok := gerr.(*json.MarshalerError); !ok {
|
||||
t.Errorf("expected JSONMarshalerError")
|
||||
} else {
|
||||
if e := jerr.Err; e != werr {
|
||||
t.Errorf("err=%#v, want %#v", e, werr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestACKindMarshalGood(t *testing.T) {
|
||||
for i, in := range []string{
|
||||
"ImageManifest",
|
||||
"ContainerRuntimeManifest",
|
||||
} {
|
||||
a := ACKind(in)
|
||||
b, err := json.Marshal(a)
|
||||
if !reflect.DeepEqual(b, []byte(`"`+in+`"`)) {
|
||||
t.Errorf("#%d: marshalled=%v, want %v", i, b, []byte(in))
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("#%d: err=%v, want nil", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
valchars = `abcdefghijklmnopqrstuvwxyz0123456789.-/`
|
||||
)
|
||||
|
||||
// ACName (an App-Container Name) is a format used by keys in different
|
||||
// formats of the App Container Standard. An ACName is restricted to
|
||||
// characters accepted by the DNS RFC[1] and "/"; all alphabetical characters
|
||||
// must be lowercase only.
|
||||
//
|
||||
// [1] http://tools.ietf.org/html/rfc1123#page-13
|
||||
type ACName string
|
||||
|
||||
func (n ACName) String() string {
|
||||
return string(n)
|
||||
}
|
||||
|
||||
func (n *ACName) Set(s string) error {
|
||||
nn, err := NewACName(s)
|
||||
if err == nil {
|
||||
*n = *nn
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Equals checks whether a given ACName is equal to this one.
|
||||
func (n ACName) Equals(o ACName) bool {
|
||||
return strings.ToLower(string(n)) == strings.ToLower(string(o))
|
||||
}
|
||||
|
||||
func (n ACName) Empty() bool {
|
||||
return n.String() == ""
|
||||
}
|
||||
|
||||
// NewACName generates a new ACName from a string. If the given string is
|
||||
// not a valid ACName, nil and an error are returned.
|
||||
func NewACName(s string) (*ACName, error) {
|
||||
if len(s) == 0 {
|
||||
return nil, fmt.Errorf("ACName cannot be empty")
|
||||
}
|
||||
for _, c := range s {
|
||||
if !strings.ContainsRune(valchars, c) {
|
||||
msg := fmt.Sprintf("invalid char in ACName: %c", c)
|
||||
return nil, ACNameError(msg)
|
||||
}
|
||||
}
|
||||
return (*ACName)(&s), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the json.Unmarshaler interface
|
||||
func (n *ACName) UnmarshalJSON(data []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
nn, err := NewACName(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*n = *nn
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements the json.Marshaler interface
|
||||
func (n *ACName) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(n.String())
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package types
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewACName(t *testing.T) {
|
||||
tests := []string{
|
||||
"asdf",
|
||||
"foo-bar-baz",
|
||||
"database",
|
||||
"example.com/database",
|
||||
"example.com/ourapp-1.0.0",
|
||||
"sub-domain.example.com/org/product/release-1.0.0",
|
||||
}
|
||||
for i, in := range tests {
|
||||
l, err := NewACName(in)
|
||||
if err != nil {
|
||||
t.Errorf("#%d: got err=%v, want nil", i, err)
|
||||
}
|
||||
if l == nil {
|
||||
t.Errorf("#%d: got l=nil, want non-nil", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewACNameBad(t *testing.T) {
|
||||
tests := []string{
|
||||
"",
|
||||
"foo#",
|
||||
"EXAMPLE.com",
|
||||
"foo.com/BAR",
|
||||
"example.com/app_1",
|
||||
}
|
||||
for i, in := range tests {
|
||||
l, err := NewACName(in)
|
||||
if l != nil {
|
||||
t.Errorf("#%d: got l=%v, want nil", i, l)
|
||||
}
|
||||
if err == nil {
|
||||
t.Errorf("#%d: got err=nil, want non-nil", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Annotations []Annotation
|
||||
|
||||
type annotations Annotations
|
||||
|
||||
type Annotation struct {
|
||||
Name ACName `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func (a Annotations) assertValid() error {
|
||||
seen := map[ACName]string{}
|
||||
for _, anno := range a {
|
||||
_, ok := seen[anno.Name]
|
||||
if ok {
|
||||
return fmt.Errorf(`duplicate annotations of name %q`, anno.Name)
|
||||
}
|
||||
seen[anno.Name] = anno.Value
|
||||
}
|
||||
if c, ok := seen["created"]; ok {
|
||||
if _, err := NewDate(c); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if h, ok := seen["homepage"]; ok {
|
||||
if _, err := NewURL(h); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if d, ok := seen["documentation"]; ok {
|
||||
if _, err := NewURL(d); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a Annotations) MarshalJSON() ([]byte, error) {
|
||||
if err := a.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(annotations(a))
|
||||
}
|
||||
|
||||
func (a *Annotations) UnmarshalJSON(data []byte) error {
|
||||
var ja annotations
|
||||
if err := json.Unmarshal(data, &ja); err != nil {
|
||||
return err
|
||||
}
|
||||
na := Annotations(ja)
|
||||
if err := a.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
*a = na
|
||||
return nil
|
||||
}
|
||||
|
||||
// Retrieve the value of an annotation by the given name from Annotations, if
|
||||
// it exists.
|
||||
func (a Annotations) Get(name string) (val string, ok bool) {
|
||||
for _, anno := range a {
|
||||
if anno.Name.String() == name {
|
||||
return anno.Value, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Set sets the value of an annotation by the given name, overwriting if one already exists.
|
||||
func (a *Annotations) Set(name ACName, value string) {
|
||||
for i, anno := range *a {
|
||||
if anno.Name.Equals(name) {
|
||||
(*a)[i] = Annotation{
|
||||
Name: name,
|
||||
Value: value,
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
anno := Annotation{
|
||||
Name: name,
|
||||
Value: value,
|
||||
}
|
||||
*a = append(*a, anno)
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func makeAnno(n, v string) Annotation {
|
||||
name, err := NewACName(n)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return Annotation{
|
||||
Name: *name,
|
||||
Value: v,
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnnotationsAssertValid(t *testing.T) {
|
||||
tests := []struct {
|
||||
in []Annotation
|
||||
werr bool
|
||||
}{
|
||||
// duplicate names should fail
|
||||
{
|
||||
[]Annotation{
|
||||
makeAnno("foo", "bar"),
|
||||
makeAnno("foo", "baz"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
// bad created should fail
|
||||
{
|
||||
[]Annotation{
|
||||
makeAnno("created", "garbage"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
// bad homepage should fail
|
||||
{
|
||||
[]Annotation{
|
||||
makeAnno("homepage", "not-A$@#URL"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
// bad documentation should fail
|
||||
{
|
||||
[]Annotation{
|
||||
makeAnno("documentation", "ftp://isnotallowed.com"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
// good cases
|
||||
{
|
||||
[]Annotation{
|
||||
makeAnno("created", "2004-05-14T23:11:14+00:00"),
|
||||
makeAnno("documentation", "http://example.com/docs"),
|
||||
},
|
||||
false,
|
||||
},
|
||||
{
|
||||
[]Annotation{
|
||||
makeAnno("foo", "bar"),
|
||||
makeAnno("homepage", "https://homepage.com"),
|
||||
},
|
||||
false,
|
||||
},
|
||||
// empty is OK
|
||||
{
|
||||
[]Annotation{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
a := Annotations(tt.in)
|
||||
err := a.assertValid()
|
||||
if gerr := (err != nil); gerr != tt.werr {
|
||||
t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnnotationsSet(t *testing.T) {
|
||||
a := Annotations{}
|
||||
|
||||
a.Set("foo", "bar")
|
||||
w := Annotations{
|
||||
Annotation{ACName("foo"), "bar"},
|
||||
}
|
||||
if !reflect.DeepEqual(w, a) {
|
||||
t.Fatalf("want %v, got %v", w, a)
|
||||
}
|
||||
|
||||
a.Set("dog", "woof")
|
||||
w = Annotations{
|
||||
Annotation{ACName("foo"), "bar"},
|
||||
Annotation{ACName("dog"), "woof"},
|
||||
}
|
||||
if !reflect.DeepEqual(w, a) {
|
||||
t.Fatalf("want %v, got %v", w, a)
|
||||
}
|
||||
|
||||
a.Set("foo", "baz")
|
||||
w = Annotations{
|
||||
Annotation{ACName("foo"), "baz"},
|
||||
Annotation{ACName("dog"), "woof"},
|
||||
}
|
||||
if !reflect.DeepEqual(w, a) {
|
||||
t.Fatalf("want %v, got %v", w, a)
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
Exec Exec `json:"exec"`
|
||||
EventHandlers []EventHandler `json:"eventHandlers,omitempty"`
|
||||
User string `json:"user"`
|
||||
Group string `json:"group"`
|
||||
WorkingDirectory string `json:"workingDirectory,omitempty"`
|
||||
Environment Environment `json:"environment,omitempty"`
|
||||
MountPoints []MountPoint `json:"mountPoints,omitempty"`
|
||||
Ports []Port `json:"ports,omitempty"`
|
||||
Isolators []Isolator `json:"isolators,omitempty"`
|
||||
}
|
||||
|
||||
// app is a model to facilitate extra validation during the
|
||||
// unmarshalling of the App
|
||||
type app App
|
||||
|
||||
func (a *App) UnmarshalJSON(data []byte) error {
|
||||
ja := app{}
|
||||
err := json.Unmarshal(data, &ja)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
na := App(ja)
|
||||
if err := na.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
if na.Environment == nil {
|
||||
na.Environment = make(Environment, 0)
|
||||
}
|
||||
*a = na
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a App) MarshalJSON() ([]byte, error) {
|
||||
if err := a.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(app(a))
|
||||
}
|
||||
|
||||
func (a *App) assertValid() error {
|
||||
if err := a.Exec.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.User == "" {
|
||||
return errors.New(`User is required`)
|
||||
}
|
||||
if a.Group == "" {
|
||||
return errors.New(`Group is required`)
|
||||
}
|
||||
if !path.IsAbs(a.WorkingDirectory) && a.WorkingDirectory != "" {
|
||||
return errors.New("WorkingDirectory must be an absolute path")
|
||||
}
|
||||
eh := make(map[string]bool)
|
||||
for _, e := range a.EventHandlers {
|
||||
name := e.Name
|
||||
if eh[name] {
|
||||
return fmt.Errorf("Only one eventHandler of name %q allowed", name)
|
||||
}
|
||||
eh[name] = true
|
||||
}
|
||||
if err := a.Environment.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package types
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAppValid(t *testing.T) {
|
||||
tests := []App{
|
||||
App{
|
||||
Exec: []string{"/bin/httpd"},
|
||||
User: "0",
|
||||
Group: "0",
|
||||
WorkingDirectory: "/tmp",
|
||||
},
|
||||
App{
|
||||
Exec: []string{"/app"},
|
||||
User: "0",
|
||||
Group: "0",
|
||||
EventHandlers: []EventHandler{
|
||||
{Name: "pre-start"},
|
||||
{Name: "post-stop"},
|
||||
},
|
||||
Environment: []EnvironmentVariable{
|
||||
{Name: "DEBUG", Value: "true"},
|
||||
},
|
||||
WorkingDirectory: "/tmp",
|
||||
},
|
||||
App{
|
||||
Exec: []string{"/app", "arg1", "arg2"},
|
||||
User: "0",
|
||||
Group: "0",
|
||||
WorkingDirectory: "/tmp",
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
if err := tt.assertValid(); err != nil {
|
||||
t.Errorf("#%d: err == %v, want nil", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppExecInvalid(t *testing.T) {
|
||||
tests := []App{
|
||||
App{
|
||||
Exec: nil,
|
||||
},
|
||||
App{
|
||||
Exec: []string{},
|
||||
User: "0",
|
||||
Group: "0",
|
||||
},
|
||||
App{
|
||||
Exec: []string{"app"},
|
||||
User: "0",
|
||||
Group: "0",
|
||||
},
|
||||
App{
|
||||
Exec: []string{"bin/app", "arg1"},
|
||||
User: "0",
|
||||
Group: "0",
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
if err := tt.assertValid(); err == nil {
|
||||
t.Errorf("#%d: err == nil, want non-nil", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppEventHandlersInvalid(t *testing.T) {
|
||||
tests := []App{
|
||||
App{
|
||||
Exec: []string{"/bin/httpd"},
|
||||
User: "0",
|
||||
Group: "0",
|
||||
EventHandlers: []EventHandler{
|
||||
EventHandler{
|
||||
Name: "pre-start",
|
||||
},
|
||||
EventHandler{
|
||||
Name: "pre-start",
|
||||
},
|
||||
},
|
||||
},
|
||||
App{
|
||||
Exec: []string{"/bin/httpd"},
|
||||
User: "0",
|
||||
Group: "0",
|
||||
EventHandlers: []EventHandler{
|
||||
EventHandler{
|
||||
Name: "post-stop",
|
||||
},
|
||||
EventHandler{
|
||||
Name: "pre-start",
|
||||
},
|
||||
EventHandler{
|
||||
Name: "post-stop",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
if err := tt.assertValid(); err == nil {
|
||||
t.Errorf("#%d: err == nil, want non-nil", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserGroupInvalid(t *testing.T) {
|
||||
tests := []App{
|
||||
App{
|
||||
Exec: []string{"/app"},
|
||||
},
|
||||
App{
|
||||
Exec: []string{"/app"},
|
||||
User: "0",
|
||||
},
|
||||
App{
|
||||
Exec: []string{"app"},
|
||||
Group: "0",
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
if err := tt.assertValid(); err == nil {
|
||||
t.Errorf("#%d: err == nil, want non-nil", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppWorkingDirectoryInvalid(t *testing.T) {
|
||||
tests := []App{
|
||||
App{
|
||||
WorkingDirectory: "stuff",
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
if err := tt.assertValid(); err == nil {
|
||||
t.Errorf("#%d: err == nil, want non-nil", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppEnvironmentInvalid(t *testing.T) {
|
||||
tests := []App{
|
||||
App{
|
||||
Environment: Environment{
|
||||
EnvironmentVariable{"0DEBUG", "true"},
|
||||
},
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
if err := tt.assertValid(); err == nil {
|
||||
t.Errorf("#%d: err == nil, want non-nil", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Date wraps time.Time to marshal/unmarshal to/from JSON strings in strict
|
||||
// accordance with RFC3339
|
||||
// TODO(jonboulle): golang's implementation seems slightly buggy here;
|
||||
// according to http://tools.ietf.org/html/rfc3339#section-5.6 , applications
|
||||
// may choose to separate the date and time with a space instead of a T
|
||||
// character (for example, `date --rfc-3339` on GNU coreutils) - but this is
|
||||
// considered an error by go's parser. File a bug?
|
||||
type Date time.Time
|
||||
|
||||
func NewDate(s string) (*Date, error) {
|
||||
t, err := time.Parse(time.RFC3339, s)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bad Date: %v", err)
|
||||
}
|
||||
d := Date(t)
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
func (d Date) String() string {
|
||||
return time.Time(d).Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func (d *Date) UnmarshalJSON(data []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
nd, err := NewDate(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*d = *nd
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d Date) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(d.String())
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
pst = time.FixedZone("Pacific", -8*60*60)
|
||||
)
|
||||
|
||||
func TestUnmarshalDate(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
|
||||
wt time.Time
|
||||
}{
|
||||
{
|
||||
`"2004-05-14T23:11:14+00:00"`,
|
||||
|
||||
time.Date(2004, 05, 14, 23, 11, 14, 0, time.UTC),
|
||||
},
|
||||
{
|
||||
`"2001-02-03T04:05:06Z"`,
|
||||
|
||||
time.Date(2001, 02, 03, 04, 05, 06, 0, time.UTC),
|
||||
},
|
||||
{
|
||||
`"2014-11-14T17:36:54-08:00"`,
|
||||
|
||||
time.Date(2014, 11, 14, 17, 36, 54, 0, pst),
|
||||
},
|
||||
{
|
||||
`"2004-05-14T23:11:14+00:00"`,
|
||||
|
||||
time.Date(2004, 05, 14, 23, 11, 14, 0, time.UTC),
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
var d Date
|
||||
if err := json.Unmarshal([]byte(tt.in), &d); err != nil {
|
||||
t.Errorf("#%d: got err=%v, want nil", i, err)
|
||||
}
|
||||
if gt := time.Time(d); !gt.Equal(tt.wt) {
|
||||
t.Errorf("#%d: got time=%v, want %v", i, gt, tt.wt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalDateBad(t *testing.T) {
|
||||
tests := []string{
|
||||
`not a json string`,
|
||||
`2014-11-14T17:36:54-08:00`,
|
||||
`"garbage"`,
|
||||
`"1416015188"`,
|
||||
`"Fri Nov 14 17:53:02 PST 2014"`,
|
||||
`"2014-11-1417:36:54"`,
|
||||
}
|
||||
for i, tt := range tests {
|
||||
var d Date
|
||||
if err := json.Unmarshal([]byte(tt), &d); err == nil {
|
||||
t.Errorf("#%d: unexpected nil err", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
type Dependencies []Dependency
|
||||
|
||||
type Dependency struct {
|
||||
App ACName `json:"app"`
|
||||
ImageID *Hash `json:"imageID,omitempty"`
|
||||
Labels Labels `json:"labels,omitempty"`
|
||||
}
|
||||
|
||||
type dependency Dependency
|
||||
|
||||
func (d Dependency) assertValid() error {
|
||||
if len(d.App) < 1 {
|
||||
return errors.New(`App cannot be empty`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d Dependency) MarshalJSON() ([]byte, error) {
|
||||
if err := d.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(dependency(d))
|
||||
}
|
||||
|
||||
func (d *Dependency) UnmarshalJSON(data []byte) error {
|
||||
var jd dependency
|
||||
if err := json.Unmarshal(data, &jd); err != nil {
|
||||
return err
|
||||
}
|
||||
nd := Dependency(jd)
|
||||
if err := nd.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
*d = nd
|
||||
return nil
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package types
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEmptyHash(t *testing.T) {
|
||||
dj := `{"app": "example.com/reduce-worker-base"}`
|
||||
|
||||
var d Dependency
|
||||
|
||||
err := d.UnmarshalJSON([]byte(dj))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Marshal to verify that marshalling works without validation errors
|
||||
buf, err := d.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Unmarshal to verify that the generated json will not create wrong empty hash
|
||||
err = d.UnmarshalJSON(buf)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
// Package types contains structs representing the various types in the app
|
||||
// container specification. It is used by the [schema manifest types](../)
|
||||
// to enforce validation.
|
||||
package types
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
var (
|
||||
envPattern = regexp.MustCompile("^[A-Za-z_][A-Za-z_0-9]*$")
|
||||
)
|
||||
|
||||
type Environment []EnvironmentVariable
|
||||
|
||||
type environment Environment
|
||||
|
||||
type EnvironmentVariable struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func (ev EnvironmentVariable) assertValid() error {
|
||||
if len(ev.Name) == 0 {
|
||||
return fmt.Errorf(`environment variable name must not be empty`)
|
||||
}
|
||||
if !envPattern.MatchString(ev.Name) {
|
||||
return fmt.Errorf(`environment variable does not have valid identifier %q`, ev.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e Environment) assertValid() error {
|
||||
seen := map[string]bool{}
|
||||
for _, env := range e {
|
||||
if err := env.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, ok := seen[env.Name]
|
||||
if ok {
|
||||
return fmt.Errorf(`duplicate environment variable of name %q`, env.Name)
|
||||
}
|
||||
seen[env.Name] = true
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e Environment) MarshalJSON() ([]byte, error) {
|
||||
if err := e.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(environment(e))
|
||||
}
|
||||
|
||||
func (e *Environment) UnmarshalJSON(data []byte) error {
|
||||
var je environment
|
||||
if err := json.Unmarshal(data, &je); err != nil {
|
||||
return err
|
||||
}
|
||||
ne := Environment(je)
|
||||
if err := ne.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
*e = ne
|
||||
return nil
|
||||
}
|
||||
|
||||
// Retrieve the value of an environment variable by the given name from
|
||||
// Environment, if it exists.
|
||||
func (e Environment) Get(name string) (value string, ok bool) {
|
||||
for _, env := range e {
|
||||
if env.Name == name {
|
||||
return env.Value, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Set sets the value of an environment variable by the given name,
|
||||
// overwriting if one already exists.
|
||||
func (e *Environment) Set(name string, value string) {
|
||||
for i, env := range *e {
|
||||
if env.Name == name {
|
||||
(*e)[i] = EnvironmentVariable{
|
||||
Name: name,
|
||||
Value: value,
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
env := EnvironmentVariable{
|
||||
Name: name,
|
||||
Value: value,
|
||||
}
|
||||
*e = append(*e, env)
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnvironmentAssertValid(t *testing.T) {
|
||||
tests := []struct {
|
||||
env Environment
|
||||
werr bool
|
||||
}{
|
||||
// duplicate names should fail
|
||||
{
|
||||
Environment{
|
||||
EnvironmentVariable{"DEBUG", "true"},
|
||||
EnvironmentVariable{"DEBUG", "true"},
|
||||
},
|
||||
true,
|
||||
},
|
||||
// empty name should fail
|
||||
{
|
||||
Environment{
|
||||
EnvironmentVariable{"", "value"},
|
||||
},
|
||||
true,
|
||||
},
|
||||
// name beginning with digit should fail
|
||||
{
|
||||
Environment{
|
||||
EnvironmentVariable{"0DEBUG", "true"},
|
||||
},
|
||||
true,
|
||||
},
|
||||
// name with non [A-Za-z0-9_] should fail
|
||||
{
|
||||
Environment{
|
||||
EnvironmentVariable{"VERBOSE-DEBUG", "true"},
|
||||
},
|
||||
true,
|
||||
},
|
||||
// accepted environment variable forms
|
||||
{
|
||||
Environment{
|
||||
EnvironmentVariable{"DEBUG", "true"},
|
||||
},
|
||||
false,
|
||||
},
|
||||
{
|
||||
Environment{
|
||||
EnvironmentVariable{"_0_DEBUG_0_", "true"},
|
||||
},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for i, test := range tests {
|
||||
env := Environment(test.env)
|
||||
err := env.assertValid()
|
||||
if gerr := (err != nil); gerr != test.werr {
|
||||
t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, test.werr, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package types
|
||||
|
||||
// An ACKindError is returned when the wrong ACKind is set in a manifest
|
||||
type ACKindError string
|
||||
|
||||
func (e ACKindError) Error() string {
|
||||
return string(e)
|
||||
}
|
||||
|
||||
// An ACVersionError is returned when a bad ACVersion is set in a manifest
|
||||
type ACVersionError string
|
||||
|
||||
func (e ACVersionError) Error() string {
|
||||
return string(e)
|
||||
}
|
||||
|
||||
// An ACNameError is returned when a bad value is used for an ACName
|
||||
type ACNameError string
|
||||
|
||||
func (e ACNameError) Error() string {
|
||||
return string(e)
|
||||
}
|
||||
|
||||
// An AMStartedOnError is returned when the wrong StartedOn is set in an ImageManifest
|
||||
type AMStartedOnError string
|
||||
|
||||
func (e AMStartedOnError) Error() string {
|
||||
return string(e)
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type EventHandler struct {
|
||||
Name string `json:"name"`
|
||||
Exec Exec `json:"exec"`
|
||||
}
|
||||
|
||||
type eventHandler EventHandler
|
||||
|
||||
func (e EventHandler) assertValid() error {
|
||||
s := e.Name
|
||||
switch s {
|
||||
case "pre-start", "post-stop":
|
||||
return nil
|
||||
case "":
|
||||
return errors.New(`eventHandler "name" cannot be empty`)
|
||||
default:
|
||||
return fmt.Errorf(`bad eventHandler "name": %q`, s)
|
||||
}
|
||||
}
|
||||
|
||||
func (e EventHandler) MarshalJSON() ([]byte, error) {
|
||||
if err := e.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(eventHandler(e))
|
||||
}
|
||||
|
||||
func (e *EventHandler) UnmarshalJSON(data []byte) error {
|
||||
var je eventHandler
|
||||
err := json.Unmarshal(data, &je)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ne := EventHandler(je)
|
||||
if err := ne.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
*e = ne
|
||||
return nil
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type Exec []string
|
||||
|
||||
type exec Exec
|
||||
|
||||
func (e Exec) assertValid() error {
|
||||
if len(e) < 1 {
|
||||
return errors.New(`Exec cannot be empty`)
|
||||
}
|
||||
if !filepath.IsAbs(e[0]) {
|
||||
return errors.New(`Exec[0] must be absolute path`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e Exec) MarshalJSON() ([]byte, error) {
|
||||
if err := e.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(exec(e))
|
||||
}
|
||||
|
||||
func (e *Exec) UnmarshalJSON(data []byte) error {
|
||||
var je exec
|
||||
err := json.Unmarshal(data, &je)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ne := Exec(je)
|
||||
if err := ne.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
*e = ne
|
||||
return nil
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package types
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestExecValid(t *testing.T) {
|
||||
tests := []Exec{
|
||||
Exec{"/bin/httpd"},
|
||||
Exec{"/app"},
|
||||
Exec{"/app", "arg1", "arg2"},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
if err := tt.assertValid(); err != nil {
|
||||
t.Errorf("#%d: err == %v, want nil", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecInvalid(t *testing.T) {
|
||||
tests := []Exec{
|
||||
Exec{},
|
||||
Exec{"app"},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
if err := tt.assertValid(); err == nil {
|
||||
t.Errorf("#%d: err == nil, want non-nil", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"crypto/sha512"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
maxHashSize = (sha512.Size / 2) + len("sha512-")
|
||||
)
|
||||
|
||||
// Hash encodes a hash specified in a string of the form:
|
||||
// "<type>-<value>"
|
||||
// for example
|
||||
// "sha512-06c733b1838136838e6d2d3e8fa5aea4c7905e92[...]"
|
||||
// Valid types are currently:
|
||||
// * sha512
|
||||
type Hash struct {
|
||||
typ string
|
||||
Val string
|
||||
}
|
||||
|
||||
func NewHash(s string) (*Hash, error) {
|
||||
elems := strings.Split(s, "-")
|
||||
if len(elems) != 2 {
|
||||
return nil, errors.New("badly formatted hash string")
|
||||
}
|
||||
nh := Hash{
|
||||
typ: elems[0],
|
||||
Val: elems[1],
|
||||
}
|
||||
if err := nh.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &nh, nil
|
||||
}
|
||||
|
||||
func (h Hash) String() string {
|
||||
return fmt.Sprintf("%s-%s", h.typ, h.Val)
|
||||
}
|
||||
|
||||
func (h *Hash) Set(s string) error {
|
||||
nh, err := NewHash(s)
|
||||
if err == nil {
|
||||
*h = *nh
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (h Hash) Empty() bool {
|
||||
return reflect.DeepEqual(h, Hash{})
|
||||
}
|
||||
|
||||
func (h Hash) assertValid() error {
|
||||
switch h.typ {
|
||||
case "sha512":
|
||||
case "":
|
||||
return fmt.Errorf("unexpected empty hash type")
|
||||
default:
|
||||
return fmt.Errorf("unrecognized hash type: %v", h.typ)
|
||||
}
|
||||
if h.Val == "" {
|
||||
return fmt.Errorf("unexpected empty hash value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Hash) UnmarshalJSON(data []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
nh, err := NewHash(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*h = *nh
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h Hash) MarshalJSON() ([]byte, error) {
|
||||
if err := h.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(h.String())
|
||||
}
|
||||
|
||||
func NewHashSHA512(b []byte) *Hash {
|
||||
h := sha512.New()
|
||||
h.Write(b)
|
||||
nh, _ := NewHash(fmt.Sprintf("sha512-%x", h.Sum(nil)))
|
||||
return nh
|
||||
}
|
||||
|
||||
func ShortHash(hash string) string {
|
||||
if len(hash) > maxHashSize {
|
||||
return hash[:maxHashSize]
|
||||
}
|
||||
return hash
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMarshalHash(t *testing.T) {
|
||||
tests := []struct {
|
||||
typ string
|
||||
val string
|
||||
|
||||
wout string
|
||||
}{
|
||||
{
|
||||
"sha512",
|
||||
"abcdefghi",
|
||||
|
||||
`"sha512-abcdefghi"`,
|
||||
},
|
||||
{
|
||||
"sha512",
|
||||
"06c733b1838136838e6d2d3e8fa5aea4c7905e92",
|
||||
|
||||
`"sha512-06c733b1838136838e6d2d3e8fa5aea4c7905e92"`,
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
h := Hash{
|
||||
typ: tt.typ,
|
||||
Val: tt.val,
|
||||
}
|
||||
b, err := json.Marshal(h)
|
||||
if err != nil {
|
||||
t.Errorf("#%d: unexpected err=%v", i, err)
|
||||
}
|
||||
if g := string(b); g != tt.wout {
|
||||
t.Errorf("#%d: got string=%v, want %v", i, g, tt.wout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarshalHashBad(t *testing.T) {
|
||||
tests := []struct {
|
||||
typ string
|
||||
val string
|
||||
}{
|
||||
{
|
||||
// empty value
|
||||
"sha512",
|
||||
"",
|
||||
},
|
||||
{
|
||||
// bad type
|
||||
"sha1",
|
||||
"abcdef",
|
||||
},
|
||||
{
|
||||
// empty type
|
||||
"",
|
||||
"abcdef",
|
||||
},
|
||||
{
|
||||
// empty empty
|
||||
"",
|
||||
"",
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
h := Hash{
|
||||
typ: tt.typ,
|
||||
Val: tt.val,
|
||||
}
|
||||
g, err := json.Marshal(h)
|
||||
if err == nil {
|
||||
t.Errorf("#%d: unexpected nil err", i)
|
||||
}
|
||||
if g != nil {
|
||||
t.Errorf("#%d: unexpected non-nil bytes: %v", i, g)
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package types
|
||||
|
||||
type Isolator struct {
|
||||
Name ACName `json:"name"`
|
||||
Val string `json:"value"`
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
var ValidOSArch = map[string][]string{
|
||||
"linux": {"amd64", "i386"},
|
||||
"freebsd": {"amd64", "i386", "arm"},
|
||||
"darwin": {"x86_64", "i386"},
|
||||
}
|
||||
|
||||
type Labels []Label
|
||||
|
||||
type labels Labels
|
||||
|
||||
type Label struct {
|
||||
Name ACName `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func (l Labels) assertValid() error {
|
||||
seen := map[ACName]string{}
|
||||
for _, lbl := range l {
|
||||
if lbl.Name == "name" {
|
||||
return fmt.Errorf(`invalid label name: "name"`)
|
||||
}
|
||||
_, ok := seen[lbl.Name]
|
||||
if ok {
|
||||
return fmt.Errorf(`duplicate labels of name %q`, lbl.Name)
|
||||
}
|
||||
seen[lbl.Name] = lbl.Value
|
||||
}
|
||||
if os, ok := seen["os"]; ok {
|
||||
if validArchs, ok := ValidOSArch[os]; !ok {
|
||||
// Not a whitelisted OS. TODO: how to warn rather than fail?
|
||||
validOses := make([]string, 0, len(ValidOSArch))
|
||||
for validOs := range ValidOSArch {
|
||||
validOses = append(validOses, validOs)
|
||||
}
|
||||
sort.Strings(validOses)
|
||||
return fmt.Errorf(`bad os %#v (must be one of: %v)`, os, validOses)
|
||||
} else {
|
||||
// Whitelisted OS. We check arch here, as arch makes sense only
|
||||
// when os is defined.
|
||||
if arch, ok := seen["arch"]; ok {
|
||||
found := false
|
||||
for _, validArch := range validArchs {
|
||||
if arch == validArch {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf(`bad arch %#v for %v (must be one of: %v)`, arch, os, validArchs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l Labels) MarshalJSON() ([]byte, error) {
|
||||
if err := l.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(labels(l))
|
||||
}
|
||||
|
||||
func (l *Labels) UnmarshalJSON(data []byte) error {
|
||||
var jl labels
|
||||
if err := json.Unmarshal(data, &jl); err != nil {
|
||||
return err
|
||||
}
|
||||
nl := Labels(jl)
|
||||
if err := nl.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
*l = nl
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get retrieves the value of the label by the given name from Labels, if it exists
|
||||
func (l Labels) Get(name string) (val string, ok bool) {
|
||||
for _, lbl := range l {
|
||||
if lbl.Name.String() == name {
|
||||
return lbl.Value, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLabels(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
errPrefix string
|
||||
}{
|
||||
{
|
||||
`[{"name": "os", "value": "linux"}, {"name": "arch", "value": "amd64"}]`,
|
||||
"",
|
||||
},
|
||||
{
|
||||
`[{"name": "os", "value": "freebsd"}, {"name": "arch", "value": "amd64"}]`,
|
||||
"",
|
||||
},
|
||||
{
|
||||
`[{"name": "os", "value": "OS/360"}, {"name": "arch", "value": "S/360"}]`,
|
||||
`bad os "OS/360"`,
|
||||
},
|
||||
{
|
||||
`[{"name": "os", "value": "linux"}, {"name": "arch", "value": "arm"}]`,
|
||||
`bad arch "arm" for linux`,
|
||||
},
|
||||
{
|
||||
`[{"name": "name"}]`,
|
||||
`invalid label name: "name"`,
|
||||
},
|
||||
{
|
||||
`[{"name": "os", "value": "linux"}, {"name": "os", "value": "freebsd"}]`,
|
||||
`duplicate labels of name "os"`,
|
||||
},
|
||||
{
|
||||
`[{"name": "arch", "value": "amd64"}, {"name": "os", "value": "freebsd"}, {"name": "arch", "value": "x86_64"}]`,
|
||||
`duplicate labels of name "arch"`,
|
||||
},
|
||||
{
|
||||
`[]`,
|
||||
"",
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
var l Labels
|
||||
if err := json.Unmarshal([]byte(tt.in), &l); err != nil {
|
||||
if tt.errPrefix == "" {
|
||||
t.Errorf("#%d: got err=%v, expected no error", i, err)
|
||||
} else if !strings.HasPrefix(err.Error(), tt.errPrefix) {
|
||||
t.Errorf("#%d: got err=%v, expected prefix %#v", i, err, tt.errPrefix)
|
||||
}
|
||||
} else {
|
||||
t.Log(l)
|
||||
if tt.errPrefix != "" {
|
||||
t.Errorf("#%d: got no err, expected prefix %#v", i, tt.errPrefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package types
|
||||
|
||||
type MountPoint struct {
|
||||
Name ACName `json:"name"`
|
||||
Path string `json:"path"`
|
||||
ReadOnly bool `json:"readOnly,omitempty"`
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package types
|
||||
|
||||
type Port struct {
|
||||
Name ACName `json:"name"`
|
||||
Protocol string `json:"protocol"`
|
||||
Port uint `json:"port"`
|
||||
SocketActivated bool `json:"socketActivated"`
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNoZeroSemVer = ACVersionError("SemVer cannot be zero")
|
||||
ErrBadSemVer = ACVersionError("SemVer is bad")
|
||||
)
|
||||
|
||||
// SemVer implements the Unmarshaler interface to define a field that must be
|
||||
// a semantic version string
|
||||
// TODO(jonboulle): extend upstream instead of wrapping?
|
||||
type SemVer semver.Version
|
||||
|
||||
// NewSemVer generates a new SemVer from a string. If the given string does
|
||||
// not represent a valid SemVer, nil and an error are returned.
|
||||
func NewSemVer(s string) (*SemVer, error) {
|
||||
nsv, err := semver.NewVersion(s)
|
||||
if err != nil {
|
||||
return nil, ErrBadSemVer
|
||||
}
|
||||
v := SemVer(*nsv)
|
||||
if v.Empty() {
|
||||
return nil, ErrNoZeroSemVer
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
func (sv SemVer) String() string {
|
||||
s := semver.Version(sv)
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func (sv SemVer) Empty() bool {
|
||||
return semver.Version(sv) == semver.Version{}
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the json.Unmarshaler interface
|
||||
func (sv *SemVer) UnmarshalJSON(data []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
v, err := NewSemVer(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*sv = *v
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements the json.Marshaler interface
|
||||
func (sv SemVer) MarshalJSON() ([]byte, error) {
|
||||
if sv.Empty() {
|
||||
return nil, ErrNoZeroSemVer
|
||||
}
|
||||
return json.Marshal(sv.String())
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
|
||||
)
|
||||
|
||||
func TestMarshalSemver(t *testing.T) {
|
||||
tests := []struct {
|
||||
sv SemVer
|
||||
|
||||
wd []byte
|
||||
}{
|
||||
{
|
||||
SemVer(semver.Version{Major: 1}),
|
||||
|
||||
[]byte(`"1.0.0"`),
|
||||
},
|
||||
{
|
||||
SemVer(semver.Version{Major: 3, Minor: 2, Patch: 1}),
|
||||
|
||||
[]byte(`"3.2.1"`),
|
||||
},
|
||||
{
|
||||
SemVer(semver.Version{Major: 3, Minor: 2, Patch: 1, PreRelease: "foo"}),
|
||||
|
||||
[]byte(`"3.2.1-foo"`),
|
||||
},
|
||||
{
|
||||
SemVer(semver.Version{Major: 1, Minor: 2, Patch: 3, PreRelease: "alpha", Metadata: "git"}),
|
||||
|
||||
[]byte(`"1.2.3-alpha+git"`),
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
d, err := json.Marshal(tt.sv)
|
||||
if !reflect.DeepEqual(d, tt.wd) {
|
||||
t.Errorf("#%d: d=%v, want %v", i, string(d), string(tt.wd))
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("#%d: err=%v, want nil", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalSemver(t *testing.T) {
|
||||
tests := []struct {
|
||||
d []byte
|
||||
|
||||
wsv SemVer
|
||||
werr bool
|
||||
}{
|
||||
{
|
||||
[]byte(`"1.0.0"`),
|
||||
|
||||
SemVer(semver.Version{Major: 1}),
|
||||
false,
|
||||
},
|
||||
{
|
||||
[]byte(`"3.2.1"`),
|
||||
SemVer(semver.Version{Major: 3, Minor: 2, Patch: 1}),
|
||||
|
||||
false,
|
||||
},
|
||||
{
|
||||
[]byte(`"3.2.1-foo"`),
|
||||
|
||||
SemVer(semver.Version{Major: 3, Minor: 2, Patch: 1, PreRelease: "foo"}),
|
||||
false,
|
||||
},
|
||||
{
|
||||
[]byte(`"1.2.3-alpha+git"`),
|
||||
|
||||
SemVer(semver.Version{Major: 1, Minor: 2, Patch: 3, PreRelease: "alpha", Metadata: "git"}),
|
||||
false,
|
||||
},
|
||||
{
|
||||
[]byte(`"1"`),
|
||||
|
||||
SemVer{},
|
||||
true,
|
||||
},
|
||||
{
|
||||
[]byte(`"1.2.3.4"`),
|
||||
|
||||
SemVer{},
|
||||
true,
|
||||
},
|
||||
{
|
||||
[]byte(`1.2.3`),
|
||||
|
||||
SemVer{},
|
||||
true,
|
||||
},
|
||||
{
|
||||
[]byte(`"v1.2.3"`),
|
||||
|
||||
SemVer{},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
var sv SemVer
|
||||
err := json.Unmarshal(tt.d, &sv)
|
||||
if !reflect.DeepEqual(sv, tt.wsv) {
|
||||
t.Errorf("#%d: semver=%#v, want %#v", i, sv, tt.wsv)
|
||||
}
|
||||
if gerr := (err != nil); gerr != tt.werr {
|
||||
t.Errorf("#%d: err==%v, want errstate %t", i, err, tt.werr)
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// URL wraps url.URL to marshal/unmarshal to/from JSON strings and enforce
|
||||
// that the scheme is HTTP/HTTPS only
|
||||
type URL url.URL
|
||||
|
||||
func NewURL(s string) (*URL, error) {
|
||||
uu, err := url.Parse(s)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bad URL: %v", err)
|
||||
}
|
||||
nu := URL(*uu)
|
||||
if err := nu.assertValidScheme(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &nu, nil
|
||||
}
|
||||
|
||||
func (u URL) String() string {
|
||||
uu := url.URL(u)
|
||||
return uu.String()
|
||||
}
|
||||
|
||||
func (u URL) assertValidScheme() error {
|
||||
switch u.Scheme {
|
||||
case "http", "https":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("bad URL scheme, must be http/https")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *URL) UnmarshalJSON(data []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
nu, err := NewURL(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*u = *nu
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u URL) MarshalJSON() ([]byte, error) {
|
||||
if err := u.assertValidScheme(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(u.String())
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func mustParseURL(t *testing.T, s string) url.URL {
|
||||
u, err := url.Parse(s)
|
||||
if err != nil {
|
||||
t.Fatalf("error parsing URL: %v", err)
|
||||
}
|
||||
return *u
|
||||
}
|
||||
|
||||
func TestMarshalURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
u url.URL
|
||||
|
||||
w string
|
||||
}{
|
||||
{
|
||||
mustParseURL(t, "http://foo.com"),
|
||||
|
||||
`"http://foo.com"`,
|
||||
},
|
||||
{
|
||||
mustParseURL(t, "http://foo.com/huh/what?is=this"),
|
||||
|
||||
`"http://foo.com/huh/what?is=this"`,
|
||||
},
|
||||
{
|
||||
mustParseURL(t, "https://example.com/bar"),
|
||||
|
||||
`"https://example.com/bar"`,
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
u := URL(tt.u)
|
||||
b, err := json.Marshal(u)
|
||||
if g := string(b); g != tt.w {
|
||||
t.Errorf("#%d: got %q, want %q", i, g, tt.w)
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("#%d: err=%v, want nil", i, err)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarshalURLBad(t *testing.T) {
|
||||
tests := []url.URL{
|
||||
mustParseURL(t, "ftp://foo.com"),
|
||||
mustParseURL(t, "unix:///hello"),
|
||||
}
|
||||
for i, tt := range tests {
|
||||
u := URL(tt)
|
||||
b, err := json.Marshal(u)
|
||||
if b != nil {
|
||||
t.Errorf("#%d: got %v, want nil", i, b)
|
||||
}
|
||||
if err == nil {
|
||||
t.Errorf("#%d: got unexpected err=nil", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
|
||||
w URL
|
||||
}{
|
||||
{
|
||||
`"http://foo.com"`,
|
||||
|
||||
URL(mustParseURL(t, "http://foo.com")),
|
||||
},
|
||||
{
|
||||
`"http://yis.com/hello?goodbye=yes"`,
|
||||
|
||||
URL(mustParseURL(t, "http://yis.com/hello?goodbye=yes")),
|
||||
},
|
||||
{
|
||||
`"https://ohai.net"`,
|
||||
|
||||
URL(mustParseURL(t, "https://ohai.net")),
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
var g URL
|
||||
err := json.Unmarshal([]byte(tt.in), &g)
|
||||
if err != nil {
|
||||
t.Errorf("#%d: want err=nil, got %v", i, err)
|
||||
}
|
||||
if !reflect.DeepEqual(g, tt.w) {
|
||||
t.Errorf("#%d: got url=%v, want %v", i, g, tt.w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalURLBad(t *testing.T) {
|
||||
var empty = URL{}
|
||||
tests := []string{
|
||||
"badjson",
|
||||
"http://google.com",
|
||||
`"ftp://example.com"`,
|
||||
`"unix://file.net"`,
|
||||
`"not a url"`,
|
||||
}
|
||||
for i, tt := range tests {
|
||||
var g URL
|
||||
err := json.Unmarshal([]byte(tt), &g)
|
||||
if err == nil {
|
||||
t.Errorf("#%d: want err, got nil", i)
|
||||
}
|
||||
if !reflect.DeepEqual(g, empty) {
|
||||
t.Errorf("#%d: got %v, want %v", i, g, empty)
|
||||
}
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNoEmptyUUID = errors.New("UUID cannot be empty")
|
||||
)
|
||||
|
||||
// UUID encodes an RFC4122-compliant UUID, marshaled to/from a string
|
||||
// TODO(jonboulle): vendor a package for this?
|
||||
// TODO(jonboulle): consider more flexibility in input string formats.
|
||||
// Right now, we only accept:
|
||||
// "6733C088-A507-4694-AABF-EDBE4FC5266F"
|
||||
// "6733C088A5074694AABFEDBE4FC5266F"
|
||||
type UUID [16]byte
|
||||
|
||||
func (u UUID) String() string {
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:16])
|
||||
}
|
||||
|
||||
func (u *UUID) Set(s string) error {
|
||||
nu, err := NewUUID(s)
|
||||
if err == nil {
|
||||
*u = *nu
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// NewUUID generates a new UUID from the given string. If the string does not
|
||||
// represent a valid UUID, nil and an error are returned.
|
||||
func NewUUID(s string) (*UUID, error) {
|
||||
s = strings.Replace(s, "-", "", -1)
|
||||
if len(s) != 32 {
|
||||
return nil, errors.New("bad UUID length != 32")
|
||||
}
|
||||
dec, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var u UUID
|
||||
for i, b := range dec {
|
||||
u[i] = b
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (u UUID) Empty() bool {
|
||||
return reflect.DeepEqual(u, UUID{})
|
||||
}
|
||||
|
||||
func (u *UUID) UnmarshalJSON(data []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
uu, err := NewUUID(s)
|
||||
if uu.Empty() {
|
||||
return ErrNoEmptyUUID
|
||||
}
|
||||
if err == nil {
|
||||
*u = *uu
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (u UUID) MarshalJSON() ([]byte, error) {
|
||||
if u.Empty() {
|
||||
return nil, ErrNoEmptyUUID
|
||||
}
|
||||
return json.Marshal(u.String())
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package types
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewUUID(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
ws string
|
||||
}{
|
||||
{
|
||||
"6733C088-A507-4694-AABF-EDBE4FC5266F",
|
||||
|
||||
"6733c088-a507-4694-aabf-edbe4fc5266f",
|
||||
},
|
||||
{
|
||||
"6733C088A5074694AABFEDBE4FC5266F",
|
||||
|
||||
"6733c088-a507-4694-aabf-edbe4fc5266f",
|
||||
},
|
||||
{
|
||||
"0aaf0a79-1a39-4d59-abbf-1bebca8209d2",
|
||||
|
||||
"0aaf0a79-1a39-4d59-abbf-1bebca8209d2",
|
||||
},
|
||||
{
|
||||
"0aaf0a791a394d59abbf1bebca8209d2",
|
||||
|
||||
"0aaf0a79-1a39-4d59-abbf-1bebca8209d2",
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
gu, err := NewUUID(tt.in)
|
||||
if err != nil {
|
||||
t.Errorf("#%d: err=%v, want %v", i, err, nil)
|
||||
}
|
||||
if gs := gu.String(); gs != tt.ws {
|
||||
t.Errorf("#%d: String()=%v, want %v", i, gs, tt.ws)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewUUIDBad(t *testing.T) {
|
||||
tests := []string{
|
||||
"asdf",
|
||||
"0AAF0A79-1A39-4D59-ABBF-1BEBCA8209D2ABC",
|
||||
"",
|
||||
}
|
||||
for i, tt := range tests {
|
||||
g, err := NewUUID(tt)
|
||||
if err == nil {
|
||||
t.Errorf("#%d: err=nil, want non-nil", i)
|
||||
}
|
||||
if g != nil {
|
||||
t.Errorf("#%d: err=%v, want %v", i, g, nil)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Volume encapsulates a volume which should be mounted into the filesystem
|
||||
// of all apps in a ContainerRuntimeManifest
|
||||
type Volume struct {
|
||||
Name ACName `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
|
||||
// currently used only by "host"
|
||||
// TODO(jonboulle): factor out?
|
||||
Source string `json:"source,omitempty"`
|
||||
ReadOnly bool `json:"readOnly,omitempty"`
|
||||
}
|
||||
|
||||
type volume Volume
|
||||
|
||||
func (v Volume) assertValid() error {
|
||||
if v.Name.Empty() {
|
||||
return errors.New("name must be set")
|
||||
}
|
||||
|
||||
switch v.Kind {
|
||||
case "empty":
|
||||
if v.Source != "" {
|
||||
return errors.New("source for empty volume must be empty")
|
||||
}
|
||||
return nil
|
||||
case "host":
|
||||
if v.Source == "" {
|
||||
return errors.New("source for host volume cannot be empty")
|
||||
}
|
||||
if !filepath.IsAbs(v.Source) {
|
||||
return errors.New("source for host volume must be absolute path")
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return errors.New(`unrecognized volume kind: should be one of "empty", "host"`)
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Volume) UnmarshalJSON(data []byte) error {
|
||||
var vv volume
|
||||
if err := json.Unmarshal(data, &vv); err != nil {
|
||||
return err
|
||||
}
|
||||
nv := Volume(vv)
|
||||
if err := nv.assertValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
*v = nv
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v Volume) MarshalJSON() ([]byte, error) {
|
||||
if err := v.assertValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(volume(v))
|
||||
}
|
||||
|
||||
func (v Volume) String() string {
|
||||
s := fmt.Sprintf("%s,kind=%s,readOnly=%t", v.Name, v.Kind, v.ReadOnly)
|
||||
if v.Source != "" {
|
||||
s = s + fmt.Sprintf("source=%s", v.Source)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// VolumeFromString takes a command line volume parameter and returns a volume
|
||||
//
|
||||
// Example volume parameters:
|
||||
// database,kind=host,source=/tmp,readOnly=true
|
||||
func VolumeFromString(vp string) (*Volume, error) {
|
||||
var vol Volume
|
||||
|
||||
vp = "name=" + vp
|
||||
v, err := url.ParseQuery(strings.Replace(vp, ",", "&", -1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for key, val := range v {
|
||||
if len(val) > 1 {
|
||||
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
|
||||
}
|
||||
|
||||
// TOOD(philips): make this less hardcoded
|
||||
switch key {
|
||||
case "name":
|
||||
acn, err := NewACName(val[0])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vol.Name = *acn
|
||||
case "kind":
|
||||
vol.Kind = val[0]
|
||||
case "source":
|
||||
vol.Source = val[0]
|
||||
case "readOnly":
|
||||
ro, err := strconv.ParseBool(val[0])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vol.ReadOnly = ro
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown volume parameter %q", key)
|
||||
}
|
||||
}
|
||||
err = vol.assertValid()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &vol, nil
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestVolumeFromString(t *testing.T) {
|
||||
tests := []struct {
|
||||
s string
|
||||
v Volume
|
||||
}{
|
||||
{
|
||||
"foobar,kind=host,source=/tmp",
|
||||
Volume{
|
||||
Name: "foobar",
|
||||
Kind: "host",
|
||||
Source: "/tmp",
|
||||
ReadOnly: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
"foobar,kind=host,source=/tmp,readOnly=true",
|
||||
Volume{
|
||||
Name: "foobar",
|
||||
Kind: "host",
|
||||
Source: "/tmp",
|
||||
ReadOnly: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
"foobar,kind=empty",
|
||||
Volume{
|
||||
Name: "foobar",
|
||||
Kind: "empty",
|
||||
},
|
||||
},
|
||||
{
|
||||
"foobar,kind=empty,readOnly=true",
|
||||
Volume{
|
||||
Name: "foobar",
|
||||
Kind: "empty",
|
||||
ReadOnly: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
v, err := VolumeFromString(tt.s)
|
||||
if err != nil {
|
||||
t.Errorf("#%d: got err=%v, want nil", i, err)
|
||||
}
|
||||
if !reflect.DeepEqual(*v, tt.v) {
|
||||
t.Errorf("#%d: v=%v, want %v", i, *v, tt.v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumeFromStringBad(t *testing.T) {
|
||||
tests := []string{
|
||||
"#foobar,kind=host,source=/tmp",
|
||||
"foobar,kind=host,source=/tmp,readOnly=true,asdf=asdf",
|
||||
"foobar,kind=empty,source=/tmp",
|
||||
}
|
||||
for i, in := range tests {
|
||||
l, err := VolumeFromString(in)
|
||||
if l != nil {
|
||||
t.Errorf("#%d: got l=%v, want nil", i, l)
|
||||
}
|
||||
if err == nil {
|
||||
t.Errorf("#%d: got err=nil, want non-nil", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
|
||||
)
|
||||
|
||||
const (
|
||||
// version represents the canonical version of the appc spec and tooling.
|
||||
// For now, the schema and tooling is coupled with the spec itself, so
|
||||
// this must be kept in sync with the VERSION file in the root of the repo.
|
||||
version string = "0.2.0+git"
|
||||
)
|
||||
|
||||
var (
|
||||
// AppContainerVersion is the SemVer representation of version
|
||||
AppContainerVersion types.SemVer
|
||||
)
|
||||
|
||||
func init() {
|
||||
v, err := types.NewSemVer(version)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
AppContainerVersion = *v
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
// Copyright 2012 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package atom provides integer codes (also known as atoms) for a fixed set of
|
||||
// frequently occurring HTML strings: tag names and attribute keys such as "p"
|
||||
// and "id".
|
||||
//
|
||||
// Sharing an atom's name between all elements with the same tag can result in
|
||||
// fewer string allocations when tokenizing and parsing HTML. Integer
|
||||
// comparisons are also generally faster than string comparisons.
|
||||
//
|
||||
// The value of an atom's particular code is not guaranteed to stay the same
|
||||
// between versions of this package. Neither is any ordering guaranteed:
|
||||
// whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to
|
||||
// be dense. The only guarantees are that e.g. looking up "div" will yield
|
||||
// atom.Div, calling atom.Div.String will return "div", and atom.Div != 0.
|
||||
package atom // import "golang.org/x/net/html/atom"
|
||||
|
||||
// Atom is an integer code for a string. The zero value maps to "".
|
||||
type Atom uint32
|
||||
|
||||
// String returns the atom's name.
|
||||
func (a Atom) String() string {
|
||||
start := uint32(a >> 8)
|
||||
n := uint32(a & 0xff)
|
||||
if start+n > uint32(len(atomText)) {
|
||||
return ""
|
||||
}
|
||||
return atomText[start : start+n]
|
||||
}
|
||||
|
||||
func (a Atom) string() string {
|
||||
return atomText[a>>8 : a>>8+a&0xff]
|
||||
}
|
||||
|
||||
// fnv computes the FNV hash with an arbitrary starting value h.
|
||||
func fnv(h uint32, s []byte) uint32 {
|
||||
for i := range s {
|
||||
h ^= uint32(s[i])
|
||||
h *= 16777619
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func match(s string, t []byte) bool {
|
||||
for i, c := range t {
|
||||
if s[i] != c {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Lookup returns the atom whose name is s. It returns zero if there is no
|
||||
// such atom. The lookup is case sensitive.
|
||||
func Lookup(s []byte) Atom {
|
||||
if len(s) == 0 || len(s) > maxAtomLen {
|
||||
return 0
|
||||
}
|
||||
h := fnv(hash0, s)
|
||||
if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) {
|
||||
return a
|
||||
}
|
||||
if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) {
|
||||
return a
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// String returns a string whose contents are equal to s. In that sense, it is
|
||||
// equivalent to string(s) but may be more efficient.
|
||||
func String(s []byte) string {
|
||||
if a := Lookup(s); a != 0 {
|
||||
return a.String()
|
||||
}
|
||||
return string(s)
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
// Copyright 2012 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package atom
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestKnown(t *testing.T) {
|
||||
for _, s := range testAtomList {
|
||||
if atom := Lookup([]byte(s)); atom.String() != s {
|
||||
t.Errorf("Lookup(%q) = %#x (%q)", s, uint32(atom), atom.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHits(t *testing.T) {
|
||||
for _, a := range table {
|
||||
if a == 0 {
|
||||
continue
|
||||
}
|
||||
got := Lookup([]byte(a.String()))
|
||||
if got != a {
|
||||
t.Errorf("Lookup(%q) = %#x, want %#x", a.String(), uint32(got), uint32(a))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMisses(t *testing.T) {
|
||||
testCases := []string{
|
||||
"",
|
||||
"\x00",
|
||||
"\xff",
|
||||
"A",
|
||||
"DIV",
|
||||
"Div",
|
||||
"dIV",
|
||||
"aa",
|
||||
"a\x00",
|
||||
"ab",
|
||||
"abb",
|
||||
"abbr0",
|
||||
"abbr ",
|
||||
" abbr",
|
||||
" a",
|
||||
"acceptcharset",
|
||||
"acceptCharset",
|
||||
"accept_charset",
|
||||
"h0",
|
||||
"h1h2",
|
||||
"h7",
|
||||
"onClick",
|
||||
"λ",
|
||||
// The following string has the same hash (0xa1d7fab7) as "onmouseover".
|
||||
"\x00\x00\x00\x00\x00\x50\x18\xae\x38\xd0\xb7",
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
got := Lookup([]byte(tc))
|
||||
if got != 0 {
|
||||
t.Errorf("Lookup(%q): got %d, want 0", tc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestForeignObject(t *testing.T) {
|
||||
const (
|
||||
afo = Foreignobject
|
||||
afO = ForeignObject
|
||||
sfo = "foreignobject"
|
||||
sfO = "foreignObject"
|
||||
)
|
||||
if got := Lookup([]byte(sfo)); got != afo {
|
||||
t.Errorf("Lookup(%q): got %#v, want %#v", sfo, got, afo)
|
||||
}
|
||||
if got := Lookup([]byte(sfO)); got != afO {
|
||||
t.Errorf("Lookup(%q): got %#v, want %#v", sfO, got, afO)
|
||||
}
|
||||
if got := afo.String(); got != sfo {
|
||||
t.Errorf("Atom(%#v).String(): got %q, want %q", afo, got, sfo)
|
||||
}
|
||||
if got := afO.String(); got != sfO {
|
||||
t.Errorf("Atom(%#v).String(): got %q, want %q", afO, got, sfO)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkLookup(b *testing.B) {
|
||||
sortedTable := make([]string, 0, len(table))
|
||||
for _, a := range table {
|
||||
if a != 0 {
|
||||
sortedTable = append(sortedTable, a.String())
|
||||
}
|
||||
}
|
||||
sort.Strings(sortedTable)
|
||||
|
||||
x := make([][]byte, 1000)
|
||||
for i := range x {
|
||||
x[i] = []byte(sortedTable[i%len(sortedTable)])
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for _, s := range x {
|
||||
Lookup(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
+636
@@ -0,0 +1,636 @@
|
||||
// Copyright 2012 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
package main
|
||||
|
||||
// This program generates table.go and table_test.go.
|
||||
// Invoke as
|
||||
//
|
||||
// go run gen.go |gofmt >table.go
|
||||
// go run gen.go -test |gofmt >table_test.go
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// identifier converts s to a Go exported identifier.
|
||||
// It converts "div" to "Div" and "accept-charset" to "AcceptCharset".
|
||||
func identifier(s string) string {
|
||||
b := make([]byte, 0, len(s))
|
||||
cap := true
|
||||
for _, c := range s {
|
||||
if c == '-' {
|
||||
cap = true
|
||||
continue
|
||||
}
|
||||
if cap && 'a' <= c && c <= 'z' {
|
||||
c -= 'a' - 'A'
|
||||
}
|
||||
cap = false
|
||||
b = append(b, byte(c))
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
var test = flag.Bool("test", false, "generate table_test.go")
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
var all []string
|
||||
all = append(all, elements...)
|
||||
all = append(all, attributes...)
|
||||
all = append(all, eventHandlers...)
|
||||
all = append(all, extra...)
|
||||
sort.Strings(all)
|
||||
|
||||
if *test {
|
||||
fmt.Printf("// generated by go run gen.go -test; DO NOT EDIT\n\n")
|
||||
fmt.Printf("package atom\n\n")
|
||||
fmt.Printf("var testAtomList = []string{\n")
|
||||
for _, s := range all {
|
||||
fmt.Printf("\t%q,\n", s)
|
||||
}
|
||||
fmt.Printf("}\n")
|
||||
return
|
||||
}
|
||||
|
||||
// uniq - lists have dups
|
||||
// compute max len too
|
||||
maxLen := 0
|
||||
w := 0
|
||||
for _, s := range all {
|
||||
if w == 0 || all[w-1] != s {
|
||||
if maxLen < len(s) {
|
||||
maxLen = len(s)
|
||||
}
|
||||
all[w] = s
|
||||
w++
|
||||
}
|
||||
}
|
||||
all = all[:w]
|
||||
|
||||
// Find hash that minimizes table size.
|
||||
var best *table
|
||||
for i := 0; i < 1000000; i++ {
|
||||
if best != nil && 1<<(best.k-1) < len(all) {
|
||||
break
|
||||
}
|
||||
h := rand.Uint32()
|
||||
for k := uint(0); k <= 16; k++ {
|
||||
if best != nil && k >= best.k {
|
||||
break
|
||||
}
|
||||
var t table
|
||||
if t.init(h, k, all) {
|
||||
best = &t
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if best == nil {
|
||||
fmt.Fprintf(os.Stderr, "failed to construct string table\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Lay out strings, using overlaps when possible.
|
||||
layout := append([]string{}, all...)
|
||||
|
||||
// Remove strings that are substrings of other strings
|
||||
for changed := true; changed; {
|
||||
changed = false
|
||||
for i, s := range layout {
|
||||
if s == "" {
|
||||
continue
|
||||
}
|
||||
for j, t := range layout {
|
||||
if i != j && t != "" && strings.Contains(s, t) {
|
||||
changed = true
|
||||
layout[j] = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Join strings where one suffix matches another prefix.
|
||||
for {
|
||||
// Find best i, j, k such that layout[i][len-k:] == layout[j][:k],
|
||||
// maximizing overlap length k.
|
||||
besti := -1
|
||||
bestj := -1
|
||||
bestk := 0
|
||||
for i, s := range layout {
|
||||
if s == "" {
|
||||
continue
|
||||
}
|
||||
for j, t := range layout {
|
||||
if i == j {
|
||||
continue
|
||||
}
|
||||
for k := bestk + 1; k <= len(s) && k <= len(t); k++ {
|
||||
if s[len(s)-k:] == t[:k] {
|
||||
besti = i
|
||||
bestj = j
|
||||
bestk = k
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if bestk > 0 {
|
||||
layout[besti] += layout[bestj][bestk:]
|
||||
layout[bestj] = ""
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
text := strings.Join(layout, "")
|
||||
|
||||
atom := map[string]uint32{}
|
||||
for _, s := range all {
|
||||
off := strings.Index(text, s)
|
||||
if off < 0 {
|
||||
panic("lost string " + s)
|
||||
}
|
||||
atom[s] = uint32(off<<8 | len(s))
|
||||
}
|
||||
|
||||
// Generate the Go code.
|
||||
fmt.Printf("// generated by go run gen.go; DO NOT EDIT\n\n")
|
||||
fmt.Printf("package atom\n\nconst (\n")
|
||||
for _, s := range all {
|
||||
fmt.Printf("\t%s Atom = %#x\n", identifier(s), atom[s])
|
||||
}
|
||||
fmt.Printf(")\n\n")
|
||||
|
||||
fmt.Printf("const hash0 = %#x\n\n", best.h0)
|
||||
fmt.Printf("const maxAtomLen = %d\n\n", maxLen)
|
||||
|
||||
fmt.Printf("var table = [1<<%d]Atom{\n", best.k)
|
||||
for i, s := range best.tab {
|
||||
if s == "" {
|
||||
continue
|
||||
}
|
||||
fmt.Printf("\t%#x: %#x, // %s\n", i, atom[s], s)
|
||||
}
|
||||
fmt.Printf("}\n")
|
||||
datasize := (1 << best.k) * 4
|
||||
|
||||
fmt.Printf("const atomText =\n")
|
||||
textsize := len(text)
|
||||
for len(text) > 60 {
|
||||
fmt.Printf("\t%q +\n", text[:60])
|
||||
text = text[60:]
|
||||
}
|
||||
fmt.Printf("\t%q\n\n", text)
|
||||
|
||||
fmt.Fprintf(os.Stderr, "%d atoms; %d string bytes + %d tables = %d total data\n", len(all), textsize, datasize, textsize+datasize)
|
||||
}
|
||||
|
||||
type byLen []string
|
||||
|
||||
func (x byLen) Less(i, j int) bool { return len(x[i]) > len(x[j]) }
|
||||
func (x byLen) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
|
||||
func (x byLen) Len() int { return len(x) }
|
||||
|
||||
// fnv computes the FNV hash with an arbitrary starting value h.
|
||||
func fnv(h uint32, s string) uint32 {
|
||||
for i := 0; i < len(s); i++ {
|
||||
h ^= uint32(s[i])
|
||||
h *= 16777619
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// A table represents an attempt at constructing the lookup table.
|
||||
// The lookup table uses cuckoo hashing, meaning that each string
|
||||
// can be found in one of two positions.
|
||||
type table struct {
|
||||
h0 uint32
|
||||
k uint
|
||||
mask uint32
|
||||
tab []string
|
||||
}
|
||||
|
||||
// hash returns the two hashes for s.
|
||||
func (t *table) hash(s string) (h1, h2 uint32) {
|
||||
h := fnv(t.h0, s)
|
||||
h1 = h & t.mask
|
||||
h2 = (h >> 16) & t.mask
|
||||
return
|
||||
}
|
||||
|
||||
// init initializes the table with the given parameters.
|
||||
// h0 is the initial hash value,
|
||||
// k is the number of bits of hash value to use, and
|
||||
// x is the list of strings to store in the table.
|
||||
// init returns false if the table cannot be constructed.
|
||||
func (t *table) init(h0 uint32, k uint, x []string) bool {
|
||||
t.h0 = h0
|
||||
t.k = k
|
||||
t.tab = make([]string, 1<<k)
|
||||
t.mask = 1<<k - 1
|
||||
for _, s := range x {
|
||||
if !t.insert(s) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// insert inserts s in the table.
|
||||
func (t *table) insert(s string) bool {
|
||||
h1, h2 := t.hash(s)
|
||||
if t.tab[h1] == "" {
|
||||
t.tab[h1] = s
|
||||
return true
|
||||
}
|
||||
if t.tab[h2] == "" {
|
||||
t.tab[h2] = s
|
||||
return true
|
||||
}
|
||||
if t.push(h1, 0) {
|
||||
t.tab[h1] = s
|
||||
return true
|
||||
}
|
||||
if t.push(h2, 0) {
|
||||
t.tab[h2] = s
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// push attempts to push aside the entry in slot i.
|
||||
func (t *table) push(i uint32, depth int) bool {
|
||||
if depth > len(t.tab) {
|
||||
return false
|
||||
}
|
||||
s := t.tab[i]
|
||||
h1, h2 := t.hash(s)
|
||||
j := h1 + h2 - i
|
||||
if t.tab[j] != "" && !t.push(j, depth+1) {
|
||||
return false
|
||||
}
|
||||
t.tab[j] = s
|
||||
return true
|
||||
}
|
||||
|
||||
// The lists of element names and attribute keys were taken from
|
||||
// http://www.whatwg.org/specs/web-apps/current-work/multipage/section-index.html
|
||||
// as of the "HTML Living Standard - Last Updated 30 May 2012" version.
|
||||
|
||||
var elements = []string{
|
||||
"a",
|
||||
"abbr",
|
||||
"address",
|
||||
"area",
|
||||
"article",
|
||||
"aside",
|
||||
"audio",
|
||||
"b",
|
||||
"base",
|
||||
"bdi",
|
||||
"bdo",
|
||||
"blockquote",
|
||||
"body",
|
||||
"br",
|
||||
"button",
|
||||
"canvas",
|
||||
"caption",
|
||||
"cite",
|
||||
"code",
|
||||
"col",
|
||||
"colgroup",
|
||||
"command",
|
||||
"data",
|
||||
"datalist",
|
||||
"dd",
|
||||
"del",
|
||||
"details",
|
||||
"dfn",
|
||||
"dialog",
|
||||
"div",
|
||||
"dl",
|
||||
"dt",
|
||||
"em",
|
||||
"embed",
|
||||
"fieldset",
|
||||
"figcaption",
|
||||
"figure",
|
||||
"footer",
|
||||
"form",
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"head",
|
||||
"header",
|
||||
"hgroup",
|
||||
"hr",
|
||||
"html",
|
||||
"i",
|
||||
"iframe",
|
||||
"img",
|
||||
"input",
|
||||
"ins",
|
||||
"kbd",
|
||||
"keygen",
|
||||
"label",
|
||||
"legend",
|
||||
"li",
|
||||
"link",
|
||||
"map",
|
||||
"mark",
|
||||
"menu",
|
||||
"meta",
|
||||
"meter",
|
||||
"nav",
|
||||
"noscript",
|
||||
"object",
|
||||
"ol",
|
||||
"optgroup",
|
||||
"option",
|
||||
"output",
|
||||
"p",
|
||||
"param",
|
||||
"pre",
|
||||
"progress",
|
||||
"q",
|
||||
"rp",
|
||||
"rt",
|
||||
"ruby",
|
||||
"s",
|
||||
"samp",
|
||||
"script",
|
||||
"section",
|
||||
"select",
|
||||
"small",
|
||||
"source",
|
||||
"span",
|
||||
"strong",
|
||||
"style",
|
||||
"sub",
|
||||
"summary",
|
||||
"sup",
|
||||
"table",
|
||||
"tbody",
|
||||
"td",
|
||||
"textarea",
|
||||
"tfoot",
|
||||
"th",
|
||||
"thead",
|
||||
"time",
|
||||
"title",
|
||||
"tr",
|
||||
"track",
|
||||
"u",
|
||||
"ul",
|
||||
"var",
|
||||
"video",
|
||||
"wbr",
|
||||
}
|
||||
|
||||
var attributes = []string{
|
||||
"accept",
|
||||
"accept-charset",
|
||||
"accesskey",
|
||||
"action",
|
||||
"alt",
|
||||
"async",
|
||||
"autocomplete",
|
||||
"autofocus",
|
||||
"autoplay",
|
||||
"border",
|
||||
"challenge",
|
||||
"charset",
|
||||
"checked",
|
||||
"cite",
|
||||
"class",
|
||||
"cols",
|
||||
"colspan",
|
||||
"command",
|
||||
"content",
|
||||
"contenteditable",
|
||||
"contextmenu",
|
||||
"controls",
|
||||
"coords",
|
||||
"crossorigin",
|
||||
"data",
|
||||
"datetime",
|
||||
"default",
|
||||
"defer",
|
||||
"dir",
|
||||
"dirname",
|
||||
"disabled",
|
||||
"download",
|
||||
"draggable",
|
||||
"dropzone",
|
||||
"enctype",
|
||||
"for",
|
||||
"form",
|
||||
"formaction",
|
||||
"formenctype",
|
||||
"formmethod",
|
||||
"formnovalidate",
|
||||
"formtarget",
|
||||
"headers",
|
||||
"height",
|
||||
"hidden",
|
||||
"high",
|
||||
"href",
|
||||
"hreflang",
|
||||
"http-equiv",
|
||||
"icon",
|
||||
"id",
|
||||
"inert",
|
||||
"ismap",
|
||||
"itemid",
|
||||
"itemprop",
|
||||
"itemref",
|
||||
"itemscope",
|
||||
"itemtype",
|
||||
"keytype",
|
||||
"kind",
|
||||
"label",
|
||||
"lang",
|
||||
"list",
|
||||
"loop",
|
||||
"low",
|
||||
"manifest",
|
||||
"max",
|
||||
"maxlength",
|
||||
"media",
|
||||
"mediagroup",
|
||||
"method",
|
||||
"min",
|
||||
"multiple",
|
||||
"muted",
|
||||
"name",
|
||||
"novalidate",
|
||||
"open",
|
||||
"optimum",
|
||||
"pattern",
|
||||
"ping",
|
||||
"placeholder",
|
||||
"poster",
|
||||
"preload",
|
||||
"radiogroup",
|
||||
"readonly",
|
||||
"rel",
|
||||
"required",
|
||||
"reversed",
|
||||
"rows",
|
||||
"rowspan",
|
||||
"sandbox",
|
||||
"spellcheck",
|
||||
"scope",
|
||||
"scoped",
|
||||
"seamless",
|
||||
"selected",
|
||||
"shape",
|
||||
"size",
|
||||
"sizes",
|
||||
"span",
|
||||
"src",
|
||||
"srcdoc",
|
||||
"srclang",
|
||||
"start",
|
||||
"step",
|
||||
"style",
|
||||
"tabindex",
|
||||
"target",
|
||||
"title",
|
||||
"translate",
|
||||
"type",
|
||||
"typemustmatch",
|
||||
"usemap",
|
||||
"value",
|
||||
"width",
|
||||
"wrap",
|
||||
}
|
||||
|
||||
var eventHandlers = []string{
|
||||
"onabort",
|
||||
"onafterprint",
|
||||
"onbeforeprint",
|
||||
"onbeforeunload",
|
||||
"onblur",
|
||||
"oncancel",
|
||||
"oncanplay",
|
||||
"oncanplaythrough",
|
||||
"onchange",
|
||||
"onclick",
|
||||
"onclose",
|
||||
"oncontextmenu",
|
||||
"oncuechange",
|
||||
"ondblclick",
|
||||
"ondrag",
|
||||
"ondragend",
|
||||
"ondragenter",
|
||||
"ondragleave",
|
||||
"ondragover",
|
||||
"ondragstart",
|
||||
"ondrop",
|
||||
"ondurationchange",
|
||||
"onemptied",
|
||||
"onended",
|
||||
"onerror",
|
||||
"onfocus",
|
||||
"onhashchange",
|
||||
"oninput",
|
||||
"oninvalid",
|
||||
"onkeydown",
|
||||
"onkeypress",
|
||||
"onkeyup",
|
||||
"onload",
|
||||
"onloadeddata",
|
||||
"onloadedmetadata",
|
||||
"onloadstart",
|
||||
"onmessage",
|
||||
"onmousedown",
|
||||
"onmousemove",
|
||||
"onmouseout",
|
||||
"onmouseover",
|
||||
"onmouseup",
|
||||
"onmousewheel",
|
||||
"onoffline",
|
||||
"ononline",
|
||||
"onpagehide",
|
||||
"onpageshow",
|
||||
"onpause",
|
||||
"onplay",
|
||||
"onplaying",
|
||||
"onpopstate",
|
||||
"onprogress",
|
||||
"onratechange",
|
||||
"onreset",
|
||||
"onresize",
|
||||
"onscroll",
|
||||
"onseeked",
|
||||
"onseeking",
|
||||
"onselect",
|
||||
"onshow",
|
||||
"onstalled",
|
||||
"onstorage",
|
||||
"onsubmit",
|
||||
"onsuspend",
|
||||
"ontimeupdate",
|
||||
"onunload",
|
||||
"onvolumechange",
|
||||
"onwaiting",
|
||||
}
|
||||
|
||||
// extra are ad-hoc values not covered by any of the lists above.
|
||||
var extra = []string{
|
||||
"align",
|
||||
"annotation",
|
||||
"annotation-xml",
|
||||
"applet",
|
||||
"basefont",
|
||||
"bgsound",
|
||||
"big",
|
||||
"blink",
|
||||
"center",
|
||||
"color",
|
||||
"desc",
|
||||
"face",
|
||||
"font",
|
||||
"foreignObject", // HTML is case-insensitive, but SVG-embedded-in-HTML is case-sensitive.
|
||||
"foreignobject",
|
||||
"frame",
|
||||
"frameset",
|
||||
"image",
|
||||
"isindex",
|
||||
"listing",
|
||||
"malignmark",
|
||||
"marquee",
|
||||
"math",
|
||||
"mglyph",
|
||||
"mi",
|
||||
"mn",
|
||||
"mo",
|
||||
"ms",
|
||||
"mtext",
|
||||
"nobr",
|
||||
"noembed",
|
||||
"noframes",
|
||||
"plaintext",
|
||||
"prompt",
|
||||
"public",
|
||||
"spacer",
|
||||
"strike",
|
||||
"svg",
|
||||
"system",
|
||||
"tt",
|
||||
"xmp",
|
||||
}
|
||||
+694
@@ -0,0 +1,694 @@
|
||||
// generated by go run gen.go; DO NOT EDIT
|
||||
|
||||
package atom
|
||||
|
||||
const (
|
||||
A Atom = 0x1
|
||||
Abbr Atom = 0x4
|
||||
Accept Atom = 0x2106
|
||||
AcceptCharset Atom = 0x210e
|
||||
Accesskey Atom = 0x3309
|
||||
Action Atom = 0x21b06
|
||||
Address Atom = 0x5d507
|
||||
Align Atom = 0x1105
|
||||
Alt Atom = 0x4503
|
||||
Annotation Atom = 0x18d0a
|
||||
AnnotationXml Atom = 0x18d0e
|
||||
Applet Atom = 0x2d106
|
||||
Area Atom = 0x31804
|
||||
Article Atom = 0x39907
|
||||
Aside Atom = 0x4f05
|
||||
Async Atom = 0x9305
|
||||
Audio Atom = 0xaf05
|
||||
Autocomplete Atom = 0xd50c
|
||||
Autofocus Atom = 0xe109
|
||||
Autoplay Atom = 0x10c08
|
||||
B Atom = 0x101
|
||||
Base Atom = 0x11404
|
||||
Basefont Atom = 0x11408
|
||||
Bdi Atom = 0x1a03
|
||||
Bdo Atom = 0x12503
|
||||
Bgsound Atom = 0x13807
|
||||
Big Atom = 0x14403
|
||||
Blink Atom = 0x14705
|
||||
Blockquote Atom = 0x14c0a
|
||||
Body Atom = 0x2f04
|
||||
Border Atom = 0x15606
|
||||
Br Atom = 0x202
|
||||
Button Atom = 0x15c06
|
||||
Canvas Atom = 0x4b06
|
||||
Caption Atom = 0x1e007
|
||||
Center Atom = 0x2df06
|
||||
Challenge Atom = 0x23e09
|
||||
Charset Atom = 0x2807
|
||||
Checked Atom = 0x33f07
|
||||
Cite Atom = 0x9704
|
||||
Class Atom = 0x3d905
|
||||
Code Atom = 0x16f04
|
||||
Col Atom = 0x17603
|
||||
Colgroup Atom = 0x17608
|
||||
Color Atom = 0x18305
|
||||
Cols Atom = 0x18804
|
||||
Colspan Atom = 0x18807
|
||||
Command Atom = 0x19b07
|
||||
Content Atom = 0x42c07
|
||||
Contenteditable Atom = 0x42c0f
|
||||
Contextmenu Atom = 0x3480b
|
||||
Controls Atom = 0x1ae08
|
||||
Coords Atom = 0x1ba06
|
||||
Crossorigin Atom = 0x1c40b
|
||||
Data Atom = 0x44304
|
||||
Datalist Atom = 0x44308
|
||||
Datetime Atom = 0x25b08
|
||||
Dd Atom = 0x28802
|
||||
Default Atom = 0x5207
|
||||
Defer Atom = 0x17105
|
||||
Del Atom = 0x4d603
|
||||
Desc Atom = 0x4804
|
||||
Details Atom = 0x6507
|
||||
Dfn Atom = 0x8303
|
||||
Dialog Atom = 0x1b06
|
||||
Dir Atom = 0x9d03
|
||||
Dirname Atom = 0x9d07
|
||||
Disabled Atom = 0x10008
|
||||
Div Atom = 0x10703
|
||||
Dl Atom = 0x13e02
|
||||
Download Atom = 0x40908
|
||||
Draggable Atom = 0x1a109
|
||||
Dropzone Atom = 0x3a208
|
||||
Dt Atom = 0x4e402
|
||||
Em Atom = 0x7f02
|
||||
Embed Atom = 0x7f05
|
||||
Enctype Atom = 0x23007
|
||||
Face Atom = 0x2dd04
|
||||
Fieldset Atom = 0x1d508
|
||||
Figcaption Atom = 0x1dd0a
|
||||
Figure Atom = 0x1f106
|
||||
Font Atom = 0x11804
|
||||
Footer Atom = 0x5906
|
||||
For Atom = 0x1fd03
|
||||
ForeignObject Atom = 0x1fd0d
|
||||
Foreignobject Atom = 0x20a0d
|
||||
Form Atom = 0x21704
|
||||
Formaction Atom = 0x2170a
|
||||
Formenctype Atom = 0x22c0b
|
||||
Formmethod Atom = 0x2470a
|
||||
Formnovalidate Atom = 0x2510e
|
||||
Formtarget Atom = 0x2660a
|
||||
Frame Atom = 0x8705
|
||||
Frameset Atom = 0x8708
|
||||
H1 Atom = 0x13602
|
||||
H2 Atom = 0x29602
|
||||
H3 Atom = 0x2c502
|
||||
H4 Atom = 0x30e02
|
||||
H5 Atom = 0x4e602
|
||||
H6 Atom = 0x27002
|
||||
Head Atom = 0x2fa04
|
||||
Header Atom = 0x2fa06
|
||||
Headers Atom = 0x2fa07
|
||||
Height Atom = 0x27206
|
||||
Hgroup Atom = 0x27a06
|
||||
Hidden Atom = 0x28606
|
||||
High Atom = 0x29304
|
||||
Hr Atom = 0x13102
|
||||
Href Atom = 0x29804
|
||||
Hreflang Atom = 0x29808
|
||||
Html Atom = 0x27604
|
||||
HttpEquiv Atom = 0x2a00a
|
||||
I Atom = 0x601
|
||||
Icon Atom = 0x42b04
|
||||
Id Atom = 0x5102
|
||||
Iframe Atom = 0x2b406
|
||||
Image Atom = 0x2ba05
|
||||
Img Atom = 0x2bf03
|
||||
Inert Atom = 0x4c105
|
||||
Input Atom = 0x3f605
|
||||
Ins Atom = 0x1cd03
|
||||
Isindex Atom = 0x2c707
|
||||
Ismap Atom = 0x2ce05
|
||||
Itemid Atom = 0x9806
|
||||
Itemprop Atom = 0x57e08
|
||||
Itemref Atom = 0x2d707
|
||||
Itemscope Atom = 0x2e509
|
||||
Itemtype Atom = 0x2ef08
|
||||
Kbd Atom = 0x1903
|
||||
Keygen Atom = 0x3906
|
||||
Keytype Atom = 0x51207
|
||||
Kind Atom = 0xfd04
|
||||
Label Atom = 0xba05
|
||||
Lang Atom = 0x29c04
|
||||
Legend Atom = 0x1a806
|
||||
Li Atom = 0x1202
|
||||
Link Atom = 0x14804
|
||||
List Atom = 0x44704
|
||||
Listing Atom = 0x44707
|
||||
Loop Atom = 0xbe04
|
||||
Low Atom = 0x13f03
|
||||
Malignmark Atom = 0x100a
|
||||
Manifest Atom = 0x5b608
|
||||
Map Atom = 0x2d003
|
||||
Mark Atom = 0x1604
|
||||
Marquee Atom = 0x5f207
|
||||
Math Atom = 0x2f704
|
||||
Max Atom = 0x30603
|
||||
Maxlength Atom = 0x30609
|
||||
Media Atom = 0xa205
|
||||
Mediagroup Atom = 0xa20a
|
||||
Menu Atom = 0x34f04
|
||||
Meta Atom = 0x45604
|
||||
Meter Atom = 0x26105
|
||||
Method Atom = 0x24b06
|
||||
Mglyph Atom = 0x2c006
|
||||
Mi Atom = 0x9b02
|
||||
Min Atom = 0x31003
|
||||
Mn Atom = 0x25402
|
||||
Mo Atom = 0x47a02
|
||||
Ms Atom = 0x2e802
|
||||
Mtext Atom = 0x31305
|
||||
Multiple Atom = 0x32108
|
||||
Muted Atom = 0x32905
|
||||
Name Atom = 0xa004
|
||||
Nav Atom = 0x3e03
|
||||
Nobr Atom = 0x7404
|
||||
Noembed Atom = 0x7d07
|
||||
Noframes Atom = 0x8508
|
||||
Noscript Atom = 0x28b08
|
||||
Novalidate Atom = 0x2550a
|
||||
Object Atom = 0x21106
|
||||
Ol Atom = 0xcd02
|
||||
Onabort Atom = 0x16007
|
||||
Onafterprint Atom = 0x1e50c
|
||||
Onbeforeprint Atom = 0x21f0d
|
||||
Onbeforeunload Atom = 0x5c90e
|
||||
Onblur Atom = 0x3e206
|
||||
Oncancel Atom = 0xb308
|
||||
Oncanplay Atom = 0x12709
|
||||
Oncanplaythrough Atom = 0x12710
|
||||
Onchange Atom = 0x3b808
|
||||
Onclick Atom = 0x2ad07
|
||||
Onclose Atom = 0x32e07
|
||||
Oncontextmenu Atom = 0x3460d
|
||||
Oncuechange Atom = 0x3530b
|
||||
Ondblclick Atom = 0x35e0a
|
||||
Ondrag Atom = 0x36806
|
||||
Ondragend Atom = 0x36809
|
||||
Ondragenter Atom = 0x3710b
|
||||
Ondragleave Atom = 0x37c0b
|
||||
Ondragover Atom = 0x3870a
|
||||
Ondragstart Atom = 0x3910b
|
||||
Ondrop Atom = 0x3a006
|
||||
Ondurationchange Atom = 0x3b010
|
||||
Onemptied Atom = 0x3a709
|
||||
Onended Atom = 0x3c007
|
||||
Onerror Atom = 0x3c707
|
||||
Onfocus Atom = 0x3ce07
|
||||
Onhashchange Atom = 0x3e80c
|
||||
Oninput Atom = 0x3f407
|
||||
Oninvalid Atom = 0x3fb09
|
||||
Onkeydown Atom = 0x40409
|
||||
Onkeypress Atom = 0x4110a
|
||||
Onkeyup Atom = 0x42107
|
||||
Onload Atom = 0x43b06
|
||||
Onloadeddata Atom = 0x43b0c
|
||||
Onloadedmetadata Atom = 0x44e10
|
||||
Onloadstart Atom = 0x4640b
|
||||
Onmessage Atom = 0x46f09
|
||||
Onmousedown Atom = 0x4780b
|
||||
Onmousemove Atom = 0x4830b
|
||||
Onmouseout Atom = 0x48e0a
|
||||
Onmouseover Atom = 0x49b0b
|
||||
Onmouseup Atom = 0x4a609
|
||||
Onmousewheel Atom = 0x4af0c
|
||||
Onoffline Atom = 0x4bb09
|
||||
Ononline Atom = 0x4c608
|
||||
Onpagehide Atom = 0x4ce0a
|
||||
Onpageshow Atom = 0x4d90a
|
||||
Onpause Atom = 0x4e807
|
||||
Onplay Atom = 0x4f206
|
||||
Onplaying Atom = 0x4f209
|
||||
Onpopstate Atom = 0x4fb0a
|
||||
Onprogress Atom = 0x5050a
|
||||
Onratechange Atom = 0x5190c
|
||||
Onreset Atom = 0x52507
|
||||
Onresize Atom = 0x52c08
|
||||
Onscroll Atom = 0x53a08
|
||||
Onseeked Atom = 0x54208
|
||||
Onseeking Atom = 0x54a09
|
||||
Onselect Atom = 0x55308
|
||||
Onshow Atom = 0x55d06
|
||||
Onstalled Atom = 0x56609
|
||||
Onstorage Atom = 0x56f09
|
||||
Onsubmit Atom = 0x57808
|
||||
Onsuspend Atom = 0x58809
|
||||
Ontimeupdate Atom = 0x1190c
|
||||
Onunload Atom = 0x59108
|
||||
Onvolumechange Atom = 0x5990e
|
||||
Onwaiting Atom = 0x5a709
|
||||
Open Atom = 0x58404
|
||||
Optgroup Atom = 0xc008
|
||||
Optimum Atom = 0x5b007
|
||||
Option Atom = 0x5c506
|
||||
Output Atom = 0x49506
|
||||
P Atom = 0xc01
|
||||
Param Atom = 0xc05
|
||||
Pattern Atom = 0x6e07
|
||||
Ping Atom = 0xab04
|
||||
Placeholder Atom = 0xc70b
|
||||
Plaintext Atom = 0xf109
|
||||
Poster Atom = 0x17d06
|
||||
Pre Atom = 0x27f03
|
||||
Preload Atom = 0x27f07
|
||||
Progress Atom = 0x50708
|
||||
Prompt Atom = 0x5bf06
|
||||
Public Atom = 0x42706
|
||||
Q Atom = 0x15101
|
||||
Radiogroup Atom = 0x30a
|
||||
Readonly Atom = 0x31908
|
||||
Rel Atom = 0x28003
|
||||
Required Atom = 0x1f508
|
||||
Reversed Atom = 0x5e08
|
||||
Rows Atom = 0x7704
|
||||
Rowspan Atom = 0x7707
|
||||
Rp Atom = 0x1eb02
|
||||
Rt Atom = 0x16502
|
||||
Ruby Atom = 0xd104
|
||||
S Atom = 0x2c01
|
||||
Samp Atom = 0x6b04
|
||||
Sandbox Atom = 0xe907
|
||||
Scope Atom = 0x2e905
|
||||
Scoped Atom = 0x2e906
|
||||
Script Atom = 0x28d06
|
||||
Seamless Atom = 0x33308
|
||||
Section Atom = 0x3dd07
|
||||
Select Atom = 0x55506
|
||||
Selected Atom = 0x55508
|
||||
Shape Atom = 0x1b505
|
||||
Size Atom = 0x53004
|
||||
Sizes Atom = 0x53005
|
||||
Small Atom = 0x1bf05
|
||||
Source Atom = 0x1cf06
|
||||
Spacer Atom = 0x30006
|
||||
Span Atom = 0x7a04
|
||||
Spellcheck Atom = 0x33a0a
|
||||
Src Atom = 0x3d403
|
||||
Srcdoc Atom = 0x3d406
|
||||
Srclang Atom = 0x41a07
|
||||
Start Atom = 0x39705
|
||||
Step Atom = 0x5bc04
|
||||
Strike Atom = 0x50e06
|
||||
Strong Atom = 0x53406
|
||||
Style Atom = 0x5db05
|
||||
Sub Atom = 0x57a03
|
||||
Summary Atom = 0x5e007
|
||||
Sup Atom = 0x5e703
|
||||
Svg Atom = 0x5ea03
|
||||
System Atom = 0x5ed06
|
||||
Tabindex Atom = 0x45c08
|
||||
Table Atom = 0x43605
|
||||
Target Atom = 0x26a06
|
||||
Tbody Atom = 0x2e05
|
||||
Td Atom = 0x4702
|
||||
Textarea Atom = 0x31408
|
||||
Tfoot Atom = 0x5805
|
||||
Th Atom = 0x13002
|
||||
Thead Atom = 0x2f905
|
||||
Time Atom = 0x11b04
|
||||
Title Atom = 0x8e05
|
||||
Tr Atom = 0xf902
|
||||
Track Atom = 0xf905
|
||||
Translate Atom = 0x16609
|
||||
Tt Atom = 0x7002
|
||||
Type Atom = 0x23304
|
||||
Typemustmatch Atom = 0x2330d
|
||||
U Atom = 0xb01
|
||||
Ul Atom = 0x5602
|
||||
Usemap Atom = 0x4ec06
|
||||
Value Atom = 0x4005
|
||||
Var Atom = 0x10903
|
||||
Video Atom = 0x2a905
|
||||
Wbr Atom = 0x14103
|
||||
Width Atom = 0x4e205
|
||||
Wrap Atom = 0x56204
|
||||
Xmp Atom = 0xef03
|
||||
)
|
||||
|
||||
const hash0 = 0xc17da63e
|
||||
|
||||
const maxAtomLen = 16
|
||||
|
||||
var table = [1 << 9]Atom{
|
||||
0x1: 0x4830b, // onmousemove
|
||||
0x2: 0x5a709, // onwaiting
|
||||
0x4: 0x5bf06, // prompt
|
||||
0x7: 0x5b007, // optimum
|
||||
0x8: 0x1604, // mark
|
||||
0xa: 0x2d707, // itemref
|
||||
0xb: 0x4d90a, // onpageshow
|
||||
0xc: 0x55506, // select
|
||||
0xd: 0x1a109, // draggable
|
||||
0xe: 0x3e03, // nav
|
||||
0xf: 0x19b07, // command
|
||||
0x11: 0xb01, // u
|
||||
0x14: 0x2fa07, // headers
|
||||
0x15: 0x44308, // datalist
|
||||
0x17: 0x6b04, // samp
|
||||
0x1a: 0x40409, // onkeydown
|
||||
0x1b: 0x53a08, // onscroll
|
||||
0x1c: 0x17603, // col
|
||||
0x20: 0x57e08, // itemprop
|
||||
0x21: 0x2a00a, // http-equiv
|
||||
0x22: 0x5e703, // sup
|
||||
0x24: 0x1f508, // required
|
||||
0x2b: 0x27f07, // preload
|
||||
0x2c: 0x21f0d, // onbeforeprint
|
||||
0x2d: 0x3710b, // ondragenter
|
||||
0x2e: 0x4e402, // dt
|
||||
0x2f: 0x57808, // onsubmit
|
||||
0x30: 0x13102, // hr
|
||||
0x31: 0x3460d, // oncontextmenu
|
||||
0x33: 0x2ba05, // image
|
||||
0x34: 0x4e807, // onpause
|
||||
0x35: 0x27a06, // hgroup
|
||||
0x36: 0xab04, // ping
|
||||
0x37: 0x55308, // onselect
|
||||
0x3a: 0x10703, // div
|
||||
0x40: 0x9b02, // mi
|
||||
0x41: 0x33308, // seamless
|
||||
0x42: 0x2807, // charset
|
||||
0x43: 0x5102, // id
|
||||
0x44: 0x4fb0a, // onpopstate
|
||||
0x45: 0x4d603, // del
|
||||
0x46: 0x5f207, // marquee
|
||||
0x47: 0x3309, // accesskey
|
||||
0x49: 0x5906, // footer
|
||||
0x4a: 0x2d106, // applet
|
||||
0x4b: 0x2ce05, // ismap
|
||||
0x51: 0x34f04, // menu
|
||||
0x52: 0x2f04, // body
|
||||
0x55: 0x8708, // frameset
|
||||
0x56: 0x52507, // onreset
|
||||
0x57: 0x14705, // blink
|
||||
0x58: 0x8e05, // title
|
||||
0x59: 0x39907, // article
|
||||
0x5b: 0x13002, // th
|
||||
0x5d: 0x15101, // q
|
||||
0x5e: 0x58404, // open
|
||||
0x5f: 0x31804, // area
|
||||
0x61: 0x43b06, // onload
|
||||
0x62: 0x3f605, // input
|
||||
0x63: 0x11404, // base
|
||||
0x64: 0x18807, // colspan
|
||||
0x65: 0x51207, // keytype
|
||||
0x66: 0x13e02, // dl
|
||||
0x68: 0x1d508, // fieldset
|
||||
0x6a: 0x31003, // min
|
||||
0x6b: 0x10903, // var
|
||||
0x6f: 0x2fa06, // header
|
||||
0x70: 0x16502, // rt
|
||||
0x71: 0x17608, // colgroup
|
||||
0x72: 0x25402, // mn
|
||||
0x74: 0x16007, // onabort
|
||||
0x75: 0x3906, // keygen
|
||||
0x76: 0x4bb09, // onoffline
|
||||
0x77: 0x23e09, // challenge
|
||||
0x78: 0x2d003, // map
|
||||
0x7a: 0x30e02, // h4
|
||||
0x7b: 0x3c707, // onerror
|
||||
0x7c: 0x30609, // maxlength
|
||||
0x7d: 0x31305, // mtext
|
||||
0x7e: 0x5805, // tfoot
|
||||
0x7f: 0x11804, // font
|
||||
0x80: 0x100a, // malignmark
|
||||
0x81: 0x45604, // meta
|
||||
0x82: 0x9305, // async
|
||||
0x83: 0x2c502, // h3
|
||||
0x84: 0x28802, // dd
|
||||
0x85: 0x29804, // href
|
||||
0x86: 0xa20a, // mediagroup
|
||||
0x87: 0x1ba06, // coords
|
||||
0x88: 0x41a07, // srclang
|
||||
0x89: 0x35e0a, // ondblclick
|
||||
0x8a: 0x4005, // value
|
||||
0x8c: 0xb308, // oncancel
|
||||
0x8e: 0x33a0a, // spellcheck
|
||||
0x8f: 0x8705, // frame
|
||||
0x91: 0x14403, // big
|
||||
0x94: 0x21b06, // action
|
||||
0x95: 0x9d03, // dir
|
||||
0x97: 0x31908, // readonly
|
||||
0x99: 0x43605, // table
|
||||
0x9a: 0x5e007, // summary
|
||||
0x9b: 0x14103, // wbr
|
||||
0x9c: 0x30a, // radiogroup
|
||||
0x9d: 0xa004, // name
|
||||
0x9f: 0x5ed06, // system
|
||||
0xa1: 0x18305, // color
|
||||
0xa2: 0x4b06, // canvas
|
||||
0xa3: 0x27604, // html
|
||||
0xa5: 0x54a09, // onseeking
|
||||
0xac: 0x1b505, // shape
|
||||
0xad: 0x28003, // rel
|
||||
0xae: 0x12710, // oncanplaythrough
|
||||
0xaf: 0x3870a, // ondragover
|
||||
0xb1: 0x1fd0d, // foreignObject
|
||||
0xb3: 0x7704, // rows
|
||||
0xb6: 0x44707, // listing
|
||||
0xb7: 0x49506, // output
|
||||
0xb9: 0x3480b, // contextmenu
|
||||
0xbb: 0x13f03, // low
|
||||
0xbc: 0x1eb02, // rp
|
||||
0xbd: 0x58809, // onsuspend
|
||||
0xbe: 0x15c06, // button
|
||||
0xbf: 0x4804, // desc
|
||||
0xc1: 0x3dd07, // section
|
||||
0xc2: 0x5050a, // onprogress
|
||||
0xc3: 0x56f09, // onstorage
|
||||
0xc4: 0x2f704, // math
|
||||
0xc5: 0x4f206, // onplay
|
||||
0xc7: 0x5602, // ul
|
||||
0xc8: 0x6e07, // pattern
|
||||
0xc9: 0x4af0c, // onmousewheel
|
||||
0xca: 0x36809, // ondragend
|
||||
0xcb: 0xd104, // ruby
|
||||
0xcc: 0xc01, // p
|
||||
0xcd: 0x32e07, // onclose
|
||||
0xce: 0x26105, // meter
|
||||
0xcf: 0x13807, // bgsound
|
||||
0xd2: 0x27206, // height
|
||||
0xd4: 0x101, // b
|
||||
0xd5: 0x2ef08, // itemtype
|
||||
0xd8: 0x1e007, // caption
|
||||
0xd9: 0x10008, // disabled
|
||||
0xdc: 0x5ea03, // svg
|
||||
0xdd: 0x1bf05, // small
|
||||
0xde: 0x44304, // data
|
||||
0xe0: 0x4c608, // ononline
|
||||
0xe1: 0x2c006, // mglyph
|
||||
0xe3: 0x7f05, // embed
|
||||
0xe4: 0xf902, // tr
|
||||
0xe5: 0x4640b, // onloadstart
|
||||
0xe7: 0x3b010, // ondurationchange
|
||||
0xed: 0x12503, // bdo
|
||||
0xee: 0x4702, // td
|
||||
0xef: 0x4f05, // aside
|
||||
0xf0: 0x29602, // h2
|
||||
0xf1: 0x50708, // progress
|
||||
0xf2: 0x14c0a, // blockquote
|
||||
0xf4: 0xba05, // label
|
||||
0xf5: 0x601, // i
|
||||
0xf7: 0x7707, // rowspan
|
||||
0xfb: 0x4f209, // onplaying
|
||||
0xfd: 0x2bf03, // img
|
||||
0xfe: 0xc008, // optgroup
|
||||
0xff: 0x42c07, // content
|
||||
0x101: 0x5190c, // onratechange
|
||||
0x103: 0x3e80c, // onhashchange
|
||||
0x104: 0x6507, // details
|
||||
0x106: 0x40908, // download
|
||||
0x109: 0xe907, // sandbox
|
||||
0x10b: 0x42c0f, // contenteditable
|
||||
0x10d: 0x37c0b, // ondragleave
|
||||
0x10e: 0x2106, // accept
|
||||
0x10f: 0x55508, // selected
|
||||
0x112: 0x2170a, // formaction
|
||||
0x113: 0x2df06, // center
|
||||
0x115: 0x44e10, // onloadedmetadata
|
||||
0x116: 0x14804, // link
|
||||
0x117: 0x11b04, // time
|
||||
0x118: 0x1c40b, // crossorigin
|
||||
0x119: 0x3ce07, // onfocus
|
||||
0x11a: 0x56204, // wrap
|
||||
0x11b: 0x42b04, // icon
|
||||
0x11d: 0x2a905, // video
|
||||
0x11e: 0x3d905, // class
|
||||
0x121: 0x5990e, // onvolumechange
|
||||
0x122: 0x3e206, // onblur
|
||||
0x123: 0x2e509, // itemscope
|
||||
0x124: 0x5db05, // style
|
||||
0x127: 0x42706, // public
|
||||
0x129: 0x2510e, // formnovalidate
|
||||
0x12a: 0x55d06, // onshow
|
||||
0x12c: 0x16609, // translate
|
||||
0x12d: 0x9704, // cite
|
||||
0x12e: 0x2e802, // ms
|
||||
0x12f: 0x1190c, // ontimeupdate
|
||||
0x130: 0xfd04, // kind
|
||||
0x131: 0x2660a, // formtarget
|
||||
0x135: 0x3c007, // onended
|
||||
0x136: 0x28606, // hidden
|
||||
0x137: 0x2c01, // s
|
||||
0x139: 0x2470a, // formmethod
|
||||
0x13a: 0x44704, // list
|
||||
0x13c: 0x27002, // h6
|
||||
0x13d: 0xcd02, // ol
|
||||
0x13e: 0x3530b, // oncuechange
|
||||
0x13f: 0x20a0d, // foreignobject
|
||||
0x143: 0x5c90e, // onbeforeunload
|
||||
0x145: 0x3a709, // onemptied
|
||||
0x146: 0x17105, // defer
|
||||
0x147: 0xef03, // xmp
|
||||
0x148: 0xaf05, // audio
|
||||
0x149: 0x1903, // kbd
|
||||
0x14c: 0x46f09, // onmessage
|
||||
0x14d: 0x5c506, // option
|
||||
0x14e: 0x4503, // alt
|
||||
0x14f: 0x33f07, // checked
|
||||
0x150: 0x10c08, // autoplay
|
||||
0x152: 0x202, // br
|
||||
0x153: 0x2550a, // novalidate
|
||||
0x156: 0x7d07, // noembed
|
||||
0x159: 0x2ad07, // onclick
|
||||
0x15a: 0x4780b, // onmousedown
|
||||
0x15b: 0x3b808, // onchange
|
||||
0x15e: 0x3fb09, // oninvalid
|
||||
0x15f: 0x2e906, // scoped
|
||||
0x160: 0x1ae08, // controls
|
||||
0x161: 0x32905, // muted
|
||||
0x163: 0x4ec06, // usemap
|
||||
0x164: 0x1dd0a, // figcaption
|
||||
0x165: 0x36806, // ondrag
|
||||
0x166: 0x29304, // high
|
||||
0x168: 0x3d403, // src
|
||||
0x169: 0x17d06, // poster
|
||||
0x16b: 0x18d0e, // annotation-xml
|
||||
0x16c: 0x5bc04, // step
|
||||
0x16d: 0x4, // abbr
|
||||
0x16e: 0x1b06, // dialog
|
||||
0x170: 0x1202, // li
|
||||
0x172: 0x47a02, // mo
|
||||
0x175: 0x1fd03, // for
|
||||
0x176: 0x1cd03, // ins
|
||||
0x178: 0x53004, // size
|
||||
0x17a: 0x5207, // default
|
||||
0x17b: 0x1a03, // bdi
|
||||
0x17c: 0x4ce0a, // onpagehide
|
||||
0x17d: 0x9d07, // dirname
|
||||
0x17e: 0x23304, // type
|
||||
0x17f: 0x21704, // form
|
||||
0x180: 0x4c105, // inert
|
||||
0x181: 0x12709, // oncanplay
|
||||
0x182: 0x8303, // dfn
|
||||
0x183: 0x45c08, // tabindex
|
||||
0x186: 0x7f02, // em
|
||||
0x187: 0x29c04, // lang
|
||||
0x189: 0x3a208, // dropzone
|
||||
0x18a: 0x4110a, // onkeypress
|
||||
0x18b: 0x25b08, // datetime
|
||||
0x18c: 0x18804, // cols
|
||||
0x18d: 0x1, // a
|
||||
0x18e: 0x43b0c, // onloadeddata
|
||||
0x191: 0x15606, // border
|
||||
0x192: 0x2e05, // tbody
|
||||
0x193: 0x24b06, // method
|
||||
0x195: 0xbe04, // loop
|
||||
0x196: 0x2b406, // iframe
|
||||
0x198: 0x2fa04, // head
|
||||
0x19e: 0x5b608, // manifest
|
||||
0x19f: 0xe109, // autofocus
|
||||
0x1a0: 0x16f04, // code
|
||||
0x1a1: 0x53406, // strong
|
||||
0x1a2: 0x32108, // multiple
|
||||
0x1a3: 0xc05, // param
|
||||
0x1a6: 0x23007, // enctype
|
||||
0x1a7: 0x2dd04, // face
|
||||
0x1a8: 0xf109, // plaintext
|
||||
0x1a9: 0x13602, // h1
|
||||
0x1aa: 0x56609, // onstalled
|
||||
0x1ad: 0x28d06, // script
|
||||
0x1ae: 0x30006, // spacer
|
||||
0x1af: 0x52c08, // onresize
|
||||
0x1b0: 0x49b0b, // onmouseover
|
||||
0x1b1: 0x59108, // onunload
|
||||
0x1b2: 0x54208, // onseeked
|
||||
0x1b4: 0x2330d, // typemustmatch
|
||||
0x1b5: 0x1f106, // figure
|
||||
0x1b6: 0x48e0a, // onmouseout
|
||||
0x1b7: 0x27f03, // pre
|
||||
0x1b8: 0x4e205, // width
|
||||
0x1bb: 0x7404, // nobr
|
||||
0x1be: 0x7002, // tt
|
||||
0x1bf: 0x1105, // align
|
||||
0x1c0: 0x3f407, // oninput
|
||||
0x1c3: 0x42107, // onkeyup
|
||||
0x1c6: 0x1e50c, // onafterprint
|
||||
0x1c7: 0x210e, // accept-charset
|
||||
0x1c8: 0x9806, // itemid
|
||||
0x1cb: 0x50e06, // strike
|
||||
0x1cc: 0x57a03, // sub
|
||||
0x1cd: 0xf905, // track
|
||||
0x1ce: 0x39705, // start
|
||||
0x1d0: 0x11408, // basefont
|
||||
0x1d6: 0x1cf06, // source
|
||||
0x1d7: 0x1a806, // legend
|
||||
0x1d8: 0x2f905, // thead
|
||||
0x1da: 0x2e905, // scope
|
||||
0x1dd: 0x21106, // object
|
||||
0x1de: 0xa205, // media
|
||||
0x1df: 0x18d0a, // annotation
|
||||
0x1e0: 0x22c0b, // formenctype
|
||||
0x1e2: 0x28b08, // noscript
|
||||
0x1e4: 0x53005, // sizes
|
||||
0x1e5: 0xd50c, // autocomplete
|
||||
0x1e6: 0x7a04, // span
|
||||
0x1e7: 0x8508, // noframes
|
||||
0x1e8: 0x26a06, // target
|
||||
0x1e9: 0x3a006, // ondrop
|
||||
0x1ea: 0x3d406, // srcdoc
|
||||
0x1ec: 0x5e08, // reversed
|
||||
0x1f0: 0x2c707, // isindex
|
||||
0x1f3: 0x29808, // hreflang
|
||||
0x1f5: 0x4e602, // h5
|
||||
0x1f6: 0x5d507, // address
|
||||
0x1fa: 0x30603, // max
|
||||
0x1fb: 0xc70b, // placeholder
|
||||
0x1fc: 0x31408, // textarea
|
||||
0x1fe: 0x4a609, // onmouseup
|
||||
0x1ff: 0x3910b, // ondragstart
|
||||
}
|
||||
|
||||
const atomText = "abbradiogrouparamalignmarkbdialogaccept-charsetbodyaccesskey" +
|
||||
"genavaluealtdescanvasidefaultfootereversedetailsampatternobr" +
|
||||
"owspanoembedfnoframesetitleasyncitemidirnamediagroupingaudio" +
|
||||
"ncancelabelooptgrouplaceholderubyautocompleteautofocusandbox" +
|
||||
"mplaintextrackindisabledivarautoplaybasefontimeupdatebdoncan" +
|
||||
"playthrough1bgsoundlowbrbigblinkblockquoteborderbuttonabortr" +
|
||||
"anslatecodefercolgroupostercolorcolspannotation-xmlcommandra" +
|
||||
"ggablegendcontrolshapecoordsmallcrossoriginsourcefieldsetfig" +
|
||||
"captionafterprintfigurequiredforeignObjectforeignobjectforma" +
|
||||
"ctionbeforeprintformenctypemustmatchallengeformmethodformnov" +
|
||||
"alidatetimeterformtargeth6heightmlhgroupreloadhiddenoscripth" +
|
||||
"igh2hreflanghttp-equivideonclickiframeimageimglyph3isindexis" +
|
||||
"mappletitemrefacenteritemscopeditemtypematheaderspacermaxlen" +
|
||||
"gth4minmtextareadonlymultiplemutedoncloseamlesspellcheckedon" +
|
||||
"contextmenuoncuechangeondblclickondragendondragenterondragle" +
|
||||
"aveondragoverondragstarticleondropzonemptiedondurationchange" +
|
||||
"onendedonerroronfocusrcdoclassectionbluronhashchangeoninputo" +
|
||||
"ninvalidonkeydownloadonkeypressrclangonkeyupublicontentedita" +
|
||||
"bleonloadeddatalistingonloadedmetadatabindexonloadstartonmes" +
|
||||
"sageonmousedownonmousemoveonmouseoutputonmouseoveronmouseupo" +
|
||||
"nmousewheelonofflinertononlineonpagehidelonpageshowidth5onpa" +
|
||||
"usemaponplayingonpopstateonprogresstrikeytypeonratechangeonr" +
|
||||
"esetonresizestrongonscrollonseekedonseekingonselectedonshowr" +
|
||||
"aponstalledonstorageonsubmitempropenonsuspendonunloadonvolum" +
|
||||
"echangeonwaitingoptimumanifestepromptoptionbeforeunloaddress" +
|
||||
"tylesummarysupsvgsystemarquee"
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
// generated by go run gen.go -test; DO NOT EDIT
|
||||
|
||||
package atom
|
||||
|
||||
var testAtomList = []string{
|
||||
"a",
|
||||
"abbr",
|
||||
"accept",
|
||||
"accept-charset",
|
||||
"accesskey",
|
||||
"action",
|
||||
"address",
|
||||
"align",
|
||||
"alt",
|
||||
"annotation",
|
||||
"annotation-xml",
|
||||
"applet",
|
||||
"area",
|
||||
"article",
|
||||
"aside",
|
||||
"async",
|
||||
"audio",
|
||||
"autocomplete",
|
||||
"autofocus",
|
||||
"autoplay",
|
||||
"b",
|
||||
"base",
|
||||
"basefont",
|
||||
"bdi",
|
||||
"bdo",
|
||||
"bgsound",
|
||||
"big",
|
||||
"blink",
|
||||
"blockquote",
|
||||
"body",
|
||||
"border",
|
||||
"br",
|
||||
"button",
|
||||
"canvas",
|
||||
"caption",
|
||||
"center",
|
||||
"challenge",
|
||||
"charset",
|
||||
"checked",
|
||||
"cite",
|
||||
"cite",
|
||||
"class",
|
||||
"code",
|
||||
"col",
|
||||
"colgroup",
|
||||
"color",
|
||||
"cols",
|
||||
"colspan",
|
||||
"command",
|
||||
"command",
|
||||
"content",
|
||||
"contenteditable",
|
||||
"contextmenu",
|
||||
"controls",
|
||||
"coords",
|
||||
"crossorigin",
|
||||
"data",
|
||||
"data",
|
||||
"datalist",
|
||||
"datetime",
|
||||
"dd",
|
||||
"default",
|
||||
"defer",
|
||||
"del",
|
||||
"desc",
|
||||
"details",
|
||||
"dfn",
|
||||
"dialog",
|
||||
"dir",
|
||||
"dirname",
|
||||
"disabled",
|
||||
"div",
|
||||
"dl",
|
||||
"download",
|
||||
"draggable",
|
||||
"dropzone",
|
||||
"dt",
|
||||
"em",
|
||||
"embed",
|
||||
"enctype",
|
||||
"face",
|
||||
"fieldset",
|
||||
"figcaption",
|
||||
"figure",
|
||||
"font",
|
||||
"footer",
|
||||
"for",
|
||||
"foreignObject",
|
||||
"foreignobject",
|
||||
"form",
|
||||
"form",
|
||||
"formaction",
|
||||
"formenctype",
|
||||
"formmethod",
|
||||
"formnovalidate",
|
||||
"formtarget",
|
||||
"frame",
|
||||
"frameset",
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"head",
|
||||
"header",
|
||||
"headers",
|
||||
"height",
|
||||
"hgroup",
|
||||
"hidden",
|
||||
"high",
|
||||
"hr",
|
||||
"href",
|
||||
"hreflang",
|
||||
"html",
|
||||
"http-equiv",
|
||||
"i",
|
||||
"icon",
|
||||
"id",
|
||||
"iframe",
|
||||
"image",
|
||||
"img",
|
||||
"inert",
|
||||
"input",
|
||||
"ins",
|
||||
"isindex",
|
||||
"ismap",
|
||||
"itemid",
|
||||
"itemprop",
|
||||
"itemref",
|
||||
"itemscope",
|
||||
"itemtype",
|
||||
"kbd",
|
||||
"keygen",
|
||||
"keytype",
|
||||
"kind",
|
||||
"label",
|
||||
"label",
|
||||
"lang",
|
||||
"legend",
|
||||
"li",
|
||||
"link",
|
||||
"list",
|
||||
"listing",
|
||||
"loop",
|
||||
"low",
|
||||
"malignmark",
|
||||
"manifest",
|
||||
"map",
|
||||
"mark",
|
||||
"marquee",
|
||||
"math",
|
||||
"max",
|
||||
"maxlength",
|
||||
"media",
|
||||
"mediagroup",
|
||||
"menu",
|
||||
"meta",
|
||||
"meter",
|
||||
"method",
|
||||
"mglyph",
|
||||
"mi",
|
||||
"min",
|
||||
"mn",
|
||||
"mo",
|
||||
"ms",
|
||||
"mtext",
|
||||
"multiple",
|
||||
"muted",
|
||||
"name",
|
||||
"nav",
|
||||
"nobr",
|
||||
"noembed",
|
||||
"noframes",
|
||||
"noscript",
|
||||
"novalidate",
|
||||
"object",
|
||||
"ol",
|
||||
"onabort",
|
||||
"onafterprint",
|
||||
"onbeforeprint",
|
||||
"onbeforeunload",
|
||||
"onblur",
|
||||
"oncancel",
|
||||
"oncanplay",
|
||||
"oncanplaythrough",
|
||||
"onchange",
|
||||
"onclick",
|
||||
"onclose",
|
||||
"oncontextmenu",
|
||||
"oncuechange",
|
||||
"ondblclick",
|
||||
"ondrag",
|
||||
"ondragend",
|
||||
"ondragenter",
|
||||
"ondragleave",
|
||||
"ondragover",
|
||||
"ondragstart",
|
||||
"ondrop",
|
||||
"ondurationchange",
|
||||
"onemptied",
|
||||
"onended",
|
||||
"onerror",
|
||||
"onfocus",
|
||||
"onhashchange",
|
||||
"oninput",
|
||||
"oninvalid",
|
||||
"onkeydown",
|
||||
"onkeypress",
|
||||
"onkeyup",
|
||||
"onload",
|
||||
"onloadeddata",
|
||||
"onloadedmetadata",
|
||||
"onloadstart",
|
||||
"onmessage",
|
||||
"onmousedown",
|
||||
"onmousemove",
|
||||
"onmouseout",
|
||||
"onmouseover",
|
||||
"onmouseup",
|
||||
"onmousewheel",
|
||||
"onoffline",
|
||||
"ononline",
|
||||
"onpagehide",
|
||||
"onpageshow",
|
||||
"onpause",
|
||||
"onplay",
|
||||
"onplaying",
|
||||
"onpopstate",
|
||||
"onprogress",
|
||||
"onratechange",
|
||||
"onreset",
|
||||
"onresize",
|
||||
"onscroll",
|
||||
"onseeked",
|
||||
"onseeking",
|
||||
"onselect",
|
||||
"onshow",
|
||||
"onstalled",
|
||||
"onstorage",
|
||||
"onsubmit",
|
||||
"onsuspend",
|
||||
"ontimeupdate",
|
||||
"onunload",
|
||||
"onvolumechange",
|
||||
"onwaiting",
|
||||
"open",
|
||||
"optgroup",
|
||||
"optimum",
|
||||
"option",
|
||||
"output",
|
||||
"p",
|
||||
"param",
|
||||
"pattern",
|
||||
"ping",
|
||||
"placeholder",
|
||||
"plaintext",
|
||||
"poster",
|
||||
"pre",
|
||||
"preload",
|
||||
"progress",
|
||||
"prompt",
|
||||
"public",
|
||||
"q",
|
||||
"radiogroup",
|
||||
"readonly",
|
||||
"rel",
|
||||
"required",
|
||||
"reversed",
|
||||
"rows",
|
||||
"rowspan",
|
||||
"rp",
|
||||
"rt",
|
||||
"ruby",
|
||||
"s",
|
||||
"samp",
|
||||
"sandbox",
|
||||
"scope",
|
||||
"scoped",
|
||||
"script",
|
||||
"seamless",
|
||||
"section",
|
||||
"select",
|
||||
"selected",
|
||||
"shape",
|
||||
"size",
|
||||
"sizes",
|
||||
"small",
|
||||
"source",
|
||||
"spacer",
|
||||
"span",
|
||||
"span",
|
||||
"spellcheck",
|
||||
"src",
|
||||
"srcdoc",
|
||||
"srclang",
|
||||
"start",
|
||||
"step",
|
||||
"strike",
|
||||
"strong",
|
||||
"style",
|
||||
"style",
|
||||
"sub",
|
||||
"summary",
|
||||
"sup",
|
||||
"svg",
|
||||
"system",
|
||||
"tabindex",
|
||||
"table",
|
||||
"target",
|
||||
"tbody",
|
||||
"td",
|
||||
"textarea",
|
||||
"tfoot",
|
||||
"th",
|
||||
"thead",
|
||||
"time",
|
||||
"title",
|
||||
"title",
|
||||
"tr",
|
||||
"track",
|
||||
"translate",
|
||||
"tt",
|
||||
"type",
|
||||
"typemustmatch",
|
||||
"u",
|
||||
"ul",
|
||||
"usemap",
|
||||
"value",
|
||||
"var",
|
||||
"video",
|
||||
"wbr",
|
||||
"width",
|
||||
"wrap",
|
||||
"xmp",
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
// Copyright 2013 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package charset provides common text encodings for HTML documents.
|
||||
//
|
||||
// The mapping from encoding labels to encodings is defined at
|
||||
// http://encoding.spec.whatwg.org.
|
||||
package charset // import "golang.org/x/net/html/charset"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"mime"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/golang.org/x/net/html"
|
||||
"golang.org/x/text/encoding"
|
||||
"golang.org/x/text/encoding/charmap"
|
||||
"golang.org/x/text/transform"
|
||||
)
|
||||
|
||||
// Lookup returns the encoding with the specified label, and its canonical
|
||||
// name. It returns nil and the empty string if label is not one of the
|
||||
// standard encodings for HTML. Matching is case-insensitive and ignores
|
||||
// leading and trailing whitespace.
|
||||
func Lookup(label string) (e encoding.Encoding, name string) {
|
||||
label = strings.ToLower(strings.Trim(label, "\t\n\r\f "))
|
||||
enc := encodings[label]
|
||||
return enc.e, enc.name
|
||||
}
|
||||
|
||||
// DetermineEncoding determines the encoding of an HTML document by examining
|
||||
// up to the first 1024 bytes of content and the declared Content-Type.
|
||||
//
|
||||
// See http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#determining-the-character-encoding
|
||||
func DetermineEncoding(content []byte, contentType string) (e encoding.Encoding, name string, certain bool) {
|
||||
if len(content) > 1024 {
|
||||
content = content[:1024]
|
||||
}
|
||||
|
||||
for _, b := range boms {
|
||||
if bytes.HasPrefix(content, b.bom) {
|
||||
e, name = Lookup(b.enc)
|
||||
return e, name, true
|
||||
}
|
||||
}
|
||||
|
||||
if _, params, err := mime.ParseMediaType(contentType); err == nil {
|
||||
if cs, ok := params["charset"]; ok {
|
||||
if e, name = Lookup(cs); e != nil {
|
||||
return e, name, true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(content) > 0 {
|
||||
e, name = prescan(content)
|
||||
if e != nil {
|
||||
return e, name, false
|
||||
}
|
||||
}
|
||||
|
||||
// Try to detect UTF-8.
|
||||
// First eliminate any partial rune at the end.
|
||||
for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- {
|
||||
b := content[i]
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
if utf8.RuneStart(b) {
|
||||
content = content[:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
hasHighBit := false
|
||||
for _, c := range content {
|
||||
if c >= 0x80 {
|
||||
hasHighBit = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasHighBit && utf8.Valid(content) {
|
||||
return encoding.Nop, "utf-8", false
|
||||
}
|
||||
|
||||
// TODO: change default depending on user's locale?
|
||||
return charmap.Windows1252, "windows-1252", false
|
||||
}
|
||||
|
||||
// NewReader returns an io.Reader that converts the content of r to UTF-8.
|
||||
// It calls DetermineEncoding to find out what r's encoding is.
|
||||
func NewReader(r io.Reader, contentType string) (io.Reader, error) {
|
||||
preview := make([]byte, 1024)
|
||||
n, err := io.ReadFull(r, preview)
|
||||
switch {
|
||||
case err == io.ErrUnexpectedEOF:
|
||||
preview = preview[:n]
|
||||
r = bytes.NewReader(preview)
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
r = io.MultiReader(bytes.NewReader(preview), r)
|
||||
}
|
||||
|
||||
if e, _, _ := DetermineEncoding(preview, contentType); e != encoding.Nop {
|
||||
r = transform.NewReader(r, e.NewDecoder())
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func prescan(content []byte) (e encoding.Encoding, name string) {
|
||||
z := html.NewTokenizer(bytes.NewReader(content))
|
||||
for {
|
||||
switch z.Next() {
|
||||
case html.ErrorToken:
|
||||
return nil, ""
|
||||
|
||||
case html.StartTagToken, html.SelfClosingTagToken:
|
||||
tagName, hasAttr := z.TagName()
|
||||
if !bytes.Equal(tagName, []byte("meta")) {
|
||||
continue
|
||||
}
|
||||
attrList := make(map[string]bool)
|
||||
gotPragma := false
|
||||
|
||||
const (
|
||||
dontKnow = iota
|
||||
doNeedPragma
|
||||
doNotNeedPragma
|
||||
)
|
||||
needPragma := dontKnow
|
||||
|
||||
name = ""
|
||||
e = nil
|
||||
for hasAttr {
|
||||
var key, val []byte
|
||||
key, val, hasAttr = z.TagAttr()
|
||||
ks := string(key)
|
||||
if attrList[ks] {
|
||||
continue
|
||||
}
|
||||
attrList[ks] = true
|
||||
for i, c := range val {
|
||||
if 'A' <= c && c <= 'Z' {
|
||||
val[i] = c + 0x20
|
||||
}
|
||||
}
|
||||
|
||||
switch ks {
|
||||
case "http-equiv":
|
||||
if bytes.Equal(val, []byte("content-type")) {
|
||||
gotPragma = true
|
||||
}
|
||||
|
||||
case "content":
|
||||
if e == nil {
|
||||
name = fromMetaElement(string(val))
|
||||
if name != "" {
|
||||
e, name = Lookup(name)
|
||||
if e != nil {
|
||||
needPragma = doNeedPragma
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case "charset":
|
||||
e, name = Lookup(string(val))
|
||||
needPragma = doNotNeedPragma
|
||||
}
|
||||
}
|
||||
|
||||
if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(name, "utf-16") {
|
||||
name = "utf-8"
|
||||
e = encoding.Nop
|
||||
}
|
||||
|
||||
if e != nil {
|
||||
return e, name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fromMetaElement(s string) string {
|
||||
for s != "" {
|
||||
csLoc := strings.Index(s, "charset")
|
||||
if csLoc == -1 {
|
||||
return ""
|
||||
}
|
||||
s = s[csLoc+len("charset"):]
|
||||
s = strings.TrimLeft(s, " \t\n\f\r")
|
||||
if !strings.HasPrefix(s, "=") {
|
||||
continue
|
||||
}
|
||||
s = s[1:]
|
||||
s = strings.TrimLeft(s, " \t\n\f\r")
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
if q := s[0]; q == '"' || q == '\'' {
|
||||
s = s[1:]
|
||||
closeQuote := strings.IndexRune(s, rune(q))
|
||||
if closeQuote == -1 {
|
||||
return ""
|
||||
}
|
||||
return s[:closeQuote]
|
||||
}
|
||||
|
||||
end := strings.IndexAny(s, "; \t\n\f\r")
|
||||
if end == -1 {
|
||||
end = len(s)
|
||||
}
|
||||
return s[:end]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var boms = []struct {
|
||||
bom []byte
|
||||
enc string
|
||||
}{
|
||||
{[]byte{0xfe, 0xff}, "utf-16be"},
|
||||
{[]byte{0xff, 0xfe}, "utf-16le"},
|
||||
{[]byte{0xef, 0xbb, 0xbf}, "utf-8"},
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
// Copyright 2013 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package charset
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/text/transform"
|
||||
)
|
||||
|
||||
func transformString(t transform.Transformer, s string) (string, error) {
|
||||
r := transform.NewReader(strings.NewReader(s), t)
|
||||
b, err := ioutil.ReadAll(r)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
var testCases = []struct {
|
||||
utf8, other, otherEncoding string
|
||||
}{
|
||||
{"Résumé", "Résumé", "utf8"},
|
||||
{"Résumé", "R\xe9sum\xe9", "latin1"},
|
||||
{"これは漢字です。", "S0\x8c0o0\"oW[g0Y0\x020", "UTF-16LE"},
|
||||
{"これは漢字です。", "0S0\x8c0oo\"[W0g0Y0\x02", "UTF-16BE"},
|
||||
{"Hello, world", "Hello, world", "ASCII"},
|
||||
{"Gdańsk", "Gda\xf1sk", "ISO-8859-2"},
|
||||
{"Ââ Čč Đđ Ŋŋ Õõ Šš Žž Åå Ää", "\xc2\xe2 \xc8\xe8 \xa9\xb9 \xaf\xbf \xd5\xf5 \xaa\xba \xac\xbc \xc5\xe5 \xc4\xe4", "ISO-8859-10"},
|
||||
{"สำหรับ", "\xca\xd3\xcb\xc3\u047a", "ISO-8859-11"},
|
||||
{"latviešu", "latvie\xf0u", "ISO-8859-13"},
|
||||
{"Seònaid", "Se\xf2naid", "ISO-8859-14"},
|
||||
{"€1 is cheap", "\xa41 is cheap", "ISO-8859-15"},
|
||||
{"românește", "rom\xe2ne\xbate", "ISO-8859-16"},
|
||||
{"nutraĵo", "nutra\xbco", "ISO-8859-3"},
|
||||
{"Kalâdlit", "Kal\xe2dlit", "ISO-8859-4"},
|
||||
{"русский", "\xe0\xe3\xe1\xe1\xda\xd8\xd9", "ISO-8859-5"},
|
||||
{"ελληνικά", "\xe5\xeb\xeb\xe7\xed\xe9\xea\xdc", "ISO-8859-7"},
|
||||
{"Kağan", "Ka\xf0an", "ISO-8859-9"},
|
||||
{"Résumé", "R\x8esum\x8e", "macintosh"},
|
||||
{"Gdańsk", "Gda\xf1sk", "windows-1250"},
|
||||
{"русский", "\xf0\xf3\xf1\xf1\xea\xe8\xe9", "windows-1251"},
|
||||
{"Résumé", "R\xe9sum\xe9", "windows-1252"},
|
||||
{"ελληνικά", "\xe5\xeb\xeb\xe7\xed\xe9\xea\xdc", "windows-1253"},
|
||||
{"Kağan", "Ka\xf0an", "windows-1254"},
|
||||
{"עִבְרִית", "\xf2\xc4\xe1\xc0\xf8\xc4\xe9\xfa", "windows-1255"},
|
||||
{"العربية", "\xc7\xe1\xda\xd1\xc8\xed\xc9", "windows-1256"},
|
||||
{"latviešu", "latvie\xf0u", "windows-1257"},
|
||||
{"Việt", "Vi\xea\xf2t", "windows-1258"},
|
||||
{"สำหรับ", "\xca\xd3\xcb\xc3\u047a", "windows-874"},
|
||||
{"русский", "\xd2\xd5\xd3\xd3\xcb\xc9\xca", "KOI8-R"},
|
||||
{"українська", "\xd5\xcb\xd2\xc1\xa7\xce\xd3\xd8\xcb\xc1", "KOI8-U"},
|
||||
{"Hello 常用國字標準字體表", "Hello \xb1`\xa5\u03b0\xea\xa6r\xbc\u0437\u01e6r\xc5\xe9\xaa\xed", "big5"},
|
||||
{"Hello 常用國字標準字體表", "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed", "gbk"},
|
||||
{"Hello 常用國字標準字體表", "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed", "gb18030"},
|
||||
{"עִבְרִית", "\x81\x30\xfb\x30\x81\x30\xf6\x34\x81\x30\xf9\x33\x81\x30\xf6\x30\x81\x30\xfb\x36\x81\x30\xf6\x34\x81\x30\xfa\x31\x81\x30\xfb\x38", "gb18030"},
|
||||
{"㧯", "\x82\x31\x89\x38", "gb18030"},
|
||||
{"これは漢字です。", "\x82\xb1\x82\xea\x82\xcd\x8a\xbf\x8e\x9a\x82\xc5\x82\xb7\x81B", "SJIS"},
|
||||
{"Hello, 世界!", "Hello, \x90\xa2\x8aE!", "SJIS"},
|
||||
{"イウエオカ", "\xb2\xb3\xb4\xb5\xb6", "SJIS"},
|
||||
{"これは漢字です。", "\xa4\xb3\xa4\xec\xa4\u03f4\xc1\xbb\xfa\xa4\u01e4\xb9\xa1\xa3", "EUC-JP"},
|
||||
{"Hello, 世界!", "Hello, \x1b$B@$3&\x1b(B!", "ISO-2022-JP"},
|
||||
{"네이트 | 즐거움의 시작, 슈파스(Spaβ) NATE", "\xb3\xd7\xc0\xcc\xc6\xae | \xc1\xf1\xb0\xc5\xbf\xf2\xc0\xc7 \xbd\xc3\xc0\xdb, \xbd\xb4\xc6\xc4\xbd\xba(Spa\xa5\xe2) NATE", "EUC-KR"},
|
||||
}
|
||||
|
||||
func TestDecode(t *testing.T) {
|
||||
for _, tc := range testCases {
|
||||
e, _ := Lookup(tc.otherEncoding)
|
||||
if e == nil {
|
||||
t.Errorf("%s: not found", tc.otherEncoding)
|
||||
continue
|
||||
}
|
||||
s, err := transformString(e.NewDecoder(), tc.other)
|
||||
if err != nil {
|
||||
t.Errorf("%s: decode %q: %v", tc.otherEncoding, tc.other, err)
|
||||
continue
|
||||
}
|
||||
if s != tc.utf8 {
|
||||
t.Errorf("%s: got %q, want %q", tc.otherEncoding, s, tc.utf8)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncode(t *testing.T) {
|
||||
for _, tc := range testCases {
|
||||
e, _ := Lookup(tc.otherEncoding)
|
||||
if e == nil {
|
||||
t.Errorf("%s: not found", tc.otherEncoding)
|
||||
continue
|
||||
}
|
||||
s, err := transformString(e.NewEncoder(), tc.utf8)
|
||||
if err != nil {
|
||||
t.Errorf("%s: encode %q: %s", tc.otherEncoding, tc.utf8, err)
|
||||
continue
|
||||
}
|
||||
if s != tc.other {
|
||||
t.Errorf("%s: got %q, want %q", tc.otherEncoding, s, tc.other)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestNames verifies that you can pass an encoding's name to Lookup and get
|
||||
// the same encoding back (except for "replacement").
|
||||
func TestNames(t *testing.T) {
|
||||
for _, e := range encodings {
|
||||
if e.name == "replacement" {
|
||||
continue
|
||||
}
|
||||
_, got := Lookup(e.name)
|
||||
if got != e.name {
|
||||
t.Errorf("got %q, want %q", got, e.name)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var sniffTestCases = []struct {
|
||||
filename, declared, want string
|
||||
}{
|
||||
{"HTTP-charset.html", "text/html; charset=iso-8859-15", "iso-8859-15"},
|
||||
{"UTF-16LE-BOM.html", "", "utf-16le"},
|
||||
{"UTF-16BE-BOM.html", "", "utf-16be"},
|
||||
{"meta-content-attribute.html", "text/html", "iso-8859-15"},
|
||||
{"meta-charset-attribute.html", "text/html", "iso-8859-15"},
|
||||
{"No-encoding-declaration.html", "text/html", "utf-8"},
|
||||
{"HTTP-vs-UTF-8-BOM.html", "text/html; charset=iso-8859-15", "utf-8"},
|
||||
{"HTTP-vs-meta-content.html", "text/html; charset=iso-8859-15", "iso-8859-15"},
|
||||
{"HTTP-vs-meta-charset.html", "text/html; charset=iso-8859-15", "iso-8859-15"},
|
||||
{"UTF-8-BOM-vs-meta-content.html", "text/html", "utf-8"},
|
||||
{"UTF-8-BOM-vs-meta-charset.html", "text/html", "utf-8"},
|
||||
}
|
||||
|
||||
func TestSniff(t *testing.T) {
|
||||
switch runtime.GOOS {
|
||||
case "nacl": // platforms that don't permit direct file system access
|
||||
t.Skipf("not supported on %q", runtime.GOOS)
|
||||
}
|
||||
|
||||
for _, tc := range sniffTestCases {
|
||||
content, err := ioutil.ReadFile("testdata/" + tc.filename)
|
||||
if err != nil {
|
||||
t.Errorf("%s: error reading file: %v", tc.filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
_, name, _ := DetermineEncoding(content, tc.declared)
|
||||
if name != tc.want {
|
||||
t.Errorf("%s: got %q, want %q", tc.filename, name, tc.want)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReader(t *testing.T) {
|
||||
switch runtime.GOOS {
|
||||
case "nacl": // platforms that don't permit direct file system access
|
||||
t.Skipf("not supported on %q", runtime.GOOS)
|
||||
}
|
||||
|
||||
for _, tc := range sniffTestCases {
|
||||
content, err := ioutil.ReadFile("testdata/" + tc.filename)
|
||||
if err != nil {
|
||||
t.Errorf("%s: error reading file: %v", tc.filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
r, err := NewReader(bytes.NewReader(content), tc.declared)
|
||||
if err != nil {
|
||||
t.Errorf("%s: error creating reader: %v", tc.filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
got, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
t.Errorf("%s: error reading from charset.NewReader: %v", tc.filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
e, _ := Lookup(tc.want)
|
||||
want, err := ioutil.ReadAll(transform.NewReader(bytes.NewReader(content), e.NewDecoder()))
|
||||
if err != nil {
|
||||
t.Errorf("%s: error decoding with hard-coded charset name: %v", tc.filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Errorf("%s: got %q, want %q", tc.filename, got, want)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var metaTestCases = []struct {
|
||||
meta, want string
|
||||
}{
|
||||
{"", ""},
|
||||
{"text/html", ""},
|
||||
{"text/html; charset utf-8", ""},
|
||||
{"text/html; charset=latin-2", "latin-2"},
|
||||
{"text/html; charset; charset = utf-8", "utf-8"},
|
||||
{`charset="big5"`, "big5"},
|
||||
{"charset='shift_jis'", "shift_jis"},
|
||||
}
|
||||
|
||||
func TestFromMeta(t *testing.T) {
|
||||
for _, tc := range metaTestCases {
|
||||
got := fromMetaElement(tc.meta)
|
||||
if got != tc.want {
|
||||
t.Errorf("%q: got %q, want %q", tc.meta, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
// Copyright 2013 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
package main
|
||||
|
||||
// Download http://encoding.spec.whatwg.org/encodings.json and use it to
|
||||
// generate table.go.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type enc struct {
|
||||
Name string
|
||||
Labels []string
|
||||
}
|
||||
|
||||
type group struct {
|
||||
Encodings []enc
|
||||
Heading string
|
||||
}
|
||||
|
||||
const specURL = "http://encoding.spec.whatwg.org/encodings.json"
|
||||
|
||||
func main() {
|
||||
resp, err := http.Get(specURL)
|
||||
if err != nil {
|
||||
log.Fatalf("error fetching %s: %s", specURL, err)
|
||||
}
|
||||
if resp.StatusCode != 200 {
|
||||
log.Fatalf("error fetching %s: HTTP status %s", specURL, resp.Status)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var groups []group
|
||||
d := json.NewDecoder(resp.Body)
|
||||
err = d.Decode(&groups)
|
||||
if err != nil {
|
||||
log.Fatalf("error reading encodings.json: %s", err)
|
||||
}
|
||||
|
||||
fmt.Println("// generated by go run gen.go; DO NOT EDIT")
|
||||
fmt.Println()
|
||||
fmt.Println("package charset")
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("import (")
|
||||
fmt.Println(`"golang.org/x/text/encoding"`)
|
||||
for _, pkg := range []string{"charmap", "japanese", "korean", "simplifiedchinese", "traditionalchinese", "unicode"} {
|
||||
fmt.Printf("\"golang.org/x/text/encoding/%s\"\n", pkg)
|
||||
}
|
||||
fmt.Println(")")
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("var encodings = map[string]struct{e encoding.Encoding; name string} {")
|
||||
for _, g := range groups {
|
||||
for _, e := range g.Encodings {
|
||||
goName, ok := miscNames[e.Name]
|
||||
if !ok {
|
||||
for k, v := range prefixes {
|
||||
if strings.HasPrefix(e.Name, k) {
|
||||
goName = v + e.Name[len(k):]
|
||||
break
|
||||
}
|
||||
}
|
||||
if goName == "" {
|
||||
log.Fatalf("unrecognized encoding name: %s", e.Name)
|
||||
}
|
||||
}
|
||||
|
||||
for _, label := range e.Labels {
|
||||
fmt.Printf("%q: {%s, %q},\n", label, goName, e.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Println("}")
|
||||
}
|
||||
|
||||
var prefixes = map[string]string{
|
||||
"iso-8859-": "charmap.ISO8859_",
|
||||
"windows-": "charmap.Windows",
|
||||
}
|
||||
|
||||
var miscNames = map[string]string{
|
||||
"utf-8": "encoding.Nop",
|
||||
"ibm866": "charmap.CodePage866",
|
||||
"iso-8859-8-i": "charmap.ISO8859_8",
|
||||
"koi8-r": "charmap.KOI8R",
|
||||
"koi8-u": "charmap.KOI8U",
|
||||
"macintosh": "charmap.Macintosh",
|
||||
"x-mac-cyrillic": "charmap.MacintoshCyrillic",
|
||||
"gbk": "simplifiedchinese.GBK",
|
||||
"gb18030": "simplifiedchinese.GB18030",
|
||||
"hz-gb-2312": "simplifiedchinese.HZGB2312",
|
||||
"big5": "traditionalchinese.Big5",
|
||||
"euc-jp": "japanese.EUCJP",
|
||||
"iso-2022-jp": "japanese.ISO2022JP",
|
||||
"shift_jis": "japanese.ShiftJIS",
|
||||
"euc-kr": "korean.EUCKR",
|
||||
"replacement": "encoding.Replacement",
|
||||
"utf-16be": "unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM)",
|
||||
"utf-16le": "unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)",
|
||||
"x-user-defined": "charmap.XUserDefined",
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
// generated by go run gen.go; DO NOT EDIT
|
||||
|
||||
package charset
|
||||
|
||||
import (
|
||||
"golang.org/x/text/encoding"
|
||||
"golang.org/x/text/encoding/charmap"
|
||||
"golang.org/x/text/encoding/japanese"
|
||||
"golang.org/x/text/encoding/korean"
|
||||
"golang.org/x/text/encoding/simplifiedchinese"
|
||||
"golang.org/x/text/encoding/traditionalchinese"
|
||||
"golang.org/x/text/encoding/unicode"
|
||||
)
|
||||
|
||||
var encodings = map[string]struct {
|
||||
e encoding.Encoding
|
||||
name string
|
||||
}{
|
||||
"unicode-1-1-utf-8": {encoding.Nop, "utf-8"},
|
||||
"utf-8": {encoding.Nop, "utf-8"},
|
||||
"utf8": {encoding.Nop, "utf-8"},
|
||||
"866": {charmap.CodePage866, "ibm866"},
|
||||
"cp866": {charmap.CodePage866, "ibm866"},
|
||||
"csibm866": {charmap.CodePage866, "ibm866"},
|
||||
"ibm866": {charmap.CodePage866, "ibm866"},
|
||||
"csisolatin2": {charmap.ISO8859_2, "iso-8859-2"},
|
||||
"iso-8859-2": {charmap.ISO8859_2, "iso-8859-2"},
|
||||
"iso-ir-101": {charmap.ISO8859_2, "iso-8859-2"},
|
||||
"iso8859-2": {charmap.ISO8859_2, "iso-8859-2"},
|
||||
"iso88592": {charmap.ISO8859_2, "iso-8859-2"},
|
||||
"iso_8859-2": {charmap.ISO8859_2, "iso-8859-2"},
|
||||
"iso_8859-2:1987": {charmap.ISO8859_2, "iso-8859-2"},
|
||||
"l2": {charmap.ISO8859_2, "iso-8859-2"},
|
||||
"latin2": {charmap.ISO8859_2, "iso-8859-2"},
|
||||
"csisolatin3": {charmap.ISO8859_3, "iso-8859-3"},
|
||||
"iso-8859-3": {charmap.ISO8859_3, "iso-8859-3"},
|
||||
"iso-ir-109": {charmap.ISO8859_3, "iso-8859-3"},
|
||||
"iso8859-3": {charmap.ISO8859_3, "iso-8859-3"},
|
||||
"iso88593": {charmap.ISO8859_3, "iso-8859-3"},
|
||||
"iso_8859-3": {charmap.ISO8859_3, "iso-8859-3"},
|
||||
"iso_8859-3:1988": {charmap.ISO8859_3, "iso-8859-3"},
|
||||
"l3": {charmap.ISO8859_3, "iso-8859-3"},
|
||||
"latin3": {charmap.ISO8859_3, "iso-8859-3"},
|
||||
"csisolatin4": {charmap.ISO8859_4, "iso-8859-4"},
|
||||
"iso-8859-4": {charmap.ISO8859_4, "iso-8859-4"},
|
||||
"iso-ir-110": {charmap.ISO8859_4, "iso-8859-4"},
|
||||
"iso8859-4": {charmap.ISO8859_4, "iso-8859-4"},
|
||||
"iso88594": {charmap.ISO8859_4, "iso-8859-4"},
|
||||
"iso_8859-4": {charmap.ISO8859_4, "iso-8859-4"},
|
||||
"iso_8859-4:1988": {charmap.ISO8859_4, "iso-8859-4"},
|
||||
"l4": {charmap.ISO8859_4, "iso-8859-4"},
|
||||
"latin4": {charmap.ISO8859_4, "iso-8859-4"},
|
||||
"csisolatincyrillic": {charmap.ISO8859_5, "iso-8859-5"},
|
||||
"cyrillic": {charmap.ISO8859_5, "iso-8859-5"},
|
||||
"iso-8859-5": {charmap.ISO8859_5, "iso-8859-5"},
|
||||
"iso-ir-144": {charmap.ISO8859_5, "iso-8859-5"},
|
||||
"iso8859-5": {charmap.ISO8859_5, "iso-8859-5"},
|
||||
"iso88595": {charmap.ISO8859_5, "iso-8859-5"},
|
||||
"iso_8859-5": {charmap.ISO8859_5, "iso-8859-5"},
|
||||
"iso_8859-5:1988": {charmap.ISO8859_5, "iso-8859-5"},
|
||||
"arabic": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"asmo-708": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"csiso88596e": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"csiso88596i": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"csisolatinarabic": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"ecma-114": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"iso-8859-6": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"iso-8859-6-e": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"iso-8859-6-i": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"iso-ir-127": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"iso8859-6": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"iso88596": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"iso_8859-6": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"iso_8859-6:1987": {charmap.ISO8859_6, "iso-8859-6"},
|
||||
"csisolatingreek": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"ecma-118": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"elot_928": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"greek": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"greek8": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"iso-8859-7": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"iso-ir-126": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"iso8859-7": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"iso88597": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"iso_8859-7": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"iso_8859-7:1987": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"sun_eu_greek": {charmap.ISO8859_7, "iso-8859-7"},
|
||||
"csiso88598e": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"csisolatinhebrew": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"hebrew": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"iso-8859-8": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"iso-8859-8-e": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"iso-ir-138": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"iso8859-8": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"iso88598": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"iso_8859-8": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"iso_8859-8:1988": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"visual": {charmap.ISO8859_8, "iso-8859-8"},
|
||||
"csiso88598i": {charmap.ISO8859_8, "iso-8859-8-i"},
|
||||
"iso-8859-8-i": {charmap.ISO8859_8, "iso-8859-8-i"},
|
||||
"logical": {charmap.ISO8859_8, "iso-8859-8-i"},
|
||||
"csisolatin6": {charmap.ISO8859_10, "iso-8859-10"},
|
||||
"iso-8859-10": {charmap.ISO8859_10, "iso-8859-10"},
|
||||
"iso-ir-157": {charmap.ISO8859_10, "iso-8859-10"},
|
||||
"iso8859-10": {charmap.ISO8859_10, "iso-8859-10"},
|
||||
"iso885910": {charmap.ISO8859_10, "iso-8859-10"},
|
||||
"l6": {charmap.ISO8859_10, "iso-8859-10"},
|
||||
"latin6": {charmap.ISO8859_10, "iso-8859-10"},
|
||||
"iso-8859-13": {charmap.ISO8859_13, "iso-8859-13"},
|
||||
"iso8859-13": {charmap.ISO8859_13, "iso-8859-13"},
|
||||
"iso885913": {charmap.ISO8859_13, "iso-8859-13"},
|
||||
"iso-8859-14": {charmap.ISO8859_14, "iso-8859-14"},
|
||||
"iso8859-14": {charmap.ISO8859_14, "iso-8859-14"},
|
||||
"iso885914": {charmap.ISO8859_14, "iso-8859-14"},
|
||||
"csisolatin9": {charmap.ISO8859_15, "iso-8859-15"},
|
||||
"iso-8859-15": {charmap.ISO8859_15, "iso-8859-15"},
|
||||
"iso8859-15": {charmap.ISO8859_15, "iso-8859-15"},
|
||||
"iso885915": {charmap.ISO8859_15, "iso-8859-15"},
|
||||
"iso_8859-15": {charmap.ISO8859_15, "iso-8859-15"},
|
||||
"l9": {charmap.ISO8859_15, "iso-8859-15"},
|
||||
"iso-8859-16": {charmap.ISO8859_16, "iso-8859-16"},
|
||||
"cskoi8r": {charmap.KOI8R, "koi8-r"},
|
||||
"koi": {charmap.KOI8R, "koi8-r"},
|
||||
"koi8": {charmap.KOI8R, "koi8-r"},
|
||||
"koi8-r": {charmap.KOI8R, "koi8-r"},
|
||||
"koi8_r": {charmap.KOI8R, "koi8-r"},
|
||||
"koi8-u": {charmap.KOI8U, "koi8-u"},
|
||||
"csmacintosh": {charmap.Macintosh, "macintosh"},
|
||||
"mac": {charmap.Macintosh, "macintosh"},
|
||||
"macintosh": {charmap.Macintosh, "macintosh"},
|
||||
"x-mac-roman": {charmap.Macintosh, "macintosh"},
|
||||
"dos-874": {charmap.Windows874, "windows-874"},
|
||||
"iso-8859-11": {charmap.Windows874, "windows-874"},
|
||||
"iso8859-11": {charmap.Windows874, "windows-874"},
|
||||
"iso885911": {charmap.Windows874, "windows-874"},
|
||||
"tis-620": {charmap.Windows874, "windows-874"},
|
||||
"windows-874": {charmap.Windows874, "windows-874"},
|
||||
"cp1250": {charmap.Windows1250, "windows-1250"},
|
||||
"windows-1250": {charmap.Windows1250, "windows-1250"},
|
||||
"x-cp1250": {charmap.Windows1250, "windows-1250"},
|
||||
"cp1251": {charmap.Windows1251, "windows-1251"},
|
||||
"windows-1251": {charmap.Windows1251, "windows-1251"},
|
||||
"x-cp1251": {charmap.Windows1251, "windows-1251"},
|
||||
"ansi_x3.4-1968": {charmap.Windows1252, "windows-1252"},
|
||||
"ascii": {charmap.Windows1252, "windows-1252"},
|
||||
"cp1252": {charmap.Windows1252, "windows-1252"},
|
||||
"cp819": {charmap.Windows1252, "windows-1252"},
|
||||
"csisolatin1": {charmap.Windows1252, "windows-1252"},
|
||||
"ibm819": {charmap.Windows1252, "windows-1252"},
|
||||
"iso-8859-1": {charmap.Windows1252, "windows-1252"},
|
||||
"iso-ir-100": {charmap.Windows1252, "windows-1252"},
|
||||
"iso8859-1": {charmap.Windows1252, "windows-1252"},
|
||||
"iso88591": {charmap.Windows1252, "windows-1252"},
|
||||
"iso_8859-1": {charmap.Windows1252, "windows-1252"},
|
||||
"iso_8859-1:1987": {charmap.Windows1252, "windows-1252"},
|
||||
"l1": {charmap.Windows1252, "windows-1252"},
|
||||
"latin1": {charmap.Windows1252, "windows-1252"},
|
||||
"us-ascii": {charmap.Windows1252, "windows-1252"},
|
||||
"windows-1252": {charmap.Windows1252, "windows-1252"},
|
||||
"x-cp1252": {charmap.Windows1252, "windows-1252"},
|
||||
"cp1253": {charmap.Windows1253, "windows-1253"},
|
||||
"windows-1253": {charmap.Windows1253, "windows-1253"},
|
||||
"x-cp1253": {charmap.Windows1253, "windows-1253"},
|
||||
"cp1254": {charmap.Windows1254, "windows-1254"},
|
||||
"csisolatin5": {charmap.Windows1254, "windows-1254"},
|
||||
"iso-8859-9": {charmap.Windows1254, "windows-1254"},
|
||||
"iso-ir-148": {charmap.Windows1254, "windows-1254"},
|
||||
"iso8859-9": {charmap.Windows1254, "windows-1254"},
|
||||
"iso88599": {charmap.Windows1254, "windows-1254"},
|
||||
"iso_8859-9": {charmap.Windows1254, "windows-1254"},
|
||||
"iso_8859-9:1989": {charmap.Windows1254, "windows-1254"},
|
||||
"l5": {charmap.Windows1254, "windows-1254"},
|
||||
"latin5": {charmap.Windows1254, "windows-1254"},
|
||||
"windows-1254": {charmap.Windows1254, "windows-1254"},
|
||||
"x-cp1254": {charmap.Windows1254, "windows-1254"},
|
||||
"cp1255": {charmap.Windows1255, "windows-1255"},
|
||||
"windows-1255": {charmap.Windows1255, "windows-1255"},
|
||||
"x-cp1255": {charmap.Windows1255, "windows-1255"},
|
||||
"cp1256": {charmap.Windows1256, "windows-1256"},
|
||||
"windows-1256": {charmap.Windows1256, "windows-1256"},
|
||||
"x-cp1256": {charmap.Windows1256, "windows-1256"},
|
||||
"cp1257": {charmap.Windows1257, "windows-1257"},
|
||||
"windows-1257": {charmap.Windows1257, "windows-1257"},
|
||||
"x-cp1257": {charmap.Windows1257, "windows-1257"},
|
||||
"cp1258": {charmap.Windows1258, "windows-1258"},
|
||||
"windows-1258": {charmap.Windows1258, "windows-1258"},
|
||||
"x-cp1258": {charmap.Windows1258, "windows-1258"},
|
||||
"x-mac-cyrillic": {charmap.MacintoshCyrillic, "x-mac-cyrillic"},
|
||||
"x-mac-ukrainian": {charmap.MacintoshCyrillic, "x-mac-cyrillic"},
|
||||
"chinese": {simplifiedchinese.GBK, "gbk"},
|
||||
"csgb2312": {simplifiedchinese.GBK, "gbk"},
|
||||
"csiso58gb231280": {simplifiedchinese.GBK, "gbk"},
|
||||
"gb2312": {simplifiedchinese.GBK, "gbk"},
|
||||
"gb_2312": {simplifiedchinese.GBK, "gbk"},
|
||||
"gb_2312-80": {simplifiedchinese.GBK, "gbk"},
|
||||
"gbk": {simplifiedchinese.GBK, "gbk"},
|
||||
"iso-ir-58": {simplifiedchinese.GBK, "gbk"},
|
||||
"x-gbk": {simplifiedchinese.GBK, "gbk"},
|
||||
"gb18030": {simplifiedchinese.GB18030, "gb18030"},
|
||||
"hz-gb-2312": {simplifiedchinese.HZGB2312, "hz-gb-2312"},
|
||||
"big5": {traditionalchinese.Big5, "big5"},
|
||||
"big5-hkscs": {traditionalchinese.Big5, "big5"},
|
||||
"cn-big5": {traditionalchinese.Big5, "big5"},
|
||||
"csbig5": {traditionalchinese.Big5, "big5"},
|
||||
"x-x-big5": {traditionalchinese.Big5, "big5"},
|
||||
"cseucpkdfmtjapanese": {japanese.EUCJP, "euc-jp"},
|
||||
"euc-jp": {japanese.EUCJP, "euc-jp"},
|
||||
"x-euc-jp": {japanese.EUCJP, "euc-jp"},
|
||||
"csiso2022jp": {japanese.ISO2022JP, "iso-2022-jp"},
|
||||
"iso-2022-jp": {japanese.ISO2022JP, "iso-2022-jp"},
|
||||
"csshiftjis": {japanese.ShiftJIS, "shift_jis"},
|
||||
"ms_kanji": {japanese.ShiftJIS, "shift_jis"},
|
||||
"shift-jis": {japanese.ShiftJIS, "shift_jis"},
|
||||
"shift_jis": {japanese.ShiftJIS, "shift_jis"},
|
||||
"sjis": {japanese.ShiftJIS, "shift_jis"},
|
||||
"windows-31j": {japanese.ShiftJIS, "shift_jis"},
|
||||
"x-sjis": {japanese.ShiftJIS, "shift_jis"},
|
||||
"cseuckr": {korean.EUCKR, "euc-kr"},
|
||||
"csksc56011987": {korean.EUCKR, "euc-kr"},
|
||||
"euc-kr": {korean.EUCKR, "euc-kr"},
|
||||
"iso-ir-149": {korean.EUCKR, "euc-kr"},
|
||||
"korean": {korean.EUCKR, "euc-kr"},
|
||||
"ks_c_5601-1987": {korean.EUCKR, "euc-kr"},
|
||||
"ks_c_5601-1989": {korean.EUCKR, "euc-kr"},
|
||||
"ksc5601": {korean.EUCKR, "euc-kr"},
|
||||
"ksc_5601": {korean.EUCKR, "euc-kr"},
|
||||
"windows-949": {korean.EUCKR, "euc-kr"},
|
||||
"csiso2022kr": {encoding.Replacement, "replacement"},
|
||||
"iso-2022-kr": {encoding.Replacement, "replacement"},
|
||||
"iso-2022-cn": {encoding.Replacement, "replacement"},
|
||||
"iso-2022-cn-ext": {encoding.Replacement, "replacement"},
|
||||
"utf-16be": {unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM), "utf-16be"},
|
||||
"utf-16": {unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM), "utf-16le"},
|
||||
"utf-16le": {unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM), "utf-16le"},
|
||||
"x-user-defined": {charmap.XUserDefined, "x-user-defined"},
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" >
|
||||
<head>
|
||||
<title>HTTP charset</title>
|
||||
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
|
||||
<link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'>
|
||||
<link rel="stylesheet" type="text/css" href="./generatedtests.css">
|
||||
<script src="http://w3c-test.org/resources/testharness.js"></script>
|
||||
<script src="http://w3c-test.org/resources/testharnessreport.js"></script>
|
||||
<meta name='flags' content='http'>
|
||||
<meta name="assert" content="The character encoding of a page can be set using the HTTP header charset declaration.">
|
||||
<style type='text/css'>
|
||||
.test div { width: 50px; }</style>
|
||||
<link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css">
|
||||
</head>
|
||||
<body>
|
||||
<p class='title'>HTTP charset</p>
|
||||
|
||||
|
||||
<div id='log'></div>
|
||||
|
||||
|
||||
<div class='test'><div id='box' class='ýäè'> </div></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class='description'>
|
||||
<p class="assertion" title="Assertion">The character encoding of a page can be set using the HTTP header charset declaration.</p>
|
||||
<div class="notes"><p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.ÜÀÚ</code>. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.</p><p>The only character encoding declaration for this HTML file is in the HTTP header, which sets the encoding to ISO 8859-15.</p></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nexttest"><div><a href="generate?test=the-input-byte-stream-003">Next test</a></div><div class="doctype">HTML5</div>
|
||||
<p class="jump">the-input-byte-stream-001<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#basics" target="_blank">Result summary & related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-001" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p>
|
||||
<div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li>
|
||||
<li>The test is read from a server that supports HTTP.</li></ul></div>
|
||||
</div>
|
||||
<script>
|
||||
test(function() {
|
||||
assert_equals(document.getElementById('box').offsetWidth, 100);
|
||||
}, " ");
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
Generated
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" >
|
||||
<head>
|
||||
<title>HTTP vs UTF-8 BOM</title>
|
||||
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
|
||||
<link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'>
|
||||
<link rel="stylesheet" type="text/css" href="./generatedtests.css">
|
||||
<script src="http://w3c-test.org/resources/testharness.js"></script>
|
||||
<script src="http://w3c-test.org/resources/testharnessreport.js"></script>
|
||||
<meta name='flags' content='http'>
|
||||
<meta name="assert" content="A character encoding set in the HTTP header has lower precedence than the UTF-8 signature.">
|
||||
<style type='text/css'>
|
||||
.test div { width: 50px; }</style>
|
||||
<link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-utf8.css">
|
||||
</head>
|
||||
<body>
|
||||
<p class='title'>HTTP vs UTF-8 BOM</p>
|
||||
|
||||
|
||||
<div id='log'></div>
|
||||
|
||||
|
||||
<div class='test'><div id='box' class='ýäè'> </div></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class='description'>
|
||||
<p class="assertion" title="Assertion">A character encoding set in the HTTP header has lower precedence than the UTF-8 signature.</p>
|
||||
<div class="notes"><p><p>The HTTP header attempts to set the character encoding to ISO 8859-15. The page starts with a UTF-8 signature.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.ýäè</code>. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.</p><p>If the test is unsuccessful, the characters  should appear at the top of the page. These represent the bytes that make up the UTF-8 signature when encountered in the ISO 8859-15 encoding.</p></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nexttest"><div><a href="generate?test=the-input-byte-stream-022">Next test</a></div><div class="doctype">HTML5</div>
|
||||
<p class="jump">the-input-byte-stream-034<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#precedence" target="_blank">Result summary & related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-034" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p>
|
||||
<div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li>
|
||||
<li>The test is read from a server that supports HTTP.</li></ul></div>
|
||||
</div>
|
||||
<script>
|
||||
test(function() {
|
||||
assert_equals(document.getElementById('box').offsetWidth, 100);
|
||||
}, " ");
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
Generated
Vendored
+49
@@ -0,0 +1,49 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" >
|
||||
<head>
|
||||
<meta charset="iso-8859-1" > <title>HTTP vs meta charset</title>
|
||||
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
|
||||
<link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'>
|
||||
<link rel="stylesheet" type="text/css" href="./generatedtests.css">
|
||||
<script src="http://w3c-test.org/resources/testharness.js"></script>
|
||||
<script src="http://w3c-test.org/resources/testharnessreport.js"></script>
|
||||
<meta name='flags' content='http'>
|
||||
<meta name="assert" content="The HTTP header has a higher precedence than an encoding declaration in a meta charset attribute.">
|
||||
<style type='text/css'>
|
||||
.test div { width: 50px; }.test div { width: 90px; }
|
||||
</style>
|
||||
<link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css">
|
||||
</head>
|
||||
<body>
|
||||
<p class='title'>HTTP vs meta charset</p>
|
||||
|
||||
|
||||
<div id='log'></div>
|
||||
|
||||
|
||||
<div class='test'><div id='box' class='ýäè'> </div></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class='description'>
|
||||
<p class="assertion" title="Assertion">The HTTP header has a higher precedence than an encoding declaration in a meta charset attribute.</p>
|
||||
<div class="notes"><p><p>The HTTP header attempts to set the character encoding to ISO 8859-15. The page contains an encoding declaration in a meta charset attribute that attempts to set the character encoding to ISO 8859-1.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.ÜÀÚ</code>. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.</p></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nexttest"><div><a href="generate?test=the-input-byte-stream-037">Next test</a></div><div class="doctype">HTML5</div>
|
||||
<p class="jump">the-input-byte-stream-018<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#precedence" target="_blank">Result summary & related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-018" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p>
|
||||
<div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li>
|
||||
<li>The test is read from a server that supports HTTP.</li></ul></div>
|
||||
</div>
|
||||
<script>
|
||||
test(function() {
|
||||
assert_equals(document.getElementById('box').offsetWidth, 100);
|
||||
}, " ");
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
Generated
Vendored
+49
@@ -0,0 +1,49 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" >
|
||||
<head>
|
||||
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" > <title>HTTP vs meta content</title>
|
||||
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
|
||||
<link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'>
|
||||
<link rel="stylesheet" type="text/css" href="./generatedtests.css">
|
||||
<script src="http://w3c-test.org/resources/testharness.js"></script>
|
||||
<script src="http://w3c-test.org/resources/testharnessreport.js"></script>
|
||||
<meta name='flags' content='http'>
|
||||
<meta name="assert" content="The HTTP header has a higher precedence than an encoding declaration in a meta content attribute.">
|
||||
<style type='text/css'>
|
||||
.test div { width: 50px; }.test div { width: 90px; }
|
||||
</style>
|
||||
<link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css">
|
||||
</head>
|
||||
<body>
|
||||
<p class='title'>HTTP vs meta content</p>
|
||||
|
||||
|
||||
<div id='log'></div>
|
||||
|
||||
|
||||
<div class='test'><div id='box' class='ýäè'> </div></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class='description'>
|
||||
<p class="assertion" title="Assertion">The HTTP header has a higher precedence than an encoding declaration in a meta content attribute.</p>
|
||||
<div class="notes"><p><p>The HTTP header attempts to set the character encoding to ISO 8859-15. The page contains an encoding declaration in a meta content attribute that attempts to set the character encoding to ISO 8859-1.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.ÜÀÚ</code>. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.</p></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nexttest"><div><a href="generate?test=the-input-byte-stream-018">Next test</a></div><div class="doctype">HTML5</div>
|
||||
<p class="jump">the-input-byte-stream-016<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#precedence" target="_blank">Result summary & related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-016" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p>
|
||||
<div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li>
|
||||
<li>The test is read from a server that supports HTTP.</li></ul></div>
|
||||
</div>
|
||||
<script>
|
||||
test(function() {
|
||||
assert_equals(document.getElementById('box').offsetWidth, 100);
|
||||
}, " ");
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
Generated
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" >
|
||||
<head>
|
||||
<title>No encoding declaration</title>
|
||||
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
|
||||
<link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'>
|
||||
<link rel="stylesheet" type="text/css" href="./generatedtests.css">
|
||||
<script src="http://w3c-test.org/resources/testharness.js"></script>
|
||||
<script src="http://w3c-test.org/resources/testharnessreport.js"></script>
|
||||
<meta name='flags' content='http'>
|
||||
<meta name="assert" content="A page with no encoding information in HTTP, BOM, XML declaration or meta element will be treated as UTF-8.">
|
||||
<style type='text/css'>
|
||||
.test div { width: 50px; }</style>
|
||||
<link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-utf8.css">
|
||||
</head>
|
||||
<body>
|
||||
<p class='title'>No encoding declaration</p>
|
||||
|
||||
|
||||
<div id='log'></div>
|
||||
|
||||
|
||||
<div class='test'><div id='box' class='ýäè'> </div></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class='description'>
|
||||
<p class="assertion" title="Assertion">A page with no encoding information in HTTP, BOM, XML declaration or meta element will be treated as UTF-8.</p>
|
||||
<div class="notes"><p><p>The test on this page contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.ýäè</code>. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.</p></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nexttest"><div><a href="generate?test=the-input-byte-stream-034">Next test</a></div><div class="doctype">HTML5</div>
|
||||
<p class="jump">the-input-byte-stream-015<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#basics" target="_blank">Result summary & related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-015" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p>
|
||||
<div class='prereq'>Assumptions: <ul><li>The test is read from a server that supports HTTP.</li></ul></div>
|
||||
</div>
|
||||
<script>
|
||||
test(function() {
|
||||
assert_equals(document.getElementById('box').offsetWidth, 100);
|
||||
}, " ");
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
These test cases come from http://www.w3.org/International/tests/html5/the-input-byte-stream/results-basics
|
||||
Generated
Vendored
+49
@@ -0,0 +1,49 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" >
|
||||
<head>
|
||||
<meta charset="iso-8859-15"> <title>UTF-8 BOM vs meta charset</title>
|
||||
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
|
||||
<link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'>
|
||||
<link rel="stylesheet" type="text/css" href="./generatedtests.css">
|
||||
<script src="http://w3c-test.org/resources/testharness.js"></script>
|
||||
<script src="http://w3c-test.org/resources/testharnessreport.js"></script>
|
||||
<meta name='flags' content='http'>
|
||||
<meta name="assert" content="A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta charset attribute declares a different encoding.">
|
||||
<style type='text/css'>
|
||||
.test div { width: 50px; }.test div { width: 90px; }
|
||||
</style>
|
||||
<link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-utf8.css">
|
||||
</head>
|
||||
<body>
|
||||
<p class='title'>UTF-8 BOM vs meta charset</p>
|
||||
|
||||
|
||||
<div id='log'></div>
|
||||
|
||||
|
||||
<div class='test'><div id='box' class='ýäè'> </div></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class='description'>
|
||||
<p class="assertion" title="Assertion">A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta charset attribute declares a different encoding.</p>
|
||||
<div class="notes"><p><p>The page contains an encoding declaration in a meta charset attribute that attempts to set the character encoding to ISO 8859-15, but the file starts with a UTF-8 signature.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.ýäè</code>. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.</p></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nexttest"><div><a href="generate?test=the-input-byte-stream-024">Next test</a></div><div class="doctype">HTML5</div>
|
||||
<p class="jump">the-input-byte-stream-038<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#precedence" target="_blank">Result summary & related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-038" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p>
|
||||
<div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li>
|
||||
<li>The test is read from a server that supports HTTP.</li></ul></div>
|
||||
</div>
|
||||
<script>
|
||||
test(function() {
|
||||
assert_equals(document.getElementById('box').offsetWidth, 100);
|
||||
}, " ");
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
Generated
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" >
|
||||
<head>
|
||||
<meta http-equiv="content-type" content="text/html; charset=iso-8859-15"> <title>UTF-8 BOM vs meta content</title>
|
||||
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
|
||||
<link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'>
|
||||
<link rel="stylesheet" type="text/css" href="./generatedtests.css">
|
||||
<script src="http://w3c-test.org/resources/testharness.js"></script>
|
||||
<script src="http://w3c-test.org/resources/testharnessreport.js"></script>
|
||||
<meta name='flags' content='http'>
|
||||
<meta name="assert" content="A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta content attribute declares a different encoding.">
|
||||
<style type='text/css'>
|
||||
.test div { width: 50px; }</style>
|
||||
<link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-utf8.css">
|
||||
</head>
|
||||
<body>
|
||||
<p class='title'>UTF-8 BOM vs meta content</p>
|
||||
|
||||
|
||||
<div id='log'></div>
|
||||
|
||||
|
||||
<div class='test'><div id='box' class='ýäè'> </div></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class='description'>
|
||||
<p class="assertion" title="Assertion">A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta content attribute declares a different encoding.</p>
|
||||
<div class="notes"><p><p>The page contains an encoding declaration in a meta content attribute that attempts to set the character encoding to ISO 8859-15, but the file starts with a UTF-8 signature.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.ýäè</code>. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.</p></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nexttest"><div><a href="generate?test=the-input-byte-stream-038">Next test</a></div><div class="doctype">HTML5</div>
|
||||
<p class="jump">the-input-byte-stream-037<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#precedence" target="_blank">Result summary & related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-037" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p>
|
||||
<div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li>
|
||||
<li>The test is read from a server that supports HTTP.</li></ul></div>
|
||||
</div>
|
||||
<script>
|
||||
test(function() {
|
||||
assert_equals(document.getElementById('box').offsetWidth, 100);
|
||||
}, " ");
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
Generated
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" >
|
||||
<head>
|
||||
<meta charset="iso-8859-15"> <title>meta charset attribute</title>
|
||||
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
|
||||
<link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'>
|
||||
<link rel="stylesheet" type="text/css" href="./generatedtests.css">
|
||||
<script src="http://w3c-test.org/resources/testharness.js"></script>
|
||||
<script src="http://w3c-test.org/resources/testharnessreport.js"></script>
|
||||
<meta name='flags' content='http'>
|
||||
<meta name="assert" content="The character encoding of the page can be set by a meta element with charset attribute.">
|
||||
<style type='text/css'>
|
||||
.test div { width: 50px; }</style>
|
||||
<link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css">
|
||||
</head>
|
||||
<body>
|
||||
<p class='title'>meta charset attribute</p>
|
||||
|
||||
|
||||
<div id='log'></div>
|
||||
|
||||
|
||||
<div class='test'><div id='box' class='ýäè'> </div></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class='description'>
|
||||
<p class="assertion" title="Assertion">The character encoding of the page can be set by a meta element with charset attribute.</p>
|
||||
<div class="notes"><p><p>The only character encoding declaration for this HTML file is in the charset attribute of the meta element, which declares the encoding to be ISO 8859-15.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.ÜÀÚ</code>. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.</p></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nexttest"><div><a href="generate?test=the-input-byte-stream-015">Next test</a></div><div class="doctype">HTML5</div>
|
||||
<p class="jump">the-input-byte-stream-009<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#basics" target="_blank">Result summary & related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-009" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p>
|
||||
<div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li>
|
||||
<li>The test is read from a server that supports HTTP.</li></ul></div>
|
||||
</div>
|
||||
<script>
|
||||
test(function() {
|
||||
assert_equals(document.getElementById('box').offsetWidth, 100);
|
||||
}, " ");
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
Generated
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" >
|
||||
<head>
|
||||
<meta http-equiv="content-type" content="text/html; charset=iso-8859-15"> <title>meta content attribute</title>
|
||||
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
|
||||
<link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'>
|
||||
<link rel="stylesheet" type="text/css" href="./generatedtests.css">
|
||||
<script src="http://w3c-test.org/resources/testharness.js"></script>
|
||||
<script src="http://w3c-test.org/resources/testharnessreport.js"></script>
|
||||
<meta name='flags' content='http'>
|
||||
<meta name="assert" content="The character encoding of the page can be set by a meta element with http-equiv and content attributes.">
|
||||
<style type='text/css'>
|
||||
.test div { width: 50px; }</style>
|
||||
<link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css">
|
||||
</head>
|
||||
<body>
|
||||
<p class='title'>meta content attribute</p>
|
||||
|
||||
|
||||
<div id='log'></div>
|
||||
|
||||
|
||||
<div class='test'><div id='box' class='ýäè'> </div></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class='description'>
|
||||
<p class="assertion" title="Assertion">The character encoding of the page can be set by a meta element with http-equiv and content attributes.</p>
|
||||
<div class="notes"><p><p>The only character encoding declaration for this HTML file is in the content attribute of the meta element, which declares the encoding to be ISO 8859-15.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.ÜÀÚ</code>. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.</p></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nexttest"><div><a href="generate?test=the-input-byte-stream-009">Next test</a></div><div class="doctype">HTML5</div>
|
||||
<p class="jump">the-input-byte-stream-007<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#basics" target="_blank">Result summary & related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-007" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p>
|
||||
<div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li>
|
||||
<li>The test is read from a server that supports HTTP.</li></ul></div>
|
||||
</div>
|
||||
<script>
|
||||
test(function() {
|
||||
assert_equals(document.getElementById('box').offsetWidth, 100);
|
||||
}, " ");
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package html
|
||||
|
||||
// Section 12.2.3.2 of the HTML5 specification says "The following elements
|
||||
// have varying levels of special parsing rules".
|
||||
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#the-stack-of-open-elements
|
||||
var isSpecialElementMap = map[string]bool{
|
||||
"address": true,
|
||||
"applet": true,
|
||||
"area": true,
|
||||
"article": true,
|
||||
"aside": true,
|
||||
"base": true,
|
||||
"basefont": true,
|
||||
"bgsound": true,
|
||||
"blockquote": true,
|
||||
"body": true,
|
||||
"br": true,
|
||||
"button": true,
|
||||
"caption": true,
|
||||
"center": true,
|
||||
"col": true,
|
||||
"colgroup": true,
|
||||
"command": true,
|
||||
"dd": true,
|
||||
"details": true,
|
||||
"dir": true,
|
||||
"div": true,
|
||||
"dl": true,
|
||||
"dt": true,
|
||||
"embed": true,
|
||||
"fieldset": true,
|
||||
"figcaption": true,
|
||||
"figure": true,
|
||||
"footer": true,
|
||||
"form": true,
|
||||
"frame": true,
|
||||
"frameset": true,
|
||||
"h1": true,
|
||||
"h2": true,
|
||||
"h3": true,
|
||||
"h4": true,
|
||||
"h5": true,
|
||||
"h6": true,
|
||||
"head": true,
|
||||
"header": true,
|
||||
"hgroup": true,
|
||||
"hr": true,
|
||||
"html": true,
|
||||
"iframe": true,
|
||||
"img": true,
|
||||
"input": true,
|
||||
"isindex": true,
|
||||
"li": true,
|
||||
"link": true,
|
||||
"listing": true,
|
||||
"marquee": true,
|
||||
"menu": true,
|
||||
"meta": true,
|
||||
"nav": true,
|
||||
"noembed": true,
|
||||
"noframes": true,
|
||||
"noscript": true,
|
||||
"object": true,
|
||||
"ol": true,
|
||||
"p": true,
|
||||
"param": true,
|
||||
"plaintext": true,
|
||||
"pre": true,
|
||||
"script": true,
|
||||
"section": true,
|
||||
"select": true,
|
||||
"style": true,
|
||||
"summary": true,
|
||||
"table": true,
|
||||
"tbody": true,
|
||||
"td": true,
|
||||
"textarea": true,
|
||||
"tfoot": true,
|
||||
"th": true,
|
||||
"thead": true,
|
||||
"title": true,
|
||||
"tr": true,
|
||||
"ul": true,
|
||||
"wbr": true,
|
||||
"xmp": true,
|
||||
}
|
||||
|
||||
func isSpecialElement(element *Node) bool {
|
||||
switch element.Namespace {
|
||||
case "", "html":
|
||||
return isSpecialElementMap[element.Data]
|
||||
case "svg":
|
||||
return element.Data == "foreignObject"
|
||||
}
|
||||
return false
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
// Copyright 2010 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package html implements an HTML5-compliant tokenizer and parser.
|
||||
|
||||
Tokenization is done by creating a Tokenizer for an io.Reader r. It is the
|
||||
caller's responsibility to ensure that r provides UTF-8 encoded HTML.
|
||||
|
||||
z := html.NewTokenizer(r)
|
||||
|
||||
Given a Tokenizer z, the HTML is tokenized by repeatedly calling z.Next(),
|
||||
which parses the next token and returns its type, or an error:
|
||||
|
||||
for {
|
||||
tt := z.Next()
|
||||
if tt == html.ErrorToken {
|
||||
// ...
|
||||
return ...
|
||||
}
|
||||
// Process the current token.
|
||||
}
|
||||
|
||||
There are two APIs for retrieving the current token. The high-level API is to
|
||||
call Token; the low-level API is to call Text or TagName / TagAttr. Both APIs
|
||||
allow optionally calling Raw after Next but before Token, Text, TagName, or
|
||||
TagAttr. In EBNF notation, the valid call sequence per token is:
|
||||
|
||||
Next {Raw} [ Token | Text | TagName {TagAttr} ]
|
||||
|
||||
Token returns an independent data structure that completely describes a token.
|
||||
Entities (such as "<") are unescaped, tag names and attribute keys are
|
||||
lower-cased, and attributes are collected into a []Attribute. For example:
|
||||
|
||||
for {
|
||||
if z.Next() == html.ErrorToken {
|
||||
// Returning io.EOF indicates success.
|
||||
return z.Err()
|
||||
}
|
||||
emitToken(z.Token())
|
||||
}
|
||||
|
||||
The low-level API performs fewer allocations and copies, but the contents of
|
||||
the []byte values returned by Text, TagName and TagAttr may change on the next
|
||||
call to Next. For example, to extract an HTML page's anchor text:
|
||||
|
||||
depth := 0
|
||||
for {
|
||||
tt := z.Next()
|
||||
switch tt {
|
||||
case ErrorToken:
|
||||
return z.Err()
|
||||
case TextToken:
|
||||
if depth > 0 {
|
||||
// emitBytes should copy the []byte it receives,
|
||||
// if it doesn't process it immediately.
|
||||
emitBytes(z.Text())
|
||||
}
|
||||
case StartTagToken, EndTagToken:
|
||||
tn, _ := z.TagName()
|
||||
if len(tn) == 1 && tn[0] == 'a' {
|
||||
if tt == StartTagToken {
|
||||
depth++
|
||||
} else {
|
||||
depth--
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Parsing is done by calling Parse with an io.Reader, which returns the root of
|
||||
the parse tree (the document element) as a *Node. It is the caller's
|
||||
responsibility to ensure that the Reader provides UTF-8 encoded HTML. For
|
||||
example, to process each anchor node in depth-first order:
|
||||
|
||||
doc, err := html.Parse(r)
|
||||
if err != nil {
|
||||
// ...
|
||||
}
|
||||
var f func(*html.Node)
|
||||
f = func(n *html.Node) {
|
||||
if n.Type == html.ElementNode && n.Data == "a" {
|
||||
// Do something with n...
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
f(c)
|
||||
}
|
||||
}
|
||||
f(doc)
|
||||
|
||||
The relevant specifications include:
|
||||
http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html and
|
||||
http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html
|
||||
*/
|
||||
package html // import "golang.org/x/net/html"
|
||||
|
||||
// The tokenization algorithm implemented by this package is not a line-by-line
|
||||
// transliteration of the relatively verbose state-machine in the WHATWG
|
||||
// specification. A more direct approach is used instead, where the program
|
||||
// counter implies the state, such as whether it is tokenizing a tag or a text
|
||||
// node. Specification compliance is verified by checking expected and actual
|
||||
// outputs over a test suite rather than aiming for algorithmic fidelity.
|
||||
|
||||
// TODO(nigeltao): Does a DOM API belong in this package or a separate one?
|
||||
// TODO(nigeltao): How does parsing interact with a JavaScript engine?
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package html
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// parseDoctype parses the data from a DoctypeToken into a name,
|
||||
// public identifier, and system identifier. It returns a Node whose Type
|
||||
// is DoctypeNode, whose Data is the name, and which has attributes
|
||||
// named "system" and "public" for the two identifiers if they were present.
|
||||
// quirks is whether the document should be parsed in "quirks mode".
|
||||
func parseDoctype(s string) (n *Node, quirks bool) {
|
||||
n = &Node{Type: DoctypeNode}
|
||||
|
||||
// Find the name.
|
||||
space := strings.IndexAny(s, whitespace)
|
||||
if space == -1 {
|
||||
space = len(s)
|
||||
}
|
||||
n.Data = s[:space]
|
||||
// The comparison to "html" is case-sensitive.
|
||||
if n.Data != "html" {
|
||||
quirks = true
|
||||
}
|
||||
n.Data = strings.ToLower(n.Data)
|
||||
s = strings.TrimLeft(s[space:], whitespace)
|
||||
|
||||
if len(s) < 6 {
|
||||
// It can't start with "PUBLIC" or "SYSTEM".
|
||||
// Ignore the rest of the string.
|
||||
return n, quirks || s != ""
|
||||
}
|
||||
|
||||
key := strings.ToLower(s[:6])
|
||||
s = s[6:]
|
||||
for key == "public" || key == "system" {
|
||||
s = strings.TrimLeft(s, whitespace)
|
||||
if s == "" {
|
||||
break
|
||||
}
|
||||
quote := s[0]
|
||||
if quote != '"' && quote != '\'' {
|
||||
break
|
||||
}
|
||||
s = s[1:]
|
||||
q := strings.IndexRune(s, rune(quote))
|
||||
var id string
|
||||
if q == -1 {
|
||||
id = s
|
||||
s = ""
|
||||
} else {
|
||||
id = s[:q]
|
||||
s = s[q+1:]
|
||||
}
|
||||
n.Attr = append(n.Attr, Attribute{Key: key, Val: id})
|
||||
if key == "public" {
|
||||
key = "system"
|
||||
} else {
|
||||
key = ""
|
||||
}
|
||||
}
|
||||
|
||||
if key != "" || s != "" {
|
||||
quirks = true
|
||||
} else if len(n.Attr) > 0 {
|
||||
if n.Attr[0].Key == "public" {
|
||||
public := strings.ToLower(n.Attr[0].Val)
|
||||
switch public {
|
||||
case "-//w3o//dtd w3 html strict 3.0//en//", "-/w3d/dtd html 4.0 transitional/en", "html":
|
||||
quirks = true
|
||||
default:
|
||||
for _, q := range quirkyIDs {
|
||||
if strings.HasPrefix(public, q) {
|
||||
quirks = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
// The following two public IDs only cause quirks mode if there is no system ID.
|
||||
if len(n.Attr) == 1 && (strings.HasPrefix(public, "-//w3c//dtd html 4.01 frameset//") ||
|
||||
strings.HasPrefix(public, "-//w3c//dtd html 4.01 transitional//")) {
|
||||
quirks = true
|
||||
}
|
||||
}
|
||||
if lastAttr := n.Attr[len(n.Attr)-1]; lastAttr.Key == "system" &&
|
||||
strings.ToLower(lastAttr.Val) == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd" {
|
||||
quirks = true
|
||||
}
|
||||
}
|
||||
|
||||
return n, quirks
|
||||
}
|
||||
|
||||
// quirkyIDs is a list of public doctype identifiers that cause a document
|
||||
// to be interpreted in quirks mode. The identifiers should be in lower case.
|
||||
var quirkyIDs = []string{
|
||||
"+//silmaril//dtd html pro v0r11 19970101//",
|
||||
"-//advasoft ltd//dtd html 3.0 aswedit + extensions//",
|
||||
"-//as//dtd html 3.0 aswedit + extensions//",
|
||||
"-//ietf//dtd html 2.0 level 1//",
|
||||
"-//ietf//dtd html 2.0 level 2//",
|
||||
"-//ietf//dtd html 2.0 strict level 1//",
|
||||
"-//ietf//dtd html 2.0 strict level 2//",
|
||||
"-//ietf//dtd html 2.0 strict//",
|
||||
"-//ietf//dtd html 2.0//",
|
||||
"-//ietf//dtd html 2.1e//",
|
||||
"-//ietf//dtd html 3.0//",
|
||||
"-//ietf//dtd html 3.2 final//",
|
||||
"-//ietf//dtd html 3.2//",
|
||||
"-//ietf//dtd html 3//",
|
||||
"-//ietf//dtd html level 0//",
|
||||
"-//ietf//dtd html level 1//",
|
||||
"-//ietf//dtd html level 2//",
|
||||
"-//ietf//dtd html level 3//",
|
||||
"-//ietf//dtd html strict level 0//",
|
||||
"-//ietf//dtd html strict level 1//",
|
||||
"-//ietf//dtd html strict level 2//",
|
||||
"-//ietf//dtd html strict level 3//",
|
||||
"-//ietf//dtd html strict//",
|
||||
"-//ietf//dtd html//",
|
||||
"-//metrius//dtd metrius presentational//",
|
||||
"-//microsoft//dtd internet explorer 2.0 html strict//",
|
||||
"-//microsoft//dtd internet explorer 2.0 html//",
|
||||
"-//microsoft//dtd internet explorer 2.0 tables//",
|
||||
"-//microsoft//dtd internet explorer 3.0 html strict//",
|
||||
"-//microsoft//dtd internet explorer 3.0 html//",
|
||||
"-//microsoft//dtd internet explorer 3.0 tables//",
|
||||
"-//netscape comm. corp.//dtd html//",
|
||||
"-//netscape comm. corp.//dtd strict html//",
|
||||
"-//o'reilly and associates//dtd html 2.0//",
|
||||
"-//o'reilly and associates//dtd html extended 1.0//",
|
||||
"-//o'reilly and associates//dtd html extended relaxed 1.0//",
|
||||
"-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//",
|
||||
"-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//",
|
||||
"-//spyglass//dtd html 2.0 extended//",
|
||||
"-//sq//dtd html 2.0 hotmetal + extensions//",
|
||||
"-//sun microsystems corp.//dtd hotjava html//",
|
||||
"-//sun microsystems corp.//dtd hotjava strict html//",
|
||||
"-//w3c//dtd html 3 1995-03-24//",
|
||||
"-//w3c//dtd html 3.2 draft//",
|
||||
"-//w3c//dtd html 3.2 final//",
|
||||
"-//w3c//dtd html 3.2//",
|
||||
"-//w3c//dtd html 3.2s draft//",
|
||||
"-//w3c//dtd html 4.0 frameset//",
|
||||
"-//w3c//dtd html 4.0 transitional//",
|
||||
"-//w3c//dtd html experimental 19960712//",
|
||||
"-//w3c//dtd html experimental 970421//",
|
||||
"-//w3c//dtd w3 html//",
|
||||
"-//w3o//dtd w3 html 3.0//",
|
||||
"-//webtechs//dtd mozilla html 2.0//",
|
||||
"-//webtechs//dtd mozilla html//",
|
||||
}
|
||||
+2253
File diff suppressed because it is too large
Load Diff
+29
@@ -0,0 +1,29 @@
|
||||
// Copyright 2010 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package html
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func TestEntityLength(t *testing.T) {
|
||||
// We verify that the length of UTF-8 encoding of each value is <= 1 + len(key).
|
||||
// The +1 comes from the leading "&". This property implies that the length of
|
||||
// unescaped text is <= the length of escaped text.
|
||||
for k, v := range entity {
|
||||
if 1+len(k) < utf8.RuneLen(v) {
|
||||
t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v))
|
||||
}
|
||||
if len(k) > longestEntityWithoutSemicolon && k[len(k)-1] != ';' {
|
||||
t.Errorf("entity name %s is %d characters, but longestEntityWithoutSemicolon=%d", k, len(k), longestEntityWithoutSemicolon)
|
||||
}
|
||||
}
|
||||
for k, v := range entity2 {
|
||||
if 1+len(k) < utf8.RuneLen(v[0])+utf8.RuneLen(v[1]) {
|
||||
t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v[0]) + string(v[1]))
|
||||
}
|
||||
}
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
// Copyright 2010 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package html
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// These replacements permit compatibility with old numeric entities that
|
||||
// assumed Windows-1252 encoding.
|
||||
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#consume-a-character-reference
|
||||
var replacementTable = [...]rune{
|
||||
'\u20AC', // First entry is what 0x80 should be replaced with.
|
||||
'\u0081',
|
||||
'\u201A',
|
||||
'\u0192',
|
||||
'\u201E',
|
||||
'\u2026',
|
||||
'\u2020',
|
||||
'\u2021',
|
||||
'\u02C6',
|
||||
'\u2030',
|
||||
'\u0160',
|
||||
'\u2039',
|
||||
'\u0152',
|
||||
'\u008D',
|
||||
'\u017D',
|
||||
'\u008F',
|
||||
'\u0090',
|
||||
'\u2018',
|
||||
'\u2019',
|
||||
'\u201C',
|
||||
'\u201D',
|
||||
'\u2022',
|
||||
'\u2013',
|
||||
'\u2014',
|
||||
'\u02DC',
|
||||
'\u2122',
|
||||
'\u0161',
|
||||
'\u203A',
|
||||
'\u0153',
|
||||
'\u009D',
|
||||
'\u017E',
|
||||
'\u0178', // Last entry is 0x9F.
|
||||
// 0x00->'\uFFFD' is handled programmatically.
|
||||
// 0x0D->'\u000D' is a no-op.
|
||||
}
|
||||
|
||||
// unescapeEntity reads an entity like "<" from b[src:] and writes the
|
||||
// corresponding "<" to b[dst:], returning the incremented dst and src cursors.
|
||||
// Precondition: b[src] == '&' && dst <= src.
|
||||
// attribute should be true if parsing an attribute value.
|
||||
func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) {
|
||||
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#consume-a-character-reference
|
||||
|
||||
// i starts at 1 because we already know that s[0] == '&'.
|
||||
i, s := 1, b[src:]
|
||||
|
||||
if len(s) <= 1 {
|
||||
b[dst] = b[src]
|
||||
return dst + 1, src + 1
|
||||
}
|
||||
|
||||
if s[i] == '#' {
|
||||
if len(s) <= 3 { // We need to have at least "&#.".
|
||||
b[dst] = b[src]
|
||||
return dst + 1, src + 1
|
||||
}
|
||||
i++
|
||||
c := s[i]
|
||||
hex := false
|
||||
if c == 'x' || c == 'X' {
|
||||
hex = true
|
||||
i++
|
||||
}
|
||||
|
||||
x := '\x00'
|
||||
for i < len(s) {
|
||||
c = s[i]
|
||||
i++
|
||||
if hex {
|
||||
if '0' <= c && c <= '9' {
|
||||
x = 16*x + rune(c) - '0'
|
||||
continue
|
||||
} else if 'a' <= c && c <= 'f' {
|
||||
x = 16*x + rune(c) - 'a' + 10
|
||||
continue
|
||||
} else if 'A' <= c && c <= 'F' {
|
||||
x = 16*x + rune(c) - 'A' + 10
|
||||
continue
|
||||
}
|
||||
} else if '0' <= c && c <= '9' {
|
||||
x = 10*x + rune(c) - '0'
|
||||
continue
|
||||
}
|
||||
if c != ';' {
|
||||
i--
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
if i <= 3 { // No characters matched.
|
||||
b[dst] = b[src]
|
||||
return dst + 1, src + 1
|
||||
}
|
||||
|
||||
if 0x80 <= x && x <= 0x9F {
|
||||
// Replace characters from Windows-1252 with UTF-8 equivalents.
|
||||
x = replacementTable[x-0x80]
|
||||
} else if x == 0 || (0xD800 <= x && x <= 0xDFFF) || x > 0x10FFFF {
|
||||
// Replace invalid characters with the replacement character.
|
||||
x = '\uFFFD'
|
||||
}
|
||||
|
||||
return dst + utf8.EncodeRune(b[dst:], x), src + i
|
||||
}
|
||||
|
||||
// Consume the maximum number of characters possible, with the
|
||||
// consumed characters matching one of the named references.
|
||||
|
||||
for i < len(s) {
|
||||
c := s[i]
|
||||
i++
|
||||
// Lower-cased characters are more common in entities, so we check for them first.
|
||||
if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' {
|
||||
continue
|
||||
}
|
||||
if c != ';' {
|
||||
i--
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
entityName := string(s[1:i])
|
||||
if entityName == "" {
|
||||
// No-op.
|
||||
} else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' {
|
||||
// No-op.
|
||||
} else if x := entity[entityName]; x != 0 {
|
||||
return dst + utf8.EncodeRune(b[dst:], x), src + i
|
||||
} else if x := entity2[entityName]; x[0] != 0 {
|
||||
dst1 := dst + utf8.EncodeRune(b[dst:], x[0])
|
||||
return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i
|
||||
} else if !attribute {
|
||||
maxLen := len(entityName) - 1
|
||||
if maxLen > longestEntityWithoutSemicolon {
|
||||
maxLen = longestEntityWithoutSemicolon
|
||||
}
|
||||
for j := maxLen; j > 1; j-- {
|
||||
if x := entity[entityName[:j]]; x != 0 {
|
||||
return dst + utf8.EncodeRune(b[dst:], x), src + j + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dst1, src1 = dst+i, src+i
|
||||
copy(b[dst:dst1], b[src:src1])
|
||||
return dst1, src1
|
||||
}
|
||||
|
||||
// unescape unescapes b's entities in-place, so that "a<b" becomes "a<b".
|
||||
// attribute should be true if parsing an attribute value.
|
||||
func unescape(b []byte, attribute bool) []byte {
|
||||
for i, c := range b {
|
||||
if c == '&' {
|
||||
dst, src := unescapeEntity(b, i, i, attribute)
|
||||
for src < len(b) {
|
||||
c := b[src]
|
||||
if c == '&' {
|
||||
dst, src = unescapeEntity(b, dst, src, attribute)
|
||||
} else {
|
||||
b[dst] = c
|
||||
dst, src = dst+1, src+1
|
||||
}
|
||||
}
|
||||
return b[0:dst]
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// lower lower-cases the A-Z bytes in b in-place, so that "aBc" becomes "abc".
|
||||
func lower(b []byte) []byte {
|
||||
for i, c := range b {
|
||||
if 'A' <= c && c <= 'Z' {
|
||||
b[i] = c + 'a' - 'A'
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
const escapedChars = "&'<>\"\r"
|
||||
|
||||
func escape(w writer, s string) error {
|
||||
i := strings.IndexAny(s, escapedChars)
|
||||
for i != -1 {
|
||||
if _, err := w.WriteString(s[:i]); err != nil {
|
||||
return err
|
||||
}
|
||||
var esc string
|
||||
switch s[i] {
|
||||
case '&':
|
||||
esc = "&"
|
||||
case '\'':
|
||||
// "'" is shorter than "'" and apos was not in HTML until HTML5.
|
||||
esc = "'"
|
||||
case '<':
|
||||
esc = "<"
|
||||
case '>':
|
||||
esc = ">"
|
||||
case '"':
|
||||
// """ is shorter than """.
|
||||
esc = """
|
||||
case '\r':
|
||||
esc = " "
|
||||
default:
|
||||
panic("unrecognized escape character")
|
||||
}
|
||||
s = s[i+1:]
|
||||
if _, err := w.WriteString(esc); err != nil {
|
||||
return err
|
||||
}
|
||||
i = strings.IndexAny(s, escapedChars)
|
||||
}
|
||||
_, err := w.WriteString(s)
|
||||
return err
|
||||
}
|
||||
|
||||
// EscapeString escapes special characters like "<" to become "<". It
|
||||
// escapes only five such characters: <, >, &, ' and ".
|
||||
// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't
|
||||
// always true.
|
||||
func EscapeString(s string) string {
|
||||
if strings.IndexAny(s, escapedChars) == -1 {
|
||||
return s
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
escape(&buf, s)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// UnescapeString unescapes entities like "<" to become "<". It unescapes a
|
||||
// larger range of entities than EscapeString escapes. For example, "á"
|
||||
// unescapes to "á", as does "á" and "&xE1;".
|
||||
// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't
|
||||
// always true.
|
||||
func UnescapeString(s string) string {
|
||||
for _, c := range s {
|
||||
if c == '&' {
|
||||
return string(unescape([]byte(s), false))
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
// Copyright 2013 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package html
|
||||
|
||||
import "testing"
|
||||
|
||||
type unescapeTest struct {
|
||||
// A short description of the test case.
|
||||
desc string
|
||||
// The HTML text.
|
||||
html string
|
||||
// The unescaped text.
|
||||
unescaped string
|
||||
}
|
||||
|
||||
var unescapeTests = []unescapeTest{
|
||||
// Handle no entities.
|
||||
{
|
||||
"copy",
|
||||
"A\ttext\nstring",
|
||||
"A\ttext\nstring",
|
||||
},
|
||||
// Handle simple named entities.
|
||||
{
|
||||
"simple",
|
||||
"& > <",
|
||||
"& > <",
|
||||
},
|
||||
// Handle hitting the end of the string.
|
||||
{
|
||||
"stringEnd",
|
||||
"& &",
|
||||
"& &",
|
||||
},
|
||||
// Handle entities with two codepoints.
|
||||
{
|
||||
"multiCodepoint",
|
||||
"text ⋛︀ blah",
|
||||
"text \u22db\ufe00 blah",
|
||||
},
|
||||
// Handle decimal numeric entities.
|
||||
{
|
||||
"decimalEntity",
|
||||
"Delta = Δ ",
|
||||
"Delta = Δ ",
|
||||
},
|
||||
// Handle hexadecimal numeric entities.
|
||||
{
|
||||
"hexadecimalEntity",
|
||||
"Lambda = λ = λ ",
|
||||
"Lambda = λ = λ ",
|
||||
},
|
||||
// Handle numeric early termination.
|
||||
{
|
||||
"numericEnds",
|
||||
"&# &#x €43 © = ©f = ©",
|
||||
"&# &#x €43 © = ©f = ©",
|
||||
},
|
||||
// Handle numeric ISO-8859-1 entity replacements.
|
||||
{
|
||||
"numericReplacements",
|
||||
"Footnote‡",
|
||||
"Footnote‡",
|
||||
},
|
||||
}
|
||||
|
||||
func TestUnescape(t *testing.T) {
|
||||
for _, tt := range unescapeTests {
|
||||
unescaped := UnescapeString(tt.html)
|
||||
if unescaped != tt.unescaped {
|
||||
t.Errorf("TestUnescape %s: want %q, got %q", tt.desc, tt.unescaped, unescaped)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnescapeEscape(t *testing.T) {
|
||||
ss := []string{
|
||||
``,
|
||||
`abc def`,
|
||||
`a & b`,
|
||||
`a&b`,
|
||||
`a & b`,
|
||||
`"`,
|
||||
`"`,
|
||||
`"<&>"`,
|
||||
`"<&>"`,
|
||||
`3&5==1 && 0<1, "0<1", a+acute=á`,
|
||||
`The special characters are: <, >, &, ' and "`,
|
||||
}
|
||||
for _, s := range ss {
|
||||
if got := UnescapeString(EscapeString(s)); got != s {
|
||||
t.Errorf("got %q want %q", got, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
// Copyright 2012 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// This example demonstrates parsing HTML data and walking the resulting tree.
|
||||
package html_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/golang.org/x/net/html"
|
||||
)
|
||||
|
||||
func ExampleParse() {
|
||||
s := `<p>Links:</p><ul><li><a href="foo">Foo</a><li><a href="/bar/baz">BarBaz</a></ul>`
|
||||
doc, err := html.Parse(strings.NewReader(s))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var f func(*html.Node)
|
||||
f = func(n *html.Node) {
|
||||
if n.Type == html.ElementNode && n.Data == "a" {
|
||||
for _, a := range n.Attr {
|
||||
if a.Key == "href" {
|
||||
fmt.Println(a.Val)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
f(c)
|
||||
}
|
||||
}
|
||||
f(doc)
|
||||
// Output:
|
||||
// foo
|
||||
// /bar/baz
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package html
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
func adjustAttributeNames(aa []Attribute, nameMap map[string]string) {
|
||||
for i := range aa {
|
||||
if newName, ok := nameMap[aa[i].Key]; ok {
|
||||
aa[i].Key = newName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func adjustForeignAttributes(aa []Attribute) {
|
||||
for i, a := range aa {
|
||||
if a.Key == "" || a.Key[0] != 'x' {
|
||||
continue
|
||||
}
|
||||
switch a.Key {
|
||||
case "xlink:actuate", "xlink:arcrole", "xlink:href", "xlink:role", "xlink:show",
|
||||
"xlink:title", "xlink:type", "xml:base", "xml:lang", "xml:space", "xmlns:xlink":
|
||||
j := strings.Index(a.Key, ":")
|
||||
aa[i].Namespace = a.Key[:j]
|
||||
aa[i].Key = a.Key[j+1:]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func htmlIntegrationPoint(n *Node) bool {
|
||||
if n.Type != ElementNode {
|
||||
return false
|
||||
}
|
||||
switch n.Namespace {
|
||||
case "math":
|
||||
if n.Data == "annotation-xml" {
|
||||
for _, a := range n.Attr {
|
||||
if a.Key == "encoding" {
|
||||
val := strings.ToLower(a.Val)
|
||||
if val == "text/html" || val == "application/xhtml+xml" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case "svg":
|
||||
switch n.Data {
|
||||
case "desc", "foreignObject", "title":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func mathMLTextIntegrationPoint(n *Node) bool {
|
||||
if n.Namespace != "math" {
|
||||
return false
|
||||
}
|
||||
switch n.Data {
|
||||
case "mi", "mo", "mn", "ms", "mtext":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Section 12.2.5.5.
|
||||
var breakout = map[string]bool{
|
||||
"b": true,
|
||||
"big": true,
|
||||
"blockquote": true,
|
||||
"body": true,
|
||||
"br": true,
|
||||
"center": true,
|
||||
"code": true,
|
||||
"dd": true,
|
||||
"div": true,
|
||||
"dl": true,
|
||||
"dt": true,
|
||||
"em": true,
|
||||
"embed": true,
|
||||
"h1": true,
|
||||
"h2": true,
|
||||
"h3": true,
|
||||
"h4": true,
|
||||
"h5": true,
|
||||
"h6": true,
|
||||
"head": true,
|
||||
"hr": true,
|
||||
"i": true,
|
||||
"img": true,
|
||||
"li": true,
|
||||
"listing": true,
|
||||
"menu": true,
|
||||
"meta": true,
|
||||
"nobr": true,
|
||||
"ol": true,
|
||||
"p": true,
|
||||
"pre": true,
|
||||
"ruby": true,
|
||||
"s": true,
|
||||
"small": true,
|
||||
"span": true,
|
||||
"strong": true,
|
||||
"strike": true,
|
||||
"sub": true,
|
||||
"sup": true,
|
||||
"table": true,
|
||||
"tt": true,
|
||||
"u": true,
|
||||
"ul": true,
|
||||
"var": true,
|
||||
}
|
||||
|
||||
// Section 12.2.5.5.
|
||||
var svgTagNameAdjustments = map[string]string{
|
||||
"altglyph": "altGlyph",
|
||||
"altglyphdef": "altGlyphDef",
|
||||
"altglyphitem": "altGlyphItem",
|
||||
"animatecolor": "animateColor",
|
||||
"animatemotion": "animateMotion",
|
||||
"animatetransform": "animateTransform",
|
||||
"clippath": "clipPath",
|
||||
"feblend": "feBlend",
|
||||
"fecolormatrix": "feColorMatrix",
|
||||
"fecomponenttransfer": "feComponentTransfer",
|
||||
"fecomposite": "feComposite",
|
||||
"feconvolvematrix": "feConvolveMatrix",
|
||||
"fediffuselighting": "feDiffuseLighting",
|
||||
"fedisplacementmap": "feDisplacementMap",
|
||||
"fedistantlight": "feDistantLight",
|
||||
"feflood": "feFlood",
|
||||
"fefunca": "feFuncA",
|
||||
"fefuncb": "feFuncB",
|
||||
"fefuncg": "feFuncG",
|
||||
"fefuncr": "feFuncR",
|
||||
"fegaussianblur": "feGaussianBlur",
|
||||
"feimage": "feImage",
|
||||
"femerge": "feMerge",
|
||||
"femergenode": "feMergeNode",
|
||||
"femorphology": "feMorphology",
|
||||
"feoffset": "feOffset",
|
||||
"fepointlight": "fePointLight",
|
||||
"fespecularlighting": "feSpecularLighting",
|
||||
"fespotlight": "feSpotLight",
|
||||
"fetile": "feTile",
|
||||
"feturbulence": "feTurbulence",
|
||||
"foreignobject": "foreignObject",
|
||||
"glyphref": "glyphRef",
|
||||
"lineargradient": "linearGradient",
|
||||
"radialgradient": "radialGradient",
|
||||
"textpath": "textPath",
|
||||
}
|
||||
|
||||
// Section 12.2.5.1
|
||||
var mathMLAttributeAdjustments = map[string]string{
|
||||
"definitionurl": "definitionURL",
|
||||
}
|
||||
|
||||
var svgAttributeAdjustments = map[string]string{
|
||||
"attributename": "attributeName",
|
||||
"attributetype": "attributeType",
|
||||
"basefrequency": "baseFrequency",
|
||||
"baseprofile": "baseProfile",
|
||||
"calcmode": "calcMode",
|
||||
"clippathunits": "clipPathUnits",
|
||||
"contentscripttype": "contentScriptType",
|
||||
"contentstyletype": "contentStyleType",
|
||||
"diffuseconstant": "diffuseConstant",
|
||||
"edgemode": "edgeMode",
|
||||
"externalresourcesrequired": "externalResourcesRequired",
|
||||
"filterres": "filterRes",
|
||||
"filterunits": "filterUnits",
|
||||
"glyphref": "glyphRef",
|
||||
"gradienttransform": "gradientTransform",
|
||||
"gradientunits": "gradientUnits",
|
||||
"kernelmatrix": "kernelMatrix",
|
||||
"kernelunitlength": "kernelUnitLength",
|
||||
"keypoints": "keyPoints",
|
||||
"keysplines": "keySplines",
|
||||
"keytimes": "keyTimes",
|
||||
"lengthadjust": "lengthAdjust",
|
||||
"limitingconeangle": "limitingConeAngle",
|
||||
"markerheight": "markerHeight",
|
||||
"markerunits": "markerUnits",
|
||||
"markerwidth": "markerWidth",
|
||||
"maskcontentunits": "maskContentUnits",
|
||||
"maskunits": "maskUnits",
|
||||
"numoctaves": "numOctaves",
|
||||
"pathlength": "pathLength",
|
||||
"patterncontentunits": "patternContentUnits",
|
||||
"patterntransform": "patternTransform",
|
||||
"patternunits": "patternUnits",
|
||||
"pointsatx": "pointsAtX",
|
||||
"pointsaty": "pointsAtY",
|
||||
"pointsatz": "pointsAtZ",
|
||||
"preservealpha": "preserveAlpha",
|
||||
"preserveaspectratio": "preserveAspectRatio",
|
||||
"primitiveunits": "primitiveUnits",
|
||||
"refx": "refX",
|
||||
"refy": "refY",
|
||||
"repeatcount": "repeatCount",
|
||||
"repeatdur": "repeatDur",
|
||||
"requiredextensions": "requiredExtensions",
|
||||
"requiredfeatures": "requiredFeatures",
|
||||
"specularconstant": "specularConstant",
|
||||
"specularexponent": "specularExponent",
|
||||
"spreadmethod": "spreadMethod",
|
||||
"startoffset": "startOffset",
|
||||
"stddeviation": "stdDeviation",
|
||||
"stitchtiles": "stitchTiles",
|
||||
"surfacescale": "surfaceScale",
|
||||
"systemlanguage": "systemLanguage",
|
||||
"tablevalues": "tableValues",
|
||||
"targetx": "targetX",
|
||||
"targety": "targetY",
|
||||
"textlength": "textLength",
|
||||
"viewbox": "viewBox",
|
||||
"viewtarget": "viewTarget",
|
||||
"xchannelselector": "xChannelSelector",
|
||||
"ychannelselector": "yChannelSelector",
|
||||
"zoomandpan": "zoomAndPan",
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package html
|
||||
|
||||
import (
|
||||
"github.com/coreos/rocket/Godeps/_workspace/src/golang.org/x/net/html/atom"
|
||||
)
|
||||
|
||||
// A NodeType is the type of a Node.
|
||||
type NodeType uint32
|
||||
|
||||
const (
|
||||
ErrorNode NodeType = iota
|
||||
TextNode
|
||||
DocumentNode
|
||||
ElementNode
|
||||
CommentNode
|
||||
DoctypeNode
|
||||
scopeMarkerNode
|
||||
)
|
||||
|
||||
// Section 12.2.3.3 says "scope markers are inserted when entering applet
|
||||
// elements, buttons, object elements, marquees, table cells, and table
|
||||
// captions, and are used to prevent formatting from 'leaking'".
|
||||
var scopeMarker = Node{Type: scopeMarkerNode}
|
||||
|
||||
// A Node consists of a NodeType and some Data (tag name for element nodes,
|
||||
// content for text) and are part of a tree of Nodes. Element nodes may also
|
||||
// have a Namespace and contain a slice of Attributes. Data is unescaped, so
|
||||
// that it looks like "a<b" rather than "a<b". For element nodes, DataAtom
|
||||
// is the atom for Data, or zero if Data is not a known tag name.
|
||||
//
|
||||
// An empty Namespace implies a "http://www.w3.org/1999/xhtml" namespace.
|
||||
// Similarly, "math" is short for "http://www.w3.org/1998/Math/MathML", and
|
||||
// "svg" is short for "http://www.w3.org/2000/svg".
|
||||
type Node struct {
|
||||
Parent, FirstChild, LastChild, PrevSibling, NextSibling *Node
|
||||
|
||||
Type NodeType
|
||||
DataAtom atom.Atom
|
||||
Data string
|
||||
Namespace string
|
||||
Attr []Attribute
|
||||
}
|
||||
|
||||
// InsertBefore inserts newChild as a child of n, immediately before oldChild
|
||||
// in the sequence of n's children. oldChild may be nil, in which case newChild
|
||||
// is appended to the end of n's children.
|
||||
//
|
||||
// It will panic if newChild already has a parent or siblings.
|
||||
func (n *Node) InsertBefore(newChild, oldChild *Node) {
|
||||
if newChild.Parent != nil || newChild.PrevSibling != nil || newChild.NextSibling != nil {
|
||||
panic("html: InsertBefore called for an attached child Node")
|
||||
}
|
||||
var prev, next *Node
|
||||
if oldChild != nil {
|
||||
prev, next = oldChild.PrevSibling, oldChild
|
||||
} else {
|
||||
prev = n.LastChild
|
||||
}
|
||||
if prev != nil {
|
||||
prev.NextSibling = newChild
|
||||
} else {
|
||||
n.FirstChild = newChild
|
||||
}
|
||||
if next != nil {
|
||||
next.PrevSibling = newChild
|
||||
} else {
|
||||
n.LastChild = newChild
|
||||
}
|
||||
newChild.Parent = n
|
||||
newChild.PrevSibling = prev
|
||||
newChild.NextSibling = next
|
||||
}
|
||||
|
||||
// AppendChild adds a node c as a child of n.
|
||||
//
|
||||
// It will panic if c already has a parent or siblings.
|
||||
func (n *Node) AppendChild(c *Node) {
|
||||
if c.Parent != nil || c.PrevSibling != nil || c.NextSibling != nil {
|
||||
panic("html: AppendChild called for an attached child Node")
|
||||
}
|
||||
last := n.LastChild
|
||||
if last != nil {
|
||||
last.NextSibling = c
|
||||
} else {
|
||||
n.FirstChild = c
|
||||
}
|
||||
n.LastChild = c
|
||||
c.Parent = n
|
||||
c.PrevSibling = last
|
||||
}
|
||||
|
||||
// RemoveChild removes a node c that is a child of n. Afterwards, c will have
|
||||
// no parent and no siblings.
|
||||
//
|
||||
// It will panic if c's parent is not n.
|
||||
func (n *Node) RemoveChild(c *Node) {
|
||||
if c.Parent != n {
|
||||
panic("html: RemoveChild called for a non-child Node")
|
||||
}
|
||||
if n.FirstChild == c {
|
||||
n.FirstChild = c.NextSibling
|
||||
}
|
||||
if c.NextSibling != nil {
|
||||
c.NextSibling.PrevSibling = c.PrevSibling
|
||||
}
|
||||
if n.LastChild == c {
|
||||
n.LastChild = c.PrevSibling
|
||||
}
|
||||
if c.PrevSibling != nil {
|
||||
c.PrevSibling.NextSibling = c.NextSibling
|
||||
}
|
||||
c.Parent = nil
|
||||
c.PrevSibling = nil
|
||||
c.NextSibling = nil
|
||||
}
|
||||
|
||||
// reparentChildren reparents all of src's child nodes to dst.
|
||||
func reparentChildren(dst, src *Node) {
|
||||
for {
|
||||
child := src.FirstChild
|
||||
if child == nil {
|
||||
break
|
||||
}
|
||||
src.RemoveChild(child)
|
||||
dst.AppendChild(child)
|
||||
}
|
||||
}
|
||||
|
||||
// clone returns a new node with the same type, data and attributes.
|
||||
// The clone has no parent, no siblings and no children.
|
||||
func (n *Node) clone() *Node {
|
||||
m := &Node{
|
||||
Type: n.Type,
|
||||
DataAtom: n.DataAtom,
|
||||
Data: n.Data,
|
||||
Attr: make([]Attribute, len(n.Attr)),
|
||||
}
|
||||
copy(m.Attr, n.Attr)
|
||||
return m
|
||||
}
|
||||
|
||||
// nodeStack is a stack of nodes.
|
||||
type nodeStack []*Node
|
||||
|
||||
// pop pops the stack. It will panic if s is empty.
|
||||
func (s *nodeStack) pop() *Node {
|
||||
i := len(*s)
|
||||
n := (*s)[i-1]
|
||||
*s = (*s)[:i-1]
|
||||
return n
|
||||
}
|
||||
|
||||
// top returns the most recently pushed node, or nil if s is empty.
|
||||
func (s *nodeStack) top() *Node {
|
||||
if i := len(*s); i > 0 {
|
||||
return (*s)[i-1]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// index returns the index of the top-most occurrence of n in the stack, or -1
|
||||
// if n is not present.
|
||||
func (s *nodeStack) index(n *Node) int {
|
||||
for i := len(*s) - 1; i >= 0; i-- {
|
||||
if (*s)[i] == n {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// insert inserts a node at the given index.
|
||||
func (s *nodeStack) insert(i int, n *Node) {
|
||||
(*s) = append(*s, nil)
|
||||
copy((*s)[i+1:], (*s)[i:])
|
||||
(*s)[i] = n
|
||||
}
|
||||
|
||||
// remove removes a node from the stack. It is a no-op if n is not present.
|
||||
func (s *nodeStack) remove(n *Node) {
|
||||
i := s.index(n)
|
||||
if i == -1 {
|
||||
return
|
||||
}
|
||||
copy((*s)[i:], (*s)[i+1:])
|
||||
j := len(*s) - 1
|
||||
(*s)[j] = nil
|
||||
*s = (*s)[:j]
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
// Copyright 2010 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package html
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// checkTreeConsistency checks that a node and its descendants are all
|
||||
// consistent in their parent/child/sibling relationships.
|
||||
func checkTreeConsistency(n *Node) error {
|
||||
return checkTreeConsistency1(n, 0)
|
||||
}
|
||||
|
||||
func checkTreeConsistency1(n *Node, depth int) error {
|
||||
if depth == 1e4 {
|
||||
return fmt.Errorf("html: tree looks like it contains a cycle")
|
||||
}
|
||||
if err := checkNodeConsistency(n); err != nil {
|
||||
return err
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
if err := checkTreeConsistency1(c, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkNodeConsistency checks that a node's parent/child/sibling relationships
|
||||
// are consistent.
|
||||
func checkNodeConsistency(n *Node) error {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
nParent := 0
|
||||
for p := n.Parent; p != nil; p = p.Parent {
|
||||
nParent++
|
||||
if nParent == 1e4 {
|
||||
return fmt.Errorf("html: parent list looks like an infinite loop")
|
||||
}
|
||||
}
|
||||
|
||||
nForward := 0
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
nForward++
|
||||
if nForward == 1e6 {
|
||||
return fmt.Errorf("html: forward list of children looks like an infinite loop")
|
||||
}
|
||||
if c.Parent != n {
|
||||
return fmt.Errorf("html: inconsistent child/parent relationship")
|
||||
}
|
||||
}
|
||||
|
||||
nBackward := 0
|
||||
for c := n.LastChild; c != nil; c = c.PrevSibling {
|
||||
nBackward++
|
||||
if nBackward == 1e6 {
|
||||
return fmt.Errorf("html: backward list of children looks like an infinite loop")
|
||||
}
|
||||
if c.Parent != n {
|
||||
return fmt.Errorf("html: inconsistent child/parent relationship")
|
||||
}
|
||||
}
|
||||
|
||||
if n.Parent != nil {
|
||||
if n.Parent == n {
|
||||
return fmt.Errorf("html: inconsistent parent relationship")
|
||||
}
|
||||
if n.Parent == n.FirstChild {
|
||||
return fmt.Errorf("html: inconsistent parent/first relationship")
|
||||
}
|
||||
if n.Parent == n.LastChild {
|
||||
return fmt.Errorf("html: inconsistent parent/last relationship")
|
||||
}
|
||||
if n.Parent == n.PrevSibling {
|
||||
return fmt.Errorf("html: inconsistent parent/prev relationship")
|
||||
}
|
||||
if n.Parent == n.NextSibling {
|
||||
return fmt.Errorf("html: inconsistent parent/next relationship")
|
||||
}
|
||||
|
||||
parentHasNAsAChild := false
|
||||
for c := n.Parent.FirstChild; c != nil; c = c.NextSibling {
|
||||
if c == n {
|
||||
parentHasNAsAChild = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !parentHasNAsAChild {
|
||||
return fmt.Errorf("html: inconsistent parent/child relationship")
|
||||
}
|
||||
}
|
||||
|
||||
if n.PrevSibling != nil && n.PrevSibling.NextSibling != n {
|
||||
return fmt.Errorf("html: inconsistent prev/next relationship")
|
||||
}
|
||||
if n.NextSibling != nil && n.NextSibling.PrevSibling != n {
|
||||
return fmt.Errorf("html: inconsistent next/prev relationship")
|
||||
}
|
||||
|
||||
if (n.FirstChild == nil) != (n.LastChild == nil) {
|
||||
return fmt.Errorf("html: inconsistent first/last relationship")
|
||||
}
|
||||
if n.FirstChild != nil && n.FirstChild == n.LastChild {
|
||||
// We have a sole child.
|
||||
if n.FirstChild.PrevSibling != nil || n.FirstChild.NextSibling != nil {
|
||||
return fmt.Errorf("html: inconsistent sole child's sibling relationship")
|
||||
}
|
||||
}
|
||||
|
||||
seen := map[*Node]bool{}
|
||||
|
||||
var last *Node
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
if seen[c] {
|
||||
return fmt.Errorf("html: inconsistent repeated child")
|
||||
}
|
||||
seen[c] = true
|
||||
last = c
|
||||
}
|
||||
if last != n.LastChild {
|
||||
return fmt.Errorf("html: inconsistent last relationship")
|
||||
}
|
||||
|
||||
var first *Node
|
||||
for c := n.LastChild; c != nil; c = c.PrevSibling {
|
||||
if !seen[c] {
|
||||
return fmt.Errorf("html: inconsistent missing child")
|
||||
}
|
||||
delete(seen, c)
|
||||
first = c
|
||||
}
|
||||
if first != n.FirstChild {
|
||||
return fmt.Errorf("html: inconsistent first relationship")
|
||||
}
|
||||
|
||||
if len(seen) != 0 {
|
||||
return fmt.Errorf("html: inconsistent forwards/backwards child list")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user