mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-12-05 05:43:36 -05:00
Merge pull request #4199 from opencloud-eu/feat/thumbnails-drop-builtin-extractors
feat(webdav)!: drop the built-in audio and GeoGebra extractors
This commit is contained in:
45 files changed
+53
-5668
No files matched your search
@@ -17,7 +17,6 @@ require (
|
||||
github.com/cenkalti/backoff v2.2.1+incompatible
|
||||
github.com/coreos/go-oidc/v3 v3.21.0
|
||||
github.com/cs3org/go-cs3apis v0.0.0-20260424072047-8d9ef7076ae9
|
||||
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
|
||||
github.com/dutchcoders/go-clamd v0.0.0-20170520113014-b970184f4d9e
|
||||
github.com/gabriel-vasile/mimetype v1.4.15
|
||||
github.com/ggwhite/go-masker v1.1.0
|
||||
|
||||
@@ -237,8 +237,6 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
|
||||
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 h1:OtSeLS5y0Uy01jaKK4mA/WVIYtpzVm63vLVAPzJXigg=
|
||||
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8/go.mod h1:apkPC/CR3s48O2D7Y++n1XWEpgPNNCjXYga3PPbJe2E=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8=
|
||||
|
||||
@@ -15,13 +15,13 @@ The webdav service provides various `GET` endpoints to get the thumbnails of a f
|
||||
Three parties can turn a file into a thumbnail:
|
||||
|
||||
- the **generator** (imagor, or the thumbnails service in its place) scales images
|
||||
- the **built-in converters** in the webdav service render plain text and extract audio cover art and GeoGebra thumbnails. The audio and GeoGebra extractors are deprecated in favour of Tika.
|
||||
- the **built-in text converter** in the webdav service renders plain text
|
||||
- an **Apache Tika server**, when configured, extracts a preview image from documents, ebooks, office files, audio, camera raws and more
|
||||
|
||||
A thumbnail is only attempted for a type that is announced (`OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` plus the built-in list) or that Tika takes (named in the Tika list, or any type when the list contains `*`). Every other type answers `404` without the file being read. For the types that pass, the first rule that applies wins:
|
||||
|
||||
1. a type the Tika list names goes to Tika, even an image (that is how camera raws get a preview: reva types them as images, and no generator reads them)
|
||||
2. text, audio and GeoGebra go to the built-in converters
|
||||
2. plain text goes to the built-in text converter
|
||||
3. an image goes to the generator as it is
|
||||
4. anything else goes to Tika if the Tika list contains `*`
|
||||
5. what is left is an announced type, and it goes to the generator as it is, which answers whether it can read it
|
||||
@@ -35,8 +35,8 @@ So `*` never sends an image to Tika. An image type that only Tika can read has t
|
||||
| `photo.jpg` | generator | generator | generator | generator | generator |
|
||||
| `photo.nef` (raw) | no preview | Tika | Tika | generator, 404 | no preview |
|
||||
| `report.pdf`, `.docx` | no preview | Tika | Tika | Tika | no preview |
|
||||
| `song.mp3` | built-in | Tika | Tika | built-in | built-in |
|
||||
| `board.ggs` | built-in | Tika | Tika | built-in | built-in |
|
||||
| `song.mp3` | no preview | Tika | Tika | Tika | no preview |
|
||||
| `board.ggs` | no preview | Tika | Tika | Tika | no preview |
|
||||
| `notes.txt` | built-in | built-in | built-in | built-in | built-in |
|
||||
| `archive.zip` | no preview | no preview | Tika | Tika | no preview |
|
||||
|
||||
@@ -78,7 +78,7 @@ Announcing a type and sending it to Tika are separate settings:
|
||||
- `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` decides what `oc:has-preview` reports in a listing.
|
||||
- The Tika list decides who makes the image.
|
||||
|
||||
A type that Tika takes is attempted even when it is not announced. A direct request can therefore get a preview that a listing reports as absent.
|
||||
A type that Tika takes is attempted even when it is not announced. A direct request can therefore get a preview that a listing reports as absent. Audio and GeoGebra are not announced by default, because only Tika extracts their previews. With Tika, add them to `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` (for example `audio/mpeg,audio/flac,audio/ogg,application/vnd.geogebra.slides,application/vnd.geogebra.pinboard`) so listings report their previews again.
|
||||
|
||||
The thumbnail is written in the type that the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever Tika returns. The answer is the same before and after a cache hit. A Windows binary maps to `image/png` by default, because the icon Tika reads from it has transparency that a JPEG would flatten onto black.
|
||||
|
||||
@@ -98,7 +98,7 @@ The webdav service caches the thumbnails it generates. Choose a backend with `WE
|
||||
##### What Is Cached
|
||||
|
||||
- every generated thumbnail, one entry per size
|
||||
- once per file, the image an extractor (Tika or a built-in converter) got from it, so a second size does not extract again
|
||||
- once per file, the image Tika or the text converter made of it, so a second size does not extract again
|
||||
- the fact that a file holds no image at all, so the extractor is asked only once
|
||||
|
||||
A failed extraction (Tika unreachable, preset not active, a broken file) is not cached and is retried on the next request.
|
||||
@@ -159,7 +159,7 @@ Without a processor two things decide, in this order. An unconstrained axis is a
|
||||
|
||||
#### Thumbnail Generator
|
||||
|
||||
The thumbnails themselves are made by a generator the webdav service POSTs to, configured with `WEBDAV_THUMBNAILS_GENERATOR_URL` (and `WEBDAV_THUMBNAILS_GENERATOR_TIMEOUT`). The built-in thumbnails service speaks the imagor image endpoint, so a real [imagor](https://imagor.net) can be put in its place without changing anything else. A source the generator cannot read answers `404`, one that is too large `403`, and `WEBDAV_THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE` caps what is sent at all; `OC_THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE` sets this and the generator's own cap together, so one does not send what the other refuses. A generator that refuses because it is busy answers `429` with its own `Retry-After`, so a client can come back instead of treating it as a missing preview. The same cap bounds an image webdav extracts itself, the cover of an audio file or the thumbnail inside a geogebra container, because a compressed entry says nothing about its size until it is read. A cropping resize asks the generator for a smart crop, so what survives is the region that carries the image; the built-in thumbnails service answers the same request with a centre crop.
|
||||
The thumbnails themselves are made by a generator the webdav service POSTs to, configured with `WEBDAV_THUMBNAILS_GENERATOR_URL` (and `WEBDAV_THUMBNAILS_GENERATOR_TIMEOUT`). The built-in thumbnails service speaks the imagor image endpoint, so a real [imagor](https://imagor.net) can be put in its place without changing anything else. A source the generator cannot read answers `404`, one that is too large `403`, and `WEBDAV_THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE` caps what is sent at all; `OC_THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE` sets this and the generator's own cap together, so one does not send what the other refuses. A generator that refuses because it is busy answers `429` with its own `Retry-After`, so a client can come back instead of treating it as a missing preview. A cropping resize asks the generator for a smart crop, so what survives is the region that carries the image; the built-in thumbnails service answers the same request with a centre crop.
|
||||
|
||||
Three settings say what is made of what. Each one is merged onto the built-in defaults, which is what their `ADDITIONAL` says: naming one type does not take the answer away from the others, and an entry for a type the defaults already answer for replaces that one entry. The first takes bare mime types, the other two take `key:value` entries:
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ type Config struct {
|
||||
TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail (or the preset named in OC_TIKA_THUMBNAIL_PRESET). A 4.1.x server works as well, with the preset activated in its config file instead." introductionVersion:"%%NEXT%%"`
|
||||
TikaThumbnailPreset string `yaml:"tika_thumbnail_preset" env:"OC_TIKA_THUMBNAIL_PRESET;WEBDAV_TIKA_THUMBNAIL_PRESET" desc:"The Tika catalog preset that unpacks the thumbnail, called as PUT /unpack/preset/<name>. It has to be active on the Tika server. A preset of your own has to bring the same filter as the built-in one, unpacking only the raster images Tika marks as THUMBNAIL or RENDERING, because the first image in the answer is taken as the thumbnail. Must not be empty." introductionVersion:"%%NEXT%%"`
|
||||
TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"The mime types sent to Tika for their thumbnail. This replaces the built-in list of the formats a Tika release serves one for. Use it to remove types from that list, or set it empty to send nothing, which leaves a Tika server shared with the search service to the search service alone. To send more types, use OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES instead. Whatever this setting holds is the whole list, so a '*' alone drops the camera raws: reva types them as images, and only a named entry sends an image to Tika. A named type goes to Tika before anything else. An entry can map a type to the name Tika uses for the format, e.g. image/x-nikon-nef:image/x-raw-nikon. That name decides which parser reads the file, so a raw that Tika only detects as a plain tiff loses its embedded preview. The formats in the built-in list need no mapping." introductionVersion:"%%NEXT%%"`
|
||||
AdditionalTikaThumbnailMimeTypes []string `yaml:"additional_tika_thumbnail_mime_types" env:"OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES" desc:"Additional mime types sent to Tika for their thumbnail. They are added to the built-in list, or to whatever OC_TIKA_THUMBNAIL_MIME_TYPES names instead. This is the usual way to send more types to Tika. A single '*' sends every type that is neither an image nor has a built-in converter, so it never sends an image. An image type that only Tika can read has to be named. An entry can carry a type mapping the same way as in OC_TIKA_THUMBNAIL_MIME_TYPES." introductionVersion:"%%NEXT%%"`
|
||||
AdditionalTikaThumbnailMimeTypes []string `yaml:"additional_tika_thumbnail_mime_types" env:"OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES" desc:"Additional mime types sent to Tika for their thumbnail. They are added to the built-in list, or to whatever OC_TIKA_THUMBNAIL_MIME_TYPES names instead. This is the usual way to send more types to Tika. A single '*' sends every type that is neither an image nor plain text, so it never sends an image. An image type that only Tika can read has to be named. An entry can carry a type mapping the same way as in OC_TIKA_THUMBNAIL_MIME_TYPES." introductionVersion:"%%NEXT%%"`
|
||||
|
||||
Context context.Context `yaml:"-"`
|
||||
}
|
||||
@@ -55,7 +55,7 @@ type Thumbnails struct {
|
||||
CacheS3Endpoint string `yaml:"cache_s3_endpoint" env:"WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT" desc:"S3 endpoint URL (for MinIO or compatible services) when WEBDAV_THUMBNAILS_CACHE_BACKEND is 's3'." introductionVersion:"9.0.0"`
|
||||
CacheS3AccessKey string `yaml:"cache_s3_access_key" env:"WEBDAV_THUMBNAILS_CACHE_S3_ACCESS_KEY" desc:"S3 access key for thumbnail cache authentication." introductionVersion:"9.0.0"`
|
||||
CacheS3SecretKey string `yaml:"cache_s3_secret_key" env:"WEBDAV_THUMBNAILS_CACHE_S3_SECRET_KEY" desc:"S3 secret key for thumbnail cache authentication." introductionVersion:"9.0.0"`
|
||||
AdditionalSourceTypes []string `yaml:"additional_source_types" env:"OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES;WEBDAV_THUMBNAILS_ADDITIONAL_SOURCE_TYPES" desc:"Additional mime types a preview is announced and attempted for, e.g. image/vnd.microsoft.icon for a generator that reads icons. The built-in list is included; this only adds to them. An announced type that the Tika list does not name and no built-in converter takes goes to the generator as it is, an image always and anything else unless the Tika list has '*'; a type the running generator cannot read answers 404. Announcing a type does not send it to Tika, naming it in the Tika list does." introductionVersion:"9.0.0"`
|
||||
AdditionalSourceTypes []string `yaml:"additional_source_types" env:"OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES;WEBDAV_THUMBNAILS_ADDITIONAL_SOURCE_TYPES" desc:"Additional mime types a preview is announced and attempted for, e.g. image/vnd.microsoft.icon for a generator that reads icons. The built-in list is included; this only adds to them. An announced type that the Tika list does not name and that is not plain text goes to the generator as it is, an image always and anything else unless the Tika list has '*'; a type the running generator cannot read answers 404. Announcing a type does not send it to Tika, naming it in the Tika list does." introductionVersion:"9.0.0"`
|
||||
|
||||
AdditionalGeneratorFormats []string `yaml:"additional_generator_formats" env:"OC_THUMBNAILS_ADDITIONAL_GENERATOR_FORMATS;WEBDAV_THUMBNAILS_ADDITIONAL_GENERATOR_FORMATS" desc:"Additional formats the thumbnail generator writes, one per type it writes, as type:format entries, e.g. image/webp:webp. The format is the name the generator's own format filter uses. The built-in list is included; an entry for a type that is already listed replaces it. A type that is not listed is asked for as a JPEG instead, because what the generator behind the URL really writes is its own business." introductionVersion:"9.0.0"`
|
||||
AdditionalOutputTypes []string `yaml:"additional_output_types" env:"OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES;WEBDAV_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES" desc:"Additional types a thumbnail is returned in, one per type of the image it is made from, as source:target entries, e.g. image/vnd.microsoft.icon:image/png. The built-in list is included; an entry for a source type that is already listed replaces it. The target is asked for by the name WEBDAV_THUMBNAILS_ADDITIONAL_GENERATOR_FORMATS gives it. A type that is not listed becomes a JPEG; a target this service has no format name for is asked for as a JPEG as well." introductionVersion:"9.0.0"`
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package preprocessor
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail"
|
||||
"image"
|
||||
"image/draw"
|
||||
@@ -13,15 +10,12 @@ import (
|
||||
"io"
|
||||
"math"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/image/font"
|
||||
"golang.org/x/image/font/opentype"
|
||||
"golang.org/x/image/math/fixed"
|
||||
|
||||
"github.com/dhowden/tag"
|
||||
)
|
||||
|
||||
// FileConverter is the interface for the file converter
|
||||
@@ -39,91 +33,6 @@ type Image struct {
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// GgsDecoder is a converter for the geogebra slides file.
|
||||
//
|
||||
// Deprecated: Tika provides the thumbnail; kept for setups without Tika.
|
||||
type GgsDecoder struct {
|
||||
thumbnailpath string
|
||||
|
||||
// a deflated entry expands by orders of magnitude, so its own size says nothing
|
||||
maxSize uint64
|
||||
}
|
||||
|
||||
func (GgsDecoder) Name() string { return "oc-ggs" }
|
||||
|
||||
// Convert reads the ggs file and returns the thumbnail image.
|
||||
//
|
||||
// TODO: this parses user-provided bytes in-process (archive/zip streams the
|
||||
// embedded thumbnail out of the .ggs container). The image itself is handed on
|
||||
// undecoded, but reading the container in webdav is an attack vector of its
|
||||
// own; Tika is the intended out-of-process extractor for embedded images.
|
||||
func (g GgsDecoder) Convert(r io.Reader) (*Image, error) {
|
||||
var buf bytes.Buffer
|
||||
_, err := io.Copy(&buf, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
zipReader, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range zipReader.File {
|
||||
if file.Name == g.thumbnailpath {
|
||||
if file.UncompressedSize64 > g.maxSize {
|
||||
return nil, errors.Errorf("the embedded image declares %d bytes, more than the %d allowed", file.UncompressedSize64, g.maxSize)
|
||||
}
|
||||
|
||||
thumbnail, err := file.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// archive/zip holds the entry to its declared size while reading,
|
||||
// so the bound here is what makes that declaration ours
|
||||
data, err := io.ReadAll(io.LimitReader(thumbnail, int64(g.maxSize)+1))
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, `could not read the embedded image`)
|
||||
}
|
||||
if uint64(len(data)) > g.maxSize {
|
||||
return nil, errors.Errorf("the embedded image is larger than the %d bytes allowed", g.maxSize)
|
||||
}
|
||||
|
||||
return &Image{ContentType: "image/png", Data: data}, nil
|
||||
}
|
||||
}
|
||||
return nil, ErrNoThumbnail
|
||||
}
|
||||
|
||||
// AudioDecoder is a converter for the audio file.
|
||||
//
|
||||
// Deprecated: Tika provides the cover art; kept for setups without Tika.
|
||||
type AudioDecoder struct{}
|
||||
|
||||
func (AudioDecoder) Name() string { return "oc-audio" }
|
||||
|
||||
// Convert reads the audio file and extracts the thumbnail image from the id3 tag.
|
||||
//
|
||||
// TODO: this parses user-provided bytes in-process (dhowden/tag reads the audio
|
||||
// metadata and pulls the embedded APIC picture). The picture itself is handed
|
||||
// on undecoded, but reading the metadata in webdav is an attack vector of its
|
||||
// own; Tika is the intended out-of-process extractor for embedded images.
|
||||
func (i AudioDecoder) Convert(r io.Reader) (*Image, error) {
|
||||
b, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m, err := tag.ReadFrom(bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
picture := m.Picture()
|
||||
if picture == nil || !strings.HasPrefix(picture.MIMEType, "image/") {
|
||||
return nil, ErrNoThumbnail
|
||||
}
|
||||
|
||||
return &Image{ContentType: picture.MIMEType, Data: picture.Data}, nil
|
||||
}
|
||||
|
||||
// TxtToImageConverter is a converter for the text file
|
||||
type TxtToImageConverter struct {
|
||||
fontLoader *FontLoader
|
||||
@@ -221,70 +130,6 @@ Scan: // Label for the scanner loop, so we can break it easily
|
||||
return &Image{ContentType: "image/png", Data: buf.Bytes()}, nil
|
||||
}
|
||||
|
||||
// GGPStruct is the layout of a ggp file (which is basically json)
|
||||
type GGPStruct struct {
|
||||
Sections []struct {
|
||||
Cards []struct {
|
||||
Element struct {
|
||||
Image struct {
|
||||
Base64Image string
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GgpDecoder is a converter for the geogebra pinboard file.
|
||||
//
|
||||
// Deprecated: see GgsDecoder.
|
||||
type GgpDecoder struct{}
|
||||
|
||||
func (GgpDecoder) Name() string { return "oc-ggp" }
|
||||
|
||||
// Convert reads the ggp file and returns the first thumbnail image.
|
||||
//
|
||||
// TODO: this parses user-provided bytes in-process (JSON/base64 extraction of
|
||||
// the embedded image). The image itself is handed on undecoded, but reading the
|
||||
// document in webdav is an attack vector of its own; Tika is the intended
|
||||
// out-of-process extractor for embedded images.
|
||||
func (j GgpDecoder) Convert(r io.Reader) (*Image, error) {
|
||||
ggp := &GGPStruct{}
|
||||
err := json.NewDecoder(r).Decode(ggp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
elem, err := extractBase64ImageFromGGP(ggp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
b, err := base64.StdEncoding.DecodeString(elem)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
contentType := http.DetectContentType(b)
|
||||
if !strings.HasPrefix(contentType, "image/") {
|
||||
return nil, ErrNoThumbnail
|
||||
}
|
||||
|
||||
return &Image{ContentType: contentType, Data: b}, nil
|
||||
}
|
||||
|
||||
func extractBase64ImageFromGGP(ggp *GGPStruct) (string, error) {
|
||||
if len(ggp.Sections) < 1 || len(ggp.Sections[0].Cards) < 1 {
|
||||
return "", ErrNoThumbnail
|
||||
}
|
||||
|
||||
raw := strings.Split(ggp.Sections[0].Cards[0].Element.Image.Base64Image, "base64,")
|
||||
if len(raw) < 2 {
|
||||
return "", ErrNoThumbnail
|
||||
}
|
||||
|
||||
return raw[1], nil
|
||||
}
|
||||
|
||||
// Draw the word in the canvas. The mixX and maxX defines the drawable range
|
||||
// (X axis) where the word can be drawn (in case the word is too big and doesn't
|
||||
// fit in the canvas), and the incY defines the increment in the Y axis if we
|
||||
@@ -345,30 +190,13 @@ func drawWord(canvas *font.Drawer, word string, minX, maxX, incY, maxY fixed.Int
|
||||
}
|
||||
}
|
||||
|
||||
// defaultMaxExtractedSize bounds an image extracted from a container when the
|
||||
// caller passes no limit of its own.
|
||||
const defaultMaxExtractedSize = 50 << 20
|
||||
|
||||
// maxExtractedSize is the caller's configured maximum input size, which bounds
|
||||
// what an extractor may produce as well. An unlimited input (0) still bounds
|
||||
// the extracted image, because the point of the limit here is the expansion
|
||||
// factor, not the size of the file the user uploaded.
|
||||
func maxExtractedSize(opts Options) uint64 {
|
||||
if opts.MaxImageSize > 0 {
|
||||
return opts.MaxImageSize
|
||||
}
|
||||
|
||||
return defaultMaxExtractedSize
|
||||
}
|
||||
|
||||
// Options carries what a converter needs from the caller. The zero value asks
|
||||
// for the defaults.
|
||||
type Options struct {
|
||||
FontMapFile string
|
||||
FontFace *opentype.FaceOptions
|
||||
MaxImageSize uint64
|
||||
Tika thumbnail.Tika
|
||||
Filename string
|
||||
FontMapFile string
|
||||
FontFace *opentype.FaceOptions
|
||||
Tika thumbnail.Tika
|
||||
Filename string
|
||||
}
|
||||
|
||||
func toTika(opts Options, mimeType string) FileConverter {
|
||||
@@ -384,7 +212,7 @@ func toTika(opts Options, mimeType string) FileConverter {
|
||||
// 1. a type the Tika list names goes to Tika, an image too, which is how a raw
|
||||
// photo is extracted instead of being handed to a generator that cannot
|
||||
// read it
|
||||
// 2. a type with a converter here is converted here
|
||||
// 2. plain text is rendered here
|
||||
// 3. an image goes to the generator
|
||||
// 4. what is left goes to Tika when it was told to take everything
|
||||
// 5. and otherwise to the generator
|
||||
@@ -419,12 +247,6 @@ func ForType(mimeType string, opts Options) FileConverter {
|
||||
}
|
||||
|
||||
return TxtToImageConverter{fontLoader: fontLoader}
|
||||
case "application/vnd.geogebra.slides":
|
||||
return GgsDecoder{thumbnailpath: "_slide0/geogebra_thumbnail.png", maxSize: maxExtractedSize(opts)}
|
||||
case "application/vnd.geogebra.pinboard":
|
||||
return GgpDecoder{}
|
||||
case "audio/flac", "audio/mpeg", "audio/ogg":
|
||||
return AudioDecoder{}
|
||||
}
|
||||
|
||||
if strings.HasPrefix(mimeType, "image/") {
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
package preprocessor
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/image/font"
|
||||
@@ -22,160 +16,7 @@ func TestPreprocessor(t *testing.T) {
|
||||
RunSpecs(t, "Preprocessor Suite")
|
||||
}
|
||||
|
||||
const ggsThumbnailPath = "_slide0/geogebra_thumbnail.png"
|
||||
|
||||
// ggsWithEntry deflates size bytes of zeros into a ggs container. lieAboutSize
|
||||
// patches the declared sizes down to one byte, the way a crafted file does.
|
||||
func ggsWithEntry(size int, lieAboutSize bool) []byte {
|
||||
var buf bytes.Buffer
|
||||
w := zip.NewWriter(&buf)
|
||||
entry, err := w.Create(ggsThumbnailPath)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = entry.Write(make([]byte, size))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(w.Close()).To(Succeed())
|
||||
|
||||
out := buf.Bytes()
|
||||
if !lieAboutSize {
|
||||
return out
|
||||
}
|
||||
|
||||
// uncompressed size: 4 bytes at offset 22 of the local header, at offset 24
|
||||
// of the central directory entry
|
||||
patch := func(signature []byte, offset int) {
|
||||
at := bytes.Index(out, signature)
|
||||
Expect(at).ToNot(Equal(-1))
|
||||
binary.LittleEndian.PutUint32(out[at+offset:], 1)
|
||||
}
|
||||
patch([]byte("PK\x03\x04"), 22)
|
||||
patch([]byte("PK\x01\x02"), 24)
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
var _ = Describe("preprocessor", func() {
|
||||
Describe("GgsDecoder", func() {
|
||||
var fileReader io.Reader
|
||||
BeforeEach(func() {
|
||||
fileContent, err := os.ReadFile("test_assets/ggs_test.ggs")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fileReader = bytes.NewReader(fileContent)
|
||||
})
|
||||
|
||||
It("hands on the embedded thumbnail as the png it is", func() {
|
||||
decoder := GgsDecoder{thumbnailpath: ggsThumbnailPath, maxSize: defaultMaxExtractedSize}
|
||||
img, err := decoder.Convert(fileReader)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img.ContentType).To(Equal("image/png"))
|
||||
Expect(img.Data).ToNot(BeEmpty())
|
||||
})
|
||||
|
||||
It("should return an error if the ggs is invalid", func() {
|
||||
decoder := GgsDecoder{thumbnailpath: ggsThumbnailPath, maxSize: defaultMaxExtractedSize}
|
||||
img, err := decoder.Convert(bytes.NewReader([]byte("not a ggs")))
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(img).To(BeNil())
|
||||
})
|
||||
|
||||
It("reports a ggs without a thumbnail as having none", func() {
|
||||
var buf bytes.Buffer
|
||||
w := zip.NewWriter(&buf)
|
||||
_, err := w.Create("geogebra.xml")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(w.Close()).To(Succeed())
|
||||
|
||||
decoder := GgsDecoder{thumbnailpath: ggsThumbnailPath, maxSize: defaultMaxExtractedSize}
|
||||
img, err := decoder.Convert(bytes.NewReader(buf.Bytes()))
|
||||
Expect(err).To(MatchError(ErrNoThumbnail))
|
||||
Expect(img).To(BeNil())
|
||||
})
|
||||
|
||||
It("refuses an entry that expands past the limit", func() {
|
||||
decoder := GgsDecoder{thumbnailpath: ggsThumbnailPath, maxSize: 1 << 20}
|
||||
|
||||
img, err := decoder.Convert(bytes.NewReader(ggsWithEntry(8<<20, false)))
|
||||
Expect(err).To(MatchError(ContainSubstring("allowed")))
|
||||
Expect(img).To(BeNil())
|
||||
})
|
||||
|
||||
It("refuses an entry whose declared size lies about the expansion", func() {
|
||||
decoder := GgsDecoder{thumbnailpath: ggsThumbnailPath, maxSize: 1 << 20}
|
||||
|
||||
// archive/zip refuses a patched header while reading, so the read stays bounded
|
||||
img, err := decoder.Convert(bytes.NewReader(ggsWithEntry(8<<20, true)))
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(img).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
Describe("should decode audio", func() {
|
||||
var fileReader io.Reader
|
||||
It("hands on the cover art in the type the tag declares", func() {
|
||||
fileContent, err := os.ReadFile("test_assets/empty.mp3")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fileReader = bytes.NewReader(fileContent)
|
||||
decoder := AudioDecoder{}
|
||||
img, err := decoder.Convert(fileReader)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img.ContentType).To(HavePrefix("image/"))
|
||||
Expect(img.Data).ToNot(BeEmpty())
|
||||
})
|
||||
It("reports an audio without cover art as having none", func() {
|
||||
fileContent, err := os.ReadFile("test_assets/empty_no_image.mp3")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fileReader = bytes.NewReader(fileContent)
|
||||
decoder := AudioDecoder{}
|
||||
img, err := decoder.Convert(fileReader)
|
||||
Expect(err).To(MatchError(ErrNoThumbnail))
|
||||
Expect(img).To(BeNil())
|
||||
})
|
||||
It("should return an error if the audio is invalid", func() {
|
||||
decoder := AudioDecoder{}
|
||||
img, err := decoder.Convert(bytes.NewReader([]byte("not an audio")))
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err).ToNot(MatchError(ErrNoThumbnail))
|
||||
Expect(img).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
Describe("GgpDecoder", func() {
|
||||
It("hands on the embedded thumbnail", func() {
|
||||
data, err := os.ReadFile("test_assets/noise.png")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
ggp := `{"sections":[{"cards":[{"element":{"image":{"base64Image":"data:image/png;base64,` + base64.StdEncoding.EncodeToString(data) + `"}}}]}]}`
|
||||
|
||||
img, err := GgpDecoder{}.Convert(strings.NewReader(ggp))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img.ContentType).To(Equal("image/png"))
|
||||
Expect(img.Data).To(Equal(data))
|
||||
})
|
||||
|
||||
DescribeTable("reports a ggp without a thumbnail as having none",
|
||||
func(ggp string) {
|
||||
img, err := GgpDecoder{}.Convert(strings.NewReader(ggp))
|
||||
Expect(err).To(MatchError(ErrNoThumbnail))
|
||||
Expect(img).To(BeNil())
|
||||
},
|
||||
Entry("no sections", `{}`),
|
||||
Entry("no cards", `{"sections":[{"cards":[]}]}`),
|
||||
Entry("no base64 image", `{"sections":[{"cards":[{"element":{"image":{"base64Image":""}}}]}]}`),
|
||||
Entry("not an image", `{"sections":[{"cards":[{"element":{"image":{"base64Image":"data:text/plain;base64,aGVsbG8="}}}]}]}`),
|
||||
)
|
||||
|
||||
It("should return an error if the ggp is invalid", func() {
|
||||
img, err := GgpDecoder{}.Convert(strings.NewReader("not a ggp"))
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err).ToNot(MatchError(ErrNoThumbnail))
|
||||
Expect(img).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
Describe("should decode text", func() {
|
||||
var decoder TxtToImageConverter
|
||||
BeforeEach(func() {
|
||||
@@ -217,14 +58,6 @@ var _ = Describe("preprocessor", func() {
|
||||
Expect(ForType("image/png", Options{})).To(BeNil())
|
||||
})
|
||||
|
||||
It("returns a GgsDecoder for a ggs", func() {
|
||||
Expect(ForType("application/vnd.geogebra.slides", Options{})).To(BeAssignableToTypeOf(GgsDecoder{}))
|
||||
})
|
||||
|
||||
It("returns an AudioDecoder for audio", func() {
|
||||
Expect(ForType("audio/mpeg", Options{})).To(BeAssignableToTypeOf(AudioDecoder{}))
|
||||
})
|
||||
|
||||
It("returns a TxtToImageConverter for text", func() {
|
||||
Expect(ForType("text/plain", Options{})).To(BeAssignableToTypeOf(TxtToImageConverter{}))
|
||||
})
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -163,7 +163,7 @@ var _ = Describe("ForType with a Tika server", func() {
|
||||
}{
|
||||
{"a named document goes to Tika", named, "application/pdf", tika},
|
||||
{"a named image goes to Tika too", named, "image/x-nikon-nef", tika},
|
||||
{"a named type with a converter goes to Tika", named, "audio/mpeg", tika},
|
||||
{"a named audio goes to Tika", named, "audio/mpeg", tika},
|
||||
{"a converter takes what the list does not name", named, "text/plain", BeAssignableToTypeOf(TxtToImageConverter{})},
|
||||
{"an image goes to the generator", named, "image/png", generator},
|
||||
{"an unnamed image goes to the generator", named, "image/heic", generator},
|
||||
@@ -172,10 +172,11 @@ var _ = Describe("ForType with a Tika server", func() {
|
||||
{"the catch-all takes a document", everything, "application/x-anything", tika},
|
||||
{"the catch-all never takes an image", everything, "image/x-nikon-nef", generator},
|
||||
{"nor a jpeg", everything, "image/jpeg", generator},
|
||||
{"nor what a converter takes", everything, "audio/mpeg", BeAssignableToTypeOf(AudioDecoder{})},
|
||||
{"nor what a converter takes", everything, "text/plain", BeAssignableToTypeOf(TxtToImageConverter{})},
|
||||
|
||||
{"without a Tika URL nothing goes to Tika", off, "application/pdf", generator},
|
||||
{"and the converters are back", off, "application/vnd.geogebra.slides", BeAssignableToTypeOf(GgsDecoder{})},
|
||||
{"nor audio, which only Tika extracts", off, "audio/mpeg", generator},
|
||||
{"and the converters are back", off, "text/plain", BeAssignableToTypeOf(TxtToImageConverter{})},
|
||||
} {
|
||||
It(c.name, func() {
|
||||
Expect(ForType(c.mimeType, Options{Tika: c.tika})).To(c.taker)
|
||||
|
||||
@@ -23,11 +23,6 @@ var GeneratorImageTypes = []string{
|
||||
// without further configuration.
|
||||
var DefaultSourceTypes = slices.Concat(GeneratorImageTypes, []string{
|
||||
"text/plain",
|
||||
"audio/flac",
|
||||
"audio/mpeg",
|
||||
"audio/ogg",
|
||||
"application/vnd.geogebra.slides",
|
||||
"application/vnd.geogebra.pinboard",
|
||||
})
|
||||
|
||||
// SourceTypes are the types a preview is announced and attempted for: the
|
||||
|
||||
@@ -17,7 +17,8 @@ var _ = Describe("SourceTypes", func() {
|
||||
},
|
||||
Entry("an image both backends read", defaults, "image/jpeg", true),
|
||||
Entry("with parameters", defaults, "image/png; charset=binary", true),
|
||||
Entry("built-in audio", defaults, "audio/mpeg", true),
|
||||
Entry("plain text", defaults, "text/plain", true),
|
||||
Entry("not audio, whose cover only Tika extracts", defaults, "audio/mpeg", false),
|
||||
Entry("not a camera raw by default", defaults, "image/x-nikon-nef", false),
|
||||
Entry("an image type the deployment added", withHeic, "image/heic", true),
|
||||
Entry("and the built-in ones are still in there", withHeic, "image/tiff", true),
|
||||
|
||||
@@ -26,11 +26,6 @@ var DefaultTypeMapping = []string{
|
||||
"image/x-icon:image/png",
|
||||
"application/x-msdownload:image/png",
|
||||
"text/plain:image/jpeg",
|
||||
"audio/flac:image/jpeg",
|
||||
"audio/mpeg:image/jpeg",
|
||||
"audio/ogg:image/jpeg",
|
||||
"application/vnd.geogebra.slides:image/jpeg",
|
||||
"application/vnd.geogebra.pinboard:image/jpeg",
|
||||
}
|
||||
|
||||
// TypeMapping says which type a thumbnail of an image is returned in, for the
|
||||
|
||||
@@ -524,8 +524,7 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R
|
||||
// is announced and not taken by Tika) is streamed straight through from
|
||||
// storage undecoded; the generator decides whether it can read it.
|
||||
// - a type Tika takes has its image extracted there.
|
||||
// - text/plain is rendered to an image here, audio and geogebra sources have
|
||||
// their embedded image extracted to bytes.
|
||||
// - text/plain is rendered to an image here.
|
||||
func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta1.Reference, auth, mimeType, filename, checksum string, logger log.Logger) (io.Reader, string, func(), error) {
|
||||
m, _, _ := mime.ParseMediaType(mimeType)
|
||||
|
||||
@@ -533,10 +532,9 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta
|
||||
// is handed to the generator as it is, which is the case for every type it
|
||||
// reads itself.
|
||||
converter := preprocessor.ForType(mimeType, preprocessor.Options{
|
||||
FontMapFile: w.fontMapFile,
|
||||
MaxImageSize: w.maxInputSize,
|
||||
Tika: w.tika,
|
||||
Filename: filename,
|
||||
FontMapFile: w.fontMapFile,
|
||||
Tika: w.tika,
|
||||
Filename: filename,
|
||||
})
|
||||
|
||||
// what the extraction found is remembered per file, so a second size does
|
||||
|
||||
@@ -811,58 +811,36 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
Expect(captured.contentType).To(Equal("application/pdf"), "the generator sees the file's own type, not a guess")
|
||||
})
|
||||
|
||||
It("converts audio to cover art before posting", func() {
|
||||
mp3Bytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "empty.mp3"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", mp3Bytes)
|
||||
It("keeps what a converter made, under one key for the whole file", func() {
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "text/plain", "notes.txt", []byte("some text"))
|
||||
|
||||
tr := &requests.ThumbnailRequest{
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"),
|
||||
Filename: "song.mp3",
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "notes.txt"),
|
||||
Filename: "notes.txt",
|
||||
Width: 64,
|
||||
Height: 64,
|
||||
}
|
||||
|
||||
_, err = wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(captured.data).ToNot(BeEmpty())
|
||||
Expect(captured.data).ToNot(Equal(mp3Bytes))
|
||||
})
|
||||
|
||||
It("keeps what an extractor found, under one key for the whole file", func() {
|
||||
mp3Bytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "empty.mp3"))
|
||||
_, err := wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", mp3Bytes)
|
||||
|
||||
tr := &requests.ThumbnailRequest{
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"),
|
||||
Filename: "song.mp3",
|
||||
Width: 64,
|
||||
Height: 64,
|
||||
}
|
||||
|
||||
_, err = wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
cached, err := testCache.Get(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "text/plain", "oc-text"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
cached, err := testCache.Get(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(cached).To(Equal(captured.data), "the cover art is kept as the source, not per size")
|
||||
Expect(cached).To(Equal(captured.data), "the rendered image is kept as the source, not per size")
|
||||
})
|
||||
|
||||
It("sends the kept source instead of extracting a second time", func() {
|
||||
pngBytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "noise.png"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"), pngBytes)).To(Succeed())
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "text/plain", "oc-text"), pngBytes)).To(Succeed())
|
||||
|
||||
//the file itself is not an mp3: extracting it would fail, so what
|
||||
//reaches the generator can only come from the cache
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", []byte("not an mp3"))
|
||||
//rendering the text would make another image, so what reaches the
|
||||
//generator can only come from the cache
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "text/plain", "notes.txt", []byte("some text"))
|
||||
|
||||
tr := &requests.ThumbnailRequest{
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"),
|
||||
Filename: "song.mp3",
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "notes.txt"),
|
||||
Filename: "notes.txt",
|
||||
Width: 128,
|
||||
Height: 128,
|
||||
}
|
||||
@@ -873,13 +851,13 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
})
|
||||
|
||||
It("asks once for a file that carries nothing, whatever size follows", func() {
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"), nil)).To(Succeed())
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "text/plain", "oc-text"), nil)).To(Succeed())
|
||||
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", []byte("not an mp3"))
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "text/plain", "notes.txt", []byte("some text"))
|
||||
|
||||
tr := &requests.ThumbnailRequest{
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"),
|
||||
Filename: "song.mp3",
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "notes.txt"),
|
||||
Filename: "notes.txt",
|
||||
Width: 256,
|
||||
Height: 256,
|
||||
}
|
||||
@@ -888,48 +866,27 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
Expect(err).To(MatchError(ErrNoThumbnail))
|
||||
Expect(captured.data).To(BeEmpty(), "the generator is not asked at all")
|
||||
|
||||
_, err = testCache.Get(thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", 256, 256, "jpg", "fill"))
|
||||
_, err = testCache.Get(thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "text/plain", 256, 256, "jpg", "fill"))
|
||||
Expect(err).To(MatchError(cache.ErrCacheMiss), "only the source entry says there is nothing")
|
||||
})
|
||||
|
||||
It("does not take another extractor's empty answer", func() {
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "tika"), nil)).To(Succeed())
|
||||
Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "text/plain", "tika"), nil)).To(Succeed())
|
||||
|
||||
mp3Bytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "empty.mp3"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", mp3Bytes)
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "text/plain", "notes.txt", []byte("some text"))
|
||||
|
||||
tr := &requests.ThumbnailRequest{
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"),
|
||||
Filename: "song.mp3",
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "notes.txt"),
|
||||
Filename: "notes.txt",
|
||||
Width: 64,
|
||||
Height: 64,
|
||||
}
|
||||
|
||||
_, err = wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
_, err := wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(captured.data).ToNot(BeEmpty())
|
||||
})
|
||||
|
||||
It("extracts the embedded thumbnail from geogebra slides", func() {
|
||||
ggsBytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "ggs_test.ggs"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "application/vnd.geogebra.slides", "deck.ggs", ggsBytes)
|
||||
|
||||
tr := &requests.ThumbnailRequest{
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "deck.ggs"),
|
||||
Filename: "deck.ggs",
|
||||
Width: 64,
|
||||
Height: 64,
|
||||
}
|
||||
|
||||
_, err = wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(captured.data).ToNot(BeEmpty())
|
||||
Expect(captured.data).ToNot(Equal(ggsBytes))
|
||||
})
|
||||
|
||||
It("renders text files to an image", func() {
|
||||
text := []byte("This is a test text for thumbnail rendering")
|
||||
|
||||
@@ -969,7 +926,13 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
})
|
||||
|
||||
It("returns an error when the file cannot be converted to an image", func() {
|
||||
tikaSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer tikaSrv.Close()
|
||||
|
||||
wf2, _ := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "bad.mp3", []byte("not a real audio file"))
|
||||
wf2.tika = thumbnail.NewTika(tikaSrv.URL, "thumbnail", []string{"audio/mpeg"}, nil)
|
||||
|
||||
tr := &requests.ThumbnailRequest{
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "bad.mp3"),
|
||||
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
# EditorConfig helps developers define and maintain consistent
|
||||
# coding styles between different editors and IDEs
|
||||
# editorconfig.org
|
||||
|
||||
root = true
|
||||
|
||||
[*.go]
|
||||
indent_style = tab
|
||||
indent_size = 3
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*]
|
||||
# We recommend you to keep these unchanged
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.7
|
||||
- tip
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
Copyright 2015, David Howden
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright notice, this
|
||||
list of conditions and the following disclaimer in the documentation and/or
|
||||
other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
# MP3/MP4/OGG/FLAC metadata parsing library
|
||||
[](https://pkg.go.dev/github.com/dhowden/tag)
|
||||
|
||||
This package provides MP3 (ID3v1,2.{2,3,4}) and MP4 (ACC, M4A, ALAC), OGG and FLAC metadata detection, parsing and artwork extraction.
|
||||
|
||||
Detect and parse tag metadata from an `io.ReadSeeker` (i.e. an `*os.File`):
|
||||
|
||||
```go
|
||||
m, err := tag.ReadFrom(f)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Print(m.Format()) // The detected format.
|
||||
log.Print(m.Title()) // The title of the track (see Metadata interface for more details).
|
||||
```
|
||||
|
||||
Parsed metadata is exported via a single interface (giving a consistent API for all supported metadata formats).
|
||||
|
||||
```go
|
||||
// Metadata is an interface which is used to describe metadata retrieved by this package.
|
||||
type Metadata interface {
|
||||
Format() Format
|
||||
FileType() FileType
|
||||
|
||||
Title() string
|
||||
Album() string
|
||||
Artist() string
|
||||
AlbumArtist() string
|
||||
Composer() string
|
||||
Genre() string
|
||||
Year() int
|
||||
|
||||
Track() (int, int) // Number, Total
|
||||
Disc() (int, int) // Number, Total
|
||||
|
||||
Picture() *Picture // Artwork
|
||||
Lyrics() string
|
||||
Comment() string
|
||||
|
||||
Raw() map[string]interface{} // NB: raw tag names are not consistent across formats.
|
||||
}
|
||||
```
|
||||
|
||||
## Audio Data Checksum (SHA1)
|
||||
|
||||
This package also provides a metadata-invariant checksum for audio files: only the audio data is used to
|
||||
construct the checksum.
|
||||
|
||||
[https://pkg.go.dev/github.com/dhowden/tag#Sum](https://pkg.go.dev/github.com/dhowden/tag#Sum)
|
||||
|
||||
## Tools
|
||||
|
||||
There are simple command-line tools which demonstrate basic tag extraction and summing:
|
||||
|
||||
```console
|
||||
$ go install github.com/dhowden/tag/cmd/tag@latest
|
||||
$ cd $GOPATH/bin
|
||||
$ ./tag 11\ High\ Hopes.m4a
|
||||
Metadata Format: MP4
|
||||
Title: High Hopes
|
||||
Album: The Division Bell
|
||||
Artist: Pink Floyd
|
||||
Composer: Abbey Road Recording Studios/David Gilmour/Polly Samson
|
||||
Year: 1994
|
||||
Track: 11 of 11
|
||||
Disc: 1 of 1
|
||||
Picture: Picture{Ext: jpeg, MIMEType: image/jpeg, Type: , Description: , Data.Size: 606109}
|
||||
|
||||
$ ./sum 11\ High\ Hopes.m4a
|
||||
2ae208c5f00a1f21f5fac9b7f6e0b8e52c06da29
|
||||
```
|
||||
-109
@@ -1,109 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package tag
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
// ReadDSFTags reads DSF metadata from the io.ReadSeeker, returning the resulting
|
||||
// metadata in a Metadata implementation, or non-nil error if there was a problem.
|
||||
// samples: http://www.2l.no/hires/index.html
|
||||
func ReadDSFTags(r io.ReadSeeker) (Metadata, error) {
|
||||
dsd, err := readString(r, 4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dsd != "DSD " {
|
||||
return nil, errors.New("expected 'DSD '")
|
||||
}
|
||||
|
||||
_, err = r.Seek(int64(16), io.SeekCurrent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
id3Pointer, err := readUint64LittleEndian(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = r.Seek(int64(id3Pointer), io.SeekStart)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
id3, err := ReadID3v2Tags(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return metadataDSF{id3}, nil
|
||||
}
|
||||
|
||||
type metadataDSF struct {
|
||||
id3 Metadata
|
||||
}
|
||||
|
||||
func (m metadataDSF) Format() Format {
|
||||
return m.id3.Format()
|
||||
}
|
||||
|
||||
func (m metadataDSF) FileType() FileType {
|
||||
return DSF
|
||||
}
|
||||
|
||||
func (m metadataDSF) Title() string {
|
||||
return m.id3.Title()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Album() string {
|
||||
return m.id3.Album()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Artist() string {
|
||||
return m.id3.Artist()
|
||||
}
|
||||
|
||||
func (m metadataDSF) AlbumArtist() string {
|
||||
return m.id3.AlbumArtist()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Composer() string {
|
||||
return m.id3.Composer()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Year() int {
|
||||
return m.id3.Year()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Genre() string {
|
||||
return m.id3.Genre()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Track() (int, int) {
|
||||
return m.id3.Track()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Disc() (int, int) {
|
||||
return m.id3.Disc()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Picture() *Picture {
|
||||
return m.id3.Picture()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Lyrics() string {
|
||||
return m.id3.Lyrics()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Comment() string {
|
||||
return m.id3.Comment()
|
||||
}
|
||||
|
||||
func (m metadataDSF) Raw() map[string]interface{} {
|
||||
return m.id3.Raw()
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package tag
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
// blockType is a type which represents an enumeration of valid FLAC blocks
|
||||
type blockType byte
|
||||
|
||||
// FLAC block types.
|
||||
const (
|
||||
// Stream Info Block 0
|
||||
// Padding Block 1
|
||||
// Application Block 2
|
||||
// Seektable Block 3
|
||||
// Cue Sheet Block 5
|
||||
vorbisCommentBlock blockType = 4
|
||||
pictureBlock blockType = 6
|
||||
)
|
||||
|
||||
// ReadFLACTags reads FLAC metadata from the io.ReadSeeker, returning the resulting
|
||||
// metadata in a Metadata implementation, or non-nil error if there was a problem.
|
||||
func ReadFLACTags(r io.ReadSeeker) (Metadata, error) {
|
||||
flac, err := readString(r, 4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if flac != "fLaC" {
|
||||
return nil, errors.New("expected 'fLaC'")
|
||||
}
|
||||
|
||||
m := &metadataFLAC{
|
||||
newMetadataVorbis(),
|
||||
}
|
||||
|
||||
for {
|
||||
last, err := m.readFLACMetadataBlock(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if last {
|
||||
break
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
type metadataFLAC struct {
|
||||
*metadataVorbis
|
||||
}
|
||||
|
||||
func (m *metadataFLAC) readFLACMetadataBlock(r io.ReadSeeker) (last bool, err error) {
|
||||
blockHeader, err := readBytes(r, 1)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if getBit(blockHeader[0], 7) {
|
||||
blockHeader[0] ^= (1 << 7)
|
||||
last = true
|
||||
}
|
||||
|
||||
blockLen, err := readInt(r, 3)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
switch blockType(blockHeader[0]) {
|
||||
case vorbisCommentBlock:
|
||||
err = m.readVorbisComment(r)
|
||||
|
||||
case pictureBlock:
|
||||
err = m.readPictureBlock(r)
|
||||
|
||||
default:
|
||||
_, err = r.Seek(int64(blockLen), io.SeekCurrent)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m *metadataFLAC) FileType() FileType {
|
||||
return FLAC
|
||||
}
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
package tag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Identify identifies the format and file type of the data in the ReadSeeker.
|
||||
func Identify(r io.ReadSeeker) (format Format, fileType FileType, err error) {
|
||||
b, err := readBytes(r, 11)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
_, err = r.Seek(-11, io.SeekCurrent)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("could not seek back to original position: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case string(b[0:4]) == "fLaC":
|
||||
return VORBIS, FLAC, nil
|
||||
|
||||
case string(b[0:4]) == "OggS":
|
||||
return VORBIS, OGG, nil
|
||||
|
||||
case string(b[4:8]) == "ftyp":
|
||||
b = b[8:11]
|
||||
fileType = UnknownFileType
|
||||
switch string(b) {
|
||||
case "M4A":
|
||||
fileType = M4A
|
||||
|
||||
case "M4B":
|
||||
fileType = M4B
|
||||
|
||||
case "M4P":
|
||||
fileType = M4P
|
||||
}
|
||||
return MP4, fileType, nil
|
||||
|
||||
case string(b[0:3]) == "ID3":
|
||||
b := b[3:]
|
||||
switch uint(b[0]) {
|
||||
case 2:
|
||||
format = ID3v2_2
|
||||
case 3:
|
||||
format = ID3v2_3
|
||||
case 4:
|
||||
format = ID3v2_4
|
||||
case 0, 1:
|
||||
fallthrough
|
||||
default:
|
||||
err = fmt.Errorf("ID3 version: %v, expected: 2, 3 or 4", uint(b[0]))
|
||||
return
|
||||
}
|
||||
return format, MP3, nil
|
||||
}
|
||||
|
||||
n, err := r.Seek(-128, io.SeekEnd)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
tag, err := readString(r, 3)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
_, err = r.Seek(-n, io.SeekCurrent)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if tag != "TAG" {
|
||||
err = ErrNoTagsFound
|
||||
return
|
||||
}
|
||||
return ID3v1, MP3, nil
|
||||
}
|
||||
-144
@@ -1,144 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package tag
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// id3v1Genres is a list of genres as given in the ID3v1 specification.
|
||||
var id3v1Genres = [...]string{
|
||||
"Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge",
|
||||
"Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", "Pop", "R&B",
|
||||
"Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska",
|
||||
"Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient",
|
||||
"Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", "Trance", "Classical",
|
||||
"Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel",
|
||||
"Noise", "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative",
|
||||
"Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic",
|
||||
"Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk",
|
||||
"Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", "Gangsta",
|
||||
"Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American",
|
||||
"Cabaret", "New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer",
|
||||
"Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro",
|
||||
"Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock",
|
||||
"National Folk", "Swing", "Fast Fusion", "Bebob", "Latin", "Revival",
|
||||
"Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock",
|
||||
"Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band",
|
||||
"Chorus", "Easy Listening", "Acoustic", "Humour", "Speech", "Chanson",
|
||||
"Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus",
|
||||
"Porn Groove", "Satire", "Slow Jam", "Club", "Tango", "Samba",
|
||||
"Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", "Freestyle",
|
||||
"Duet", "Punk Rock", "Drum Solo", "Acapella", "Euro-House", "Dance Hall",
|
||||
}
|
||||
|
||||
// ErrNotID3v1 is an error which is returned when no ID3v1 header is found.
|
||||
var ErrNotID3v1 = errors.New("invalid ID3v1 header")
|
||||
|
||||
// ReadID3v1Tags reads ID3v1 tags from the io.ReadSeeker. Returns ErrNotID3v1
|
||||
// if there are no ID3v1 tags, otherwise non-nil error if there was a problem.
|
||||
func ReadID3v1Tags(r io.ReadSeeker) (Metadata, error) {
|
||||
_, err := r.Seek(-128, io.SeekEnd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if tag, err := readString(r, 3); err != nil {
|
||||
return nil, err
|
||||
} else if tag != "TAG" {
|
||||
return nil, ErrNotID3v1
|
||||
}
|
||||
|
||||
title, err := readString(r, 30)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
artist, err := readString(r, 30)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
album, err := readString(r, 30)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
year, err := readString(r, 4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
commentBytes, err := readBytes(r, 30)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var comment string
|
||||
var track int
|
||||
if commentBytes[28] == 0 {
|
||||
comment = trimString(string(commentBytes[:28]))
|
||||
track = int(commentBytes[29])
|
||||
} else {
|
||||
comment = trimString(string(commentBytes))
|
||||
}
|
||||
|
||||
var genre string
|
||||
genreID, err := readBytes(r, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int(genreID[0]) < len(id3v1Genres) {
|
||||
genre = id3v1Genres[int(genreID[0])]
|
||||
}
|
||||
|
||||
m := make(map[string]interface{})
|
||||
m["title"] = trimString(title)
|
||||
m["artist"] = trimString(artist)
|
||||
m["album"] = trimString(album)
|
||||
m["year"] = trimString(year)
|
||||
m["comment"] = trimString(comment)
|
||||
m["track"] = track
|
||||
m["genre"] = genre
|
||||
|
||||
return metadataID3v1(m), nil
|
||||
}
|
||||
|
||||
func trimString(x string) string {
|
||||
return strings.TrimSpace(strings.Trim(x, "\x00"))
|
||||
}
|
||||
|
||||
// metadataID3v1 is the implementation of Metadata used for ID3v1 tags.
|
||||
type metadataID3v1 map[string]interface{}
|
||||
|
||||
func (metadataID3v1) Format() Format { return ID3v1 }
|
||||
func (metadataID3v1) FileType() FileType { return MP3 }
|
||||
func (m metadataID3v1) Raw() map[string]interface{} { return m }
|
||||
|
||||
func (m metadataID3v1) Title() string { return m["title"].(string) }
|
||||
func (m metadataID3v1) Album() string { return m["album"].(string) }
|
||||
func (m metadataID3v1) Artist() string { return m["artist"].(string) }
|
||||
func (m metadataID3v1) Genre() string { return m["genre"].(string) }
|
||||
|
||||
func (m metadataID3v1) Year() int {
|
||||
y := m["year"].(string)
|
||||
n, err := strconv.Atoi(y)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (m metadataID3v1) Track() (int, int) { return m["track"].(int), 0 }
|
||||
|
||||
func (m metadataID3v1) AlbumArtist() string { return "" }
|
||||
func (m metadataID3v1) Composer() string { return "" }
|
||||
func (metadataID3v1) Disc() (int, int) { return 0, 0 }
|
||||
func (m metadataID3v1) Picture() *Picture { return nil }
|
||||
func (m metadataID3v1) Lyrics() string { return "" }
|
||||
func (m metadataID3v1) Comment() string { return m["comment"].(string) }
|
||||
-469
@@ -1,469 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package tag
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Genre definitions 0-79 follow the ID3 tag specification of 1999.
|
||||
// More genres have been successively introduced in later Winamp versions.
|
||||
// https://en.wikipedia.org/wiki/List_of_ID3v1_genres#Extension_by_Winamp
|
||||
var id3v2Genres = [...]string{
|
||||
"Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge",
|
||||
"Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", "Pop", "R&B",
|
||||
"Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska",
|
||||
"Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient",
|
||||
"Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", "Trance", "Classical",
|
||||
"Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel",
|
||||
"Noise", "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative",
|
||||
"Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic",
|
||||
"Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk",
|
||||
"Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", "Gangsta",
|
||||
"Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American",
|
||||
"Cabaret", "New Wave", "Psychedelic", "Rave", "Showtunes", "Trailer",
|
||||
"Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro",
|
||||
"Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock",
|
||||
"National Folk", "Swing", "Fast Fusion", "Bebob", "Latin", "Revival",
|
||||
"Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock",
|
||||
"Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band",
|
||||
"Chorus", "Easy Listening", "Acoustic", "Humour", "Speech", "Chanson",
|
||||
"Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus",
|
||||
"Porn Groove", "Satire", "Slow Jam", "Club", "Tango", "Samba",
|
||||
"Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", "Freestyle",
|
||||
"Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall",
|
||||
"Goa", "Drum & Bass", "Club-House", "Hardcore", "Terror", "Indie",
|
||||
"Britpop", "Negerpunk", "Polsk Punk", "Beat", "Christian Gangsta Rap",
|
||||
"Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian",
|
||||
"Christian Rock ", "Merengue", "Salsa", "Thrash Metal", "Anime", "JPop",
|
||||
"Synthpop",
|
||||
"Christmas", "Art Rock", "Baroque", "Bhangra", "Big Beat", "Breakbeat",
|
||||
"Chillout", "Downtempo", "Dub", "EBM", "Eclectic", "Electro",
|
||||
"Electroclash", "Emo", "Experimental", "Garage", "Global", "IDM",
|
||||
"Illbient", "Industro-Goth", "Jam Band", "Krautrock", "Leftfield", "Lounge",
|
||||
"Math Rock", "New Romantic", "Nu-Breakz", "Post-Punk", "Post-Rock", "Psytrance",
|
||||
"Shoegaze", "Space Rock", "Trop Rock", "World Music", "Neoclassical", "Audiobook",
|
||||
"Audio Theatre", "Neue Deutsche Welle", "Podcast", "Indie Rock", "G-Funk", "Dubstep",
|
||||
"Garage Rock", "Psybient",
|
||||
}
|
||||
|
||||
// id3v2Header is a type which represents an ID3v2 tag header.
|
||||
type id3v2Header struct {
|
||||
Version Format
|
||||
Unsynchronisation bool
|
||||
ExtendedHeader bool
|
||||
Experimental bool
|
||||
Size uint
|
||||
}
|
||||
|
||||
// readID3v2Header reads the ID3v2 header from the given io.Reader.
|
||||
// offset it number of bytes of header that was read
|
||||
func readID3v2Header(r io.Reader) (h *id3v2Header, offset uint, err error) {
|
||||
offset = 10
|
||||
b, err := readBytes(r, offset)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("expected to read 10 bytes (ID3v2Header): %v", err)
|
||||
}
|
||||
|
||||
if string(b[0:3]) != "ID3" {
|
||||
return nil, 0, fmt.Errorf("expected to read \"ID3\"")
|
||||
}
|
||||
|
||||
b = b[3:]
|
||||
var vers Format
|
||||
switch uint(b[0]) {
|
||||
case 2:
|
||||
vers = ID3v2_2
|
||||
case 3:
|
||||
vers = ID3v2_3
|
||||
case 4:
|
||||
vers = ID3v2_4
|
||||
case 0, 1:
|
||||
fallthrough
|
||||
default:
|
||||
return nil, 0, fmt.Errorf("ID3 version: %v, expected: 2, 3 or 4", uint(b[0]))
|
||||
}
|
||||
|
||||
// NB: We ignore b[1] (the revision) as we don't currently rely on it.
|
||||
h = &id3v2Header{
|
||||
Version: vers,
|
||||
Unsynchronisation: getBit(b[2], 7),
|
||||
ExtendedHeader: getBit(b[2], 6),
|
||||
Experimental: getBit(b[2], 5),
|
||||
Size: uint(get7BitChunkedInt(b[3:7])),
|
||||
}
|
||||
|
||||
if h.ExtendedHeader {
|
||||
switch vers {
|
||||
case ID3v2_3:
|
||||
b, err := readBytes(r, 4)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("expected to read 4 bytes (ID3v23 extended header len): %v", err)
|
||||
}
|
||||
// skip header, size is excluding len bytes
|
||||
extendedHeaderSize := uint(getInt(b))
|
||||
_, err = readBytes(r, extendedHeaderSize)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("expected to read %d bytes (ID3v23 skip extended header): %v", extendedHeaderSize, err)
|
||||
}
|
||||
offset += extendedHeaderSize
|
||||
case ID3v2_4:
|
||||
b, err := readBytes(r, 4)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("expected to read 4 bytes (ID3v24 extended header len): %v", err)
|
||||
}
|
||||
// skip header, size is synchsafe int including len bytes
|
||||
extendedHeaderSize := uint(get7BitChunkedInt(b)) - 4
|
||||
_, err = readBytes(r, extendedHeaderSize)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("expected to read %d bytes (ID3v24 skip extended header): %v", extendedHeaderSize, err)
|
||||
}
|
||||
offset += extendedHeaderSize
|
||||
default:
|
||||
// nop, only 2.3 and 2.4 should have extended header
|
||||
}
|
||||
}
|
||||
|
||||
return h, offset, nil
|
||||
}
|
||||
|
||||
// id3v2FrameFlags is a type which represents the flags which can be set on an ID3v2 frame.
|
||||
type id3v2FrameFlags struct {
|
||||
// Message (ID3 2.3.0 and 2.4.0)
|
||||
TagAlterPreservation bool
|
||||
FileAlterPreservation bool
|
||||
ReadOnly bool
|
||||
|
||||
// Format (ID3 2.3.0 and 2.4.0)
|
||||
Compression bool
|
||||
Encryption bool
|
||||
GroupIdentity bool
|
||||
// ID3 2.4.0 only (see http://id3.org/id3v2.4.0-structure sec 4.1)
|
||||
Unsynchronisation bool
|
||||
DataLengthIndicator bool
|
||||
}
|
||||
|
||||
func readID3v23FrameFlags(r io.Reader) (*id3v2FrameFlags, error) {
|
||||
b, err := readBytes(r, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg := b[0]
|
||||
fmt := b[1]
|
||||
|
||||
return &id3v2FrameFlags{
|
||||
TagAlterPreservation: getBit(msg, 7),
|
||||
FileAlterPreservation: getBit(msg, 6),
|
||||
ReadOnly: getBit(msg, 5),
|
||||
Compression: getBit(fmt, 7),
|
||||
Encryption: getBit(fmt, 6),
|
||||
GroupIdentity: getBit(fmt, 5),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func readID3v24FrameFlags(r io.Reader) (*id3v2FrameFlags, error) {
|
||||
b, err := readBytes(r, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg := b[0]
|
||||
fmt := b[1]
|
||||
|
||||
return &id3v2FrameFlags{
|
||||
TagAlterPreservation: getBit(msg, 6),
|
||||
FileAlterPreservation: getBit(msg, 5),
|
||||
ReadOnly: getBit(msg, 4),
|
||||
GroupIdentity: getBit(fmt, 6),
|
||||
Compression: getBit(fmt, 3),
|
||||
Encryption: getBit(fmt, 2),
|
||||
Unsynchronisation: getBit(fmt, 1),
|
||||
DataLengthIndicator: getBit(fmt, 0),
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
func readID3v2_2FrameHeader(r io.Reader) (name string, size uint, headerSize uint, err error) {
|
||||
name, err = readString(r, 3)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
size, err = readUint(r, 3)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
headerSize = 6
|
||||
return
|
||||
}
|
||||
|
||||
func readID3v2_3FrameHeader(r io.Reader) (name string, size uint, headerSize uint, err error) {
|
||||
name, err = readString(r, 4)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
size, err = readUint(r, 4)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
headerSize = 8
|
||||
return
|
||||
}
|
||||
|
||||
func readID3v2_4FrameHeader(r io.Reader) (name string, size uint, headerSize uint, err error) {
|
||||
name, err = readString(r, 4)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
size, err = read7BitChunkedUint(r, 4)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
headerSize = 8
|
||||
return
|
||||
}
|
||||
|
||||
// readID3v2Frames reads ID3v2 frames from the given reader using the ID3v2Header.
|
||||
func readID3v2Frames(r io.Reader, offset uint, h *id3v2Header) (map[string]interface{}, error) {
|
||||
result := make(map[string]interface{})
|
||||
|
||||
for offset < h.Size {
|
||||
var err error
|
||||
var name string
|
||||
var size, headerSize uint
|
||||
var flags *id3v2FrameFlags
|
||||
|
||||
switch h.Version {
|
||||
case ID3v2_2:
|
||||
name, size, headerSize, err = readID3v2_2FrameHeader(r)
|
||||
|
||||
case ID3v2_3:
|
||||
name, size, headerSize, err = readID3v2_3FrameHeader(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
flags, err = readID3v23FrameFlags(r)
|
||||
headerSize += 2
|
||||
|
||||
case ID3v2_4:
|
||||
name, size, headerSize, err = readID3v2_4FrameHeader(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
flags, err = readID3v24FrameFlags(r)
|
||||
headerSize += 2
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// FIXME: Do we still need this?
|
||||
// if size=0, we certainly are in a padding zone. ignore the rest of
|
||||
// the tags
|
||||
if size == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
offset += headerSize + size
|
||||
|
||||
// Avoid corrupted padding (see http://id3.org/Compliance%20Issues).
|
||||
if !validID3Frame(h.Version, name) && offset > h.Size {
|
||||
break
|
||||
}
|
||||
|
||||
if flags != nil {
|
||||
if flags.Compression {
|
||||
switch h.Version {
|
||||
case ID3v2_3:
|
||||
// No data length indicator defined.
|
||||
if _, err := read7BitChunkedUint(r, 4); err != nil { // read 4
|
||||
return nil, err
|
||||
}
|
||||
size -= 4
|
||||
|
||||
case ID3v2_4:
|
||||
// Must have a data length indicator (to give the size) if compression is enabled.
|
||||
if !flags.DataLengthIndicator {
|
||||
return nil, errors.New("compression without data length indicator")
|
||||
}
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported compression flag used in %v", h.Version)
|
||||
}
|
||||
}
|
||||
|
||||
if flags.DataLengthIndicator {
|
||||
if h.Version == ID3v2_3 {
|
||||
return nil, fmt.Errorf("data length indicator set but not defined for %v", ID3v2_3)
|
||||
}
|
||||
|
||||
size, err = read7BitChunkedUint(r, 4)
|
||||
if err != nil { // read 4
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if flags.Encryption {
|
||||
_, err = readBytes(r, 1) // read 1 byte of encryption method
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
size--
|
||||
}
|
||||
}
|
||||
|
||||
b, err := readBytes(r, size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// There can be multiple tag with the same name. Append a number to the
|
||||
// name if there is more than one.
|
||||
rawName := name
|
||||
if _, ok := result[rawName]; ok {
|
||||
for i := 0; ok; i++ {
|
||||
rawName = name + "_" + strconv.Itoa(i)
|
||||
_, ok = result[rawName]
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case name == "TXXX" || name == "TXX":
|
||||
t, err := readTextWithDescrFrame(b, false, true) // no lang, but enc
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[rawName] = t
|
||||
|
||||
case name[0] == 'T':
|
||||
txt, err := readTFrame(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[rawName] = txt
|
||||
|
||||
case name == "UFID" || name == "UFI":
|
||||
t, err := readUFID(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[rawName] = t
|
||||
|
||||
case name == "WXXX" || name == "WXX":
|
||||
t, err := readTextWithDescrFrame(b, false, false) // no lang, no enc
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[rawName] = t
|
||||
|
||||
case name[0] == 'W':
|
||||
txt, err := readWFrame(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[rawName] = txt
|
||||
|
||||
case name == "COMM" || name == "COM" || name == "USLT" || name == "ULT":
|
||||
t, err := readTextWithDescrFrame(b, true, true) // both lang and enc
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not read %q (%q): %v", name, rawName, err)
|
||||
}
|
||||
result[rawName] = t
|
||||
|
||||
case name == "APIC":
|
||||
p, err := readAPICFrame(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[rawName] = p
|
||||
|
||||
case name == "PIC":
|
||||
p, err := readPICFrame(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[rawName] = p
|
||||
|
||||
default:
|
||||
result[rawName] = b
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type unsynchroniser struct {
|
||||
io.Reader
|
||||
ff bool
|
||||
}
|
||||
|
||||
// filter io.Reader which skip the Unsynchronisation bytes
|
||||
func (r *unsynchroniser) Read(p []byte) (int, error) {
|
||||
b := make([]byte, 1)
|
||||
i := 0
|
||||
for i < len(p) {
|
||||
if n, err := r.Reader.Read(b); err != nil || n == 0 {
|
||||
return i, err
|
||||
}
|
||||
if r.ff && b[0] == 0x00 {
|
||||
r.ff = false
|
||||
continue
|
||||
}
|
||||
p[i] = b[0]
|
||||
i++
|
||||
r.ff = (b[0] == 0xFF)
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
|
||||
// ReadID3v2Tags parses ID3v2.{2,3,4} tags from the io.ReadSeeker into a Metadata, returning
|
||||
// non-nil error on failure.
|
||||
func ReadID3v2Tags(r io.ReadSeeker) (Metadata, error) {
|
||||
h, offset, err := readID3v2Header(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ur io.Reader = r
|
||||
if h.Unsynchronisation {
|
||||
ur = &unsynchroniser{Reader: r}
|
||||
}
|
||||
|
||||
f, err := readID3v2Frames(ur, offset, h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return metadataID3v2{header: h, frames: f}, nil
|
||||
}
|
||||
|
||||
var id3v2genreRe = regexp.MustCompile(`(.*[^(]|.* |^)\(([0-9]+)\) *(.*)$`)
|
||||
|
||||
// id3v2genre parse a id3v2 genre tag and expand the numeric genres
|
||||
func id3v2genre(genre string) string {
|
||||
c := true
|
||||
for c {
|
||||
orig := genre
|
||||
if match := id3v2genreRe.FindStringSubmatch(genre); len(match) > 0 {
|
||||
if genreID, err := strconv.Atoi(match[2]); err == nil {
|
||||
if genreID < len(id3v2Genres) {
|
||||
genre = id3v2Genres[genreID]
|
||||
if match[1] != "" {
|
||||
genre = strings.TrimSpace(match[1]) + " " + genre
|
||||
}
|
||||
if match[3] != "" {
|
||||
genre = genre + " " + match[3]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
c = (orig != genre)
|
||||
}
|
||||
return strings.Replace(genre, "((", "(", -1)
|
||||
}
|
||||
-655
@@ -1,655 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package tag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
// DefaultUTF16WithBOMByteOrder is the byte order used when the "UTF16 with BOM" encoding
|
||||
// is specified without a corresponding BOM in the data.
|
||||
var DefaultUTF16WithBOMByteOrder binary.ByteOrder = binary.LittleEndian
|
||||
|
||||
// ID3v2.2.0 frames (see http://id3.org/id3v2-00, sec 4).
|
||||
var id3v22Frames = map[string]string{
|
||||
"BUF": "Recommended buffer size",
|
||||
|
||||
"CNT": "Play counter",
|
||||
"COM": "Comments",
|
||||
"CRA": "Audio encryption",
|
||||
"CRM": "Encrypted meta frame",
|
||||
|
||||
"ETC": "Event timing codes",
|
||||
"EQU": "Equalization",
|
||||
|
||||
"GEO": "General encapsulated object",
|
||||
|
||||
"IPL": "Involved people list",
|
||||
|
||||
"LNK": "Linked information",
|
||||
|
||||
"MCI": "Music CD Identifier",
|
||||
"MLL": "MPEG location lookup table",
|
||||
|
||||
"PIC": "Attached picture",
|
||||
"POP": "Popularimeter",
|
||||
|
||||
"REV": "Reverb",
|
||||
"RVA": "Relative volume adjustment",
|
||||
|
||||
"SLT": "Synchronized lyric/text",
|
||||
"STC": "Synced tempo codes",
|
||||
|
||||
"TAL": "Album/Movie/Show title",
|
||||
"TBP": "BPM (Beats Per Minute)",
|
||||
"TCM": "Composer",
|
||||
"TCO": "Content type",
|
||||
"TCR": "Copyright message",
|
||||
"TDA": "Date",
|
||||
"TDY": "Playlist delay",
|
||||
"TEN": "Encoded by",
|
||||
"TFT": "File type",
|
||||
"TIM": "Time",
|
||||
"TKE": "Initial key",
|
||||
"TLA": "Language(s)",
|
||||
"TLE": "Length",
|
||||
"TMT": "Media type",
|
||||
"TOA": "Original artist(s)/performer(s)",
|
||||
"TOF": "Original filename",
|
||||
"TOL": "Original Lyricist(s)/text writer(s)",
|
||||
"TOR": "Original release year",
|
||||
"TOT": "Original album/Movie/Show title",
|
||||
"TP1": "Lead artist(s)/Lead performer(s)/Soloist(s)/Performing group",
|
||||
"TP2": "Band/Orchestra/Accompaniment",
|
||||
"TP3": "Conductor/Performer refinement",
|
||||
"TP4": "Interpreted, remixed, or otherwise modified by",
|
||||
"TPA": "Part of a set",
|
||||
"TPB": "Publisher",
|
||||
"TRC": "ISRC (International Standard Recording Code)",
|
||||
"TRD": "Recording dates",
|
||||
"TRK": "Track number/Position in set",
|
||||
"TSI": "Size",
|
||||
"TSS": "Software/hardware and settings used for encoding",
|
||||
"TT1": "Content group description",
|
||||
"TT2": "Title/Songname/Content description",
|
||||
"TT3": "Subtitle/Description refinement",
|
||||
"TXT": "Lyricist/text writer",
|
||||
"TXX": "User defined text information frame",
|
||||
"TYE": "Year",
|
||||
|
||||
"UFI": "Unique file identifier",
|
||||
"ULT": "Unsychronized lyric/text transcription",
|
||||
|
||||
"WAF": "Official audio file webpage",
|
||||
"WAR": "Official artist/performer webpage",
|
||||
"WAS": "Official audio source webpage",
|
||||
"WCM": "Commercial information",
|
||||
"WCP": "Copyright/Legal information",
|
||||
"WPB": "Publishers official webpage",
|
||||
"WXX": "User defined URL link frame",
|
||||
}
|
||||
|
||||
// ID3v2.3.0 frames (see http://id3.org/id3v2.3.0#Declared_ID3v2_frames).
|
||||
var id3v23Frames = map[string]string{
|
||||
"AENC": "Audio encryption]",
|
||||
"APIC": "Attached picture",
|
||||
"COMM": "Comments",
|
||||
"COMR": "Commercial frame",
|
||||
"ENCR": "Encryption method registration",
|
||||
"EQUA": "Equalization",
|
||||
"ETCO": "Event timing codes",
|
||||
"GEOB": "General encapsulated object",
|
||||
"GRID": "Group identification registration",
|
||||
"IPLS": "Involved people list",
|
||||
"LINK": "Linked information",
|
||||
"MCDI": "Music CD identifier",
|
||||
"MLLT": "MPEG location lookup table",
|
||||
"OWNE": "Ownership frame",
|
||||
"PRIV": "Private frame",
|
||||
"PCNT": "Play counter",
|
||||
"POPM": "Popularimeter",
|
||||
"POSS": "Position synchronisation frame",
|
||||
"RBUF": "Recommended buffer size",
|
||||
"RVAD": "Relative volume adjustment",
|
||||
"RVRB": "Reverb",
|
||||
"SYLT": "Synchronized lyric/text",
|
||||
"SYTC": "Synchronized tempo codes",
|
||||
"TALB": "Album/Movie/Show title",
|
||||
"TBPM": "BPM (beats per minute)",
|
||||
"TCMP": "iTunes Compilation Flag",
|
||||
"TCOM": "Composer",
|
||||
"TCON": "Content type",
|
||||
"TCOP": "Copyright message",
|
||||
"TDAT": "Date",
|
||||
"TDLY": "Playlist delay",
|
||||
"TENC": "Encoded by",
|
||||
"TEXT": "Lyricist/Text writer",
|
||||
"TFLT": "File type",
|
||||
"TIME": "Time",
|
||||
"TIT1": "Content group description",
|
||||
"TIT2": "Title/songname/content description",
|
||||
"TIT3": "Subtitle/Description refinement",
|
||||
"TKEY": "Initial key",
|
||||
"TLAN": "Language(s)",
|
||||
"TLEN": "Length",
|
||||
"TMED": "Media type",
|
||||
"TOAL": "Original album/movie/show title",
|
||||
"TOFN": "Original filename",
|
||||
"TOLY": "Original lyricist(s)/text writer(s)",
|
||||
"TOPE": "Original artist(s)/performer(s)",
|
||||
"TORY": "Original release year",
|
||||
"TOWN": "File owner/licensee",
|
||||
"TPE1": "Lead performer(s)/Soloist(s)",
|
||||
"TPE2": "Band/orchestra/accompaniment",
|
||||
"TPE3": "Conductor/performer refinement",
|
||||
"TPE4": "Interpreted, remixed, or otherwise modified by",
|
||||
"TPOS": "Part of a set",
|
||||
"TPUB": "Publisher",
|
||||
"TRCK": "Track number/Position in set",
|
||||
"TRDA": "Recording dates",
|
||||
"TRSN": "Internet radio station name",
|
||||
"TRSO": "Internet radio station owner",
|
||||
"TSIZ": "Size",
|
||||
"TSO2": "iTunes uses this for Album Artist sort order",
|
||||
"TSOC": "iTunes uses this for Composer sort order",
|
||||
"TSRC": "ISRC (international standard recording code)",
|
||||
"TSSE": "Software/Hardware and settings used for encoding",
|
||||
"TYER": "Year",
|
||||
"TXXX": "User defined text information frame",
|
||||
"UFID": "Unique file identifier",
|
||||
"USER": "Terms of use",
|
||||
"USLT": "Unsychronized lyric/text transcription",
|
||||
"WCOM": "Commercial information",
|
||||
"WCOP": "Copyright/Legal information",
|
||||
"WOAF": "Official audio file webpage",
|
||||
"WOAR": "Official artist/performer webpage",
|
||||
"WOAS": "Official audio source webpage",
|
||||
"WORS": "Official internet radio station homepage",
|
||||
"WPAY": "Payment",
|
||||
"WPUB": "Publishers official webpage",
|
||||
"WXXX": "User defined URL link frame",
|
||||
}
|
||||
|
||||
// ID3v2.4.0 frames (see http://id3.org/id3v2.4.0-frames, sec 4).
|
||||
var id3v24Frames = map[string]string{
|
||||
"AENC": "Audio encryption",
|
||||
"APIC": "Attached picture",
|
||||
"ASPI": "Audio seek point index",
|
||||
|
||||
"COMM": "Comments",
|
||||
"COMR": "Commercial frame",
|
||||
|
||||
"ENCR": "Encryption method registration",
|
||||
"EQU2": "Equalisation (2)",
|
||||
"ETCO": "Event timing codes",
|
||||
|
||||
"GEOB": "General encapsulated object",
|
||||
"GRID": "Group identification registration",
|
||||
|
||||
"LINK": "Linked information",
|
||||
|
||||
"MCDI": "Music CD identifier",
|
||||
"MLLT": "MPEG location lookup table",
|
||||
|
||||
"OWNE": "Ownership frame",
|
||||
|
||||
"PRIV": "Private frame",
|
||||
"PCNT": "Play counter",
|
||||
"POPM": "Popularimeter",
|
||||
"POSS": "Position synchronisation frame",
|
||||
|
||||
"RBUF": "Recommended buffer size",
|
||||
"RVA2": "Relative volume adjustment (2)",
|
||||
"RVRB": "Reverb",
|
||||
|
||||
"SEEK": "Seek frame",
|
||||
"SIGN": "Signature frame",
|
||||
"SYLT": "Synchronised lyric/text",
|
||||
"SYTC": "Synchronised tempo codes",
|
||||
|
||||
"TALB": "Album/Movie/Show title",
|
||||
"TBPM": "BPM (beats per minute)",
|
||||
"TCMP": "iTunes Compilation Flag",
|
||||
"TCOM": "Composer",
|
||||
"TCON": "Content type",
|
||||
"TCOP": "Copyright message",
|
||||
"TDEN": "Encoding time",
|
||||
"TDLY": "Playlist delay",
|
||||
"TDOR": "Original release time",
|
||||
"TDRC": "Recording time",
|
||||
"TDRL": "Release time",
|
||||
"TDTG": "Tagging time",
|
||||
"TENC": "Encoded by",
|
||||
"TEXT": "Lyricist/Text writer",
|
||||
"TFLT": "File type",
|
||||
"TIPL": "Involved people list",
|
||||
"TIT1": "Content group description",
|
||||
"TIT2": "Title/songname/content description",
|
||||
"TIT3": "Subtitle/Description refinement",
|
||||
"TKEY": "Initial key",
|
||||
"TLAN": "Language(s)",
|
||||
"TLEN": "Length",
|
||||
"TMCL": "Musician credits list",
|
||||
"TMED": "Media type",
|
||||
"TMOO": "Mood",
|
||||
"TOAL": "Original album/movie/show title",
|
||||
"TOFN": "Original filename",
|
||||
"TOLY": "Original lyricist(s)/text writer(s)",
|
||||
"TOPE": "Original artist(s)/performer(s)",
|
||||
"TOWN": "File owner/licensee",
|
||||
"TPE1": "Lead performer(s)/Soloist(s)",
|
||||
"TPE2": "Band/orchestra/accompaniment",
|
||||
"TPE3": "Conductor/performer refinement",
|
||||
"TPE4": "Interpreted, remixed, or otherwise modified by",
|
||||
"TPOS": "Part of a set",
|
||||
"TPRO": "Produced notice",
|
||||
"TPUB": "Publisher",
|
||||
"TRCK": "Track number/Position in set",
|
||||
"TRSN": "Internet radio station name",
|
||||
"TRSO": "Internet radio station owner",
|
||||
"TSO2": "iTunes uses this for Album Artist sort order",
|
||||
"TSOA": "Album sort order",
|
||||
"TSOC": "iTunes uses this for Composer sort order",
|
||||
"TSOP": "Performer sort order",
|
||||
"TSOT": "Title sort order",
|
||||
"TSRC": "ISRC (international standard recording code)",
|
||||
"TSSE": "Software/Hardware and settings used for encoding",
|
||||
"TSST": "Set subtitle",
|
||||
"TXXX": "User defined text information frame",
|
||||
|
||||
"UFID": "Unique file identifier",
|
||||
"USER": "Terms of use",
|
||||
"USLT": "Unsynchronised lyric/text transcription",
|
||||
|
||||
"WCOM": "Commercial information",
|
||||
"WCOP": "Copyright/Legal information",
|
||||
"WOAF": "Official audio file webpage",
|
||||
"WOAR": "Official artist/performer webpage",
|
||||
"WOAS": "Official audio source webpage",
|
||||
"WORS": "Official Internet radio station homepage",
|
||||
"WPAY": "Payment",
|
||||
"WPUB": "Publishers official webpage",
|
||||
"WXXX": "User defined URL link frame",
|
||||
}
|
||||
|
||||
// ID3 frames that are defined in the specs.
|
||||
var id3Frames = map[Format]map[string]string{
|
||||
ID3v2_2: id3v22Frames,
|
||||
ID3v2_3: id3v23Frames,
|
||||
ID3v2_4: id3v24Frames,
|
||||
}
|
||||
|
||||
func validID3Frame(version Format, name string) bool {
|
||||
names, ok := id3Frames[version]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
_, ok = names[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
func readWFrame(b []byte) (string, error) {
|
||||
// Frame text is always encoded in ISO-8859-1
|
||||
b = append([]byte{0}, b...)
|
||||
return readTFrame(b)
|
||||
}
|
||||
|
||||
func readTFrame(b []byte) (string, error) {
|
||||
if len(b) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
txt, err := decodeText(b[0], b[1:])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.Join(strings.Split(txt, string(singleZero)), ""), nil
|
||||
}
|
||||
|
||||
const (
|
||||
encodingISO8859 byte = 0
|
||||
encodingUTF16WithBOM byte = 1
|
||||
encodingUTF16 byte = 2
|
||||
encodingUTF8 byte = 3
|
||||
)
|
||||
|
||||
func decodeText(enc byte, b []byte) (string, error) {
|
||||
if len(b) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
switch enc {
|
||||
case encodingISO8859: // ISO-8859-1
|
||||
return decodeISO8859(b), nil
|
||||
|
||||
case encodingUTF16WithBOM: // UTF-16 with byte order marker
|
||||
if len(b) == 1 {
|
||||
return "", nil
|
||||
}
|
||||
return decodeUTF16WithBOM(b)
|
||||
|
||||
case encodingUTF16: // UTF-16 without byte order (assuming BigEndian)
|
||||
if len(b) == 1 {
|
||||
return "", nil
|
||||
}
|
||||
return decodeUTF16(b, binary.BigEndian)
|
||||
|
||||
case encodingUTF8: // UTF-8
|
||||
return string(b), nil
|
||||
|
||||
default: // Fallback to ISO-8859-1
|
||||
return decodeISO8859(b), nil
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
singleZero = []byte{0}
|
||||
doubleZero = []byte{0, 0}
|
||||
)
|
||||
|
||||
func dataSplit(b []byte, enc byte) [][]byte {
|
||||
delim := singleZero
|
||||
if enc == encodingUTF16 || enc == encodingUTF16WithBOM {
|
||||
delim = doubleZero
|
||||
}
|
||||
|
||||
result := bytes.SplitN(b, delim, 2)
|
||||
if len(result) != 2 {
|
||||
return result
|
||||
}
|
||||
|
||||
if len(result[1]) == 0 {
|
||||
return result
|
||||
}
|
||||
|
||||
if result[1][0] == 0 {
|
||||
// there was a double (or triple) 0 and we cut too early
|
||||
result[0] = append(result[0], result[1][0])
|
||||
result[1] = result[1][1:]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func decodeISO8859(b []byte) string {
|
||||
r := make([]rune, len(b))
|
||||
for i, x := range b {
|
||||
r[i] = rune(x)
|
||||
}
|
||||
return string(r)
|
||||
}
|
||||
|
||||
func decodeUTF16WithBOM(b []byte) (string, error) {
|
||||
if len(b) < 2 {
|
||||
return "", errors.New("invalid encoding: expected at least 2 bytes for UTF-16 byte order mark")
|
||||
}
|
||||
|
||||
var bo binary.ByteOrder
|
||||
switch {
|
||||
case b[0] == 0xFE && b[1] == 0xFF:
|
||||
bo = binary.BigEndian
|
||||
b = b[2:]
|
||||
|
||||
case b[0] == 0xFF && b[1] == 0xFE:
|
||||
bo = binary.LittleEndian
|
||||
b = b[2:]
|
||||
|
||||
default:
|
||||
bo = DefaultUTF16WithBOMByteOrder
|
||||
}
|
||||
return decodeUTF16(b, bo)
|
||||
}
|
||||
|
||||
func decodeUTF16(b []byte, bo binary.ByteOrder) (string, error) {
|
||||
if len(b)%2 != 0 {
|
||||
return "", errors.New("invalid encoding: expected even number of bytes for UTF-16 encoded text")
|
||||
}
|
||||
s := make([]uint16, 0, len(b)/2)
|
||||
for i := 0; i < len(b); i += 2 {
|
||||
s = append(s, bo.Uint16(b[i:i+2]))
|
||||
}
|
||||
return string(utf16.Decode(s)), nil
|
||||
}
|
||||
|
||||
// Comm is a type used in COMM, UFID, TXXX, WXXX and USLT tag.
|
||||
// It's a text with a description and a specified language
|
||||
// For WXXX, TXXX and UFID, we don't set a Language
|
||||
type Comm struct {
|
||||
Language string
|
||||
Description string
|
||||
Text string
|
||||
}
|
||||
|
||||
// String returns a string representation of the underlying Comm instance.
|
||||
func (t Comm) String() string {
|
||||
if t.Language != "" {
|
||||
return fmt.Sprintf("Text{Lang: '%v', Description: '%v', %v lines}",
|
||||
t.Language, t.Description, strings.Count(t.Text, "\n"))
|
||||
}
|
||||
return fmt.Sprintf("Text{Description: '%v', %v}", t.Description, t.Text)
|
||||
}
|
||||
|
||||
// IDv2.{3,4}
|
||||
// -- Header
|
||||
// <Header for 'Unsynchronised lyrics/text transcription', ID: "USLT">
|
||||
// <Header for 'Comment', ID: "COMM">
|
||||
// -- readTextWithDescrFrame(data, true, true)
|
||||
// Text encoding $xx
|
||||
// Language $xx xx xx
|
||||
// Content descriptor <text string according to encoding> $00 (00)
|
||||
// Lyrics/text <full text string according to encoding>
|
||||
// -- Header
|
||||
// <Header for 'User defined text information frame', ID: "TXXX">
|
||||
// <Header for 'User defined URL link frame', ID: "WXXX">
|
||||
// -- readTextWithDescrFrame(data, false, <isDataEncoded>)
|
||||
// Text encoding $xx
|
||||
// Description <text string according to encoding> $00 (00)
|
||||
// Value <text string according to encoding>
|
||||
func readTextWithDescrFrame(b []byte, hasLang bool, encoded bool) (*Comm, error) {
|
||||
if len(b) == 0 {
|
||||
return nil, errors.New("error decoding tag description text: invalid encoding")
|
||||
}
|
||||
enc := b[0]
|
||||
b = b[1:]
|
||||
|
||||
c := &Comm{}
|
||||
if hasLang {
|
||||
if len(b) < 3 {
|
||||
return nil, errors.New("hasLang set but not enough data for language information")
|
||||
}
|
||||
c.Language = string(b[:3])
|
||||
b = b[3:]
|
||||
}
|
||||
|
||||
descTextSplit := dataSplit(b, enc)
|
||||
if len(descTextSplit) == 0 {
|
||||
return nil, errors.New("error decoding tag description text: invalid encoding")
|
||||
}
|
||||
|
||||
desc, err := decodeText(enc, descTextSplit[0])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error decoding tag description text: %v", err)
|
||||
}
|
||||
c.Description = desc
|
||||
|
||||
if len(descTextSplit) == 1 {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
if !encoded {
|
||||
enc = byte(0)
|
||||
}
|
||||
text, err := decodeText(enc, descTextSplit[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error decoding tag text: %v", err)
|
||||
}
|
||||
c.Text = text
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// UFID is composed of a provider (frequently a URL and a binary identifier)
|
||||
// The identifier can be a text (Musicbrainz use texts, but not necessary)
|
||||
type UFID struct {
|
||||
Provider string
|
||||
Identifier []byte
|
||||
}
|
||||
|
||||
func (u UFID) String() string {
|
||||
return fmt.Sprintf("%v (%v)", u.Provider, string(u.Identifier))
|
||||
}
|
||||
|
||||
func readUFID(b []byte) (*UFID, error) {
|
||||
result := bytes.SplitN(b, singleZero, 2)
|
||||
if len(result) != 2 {
|
||||
return nil, errors.New("expected to split UFID data into 2 pieces")
|
||||
}
|
||||
|
||||
return &UFID{
|
||||
Provider: string(result[0]),
|
||||
Identifier: result[1],
|
||||
}, nil
|
||||
}
|
||||
|
||||
var pictureTypes = map[byte]string{
|
||||
0x00: "Other",
|
||||
0x01: "32x32 pixels 'file icon' (PNG only)",
|
||||
0x02: "Other file icon",
|
||||
0x03: "Cover (front)",
|
||||
0x04: "Cover (back)",
|
||||
0x05: "Leaflet page",
|
||||
0x06: "Media (e.g. lable side of CD)",
|
||||
0x07: "Lead artist/lead performer/soloist",
|
||||
0x08: "Artist/performer",
|
||||
0x09: "Conductor",
|
||||
0x0A: "Band/Orchestra",
|
||||
0x0B: "Composer",
|
||||
0x0C: "Lyricist/text writer",
|
||||
0x0D: "Recording Location",
|
||||
0x0E: "During recording",
|
||||
0x0F: "During performance",
|
||||
0x10: "Movie/video screen capture",
|
||||
0x11: "A bright coloured fish",
|
||||
0x12: "Illustration",
|
||||
0x13: "Band/artist logotype",
|
||||
0x14: "Publisher/Studio logotype",
|
||||
}
|
||||
|
||||
// Picture is a type which represents an attached picture extracted from metadata.
|
||||
type Picture struct {
|
||||
Ext string // Extension of the picture file.
|
||||
MIMEType string // MIMEType of the picture.
|
||||
Type string // Type of the picture (see pictureTypes).
|
||||
Description string // Description.
|
||||
Data []byte // Raw picture data.
|
||||
}
|
||||
|
||||
// String returns a string representation of the underlying Picture instance.
|
||||
func (p Picture) String() string {
|
||||
return fmt.Sprintf("Picture{Ext: %v, MIMEType: %v, Type: %v, Description: %v, Data.Size: %v}",
|
||||
p.Ext, p.MIMEType, p.Type, p.Description, len(p.Data))
|
||||
}
|
||||
|
||||
// IDv2.2
|
||||
// -- Header
|
||||
// Attached picture "PIC"
|
||||
// Frame size $xx xx xx
|
||||
// -- readPICFrame
|
||||
// Text encoding $xx
|
||||
// Image format $xx xx xx
|
||||
// Picture type $xx
|
||||
// Description <textstring> $00 (00)
|
||||
// Picture data <binary data>
|
||||
func readPICFrame(b []byte) (*Picture, error) {
|
||||
if len(b) < 5 {
|
||||
return nil, errors.New("invalid PIC frame")
|
||||
}
|
||||
|
||||
enc := b[0]
|
||||
ext := string(b[1:4])
|
||||
picType := b[4]
|
||||
|
||||
descDataSplit := dataSplit(b[5:], enc)
|
||||
if len(descDataSplit) != 2 {
|
||||
return nil, errors.New("error decoding PIC description text: invalid encoding")
|
||||
}
|
||||
desc, err := decodeText(enc, descDataSplit[0])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error decoding PIC description text: %v", err)
|
||||
}
|
||||
|
||||
var mimeType string
|
||||
switch ext {
|
||||
case "jpeg", "jpg":
|
||||
mimeType = "image/jpeg"
|
||||
case "png":
|
||||
mimeType = "image/png"
|
||||
}
|
||||
|
||||
return &Picture{
|
||||
Ext: ext,
|
||||
MIMEType: mimeType,
|
||||
Type: pictureTypes[picType],
|
||||
Description: desc,
|
||||
Data: descDataSplit[1],
|
||||
}, nil
|
||||
}
|
||||
|
||||
// IDv2.{3,4}
|
||||
// -- Header
|
||||
// <Header for 'Attached picture', ID: "APIC">
|
||||
// -- readAPICFrame
|
||||
// Text encoding $xx
|
||||
// MIME type <text string> $00
|
||||
// Picture type $xx
|
||||
// Description <text string according to encoding> $00 (00)
|
||||
// Picture data <binary data>
|
||||
func readAPICFrame(b []byte) (*Picture, error) {
|
||||
if len(b) == 0 {
|
||||
return nil, errors.New("error decoding APIC: invalid encoding")
|
||||
}
|
||||
enc := b[0]
|
||||
mimeDataSplit := bytes.SplitN(b[1:], singleZero, 2)
|
||||
if len(mimeDataSplit) != 2 {
|
||||
return nil, errors.New("error decoding APIC: invalid encoding")
|
||||
}
|
||||
|
||||
mimeType := string(mimeDataSplit[0])
|
||||
|
||||
b = mimeDataSplit[1]
|
||||
if len(b) < 1 {
|
||||
return nil, fmt.Errorf("error decoding APIC mimetype")
|
||||
}
|
||||
picType := b[0]
|
||||
|
||||
descDataSplit := dataSplit(b[1:], enc)
|
||||
if len(descDataSplit) != 2 {
|
||||
return nil, errors.New("error decoding APIC description text: invalid encoding")
|
||||
}
|
||||
desc, err := decodeText(enc, descDataSplit[0])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error decoding APIC description text: %v", err)
|
||||
}
|
||||
|
||||
var ext string
|
||||
switch mimeType {
|
||||
case "image/jpeg":
|
||||
ext = "jpg"
|
||||
case "image/png":
|
||||
ext = "png"
|
||||
}
|
||||
|
||||
return &Picture{
|
||||
Ext: ext,
|
||||
MIMEType: mimeType,
|
||||
Type: pictureTypes[picType],
|
||||
Description: desc,
|
||||
Data: descDataSplit[1],
|
||||
}, nil
|
||||
}
|
||||
-152
@@ -1,152 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package tag
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type frameNames map[string][2]string
|
||||
|
||||
func (f frameNames) Name(s string, fm Format) string {
|
||||
l, ok := f[s]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
switch fm {
|
||||
case ID3v2_2:
|
||||
return l[0]
|
||||
case ID3v2_3:
|
||||
return l[1]
|
||||
case ID3v2_4:
|
||||
if s == "year" {
|
||||
return "TDRC"
|
||||
}
|
||||
return l[1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var frames = frameNames(map[string][2]string{
|
||||
"title": [2]string{"TT2", "TIT2"},
|
||||
"artist": [2]string{"TP1", "TPE1"},
|
||||
"album": [2]string{"TAL", "TALB"},
|
||||
"album_artist": [2]string{"TP2", "TPE2"},
|
||||
"composer": [2]string{"TCM", "TCOM"},
|
||||
"year": [2]string{"TYE", "TYER"},
|
||||
"track": [2]string{"TRK", "TRCK"},
|
||||
"disc": [2]string{"TPA", "TPOS"},
|
||||
"genre": [2]string{"TCO", "TCON"},
|
||||
"picture": [2]string{"PIC", "APIC"},
|
||||
"lyrics": [2]string{"", "USLT"},
|
||||
"comment": [2]string{"COM", "COMM"},
|
||||
})
|
||||
|
||||
// metadataID3v2 is the implementation of Metadata used for ID3v2 tags.
|
||||
type metadataID3v2 struct {
|
||||
header *id3v2Header
|
||||
frames map[string]interface{}
|
||||
}
|
||||
|
||||
func (m metadataID3v2) getString(k string) string {
|
||||
v, ok := m.frames[k]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return v.(string)
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Format() Format { return m.header.Version }
|
||||
func (m metadataID3v2) FileType() FileType { return MP3 }
|
||||
func (m metadataID3v2) Raw() map[string]interface{} { return m.frames }
|
||||
|
||||
func (m metadataID3v2) Title() string {
|
||||
return m.getString(frames.Name("title", m.Format()))
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Artist() string {
|
||||
return m.getString(frames.Name("artist", m.Format()))
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Album() string {
|
||||
return m.getString(frames.Name("album", m.Format()))
|
||||
}
|
||||
|
||||
func (m metadataID3v2) AlbumArtist() string {
|
||||
return m.getString(frames.Name("album_artist", m.Format()))
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Composer() string {
|
||||
return m.getString(frames.Name("composer", m.Format()))
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Genre() string {
|
||||
return id3v2genre(m.getString(frames.Name("genre", m.Format())))
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Year() int {
|
||||
stringYear := m.getString(frames.Name("year", m.Format()))
|
||||
|
||||
if year, err := strconv.Atoi(stringYear); err == nil {
|
||||
return year
|
||||
}
|
||||
|
||||
date, err := time.Parse(time.DateOnly, stringYear)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
return date.Year()
|
||||
}
|
||||
|
||||
func parseXofN(s string) (x, n int) {
|
||||
xn := strings.Split(s, "/")
|
||||
if len(xn) != 2 {
|
||||
x, _ = strconv.Atoi(s)
|
||||
return x, 0
|
||||
}
|
||||
x, _ = strconv.Atoi(strings.TrimSpace(xn[0]))
|
||||
n, _ = strconv.Atoi(strings.TrimSpace(xn[1]))
|
||||
return x, n
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Track() (int, int) {
|
||||
return parseXofN(m.getString(frames.Name("track", m.Format())))
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Disc() (int, int) {
|
||||
return parseXofN(m.getString(frames.Name("disc", m.Format())))
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Lyrics() string {
|
||||
t, ok := m.frames[frames.Name("lyrics", m.Format())]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return t.(*Comm).Text
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Comment() string {
|
||||
t, ok := m.frames[frames.Name("comment", m.Format())]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
// id3v23 has Text, id3v24 has Description
|
||||
if t.(*Comm).Description == "" {
|
||||
return trimString(t.(*Comm).Text)
|
||||
}
|
||||
return trimString(t.(*Comm).Description)
|
||||
}
|
||||
|
||||
func (m metadataID3v2) Picture() *Picture {
|
||||
v, ok := m.frames[frames.Name("picture", m.Format())]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return v.(*Picture)
|
||||
}
|
||||
-379
@@ -1,379 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package tag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var atomTypes = map[int]string{
|
||||
0: "implicit", // automatic based on atom name
|
||||
1: "text",
|
||||
13: "jpeg",
|
||||
14: "png",
|
||||
21: "uint8",
|
||||
}
|
||||
|
||||
// NB: atoms does not include "----", this is handled separately
|
||||
var atoms = atomNames(map[string]string{
|
||||
"\xa9alb": "album",
|
||||
"\xa9art": "artist",
|
||||
"\xa9ART": "artist",
|
||||
"aART": "album_artist",
|
||||
"\xa9day": "year",
|
||||
"\xa9nam": "title",
|
||||
"\xa9gen": "genre",
|
||||
"trkn": "track",
|
||||
"\xa9wrt": "composer",
|
||||
"\xa9too": "encoder",
|
||||
"cprt": "copyright",
|
||||
"covr": "picture",
|
||||
"\xa9grp": "grouping",
|
||||
"keyw": "keyword",
|
||||
"\xa9lyr": "lyrics",
|
||||
"\xa9cmt": "comment",
|
||||
"tmpo": "tempo",
|
||||
"cpil": "compilation",
|
||||
"disk": "disc",
|
||||
})
|
||||
|
||||
var means = map[string]bool{
|
||||
"com.apple.iTunes": true,
|
||||
"com.mixedinkey.mixedinkey": true,
|
||||
"com.serato.dj": true,
|
||||
}
|
||||
|
||||
// Detect PNG image if "implicit" class is used
|
||||
var pngHeader = []byte{137, 80, 78, 71, 13, 10, 26, 10}
|
||||
|
||||
type atomNames map[string]string
|
||||
|
||||
func (f atomNames) Name(n string) []string {
|
||||
res := make([]string, 1)
|
||||
for k, v := range f {
|
||||
if v == n {
|
||||
res = append(res, k)
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// metadataMP4 is the implementation of Metadata for MP4 tag (atom) data.
|
||||
type metadataMP4 struct {
|
||||
fileType FileType
|
||||
data map[string]interface{}
|
||||
}
|
||||
|
||||
// ReadAtoms reads MP4 metadata atoms from the io.ReadSeeker into a Metadata, returning
|
||||
// non-nil error if there was a problem.
|
||||
func ReadAtoms(r io.ReadSeeker) (Metadata, error) {
|
||||
m := metadataMP4{
|
||||
data: make(map[string]interface{}),
|
||||
fileType: UnknownFileType,
|
||||
}
|
||||
err := m.readAtoms(r)
|
||||
return m, err
|
||||
}
|
||||
|
||||
func (m metadataMP4) readAtoms(r io.ReadSeeker) error {
|
||||
for {
|
||||
name, size, err := readAtomHeader(r)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
switch name {
|
||||
case "meta":
|
||||
// next_item_id (int32)
|
||||
_, err := readBytes(r, 4)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fallthrough
|
||||
|
||||
case "moov", "udta", "ilst":
|
||||
return m.readAtoms(r)
|
||||
}
|
||||
|
||||
_, ok := atoms[name]
|
||||
var data []string
|
||||
if name == "----" {
|
||||
name, data, err = readCustomAtom(r, size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if name != "----" {
|
||||
ok = true
|
||||
size = 0 // already read data
|
||||
}
|
||||
}
|
||||
|
||||
if !ok {
|
||||
_, err := r.Seek(int64(size-8), io.SeekCurrent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
err = m.readAtomData(r, name, size-8, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m metadataMP4) readAtomData(r io.ReadSeeker, name string, size uint32, processedData []string) error {
|
||||
var b []byte
|
||||
var err error
|
||||
var contentType string
|
||||
if len(processedData) > 0 {
|
||||
b = []byte(strings.Join(processedData, ";")) // add delimiter if multiple data fields
|
||||
contentType = "text"
|
||||
} else {
|
||||
// read the data
|
||||
b, err = readBytes(r, uint(size))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(b) < 8 {
|
||||
return fmt.Errorf("invalid encoding: expected at least %d bytes, got %d", 8, len(b))
|
||||
}
|
||||
|
||||
// "data" + size (4 bytes each)
|
||||
b = b[8:]
|
||||
|
||||
if len(b) < 4 {
|
||||
return fmt.Errorf("invalid encoding: expected at least %d bytes, for class, got %d", 4, len(b))
|
||||
}
|
||||
class := getInt(b[1:4])
|
||||
var ok bool
|
||||
contentType, ok = atomTypes[class]
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid content type: %v (%x) (%x)", class, b[1:4], b)
|
||||
}
|
||||
|
||||
// 4: atom version (1 byte) + atom flags (3 bytes)
|
||||
// 4: NULL (usually locale indicator)
|
||||
if len(b) < 8 {
|
||||
return fmt.Errorf("invalid encoding: expected at least %d bytes, for atom version and flags, got %d", 8, len(b))
|
||||
}
|
||||
b = b[8:]
|
||||
}
|
||||
|
||||
if name == "trkn" || name == "disk" {
|
||||
if len(b) < 6 {
|
||||
return fmt.Errorf("invalid encoding: expected at least %d bytes, for track and disk numbers, got %d", 6, len(b))
|
||||
}
|
||||
|
||||
m.data[name] = int(b[3])
|
||||
m.data[name+"_count"] = int(b[5])
|
||||
return nil
|
||||
}
|
||||
|
||||
if contentType == "implicit" {
|
||||
if name == "covr" {
|
||||
if bytes.HasPrefix(b, pngHeader) {
|
||||
contentType = "png"
|
||||
}
|
||||
// TODO(dhowden): Detect JPEG formats too (harder).
|
||||
}
|
||||
}
|
||||
|
||||
var data interface{}
|
||||
switch contentType {
|
||||
case "implicit":
|
||||
if _, ok := atoms[name]; ok {
|
||||
return fmt.Errorf("unhandled implicit content type for required atom: %q", name)
|
||||
}
|
||||
return nil
|
||||
|
||||
case "text":
|
||||
data = string(b)
|
||||
|
||||
case "uint8":
|
||||
if len(b) < 1 {
|
||||
return fmt.Errorf("invalid encoding: expected at least %d bytes, for integer tag data, got %d", 1, len(b))
|
||||
}
|
||||
data = getInt(b[:1])
|
||||
|
||||
case "jpeg", "png":
|
||||
data = &Picture{
|
||||
Ext: contentType,
|
||||
MIMEType: "image/" + contentType,
|
||||
Data: b,
|
||||
}
|
||||
}
|
||||
m.data[name] = data
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readAtomHeader(r io.ReadSeeker) (name string, size uint32, err error) {
|
||||
err = binary.Read(r, binary.BigEndian, &size)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
name, err = readString(r, 4)
|
||||
return
|
||||
}
|
||||
|
||||
// Generic atom.
|
||||
// Should have 3 sub atoms : mean, name and data.
|
||||
// We check that mean is "com.apple.iTunes" or others and we use the subname as
|
||||
// the name, and move to the data atom.
|
||||
// Data atom could have multiple data values, each with a header.
|
||||
// If anything goes wrong, we jump at the end of the "----" atom.
|
||||
func readCustomAtom(r io.ReadSeeker, size uint32) (_ string, data []string, _ error) {
|
||||
subNames := make(map[string]string)
|
||||
|
||||
for size > 8 {
|
||||
subName, subSize, err := readAtomHeader(r)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
// Remove the size of the atom from the size counter
|
||||
if size >= subSize {
|
||||
size -= subSize
|
||||
} else {
|
||||
return "", nil, errors.New("--- invalid size")
|
||||
}
|
||||
|
||||
b, err := readBytes(r, uint(subSize-8))
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
if len(b) < 4 {
|
||||
return "", nil, fmt.Errorf("invalid encoding: expected at least %d bytes, got %d", 4, len(b))
|
||||
}
|
||||
switch subName {
|
||||
case "mean", "name":
|
||||
subNames[subName] = string(b[4:])
|
||||
case "data":
|
||||
data = append(data, string(b[4:]))
|
||||
}
|
||||
}
|
||||
|
||||
// there should remain only the header size
|
||||
if size != 8 {
|
||||
err := errors.New("---- atom out of bounds")
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
if !means[subNames["mean"]] || subNames["name"] == "" || len(data) == 0 {
|
||||
return "----", nil, nil
|
||||
}
|
||||
|
||||
return subNames["name"], data, nil
|
||||
}
|
||||
|
||||
func (metadataMP4) Format() Format { return MP4 }
|
||||
func (m metadataMP4) FileType() FileType { return m.fileType }
|
||||
|
||||
func (m metadataMP4) Raw() map[string]interface{} { return m.data }
|
||||
|
||||
func (m metadataMP4) getString(n []string) string {
|
||||
for _, k := range n {
|
||||
if x, ok := m.data[k]; ok {
|
||||
return x.(string)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m metadataMP4) getInt(n []string) int {
|
||||
for _, k := range n {
|
||||
if x, ok := m.data[k]; ok {
|
||||
return x.(int)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m metadataMP4) Title() string {
|
||||
return m.getString(atoms.Name("title"))
|
||||
}
|
||||
|
||||
func (m metadataMP4) Artist() string {
|
||||
return m.getString(atoms.Name("artist"))
|
||||
}
|
||||
|
||||
func (m metadataMP4) Album() string {
|
||||
return m.getString(atoms.Name("album"))
|
||||
}
|
||||
|
||||
func (m metadataMP4) AlbumArtist() string {
|
||||
return m.getString(atoms.Name("album_artist"))
|
||||
}
|
||||
|
||||
func (m metadataMP4) Composer() string {
|
||||
return m.getString(atoms.Name("composer"))
|
||||
}
|
||||
|
||||
func (m metadataMP4) Genre() string {
|
||||
return m.getString(atoms.Name("genre"))
|
||||
}
|
||||
|
||||
func (m metadataMP4) Year() int {
|
||||
date := m.getString(atoms.Name("year"))
|
||||
if len(date) >= 4 {
|
||||
year, _ := strconv.Atoi(date[:4])
|
||||
return year
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m metadataMP4) Track() (int, int) {
|
||||
x := m.getInt([]string{"trkn"})
|
||||
if n, ok := m.data["trkn_count"]; ok {
|
||||
return x, n.(int)
|
||||
}
|
||||
return x, 0
|
||||
}
|
||||
|
||||
func (m metadataMP4) Disc() (int, int) {
|
||||
x := m.getInt([]string{"disk"})
|
||||
if n, ok := m.data["disk_count"]; ok {
|
||||
return x, n.(int)
|
||||
}
|
||||
return x, 0
|
||||
}
|
||||
|
||||
func (m metadataMP4) Lyrics() string {
|
||||
t, ok := m.data["\xa9lyr"]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return t.(string)
|
||||
}
|
||||
|
||||
func (m metadataMP4) Comment() string {
|
||||
t, ok := m.data["\xa9cmt"]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return t.(string)
|
||||
}
|
||||
|
||||
func (m metadataMP4) Picture() *Picture {
|
||||
v, ok := m.data["covr"]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
p, _ := v.(*Picture)
|
||||
return p
|
||||
}
|
||||
-174
@@ -1,174 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package tag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
var (
|
||||
vorbisCommentPrefix = []byte("\x03vorbis")
|
||||
opusTagsPrefix = []byte("OpusTags")
|
||||
)
|
||||
|
||||
var oggCRC32Poly04c11db7 = oggCRCTable(0x04c11db7)
|
||||
|
||||
type crc32Table [256]uint32
|
||||
|
||||
func oggCRCTable(poly uint32) *crc32Table {
|
||||
var t crc32Table
|
||||
|
||||
for i := 0; i < 256; i++ {
|
||||
crc := uint32(i) << 24
|
||||
for j := 0; j < 8; j++ {
|
||||
if crc&0x80000000 != 0 {
|
||||
crc = (crc << 1) ^ poly
|
||||
} else {
|
||||
crc <<= 1
|
||||
}
|
||||
}
|
||||
t[i] = crc
|
||||
}
|
||||
|
||||
return &t
|
||||
}
|
||||
|
||||
func oggCRCUpdate(crc uint32, tab *crc32Table, p []byte) uint32 {
|
||||
for _, v := range p {
|
||||
crc = (crc << 8) ^ tab[byte(crc>>24)^v]
|
||||
}
|
||||
return crc
|
||||
}
|
||||
|
||||
type oggPageHeader struct {
|
||||
Magic [4]byte // "OggS"
|
||||
Version uint8
|
||||
Flags uint8
|
||||
GranulePosition uint64
|
||||
SerialNumber uint32
|
||||
SequenceNumber uint32
|
||||
CRC uint32
|
||||
Segments uint8
|
||||
}
|
||||
|
||||
type oggDemuxer struct {
|
||||
packetBufs map[uint32]*bytes.Buffer
|
||||
}
|
||||
|
||||
// Read ogg packets, can return empty slice of packets and nil err
|
||||
// if more data is needed
|
||||
func (o *oggDemuxer) Read(r io.Reader) ([][]byte, error) {
|
||||
headerBuf := &bytes.Buffer{}
|
||||
var oh oggPageHeader
|
||||
if err := binary.Read(io.TeeReader(r, headerBuf), binary.LittleEndian, &oh); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if bytes.Compare(oh.Magic[:], []byte("OggS")) != 0 {
|
||||
// TODO: seek for syncword?
|
||||
return nil, errors.New("expected 'OggS'")
|
||||
}
|
||||
|
||||
segmentTable := make([]byte, oh.Segments)
|
||||
if _, err := io.ReadFull(r, segmentTable); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var segmentsSize int64
|
||||
for _, s := range segmentTable {
|
||||
segmentsSize += int64(s)
|
||||
}
|
||||
segmentsData := make([]byte, segmentsSize)
|
||||
if _, err := io.ReadFull(r, segmentsData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
headerBytes := headerBuf.Bytes()
|
||||
// reset CRC to zero in header before checksum
|
||||
headerBytes[22] = 0
|
||||
headerBytes[23] = 0
|
||||
headerBytes[24] = 0
|
||||
headerBytes[25] = 0
|
||||
crc := oggCRCUpdate(0, oggCRC32Poly04c11db7, headerBytes)
|
||||
crc = oggCRCUpdate(crc, oggCRC32Poly04c11db7, segmentTable)
|
||||
crc = oggCRCUpdate(crc, oggCRC32Poly04c11db7, segmentsData)
|
||||
if crc != oh.CRC {
|
||||
return nil, fmt.Errorf("expected crc %x != %x", oh.CRC, crc)
|
||||
}
|
||||
|
||||
if o.packetBufs == nil {
|
||||
o.packetBufs = map[uint32]*bytes.Buffer{}
|
||||
}
|
||||
|
||||
var packetBuf *bytes.Buffer
|
||||
continued := oh.Flags&0x1 != 0
|
||||
if continued {
|
||||
if b, ok := o.packetBufs[oh.SerialNumber]; ok {
|
||||
packetBuf = b
|
||||
} else {
|
||||
return nil, fmt.Errorf("could not find continued packet %d", oh.SerialNumber)
|
||||
}
|
||||
} else {
|
||||
packetBuf = &bytes.Buffer{}
|
||||
}
|
||||
|
||||
var packets [][]byte
|
||||
var p int
|
||||
for _, s := range segmentTable {
|
||||
packetBuf.Write(segmentsData[p : p+int(s)])
|
||||
if s < 255 {
|
||||
packets = append(packets, packetBuf.Bytes())
|
||||
packetBuf = &bytes.Buffer{}
|
||||
}
|
||||
p += int(s)
|
||||
}
|
||||
|
||||
o.packetBufs[oh.SerialNumber] = packetBuf
|
||||
|
||||
return packets, nil
|
||||
}
|
||||
|
||||
// ReadOGGTags reads OGG metadata from the io.ReadSeeker, returning the resulting
|
||||
// metadata in a Metadata implementation, or non-nil error if there was a problem.
|
||||
// See http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html
|
||||
// and http://www.xiph.org/ogg/doc/framing.html for details.
|
||||
// For Opus see https://tools.ietf.org/html/rfc7845
|
||||
func ReadOGGTags(r io.Reader) (Metadata, error) {
|
||||
od := &oggDemuxer{}
|
||||
for {
|
||||
bs, err := od.Read(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, b := range bs {
|
||||
switch {
|
||||
case bytes.HasPrefix(b, vorbisCommentPrefix):
|
||||
m := &metadataOGG{
|
||||
newMetadataVorbis(),
|
||||
}
|
||||
err = m.readVorbisComment(bytes.NewReader(b[len(vorbisCommentPrefix):]))
|
||||
return m, err
|
||||
case bytes.HasPrefix(b, opusTagsPrefix):
|
||||
m := &metadataOGG{
|
||||
newMetadataVorbis(),
|
||||
}
|
||||
err = m.readVorbisComment(bytes.NewReader(b[len(opusTagsPrefix):]))
|
||||
return m, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type metadataOGG struct {
|
||||
*metadataVorbis
|
||||
}
|
||||
|
||||
func (m *metadataOGG) FileType() FileType {
|
||||
return OGG
|
||||
}
|
||||
-219
@@ -1,219 +0,0 @@
|
||||
package tag
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Sum creates a checksum of the audio file data provided by the io.ReadSeeker which is metadata
|
||||
// (ID3, MP4) invariant.
|
||||
func Sum(r io.ReadSeeker) (string, error) {
|
||||
b, err := readBytes(r, 11)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
_, err = r.Seek(-11, io.SeekCurrent)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("could not seek back to original position: %v", err)
|
||||
}
|
||||
|
||||
switch {
|
||||
case string(b[0:4]) == "fLaC":
|
||||
return SumFLAC(r)
|
||||
|
||||
case string(b[4:11]) == "ftypM4A":
|
||||
return SumAtoms(r)
|
||||
|
||||
case string(b[0:3]) == "ID3":
|
||||
return SumID3v2(r)
|
||||
}
|
||||
|
||||
h, err := SumID3v1(r)
|
||||
if err != nil {
|
||||
if err == ErrNotID3v1 {
|
||||
return SumAll(r)
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// SumAll returns a checksum of the content from the reader (until EOF).
|
||||
func SumAll(r io.ReadSeeker) (string, error) {
|
||||
h := sha1.New()
|
||||
_, err := io.Copy(h, r)
|
||||
if err != nil {
|
||||
return "", nil
|
||||
}
|
||||
return hashSum(h), nil
|
||||
}
|
||||
|
||||
// SumAtoms constructs a checksum of MP4 audio file data provided by the io.ReadSeeker which is
|
||||
// metadata invariant.
|
||||
func SumAtoms(r io.ReadSeeker) (string, error) {
|
||||
for {
|
||||
var size uint32
|
||||
err := binary.Read(r, binary.BigEndian, &size)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return "", fmt.Errorf("reached EOF before audio data")
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
|
||||
name, err := readString(r, 4)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
switch name {
|
||||
case "meta":
|
||||
// next_item_id (int32)
|
||||
_, err := r.Seek(4, io.SeekCurrent)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
fallthrough
|
||||
|
||||
case "moov", "udta", "ilst":
|
||||
continue
|
||||
|
||||
case "mdat": // stop when we get to the data
|
||||
h := sha1.New()
|
||||
_, err := io.CopyN(h, r, int64(size-8))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading audio data: %v", err)
|
||||
}
|
||||
return hashSum(h), nil
|
||||
}
|
||||
|
||||
_, err = r.Seek(int64(size-8), io.SeekCurrent)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading '%v' tag: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sizeToEndOffset(r io.ReadSeeker, offset int64) (int64, error) {
|
||||
n, err := r.Seek(-128, io.SeekEnd)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("error seeking end offset (%d bytes): %v", offset, err)
|
||||
}
|
||||
|
||||
_, err = r.Seek(-n, io.SeekCurrent)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("error seeking back to original position: %v", err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// SumID3v1 constructs a checksum of MP3 audio file data (assumed to have ID3v1 tags) provided
|
||||
// by the io.ReadSeeker which is metadata invariant.
|
||||
func SumID3v1(r io.ReadSeeker) (string, error) {
|
||||
n, err := sizeToEndOffset(r, 128)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error determining read size to ID3v1 header: %v", err)
|
||||
}
|
||||
|
||||
// TODO: improve this check???
|
||||
if n <= 0 {
|
||||
return "", fmt.Errorf("file size must be greater than 128 bytes (ID3v1 header size) for MP3")
|
||||
}
|
||||
|
||||
h := sha1.New()
|
||||
_, err = io.CopyN(h, r, n)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading %v bytes: %v", n, err)
|
||||
}
|
||||
return hashSum(h), nil
|
||||
}
|
||||
|
||||
// SumID3v2 constructs a checksum of MP3 audio file data (assumed to have ID3v2 tags) provided by the
|
||||
// io.ReadSeeker which is metadata invariant.
|
||||
func SumID3v2(r io.ReadSeeker) (string, error) {
|
||||
header, _, err := readID3v2Header(r)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading ID3v2 header: %v", err)
|
||||
}
|
||||
|
||||
_, err = r.Seek(int64(header.Size), io.SeekCurrent)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error seeking to end of ID3V2 header: %v", err)
|
||||
}
|
||||
|
||||
n, err := sizeToEndOffset(r, 128)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error determining read size to ID3v1 header: %v", err)
|
||||
}
|
||||
|
||||
// TODO: remove this check?????
|
||||
if n < 0 {
|
||||
return "", fmt.Errorf("file size must be greater than 128 bytes for MP3: %v bytes", n)
|
||||
}
|
||||
|
||||
h := sha1.New()
|
||||
_, err = io.CopyN(h, r, n)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading %v bytes: %v", n, err)
|
||||
}
|
||||
return hashSum(h), nil
|
||||
}
|
||||
|
||||
// SumFLAC costructs a checksum of the FLAC audio file data provided by the io.ReadSeeker (ignores
|
||||
// metadata fields).
|
||||
func SumFLAC(r io.ReadSeeker) (string, error) {
|
||||
flac, err := readString(r, 4)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if flac != "fLaC" {
|
||||
return "", errors.New("expected 'fLaC'")
|
||||
}
|
||||
|
||||
for {
|
||||
last, err := skipFLACMetadataBlock(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if last {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
h := sha1.New()
|
||||
_, err = io.Copy(h, r)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading data bytes from FLAC: %v", err)
|
||||
}
|
||||
return hashSum(h), nil
|
||||
}
|
||||
|
||||
func skipFLACMetadataBlock(r io.ReadSeeker) (last bool, err error) {
|
||||
blockHeader, err := readBytes(r, 1)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if getBit(blockHeader[0], 7) {
|
||||
blockHeader[0] ^= (1 << 7)
|
||||
last = true
|
||||
}
|
||||
|
||||
blockLen, err := readInt(r, 3)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
_, err = r.Seek(int64(blockLen), io.SeekCurrent)
|
||||
return
|
||||
}
|
||||
|
||||
func hashSum(h hash.Hash) string {
|
||||
return fmt.Sprintf("%x", h.Sum([]byte{}))
|
||||
}
|
||||
-147
@@ -1,147 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package tag provides MP3 (ID3: v1, 2.2, 2.3 and 2.4), MP4, FLAC and OGG metadata detection,
|
||||
// parsing and artwork extraction.
|
||||
//
|
||||
// Detect and parse tag metadata from an io.ReadSeeker (i.e. an *os.File):
|
||||
// m, err := tag.ReadFrom(f)
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
// log.Print(m.Format()) // The detected format.
|
||||
// log.Print(m.Title()) // The title of the track (see Metadata interface for more details).
|
||||
package tag
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// ErrNoTagsFound is the error returned by ReadFrom when the metadata format
|
||||
// cannot be identified.
|
||||
var ErrNoTagsFound = errors.New("no tags found")
|
||||
|
||||
// ReadFrom detects and parses audio file metadata tags (currently supports ID3v1,2.{2,3,4}, MP4, FLAC/OGG).
|
||||
// Returns non-nil error if the format of the given data could not be determined, or if there was a problem
|
||||
// parsing the data.
|
||||
func ReadFrom(r io.ReadSeeker) (Metadata, error) {
|
||||
b, err := readBytes(r, 11)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = r.Seek(-11, io.SeekCurrent)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not seek back to original position: %v", err)
|
||||
}
|
||||
|
||||
switch {
|
||||
case string(b[0:4]) == "fLaC":
|
||||
return ReadFLACTags(r)
|
||||
|
||||
case string(b[0:4]) == "OggS":
|
||||
return ReadOGGTags(r)
|
||||
|
||||
case string(b[4:8]) == "ftyp":
|
||||
return ReadAtoms(r)
|
||||
|
||||
case string(b[0:3]) == "ID3":
|
||||
return ReadID3v2Tags(r)
|
||||
|
||||
case string(b[0:4]) == "DSD ":
|
||||
return ReadDSFTags(r)
|
||||
}
|
||||
|
||||
m, err := ReadID3v1Tags(r)
|
||||
if err != nil {
|
||||
if err == ErrNotID3v1 {
|
||||
err = ErrNoTagsFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Format is an enumeration of metadata types supported by this package.
|
||||
type Format string
|
||||
|
||||
// Supported tag formats.
|
||||
const (
|
||||
UnknownFormat Format = "" // Unknown Format.
|
||||
ID3v1 Format = "ID3v1" // ID3v1 tag format.
|
||||
ID3v2_2 Format = "ID3v2.2" // ID3v2.2 tag format.
|
||||
ID3v2_3 Format = "ID3v2.3" // ID3v2.3 tag format (most common).
|
||||
ID3v2_4 Format = "ID3v2.4" // ID3v2.4 tag format.
|
||||
MP4 Format = "MP4" // MP4 tag (atom) format (see http://www.ftyps.com/ for a full file type list)
|
||||
VORBIS Format = "VORBIS" // Vorbis Comment tag format.
|
||||
)
|
||||
|
||||
// FileType is an enumeration of the audio file types supported by this package, in particular
|
||||
// there are audio file types which share metadata formats, and this type is used to distinguish
|
||||
// between them.
|
||||
type FileType string
|
||||
|
||||
// Supported file types.
|
||||
const (
|
||||
UnknownFileType FileType = "" // Unknown FileType.
|
||||
MP3 FileType = "MP3" // MP3 file
|
||||
M4A FileType = "M4A" // M4A file Apple iTunes (ACC) Audio
|
||||
M4B FileType = "M4B" // M4A file Apple iTunes (ACC) Audio Book
|
||||
M4P FileType = "M4P" // M4A file Apple iTunes (ACC) AES Protected Audio
|
||||
ALAC FileType = "ALAC" // Apple Lossless file FIXME: actually detect this
|
||||
FLAC FileType = "FLAC" // FLAC file
|
||||
OGG FileType = "OGG" // OGG file
|
||||
DSF FileType = "DSF" // DSF file DSD Sony format see https://dsd-guide.com/sites/default/files/white-papers/DSFFileFormatSpec_E.pdf
|
||||
)
|
||||
|
||||
// Metadata is an interface which is used to describe metadata retrieved by this package.
|
||||
type Metadata interface {
|
||||
// Format returns the metadata Format used to encode the data.
|
||||
Format() Format
|
||||
|
||||
// FileType returns the file type of the audio file.
|
||||
FileType() FileType
|
||||
|
||||
// Title returns the title of the track.
|
||||
Title() string
|
||||
|
||||
// Album returns the album name of the track.
|
||||
Album() string
|
||||
|
||||
// Artist returns the artist name of the track.
|
||||
Artist() string
|
||||
|
||||
// AlbumArtist returns the album artist name of the track.
|
||||
AlbumArtist() string
|
||||
|
||||
// Composer returns the composer of the track.
|
||||
Composer() string
|
||||
|
||||
// Year returns the year of the track.
|
||||
Year() int
|
||||
|
||||
// Genre returns the genre of the track.
|
||||
Genre() string
|
||||
|
||||
// Track returns the track number and total tracks, or zero values if unavailable.
|
||||
Track() (int, int)
|
||||
|
||||
// Disc returns the disc number and total discs, or zero values if unavailable.
|
||||
Disc() (int, int)
|
||||
|
||||
// Picture returns a picture, or nil if not available.
|
||||
Picture() *Picture
|
||||
|
||||
// Lyrics returns the lyrics, or an empty string if unavailable.
|
||||
Lyrics() string
|
||||
|
||||
// Comment returns the comment, or an empty string if unavailable.
|
||||
Comment() string
|
||||
|
||||
// Raw returns the raw mapping of retrieved tag names and associated values.
|
||||
// NB: tag/atom names are not standardised between formats.
|
||||
Raw() map[string]interface{}
|
||||
}
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package tag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
)
|
||||
|
||||
func getBit(b byte, n uint) bool {
|
||||
x := byte(1 << n)
|
||||
return (b & x) == x
|
||||
}
|
||||
|
||||
func get7BitChunkedInt(b []byte) int {
|
||||
var n int
|
||||
for _, x := range b {
|
||||
n = n << 7
|
||||
n |= int(x)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func getInt(b []byte) int {
|
||||
var n int
|
||||
for _, x := range b {
|
||||
n = n << 8
|
||||
n |= int(x)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func readUint64LittleEndian(r io.Reader) (uint64, error) {
|
||||
b, err := readBytes(r, 8)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return binary.LittleEndian.Uint64(b), nil
|
||||
}
|
||||
|
||||
// readBytesMaxUpfront is the max up-front allocation allowed
|
||||
const readBytesMaxUpfront = 10 << 20 // 10MB
|
||||
|
||||
func readBytes(r io.Reader, n uint) ([]byte, error) {
|
||||
if n > readBytesMaxUpfront {
|
||||
b := &bytes.Buffer{}
|
||||
if _, err := io.CopyN(b, r, int64(n)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
b := make([]byte, n)
|
||||
_, err := io.ReadFull(r, b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func readString(r io.Reader, n uint) (string, error) {
|
||||
b, err := readBytes(r, n)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
func readUint(r io.Reader, n uint) (uint, error) {
|
||||
x, err := readInt(r, n)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return uint(x), nil
|
||||
}
|
||||
|
||||
func readInt(r io.Reader, n uint) (int, error) {
|
||||
b, err := readBytes(r, n)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return getInt(b), nil
|
||||
}
|
||||
|
||||
func read7BitChunkedUint(r io.Reader, n uint) (uint, error) {
|
||||
b, err := readBytes(r, n)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return uint(get7BitChunkedInt(b)), nil
|
||||
}
|
||||
|
||||
func readUint32LittleEndian(r io.Reader) (uint32, error) {
|
||||
b, err := readBytes(r, 4)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return binary.LittleEndian.Uint32(b), nil
|
||||
}
|
||||
-266
@@ -1,266 +0,0 @@
|
||||
// Copyright 2015, David Howden
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package tag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newMetadataVorbis() *metadataVorbis {
|
||||
return &metadataVorbis{
|
||||
c: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
type metadataVorbis struct {
|
||||
c map[string]string // the vorbis comments
|
||||
p *Picture
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) readVorbisComment(r io.Reader) error {
|
||||
vendorLen, err := readUint32LittleEndian(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
vendor, err := readString(r, uint(vendorLen))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m.c["vendor"] = vendor
|
||||
|
||||
commentsLen, err := readUint32LittleEndian(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i := uint32(0); i < commentsLen; i++ {
|
||||
l, err := readUint32LittleEndian(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s, err := readString(r, uint(l))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
k, v, err := parseComment(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m.c[strings.ToLower(k)] = v
|
||||
}
|
||||
|
||||
if b64data, ok := m.c["metadata_block_picture"]; ok {
|
||||
data, err := base64.StdEncoding.DecodeString(b64data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m.readPictureBlock(bytes.NewReader(data))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) readPictureBlock(r io.Reader) error {
|
||||
b, err := readInt(r, 4)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pictureType, ok := pictureTypes[byte(b)]
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid picture type: %v", b)
|
||||
}
|
||||
mimeLen, err := readUint(r, 4)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mime, err := readString(r, mimeLen)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ext := ""
|
||||
switch mime {
|
||||
case "image/jpeg":
|
||||
ext = "jpg"
|
||||
case "image/png":
|
||||
ext = "png"
|
||||
case "image/gif":
|
||||
ext = "gif"
|
||||
}
|
||||
|
||||
descLen, err := readUint(r, 4)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
desc, err := readString(r, descLen)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// We skip width <32>, height <32>, colorDepth <32>, coloresUsed <32>
|
||||
_, err = readInt(r, 4) // width
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = readInt(r, 4) // height
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = readInt(r, 4) // color depth
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = readInt(r, 4) // colors used
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dataLen, err := readInt(r, 4)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data := make([]byte, dataLen)
|
||||
_, err = io.ReadFull(r, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m.p = &Picture{
|
||||
Ext: ext,
|
||||
MIMEType: mime,
|
||||
Type: pictureType,
|
||||
Description: desc,
|
||||
Data: data,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseComment(c string) (k, v string, err error) {
|
||||
kv := strings.SplitN(c, "=", 2)
|
||||
if len(kv) != 2 {
|
||||
err = errors.New("vorbis comment must contain '='")
|
||||
return
|
||||
}
|
||||
k = kv[0]
|
||||
v = kv[1]
|
||||
return
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Format() Format {
|
||||
return VORBIS
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Raw() map[string]interface{} {
|
||||
raw := make(map[string]interface{}, len(m.c))
|
||||
for k, v := range m.c {
|
||||
raw[k] = v
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Title() string {
|
||||
return m.c["title"]
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Artist() string {
|
||||
// ARTIST
|
||||
// The artist generally considered responsible for the work. In popular music
|
||||
// this is usually the performing band or singer. For classical music it would
|
||||
// be the composer. For an audio book it would be the author of the original text.
|
||||
return m.c["artist"]
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Album() string {
|
||||
return m.c["album"]
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) AlbumArtist() string {
|
||||
// This field isn't actually included in the standard, though
|
||||
// it is commonly assigned to albumartist.
|
||||
return m.c["albumartist"]
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Composer() string {
|
||||
if m.c["composer"] != "" {
|
||||
return m.c["composer"]
|
||||
}
|
||||
// PERFORMER
|
||||
// The artist(s) who performed the work. In classical music this would be the
|
||||
// conductor, orchestra, soloists. In an audio book it would be the actor who
|
||||
// did the reading. In popular music this is typically the same as the ARTIST
|
||||
// and is omitted.
|
||||
if m.c["performer"] != "" {
|
||||
return m.c["performer"]
|
||||
}
|
||||
return m.c["artist"]
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Genre() string {
|
||||
return m.c["genre"]
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Year() int {
|
||||
var dateFormat string
|
||||
|
||||
// The date need to follow the international standard https://en.wikipedia.org/wiki/ISO_8601
|
||||
// and obviously the VorbisComment standard https://wiki.xiph.org/VorbisComment#Date_and_time
|
||||
switch len(m.c["date"]) {
|
||||
case 0:
|
||||
// Fallback on year tag as some files use that.
|
||||
if len(m.c["year"]) != 0 {
|
||||
year, err := strconv.Atoi(m.c["year"])
|
||||
if err == nil {
|
||||
return year
|
||||
}
|
||||
}
|
||||
return 0
|
||||
case 4:
|
||||
dateFormat = "2006"
|
||||
case 7:
|
||||
dateFormat = "2006-01"
|
||||
case 10:
|
||||
dateFormat = "2006-01-02"
|
||||
}
|
||||
|
||||
t, _ := time.Parse(dateFormat, m.c["date"])
|
||||
return t.Year()
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Track() (int, int) {
|
||||
x, _ := strconv.Atoi(m.c["tracknumber"])
|
||||
// https://wiki.xiph.org/Field_names
|
||||
n, _ := strconv.Atoi(m.c["tracktotal"])
|
||||
return x, n
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Disc() (int, int) {
|
||||
// https://wiki.xiph.org/Field_names
|
||||
x, _ := strconv.Atoi(m.c["discnumber"])
|
||||
n, _ := strconv.Atoi(m.c["disctotal"])
|
||||
return x, n
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Lyrics() string {
|
||||
return m.c["lyrics"]
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Comment() string {
|
||||
if m.c["comment"] != "" {
|
||||
return m.c["comment"]
|
||||
}
|
||||
return m.c["description"]
|
||||
}
|
||||
|
||||
func (m *metadataVorbis) Picture() *Picture {
|
||||
return m.p
|
||||
}
|
||||
Generated
-7
@@ -1,7 +0,0 @@
|
||||
.DS_Store
|
||||
TODO
|
||||
tmp/**/*
|
||||
*.coverprofile
|
||||
.vscode
|
||||
.idea/
|
||||
*.log
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
language: go
|
||||
go:
|
||||
- tip
|
||||
- 1.16.x
|
||||
- 1.15.x
|
||||
|
||||
cache:
|
||||
directories:
|
||||
- $GOPATH/pkg/mod
|
||||
|
||||
# allow internal package imports, necessary for forked repositories
|
||||
go_import_path: github.com/onsi/ginkgo
|
||||
|
||||
install:
|
||||
- GO111MODULE="off" go get -v -t ./...
|
||||
- GO111MODULE="off" go get golang.org/x/tools/cmd/cover
|
||||
- GO111MODULE="off" go get github.com/onsi/gomega
|
||||
- GO111MODULE="off" go install github.com/onsi/ginkgo/ginkgo
|
||||
- export PATH=$GOPATH/bin:$PATH
|
||||
|
||||
script:
|
||||
- GO111MODULE="on" go mod tidy && git diff --exit-code go.mod go.sum
|
||||
- go vet
|
||||
- ginkgo -r --randomizeAllSpecs --randomizeSuites --race --trace
|
||||
-393
@@ -1,393 +0,0 @@
|
||||
## 1.16.5
|
||||
|
||||
Ginkgo 2.0 now has a Release Candidate. 1.16.5 advertises the existence of the RC.
|
||||
1.16.5 deprecates GinkgoParallelNode in favor of GinkgoParallelProcess
|
||||
|
||||
You can silence the RC advertisement by setting an `ACK_GINKG_RC=true` environment variable or creating a file in your home directory called `.ack-ginkgo-rc`
|
||||
|
||||
## 1.16.4
|
||||
|
||||
### Fixes
|
||||
1.16.4 retracts 1.16.3. There are no code changes. The 1.16.3 tag was associated with the wrong commit and an attempt to change it after-the-fact has proven problematic. 1.16.4 retracts 1.16.3 in Ginkgo's go.mod and creates a new, correctly tagged, release.
|
||||
|
||||
## 1.16.3
|
||||
|
||||
### Features
|
||||
- Measure is now deprecated and emits a deprecation warning.
|
||||
|
||||
## 1.16.2
|
||||
|
||||
### Fixes
|
||||
- Deprecations can be suppressed by setting an `ACK_GINKGO_DEPRECATIONS=<semver>` environment variable.
|
||||
|
||||
## 1.16.1
|
||||
|
||||
### Fixes
|
||||
- Supress --stream deprecation warning on windows (#793)
|
||||
|
||||
## 1.16.0
|
||||
|
||||
### Features
|
||||
- Advertise Ginkgo 2.0. Introduce deprecations. [9ef1913]
|
||||
- Update README.md to advertise that Ginkgo 2.0 is coming.
|
||||
- Backport the 2.0 DeprecationTracker and start alerting users
|
||||
about upcoming deprecations.
|
||||
|
||||
- Add slim-sprig template functions to bootstrap/generate (#775) [9162b86]
|
||||
|
||||
### Fixes
|
||||
- Fix accidental reference to 1488 (#784) [9fb7fe4]
|
||||
|
||||
## 1.15.2
|
||||
|
||||
### Fixes
|
||||
- ignore blank `-focus` and `-skip` flags (#780) [e90a4a0]
|
||||
|
||||
## 1.15.1
|
||||
|
||||
### Fixes
|
||||
- reporters/junit: Use `system-out` element instead of `passed` (#769) [9eda305]
|
||||
|
||||
## 1.15.0
|
||||
|
||||
### Features
|
||||
- Adds 'outline' command to print the outline of specs/containers in a file (#754) [071c369] [6803cc3] [935b538] [06744e8] [0c40583]
|
||||
- Add support for using template to generate tests (#752) [efb9e69]
|
||||
- Add a Chinese Doc #755 (#756) [5207632]
|
||||
- cli: allow multiple -focus and -skip flags (#736) [9a782fb]
|
||||
|
||||
### Fixes
|
||||
- Add _internal to filename of tests created with internal flag (#751) [43c12da]
|
||||
|
||||
## 1.14.2
|
||||
|
||||
### Fixes
|
||||
- correct handling windows backslash in import path (#721) [97f3d51]
|
||||
- Add additional methods to GinkgoT() to improve compatibility with the testing.TB interface [b5fe44d]
|
||||
|
||||
## 1.14.1
|
||||
|
||||
### Fixes
|
||||
- Discard exported method declaration when running ginkgo bootstrap (#558) [f4b0240]
|
||||
|
||||
## 1.14.0
|
||||
|
||||
### Features
|
||||
- Defer running top-level container nodes until RunSpecs is called [d44dedf]
|
||||
- [Document Ginkgo lifecycle](http://onsi.github.io/ginkgo/#understanding-ginkgos-lifecycle)
|
||||
- Add `extensions/globals` package (#692) [3295c8f] - this can be helpful in contexts where you are test-driving your test-generation code (see [#692](https://github.com/onsi/ginkgo/pull/692))
|
||||
- Print Skip reason in JUnit reporter if one was provided [820dfab]
|
||||
|
||||
## 1.13.0
|
||||
|
||||
### Features
|
||||
- Add a version of table.Entry that allows dumping the entry parameters. (#689) [21eaef2]
|
||||
|
||||
### Fixes
|
||||
- Ensure integration tests pass in an environment sans GOPATH [606fba2]
|
||||
- Add books package (#568) [fc0e44e]
|
||||
- doc(readme): installation via "tools package" (#677) [83bb20e]
|
||||
- Solve the undefined: unix.Dup2 compile error on mips64le (#680) [0624f75]
|
||||
- Import package without dot (#687) [6321024]
|
||||
- Fix integration tests to stop require GOPATH (#686) [a912ec5]
|
||||
|
||||
## 1.12.3
|
||||
|
||||
### Fixes
|
||||
- Print correct code location of failing table test (#666) [c6d7afb]
|
||||
|
||||
## 1.12.2
|
||||
|
||||
### Fixes
|
||||
- Update dependencies [ea4a036]
|
||||
|
||||
## 1.12.1
|
||||
|
||||
### Fixes
|
||||
- Make unfocus ("blur") much faster (#674) [8b18061]
|
||||
- Fix typo (#673) [7fdcbe8]
|
||||
- Test against 1.14 and remove 1.12 [d5c2ad6]
|
||||
- Test if a coverprofile content is empty before checking its latest character (#670) [14d9fa2]
|
||||
- replace tail package with maintained one. this fixes go get errors (#667) [4ba33d4]
|
||||
- improve ginkgo performance - makes progress on #644 [a14f98e]
|
||||
- fix convert integration tests [1f8ba69]
|
||||
- fix typo succesful -> successful (#663) [1ea49cf]
|
||||
- Fix invalid link (#658) [b886136]
|
||||
- convert utility : Include comments from source (#657) [1077c6d]
|
||||
- Explain what BDD means [d79e7fb]
|
||||
- skip race detector test on unsupported platform (#642) [f8ab89d]
|
||||
- Use Dup2 from golang.org/x/sys/unix instead of syscallDup (#638) [5d53c55]
|
||||
- Fix missing newline in combined coverage file (#641) [6a07ea2]
|
||||
- check if a spec is run before returning SpecSummary (#645) [8850000]
|
||||
|
||||
## 1.12.0
|
||||
|
||||
### Features
|
||||
- Add module definition (#630) [78916ab]
|
||||
|
||||
## 1.11.0
|
||||
|
||||
### Features
|
||||
- Add syscall for riscv64 architecture [f66e896]
|
||||
- teamcity reporter: output location of test failure as well as test definition (#626) [9869142]
|
||||
- teamcity reporter: output newline after every service message (#625) [3cfa02d]
|
||||
- Add support for go module when running `generate` command (#578) [9c89e3f]
|
||||
|
||||
## 1.10.3
|
||||
|
||||
### Fixes
|
||||
- Set go_import_path in travis.yml to allow internal packages in forks (#607) [3b721db]
|
||||
- Add integration test [d90e0dc]
|
||||
- Fix coverage files combining [e5dde8c]
|
||||
- A new CLI option: -ginkgo.reportFile <file path> (#601) [034fd25]
|
||||
|
||||
## 1.10.2
|
||||
|
||||
### Fixes
|
||||
- speed up table entry generateIt() (#609) [5049dc5]
|
||||
- Fix. Write errors to stderr instead of stdout (#610) [7bb3091]
|
||||
|
||||
## 1.10.1
|
||||
|
||||
### Fixes
|
||||
- stack backtrace: fix skipping (#600) [2a4c0bd]
|
||||
|
||||
## 1.10.0
|
||||
|
||||
### Fixes
|
||||
- stack backtrace: fix alignment and skipping [66915d6]
|
||||
- fix typo in documentation [8f97b93]
|
||||
|
||||
## 1.9.0
|
||||
|
||||
### Features
|
||||
- Option to print output into report, when tests have passed [0545415]
|
||||
|
||||
### Fixes
|
||||
- Fixed typos in comments [0ecbc58]
|
||||
- gofmt code [a7f8bfb]
|
||||
- Simplify code [7454d00]
|
||||
- Simplify concatenation, incrementation and function assignment [4825557]
|
||||
- Avoid unnecessary conversions [9d9403c]
|
||||
- JUnit: include more detailed information about panic [19cca4b]
|
||||
- Print help to stdout when the user asks for help [4cb7441]
|
||||
|
||||
|
||||
## 1.8.0
|
||||
|
||||
### New Features
|
||||
- allow config of the vet flag for `go test` (#562) [3cd45fa]
|
||||
- Support projects using go modules [d56ee76]
|
||||
|
||||
### Fixes and Minor Improvements
|
||||
- chore(godoc): fixes typos in Measurement funcs [dbaca8e]
|
||||
- Optimize focus to avoid allocations [f493786]
|
||||
- Ensure generated test file names are underscored [505cc35]
|
||||
|
||||
## 1.7.0
|
||||
|
||||
### New Features
|
||||
- Add JustAfterEach (#484) [0d4f080]
|
||||
|
||||
### Fixes
|
||||
- Correctly round suite time in junit reporter [2445fc1]
|
||||
- Avoid using -i argument to go test for Golang 1.10+ [46bbc26]
|
||||
|
||||
## 1.6.0
|
||||
|
||||
### New Features
|
||||
- add --debug flag to emit node output to files (#499) [39febac]
|
||||
|
||||
### Fixes
|
||||
- fix: for `go vet` to pass [69338ec]
|
||||
- docs: fix for contributing instructions [7004cb1]
|
||||
- consolidate and streamline contribution docs (#494) [d848015]
|
||||
- Make generated Junit file compatable with "Maven Surefire" (#488) [e51bee6]
|
||||
- all: gofmt [000d317]
|
||||
- Increase eventually timeout to 30s [c73579c]
|
||||
- Clarify asynchronous test behaviour [294d8f4]
|
||||
- Travis badge should only show master [26d2143]
|
||||
|
||||
## 1.5.0 5/10/2018
|
||||
|
||||
### New Features
|
||||
- Supports go v1.10 (#443, #446, #451) [e873237, 468e89e, e37dbfe, a37f4c0, c0b857d, bca5260, 4177ca8]
|
||||
- Add a When() synonym for Context() (#386) [747514b, 7484dad, 7354a07, dd826c8]
|
||||
- Re-add noisySkippings flag [652e15c]
|
||||
- Allow coverage to be displayed for focused specs (#367) [11459a8]
|
||||
- Handle -outputdir flag (#364) [228e3a8]
|
||||
- Handle -coverprofile flag (#355) [43392d5]
|
||||
|
||||
### Fixes
|
||||
- When using custom reporters register the custom reporters *before* the default reporter. This allows users to see the output of any print statements in their customer reporters. (#365) [8382b23]
|
||||
- When running a test and calculating the coverage using the `-coverprofile` and `-outputdir` flags, Ginkgo fails with an error if the directory does not exist. This is due to an [issue in go 1.10](https://github.com/golang/go/issues/24588) (#446) [b36a6e0]
|
||||
- `unfocus` command ignores vendor folder (#459) [e5e551c, c556e43, a3b6351, 9a820dd]
|
||||
- Ignore packages whose tests are all ignored by go (#456) [7430ca7, 6d8be98]
|
||||
- Increase the threshold when checking time measuments (#455) [2f714bf, 68f622c]
|
||||
- Fix race condition in coverage tests (#423) [a5a8ff7, ab9c08b]
|
||||
- Add an extra new line after reporting spec run completion for test2json [874520d]
|
||||
- added name name field to junit reported testsuite [ae61c63]
|
||||
- Do not set the run time of a spec when the dryRun flag is used (#438) [457e2d9, ba8e856]
|
||||
- Process FWhen and FSpecify when unfocusing (#434) [9008c7b, ee65bd, df87dfe]
|
||||
- Synchronise the access to the state of specs to avoid race conditions (#430) [7d481bc, ae6829d]
|
||||
- Added Duration on GinkgoTestDescription (#383) [5f49dad, 528417e, 0747408, 329d7ed]
|
||||
- Fix Ginkgo stack trace on failure for Specify (#415) [b977ede, 65ca40e, 6c46eb8]
|
||||
- Update README with Go 1.6+, Golang -> Go (#409) [17f6b97, bc14b66, 20d1598]
|
||||
- Use fmt.Errorf instead of errors.New(fmt.Sprintf (#401) [a299f56, 44e2eaa]
|
||||
- Imports in generated code should follow conventions (#398) [0bec0b0, e8536d8]
|
||||
- Prevent data race error when Recording a benchmark value from multiple go routines (#390) [c0c4881, 7a241e9]
|
||||
- Replace GOPATH in Environment [4b883f0]
|
||||
|
||||
|
||||
## 1.4.0 7/16/2017
|
||||
|
||||
- `ginkgo` now provides a hint if you accidentally forget to run `ginkgo bootstrap` to generate a `*_suite_test.go` file that actually invokes the Ginkgo test runner. [#345](https://github.com/onsi/ginkgo/pull/345)
|
||||
- thanks to improvements in `go test -c` `ginkgo` no longer needs to fix Go's compilation output to ensure compilation errors are expressed relative to the CWD. [#357]
|
||||
- `ginkgo watch -watchRegExp=...` allows you to specify a custom regular expression to watch. Only files matching the regular expression are watched for changes (the default is `\.go$`) [#356]
|
||||
- `ginkgo` now always emits compilation output. Previously, only failed compilation output was printed out. [#277]
|
||||
- `ginkgo -requireSuite` now fails the test run if there are `*_test.go` files but `go test` fails to detect any tests. Typically this means you forgot to run `ginkgo bootstrap` to generate a suite file. [#344]
|
||||
- `ginkgo -timeout=DURATION` allows you to adjust the timeout for the entire test suite (default is 24 hours) [#248]
|
||||
|
||||
## 1.3.0 3/28/2017
|
||||
|
||||
Improvements:
|
||||
|
||||
- Significantly improved parallel test distribution. Now instead of pre-sharding test cases across workers (which can result in idle workers and poor test performance) Ginkgo uses a shared queue to keep all workers busy until all tests are complete. This improves test-time performance and consistency.
|
||||
- `Skip(message)` can be used to skip the current test.
|
||||
- Added `extensions/table` - a Ginkgo DSL for [Table Driven Tests](http://onsi.github.io/ginkgo/#table-driven-tests)
|
||||
- Add `GinkgoRandomSeed()` - shorthand for `config.GinkgoConfig.RandomSeed`
|
||||
- Support for retrying flaky tests with `--flakeAttempts`
|
||||
- `ginkgo ./...` now recurses as you'd expect
|
||||
- Added `Specify` a synonym for `It`
|
||||
- Support colorise on Windows
|
||||
- Broader support for various go compilation flags in the `ginkgo` CLI
|
||||
|
||||
Bug Fixes:
|
||||
|
||||
- Ginkgo tests now fail when you `panic(nil)` (#167)
|
||||
|
||||
## 1.2.0 5/31/2015
|
||||
|
||||
Improvements
|
||||
|
||||
- `ginkgo -coverpkg` calls down to `go test -coverpkg` (#160)
|
||||
- `ginkgo -afterSuiteHook COMMAND` invokes the passed-in `COMMAND` after a test suite completes (#152)
|
||||
- Relaxed requirement for Go 1.4+. `ginkgo` now works with Go v1.3+ (#166)
|
||||
|
||||
## 1.2.0-beta
|
||||
|
||||
Ginkgo now requires Go 1.4+
|
||||
|
||||
Improvements:
|
||||
|
||||
- Call reporters in reverse order when announcing spec completion -- allows custom reporters to emit output before the default reporter does.
|
||||
- Improved focus behavior. Now, this:
|
||||
|
||||
```golang
|
||||
FDescribe("Some describe", func() {
|
||||
It("A", func() {})
|
||||
|
||||
FIt("B", func() {})
|
||||
})
|
||||
```
|
||||
|
||||
will run `B` but *not* `A`. This tends to be a common usage pattern when in the thick of writing and debugging tests.
|
||||
- When `SIGINT` is received, Ginkgo will emit the contents of the `GinkgoWriter` before running the `AfterSuite`. Useful for debugging stuck tests.
|
||||
- When `--progress` is set, Ginkgo will write test progress (in particular, Ginkgo will say when it is about to run a BeforeEach, AfterEach, It, etc...) to the `GinkgoWriter`. This is useful for debugging stuck tests and tests that generate many logs.
|
||||
- Improved output when an error occurs in a setup or teardown block.
|
||||
- When `--dryRun` is set, Ginkgo will walk the spec tree and emit to its reporter *without* actually running anything. Best paired with `-v` to understand which specs will run in which order.
|
||||
- Add `By` to help document long `It`s. `By` simply writes to the `GinkgoWriter`.
|
||||
- Add support for precompiled tests:
|
||||
- `ginkgo build <path-to-package>` will now compile the package, producing a file named `package.test`
|
||||
- The compiled `package.test` file can be run directly. This runs the tests in series.
|
||||
- To run precompiled tests in parallel, you can run: `ginkgo -p package.test`
|
||||
- Support `bootstrap`ping and `generate`ing [Agouti](http://agouti.org) specs.
|
||||
- `ginkgo generate` and `ginkgo bootstrap` now honor the package name already defined in a given directory
|
||||
- The `ginkgo` CLI ignores `SIGQUIT`. Prevents its stack dump from interlacing with the underlying test suite's stack dump.
|
||||
- The `ginkgo` CLI now compiles tests into a temporary directory instead of the package directory. This necessitates upgrading to Go v1.4+.
|
||||
- `ginkgo -notify` now works on Linux
|
||||
|
||||
Bug Fixes:
|
||||
|
||||
- If --skipPackages is used and all packages are skipped, Ginkgo should exit 0.
|
||||
- Fix tempfile leak when running in parallel
|
||||
- Fix incorrect failure message when a panic occurs during a parallel test run
|
||||
- Fixed an issue where a pending test within a focused context (or a focused test within a pending context) would skip all other tests.
|
||||
- Be more consistent about handling SIGTERM as well as SIGINT
|
||||
- When interupted while concurrently compiling test suites in the background, Ginkgo now cleans up the compiled artifacts.
|
||||
- Fixed a long standing bug where `ginkgo -p` would hang if a process spawned by one of the Ginkgo parallel nodes does not exit. (Hooray!)
|
||||
|
||||
## 1.1.0 (8/2/2014)
|
||||
|
||||
No changes, just dropping the beta.
|
||||
|
||||
## 1.1.0-beta (7/22/2014)
|
||||
New Features:
|
||||
|
||||
- `ginkgo watch` now monitors packages *and their dependencies* for changes. The depth of the dependency tree can be modified with the `-depth` flag.
|
||||
- Test suites with a programmatic focus (`FIt`, `FDescribe`, etc...) exit with non-zero status code, even when they pass. This allows CI systems to detect accidental commits of focused test suites.
|
||||
- `ginkgo -p` runs the testsuite in parallel with an auto-detected number of nodes.
|
||||
- `ginkgo -tags=TAG_LIST` passes a list of tags down to the `go build` command.
|
||||
- `ginkgo --failFast` aborts the test suite after the first failure.
|
||||
- `ginkgo generate file_1 file_2` can take multiple file arguments.
|
||||
- Ginkgo now summarizes any spec failures that occurred at the end of the test run.
|
||||
- `ginkgo --randomizeSuites` will run tests *suites* in random order using the generated/passed-in seed.
|
||||
|
||||
Improvements:
|
||||
|
||||
- `ginkgo -skipPackage` now takes a comma-separated list of strings. If the *relative path* to a package matches one of the entries in the comma-separated list, that package is skipped.
|
||||
- `ginkgo --untilItFails` no longer recompiles between attempts.
|
||||
- Ginkgo now panics when a runnable node (`It`, `BeforeEach`, `JustBeforeEach`, `AfterEach`, `Measure`) is nested within another runnable node. This is always a mistake. Any test suites that panic because of this change should be fixed.
|
||||
|
||||
Bug Fixes:
|
||||
|
||||
- `ginkgo boostrap` and `ginkgo generate` no longer fail when dealing with `hyphen-separated-packages`.
|
||||
- parallel specs are now better distributed across nodes - fixed a crashing bug where (for example) distributing 11 tests across 7 nodes would panic
|
||||
|
||||
## 1.0.0 (5/24/2014)
|
||||
New Features:
|
||||
|
||||
- Add `GinkgoParallelNode()` - shorthand for `config.GinkgoConfig.ParallelNode`
|
||||
|
||||
Improvements:
|
||||
|
||||
- When compilation fails, the compilation output is rewritten to present a correct *relative* path. Allows ⌘-clicking in iTerm open the file in your text editor.
|
||||
- `--untilItFails` and `ginkgo watch` now generate new random seeds between test runs, unless a particular random seed is specified.
|
||||
|
||||
Bug Fixes:
|
||||
|
||||
- `-cover` now generates a correctly combined coverprofile when running with in parallel with multiple `-node`s.
|
||||
- Print out the contents of the `GinkgoWriter` when `BeforeSuite` or `AfterSuite` fail.
|
||||
- Fix all remaining race conditions in Ginkgo's test suite.
|
||||
|
||||
## 1.0.0-beta (4/14/2014)
|
||||
Breaking changes:
|
||||
|
||||
- `thirdparty/gomocktestreporter` is gone. Use `GinkgoT()` instead
|
||||
- Modified the Reporter interface
|
||||
- `watch` is now a subcommand, not a flag.
|
||||
|
||||
DSL changes:
|
||||
|
||||
- `BeforeSuite` and `AfterSuite` for setting up and tearing down test suites.
|
||||
- `AfterSuite` is triggered on interrupt (`^C`) as well as exit.
|
||||
- `SynchronizedBeforeSuite` and `SynchronizedAfterSuite` for setting up and tearing down singleton resources across parallel nodes.
|
||||
|
||||
CLI changes:
|
||||
|
||||
- `watch` is now a subcommand, not a flag
|
||||
- `--nodot` flag can be passed to `ginkgo generate` and `ginkgo bootstrap` to avoid dot imports. This explicitly imports all exported identifiers in Ginkgo and Gomega. Refreshing this list can be done by running `ginkgo nodot`
|
||||
- Additional arguments can be passed to specs. Pass them after the `--` separator
|
||||
- `--skipPackage` flag takes a regexp and ignores any packages with package names passing said regexp.
|
||||
- `--trace` flag prints out full stack traces when errors occur, not just the line at which the error occurs.
|
||||
|
||||
Misc:
|
||||
|
||||
- Start using semantic versioning
|
||||
- Start maintaining changelog
|
||||
|
||||
Major refactor:
|
||||
|
||||
- Pull out Ginkgo's internal to `internal`
|
||||
- Rename `example` everywhere to `spec`
|
||||
- Much more!
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
# Contributing to Ginkgo
|
||||
|
||||
Your contributions to Ginkgo are essential for its long-term maintenance and improvement.
|
||||
|
||||
- Please **open an issue first** - describe what problem you are trying to solve and give the community a forum for input and feedback ahead of investing time in writing code!
|
||||
- Ensure adequate test coverage:
|
||||
- When adding to the Ginkgo library, add unit and/or integration tests (under the `integration` folder).
|
||||
- When adding to the Ginkgo CLI, note that there are very few unit tests. Please add an integration test.
|
||||
- Update the documentation. Ginko uses `godoc` comments and documentation on the `gh-pages` branch.
|
||||
If relevant, please submit a docs PR to that branch alongside your code PR.
|
||||
|
||||
Thanks for supporting Ginkgo!
|
||||
|
||||
## Setup
|
||||
|
||||
Fork the repo, then:
|
||||
|
||||
```
|
||||
go get github.com/onsi/ginkgo
|
||||
go get github.com/onsi/gomega/...
|
||||
cd $GOPATH/src/github.com/onsi/ginkgo
|
||||
git remote add fork git@github.com:<NAME>/ginkgo.git
|
||||
|
||||
ginkgo -r -p # ensure tests are green
|
||||
go vet ./... # ensure linter is happy
|
||||
```
|
||||
|
||||
## Making the PR
|
||||
- go to a new branch `git checkout -b my-feature`
|
||||
- make your changes
|
||||
- run tests and linter again (see above)
|
||||
- `git push fork`
|
||||
- open PR 🎉
|
||||
-169
@@ -1,169 +0,0 @@
|
||||

|
||||
|
||||
[](https://github.com/onsi/ginkgo/actions?query=workflow%3Atest+branch%3Amaster)
|
||||
|
||||
Jump to the [docs](https://onsi.github.io/ginkgo/) | [中文文档](https://ke-chain.github.io/ginkgodoc) to learn more. To start rolling your Ginkgo tests *now* [keep reading](#set-me-up)!
|
||||
|
||||
If you have a question, comment, bug report, feature request, etc. please open a GitHub issue, or visit the [Ginkgo Slack channel](https://app.slack.com/client/T029RQSE6/CQQ50BBNW).
|
||||
|
||||
# Ginkgo 2.0 Release Candidate is available!
|
||||
|
||||
An effort is underway to develop and deliver Ginkgo 2.0. The work is happening in the [ver2](https://github.com/onsi/ginkgo/tree/ver2) branch and a changelog and migration guide is being maintained on that branch [here](https://github.com/onsi/ginkgo/blob/ver2/docs/MIGRATING_TO_V2.md). Issue [#711](https://github.com/onsi/ginkgo/issues/711) is the central place for discussion.
|
||||
|
||||
As described in the [changelog](https://github.com/onsi/ginkgo/blob/ver2/docs/MIGRATING_TO_V2.md) and [proposal](https://docs.google.com/document/d/1h28ZknXRsTLPNNiOjdHIO-F2toCzq4xoZDXbfYaBdoQ/edit#), Ginkgo 2.0 will clean up the Ginkgo codebase, deprecate and remove some v1 functionality, and add several new much-requested features. To help users get ready for the migration, Ginkgo v1 has started emitting deprecation warnings for features that will no longer be supported with links to documentation for how to migrate away from these features. If you have concerns or comments please chime in on [#711](https://github.com/onsi/ginkgo/issues/711).
|
||||
|
||||
Please start exploring and using the V2 release! To get started follow the [Using the Release Candidate](https://github.com/onsi/ginkgo/blob/ver2/docs/MIGRATING_TO_V2.md#using-the-beta) directions in the migration guide.
|
||||
|
||||
## TLDR
|
||||
Ginkgo builds on Go's `testing` package, allowing expressive [Behavior-Driven Development](https://en.wikipedia.org/wiki/Behavior-driven_development) ("BDD") style tests.
|
||||
It is typically (and optionally) paired with the [Gomega](https://github.com/onsi/gomega) matcher library.
|
||||
|
||||
```go
|
||||
Describe("the strings package", func() {
|
||||
Context("strings.Contains()", func() {
|
||||
When("the string contains the substring in the middle", func() {
|
||||
It("returns `true`", func() {
|
||||
Expect(strings.Contains("Ginkgo is awesome", "is")).To(BeTrue())
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Feature List
|
||||
|
||||
- Ginkgo uses Go's `testing` package and can live alongside your existing `testing` tests. It's easy to [bootstrap](https://onsi.github.io/ginkgo/#bootstrapping-a-suite) and start writing your [first tests](https://onsi.github.io/ginkgo/#adding-specs-to-a-suite)
|
||||
|
||||
- Ginkgo allows you to write tests in Go using expressive [Behavior-Driven Development](https://en.wikipedia.org/wiki/Behavior-driven_development) ("BDD") style:
|
||||
- Nestable [`Describe`, `Context` and `When` container blocks](https://onsi.github.io/ginkgo/#organizing-specs-with-containers-describe-and-context)
|
||||
- [`BeforeEach` and `AfterEach` blocks](https://onsi.github.io/ginkgo/#extracting-common-setup-beforeeach) for setup and teardown
|
||||
- [`It` and `Specify` blocks](https://onsi.github.io/ginkgo/#individual-specs-it) that hold your assertions
|
||||
- [`JustBeforeEach` blocks](https://onsi.github.io/ginkgo/#separating-creation-and-configuration-justbeforeeach) that separate creation from configuration (also known as the subject action pattern).
|
||||
- [`BeforeSuite` and `AfterSuite` blocks](https://onsi.github.io/ginkgo/#global-setup-and-teardown-beforesuite-and-aftersuite) to prep for and cleanup after a suite.
|
||||
|
||||
- A comprehensive test runner that lets you:
|
||||
- Mark specs as [pending](https://onsi.github.io/ginkgo/#pending-specs)
|
||||
- [Focus](https://onsi.github.io/ginkgo/#focused-specs) individual specs, and groups of specs, either programmatically or on the command line
|
||||
- Run your tests in [random order](https://onsi.github.io/ginkgo/#spec-permutation), and then reuse random seeds to replicate the same order.
|
||||
- Break up your test suite into parallel processes for straightforward [test parallelization](https://onsi.github.io/ginkgo/#parallel-specs)
|
||||
|
||||
- `ginkgo`: a command line interface with plenty of handy command line arguments for [running your tests](https://onsi.github.io/ginkgo/#running-tests) and [generating](https://onsi.github.io/ginkgo/#generators) test files. Here are a few choice examples:
|
||||
- `ginkgo -nodes=N` runs your tests in `N` parallel processes and print out coherent output in realtime
|
||||
- `ginkgo -cover` runs your tests using Go's code coverage tool
|
||||
- `ginkgo convert` converts an XUnit-style `testing` package to a Ginkgo-style package
|
||||
- `ginkgo -focus="REGEXP"` and `ginkgo -skip="REGEXP"` allow you to specify a subset of tests to run via regular expression
|
||||
- `ginkgo -r` runs all tests suites under the current directory
|
||||
- `ginkgo -v` prints out identifying information for each tests just before it runs
|
||||
|
||||
And much more: run `ginkgo help` for details!
|
||||
|
||||
The `ginkgo` CLI is convenient, but purely optional -- Ginkgo works just fine with `go test`
|
||||
|
||||
- `ginkgo watch` [watches](https://onsi.github.io/ginkgo/#watching-for-changes) packages *and their dependencies* for changes, then reruns tests. Run tests immediately as you develop!
|
||||
|
||||
- Built-in support for testing [asynchronicity](https://onsi.github.io/ginkgo/#asynchronous-tests)
|
||||
|
||||
- Built-in support for [benchmarking](https://onsi.github.io/ginkgo/#benchmark-tests) your code. Control the number of benchmark samples as you gather runtimes and other, arbitrary, bits of numerical information about your code.
|
||||
|
||||
- [Completions for Sublime Text](https://github.com/onsi/ginkgo-sublime-completions): just use [Package Control](https://sublime.wbond.net/) to install `Ginkgo Completions`.
|
||||
|
||||
- [Completions for VSCode](https://github.com/onsi/vscode-ginkgo): just use VSCode's extension installer to install `vscode-ginkgo`.
|
||||
|
||||
- [Ginkgo tools for VSCode](https://marketplace.visualstudio.com/items?itemName=joselitofilho.ginkgotestexplorer): just use VSCode's extension installer to install `ginkgoTestExplorer`.
|
||||
|
||||
- Straightforward support for third-party testing libraries such as [Gomock](https://code.google.com/p/gomock/) and [Testify](https://github.com/stretchr/testify). Check out the [docs](https://onsi.github.io/ginkgo/#third-party-integrations) for details.
|
||||
|
||||
- A modular architecture that lets you easily:
|
||||
- Write [custom reporters](https://onsi.github.io/ginkgo/#writing-custom-reporters) (for example, Ginkgo comes with a [JUnit XML reporter](https://onsi.github.io/ginkgo/#generating-junit-xml-output) and a TeamCity reporter).
|
||||
- [Adapt an existing matcher library (or write your own!)](https://onsi.github.io/ginkgo/#using-other-matcher-libraries) to work with Ginkgo
|
||||
|
||||
## [Gomega](https://github.com/onsi/gomega): Ginkgo's Preferred Matcher Library
|
||||
|
||||
Ginkgo is best paired with Gomega. Learn more about Gomega [here](https://onsi.github.io/gomega/)
|
||||
|
||||
## [Agouti](https://github.com/sclevine/agouti): A Go Acceptance Testing Framework
|
||||
|
||||
Agouti allows you run WebDriver integration tests. Learn more about Agouti [here](https://agouti.org)
|
||||
|
||||
## Getting Started
|
||||
|
||||
You'll need the Go command-line tools. Follow the [installation instructions](https://golang.org/doc/install) if you don't have it installed.
|
||||
|
||||
### Global installation
|
||||
To install the Ginkgo command line interface:
|
||||
```bash
|
||||
go get -u github.com/onsi/ginkgo/ginkgo
|
||||
```
|
||||
Note that this will install it to `$GOBIN`, which will need to be in the `$PATH` (or equivalent). Run `go help install` for more information.
|
||||
|
||||
### Go module ["tools package"](https://github.com/golang/go/issues/25922):
|
||||
Create (or update) a file called `tools/tools.go` with the following contents:
|
||||
```go
|
||||
// +build tools
|
||||
|
||||
package tools
|
||||
|
||||
import (
|
||||
_ "github.com/onsi/ginkgo/ginkgo"
|
||||
)
|
||||
|
||||
// This file imports packages that are used when running go generate, or used
|
||||
// during the development process but not otherwise depended on by built code.
|
||||
```
|
||||
The Ginkgo command can then be run via `go run github.com/onsi/ginkgo/ginkgo`.
|
||||
This approach allows the version of Ginkgo to be maintained under source control for reproducible results,
|
||||
and is well suited to automated test pipelines.
|
||||
|
||||
### Bootstrapping
|
||||
```bash
|
||||
cd path/to/package/you/want/to/test
|
||||
|
||||
ginkgo bootstrap # set up a new ginkgo suite
|
||||
ginkgo generate # will create a sample test file. edit this file and add your tests then...
|
||||
|
||||
go test # to run your tests
|
||||
|
||||
ginkgo # also runs your tests
|
||||
|
||||
```
|
||||
|
||||
## I'm new to Go: What are my testing options?
|
||||
|
||||
Of course, I heartily recommend [Ginkgo](https://github.com/onsi/ginkgo) and [Gomega](https://github.com/onsi/gomega). Both packages are seeing heavy, daily, production use on a number of projects and boast a mature and comprehensive feature-set.
|
||||
|
||||
With that said, it's great to know what your options are :)
|
||||
|
||||
### What Go gives you out of the box
|
||||
|
||||
Testing is a first class citizen in Go, however Go's built-in testing primitives are somewhat limited: The [testing](https://golang.org/pkg/testing) package provides basic XUnit style tests and no assertion library.
|
||||
|
||||
### Matcher libraries for Go's XUnit style tests
|
||||
|
||||
A number of matcher libraries have been written to augment Go's built-in XUnit style tests. Here are two that have gained traction:
|
||||
|
||||
- [testify](https://github.com/stretchr/testify)
|
||||
- [gocheck](https://labix.org/gocheck)
|
||||
|
||||
You can also use Ginkgo's matcher library [Gomega](https://github.com/onsi/gomega) in [XUnit style tests](https://onsi.github.io/gomega/#using-gomega-with-golangs-xunitstyle-tests)
|
||||
|
||||
### BDD style testing frameworks
|
||||
|
||||
There are a handful of BDD-style testing frameworks written for Go. Here are a few:
|
||||
|
||||
- [Ginkgo](https://github.com/onsi/ginkgo) ;)
|
||||
- [GoConvey](https://github.com/smartystreets/goconvey)
|
||||
- [Goblin](https://github.com/franela/goblin)
|
||||
- [Mao](https://github.com/azer/mao)
|
||||
- [Zen](https://github.com/pranavraja/zen)
|
||||
|
||||
Finally, @shageman has [put together](https://github.com/shageman/gotestit) a comprehensive comparison of Go testing libraries.
|
||||
|
||||
Go explore!
|
||||
|
||||
## License
|
||||
|
||||
Ginkgo is MIT-Licensed
|
||||
|
||||
## Contributing
|
||||
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md)
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
A Ginkgo release is a tagged git sha and a GitHub release. To cut a release:
|
||||
|
||||
1. Ensure CHANGELOG.md is up to date.
|
||||
- Use `git log --pretty=format:'- %s [%h]' HEAD...vX.X.X` to list all the commits since the last release
|
||||
- Categorize the changes into
|
||||
- Breaking Changes (requires a major version)
|
||||
- New Features (minor version)
|
||||
- Fixes (fix version)
|
||||
- Maintenance (which in general should not be mentioned in `CHANGELOG.md` as they have no user impact)
|
||||
1. Update `VERSION` in `config/config.go`
|
||||
1. Commit, push, and release:
|
||||
```
|
||||
git commit -m "vM.m.p"
|
||||
git push
|
||||
gh release create "vM.m.p"
|
||||
git fetch --tags origin master
|
||||
```
|
||||
-681
@@ -1,681 +0,0 @@
|
||||
/*
|
||||
Ginkgo is a BDD-style testing framework for Golang
|
||||
|
||||
The godoc documentation describes Ginkgo's API. More comprehensive documentation (with examples!) is available at http://onsi.github.io/ginkgo/
|
||||
|
||||
Ginkgo's preferred matcher library is [Gomega](http://github.com/onsi/gomega)
|
||||
|
||||
Ginkgo on Github: http://github.com/onsi/ginkgo
|
||||
|
||||
Ginkgo is MIT-Licensed
|
||||
*/
|
||||
package ginkgo
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/onsi/ginkgo/config"
|
||||
"github.com/onsi/ginkgo/internal/codelocation"
|
||||
"github.com/onsi/ginkgo/internal/global"
|
||||
"github.com/onsi/ginkgo/internal/remote"
|
||||
"github.com/onsi/ginkgo/internal/testingtproxy"
|
||||
"github.com/onsi/ginkgo/internal/writer"
|
||||
"github.com/onsi/ginkgo/reporters"
|
||||
"github.com/onsi/ginkgo/reporters/stenographer"
|
||||
colorable "github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable"
|
||||
"github.com/onsi/ginkgo/types"
|
||||
)
|
||||
|
||||
var deprecationTracker = types.NewDeprecationTracker()
|
||||
|
||||
const GINKGO_VERSION = config.VERSION
|
||||
const GINKGO_PANIC = `
|
||||
Your test failed.
|
||||
Ginkgo panics to prevent subsequent assertions from running.
|
||||
Normally Ginkgo rescues this panic so you shouldn't see it.
|
||||
|
||||
But, if you make an assertion in a goroutine, Ginkgo can't capture the panic.
|
||||
To circumvent this, you should call
|
||||
|
||||
defer GinkgoRecover()
|
||||
|
||||
at the top of the goroutine that caused this panic.
|
||||
`
|
||||
|
||||
func init() {
|
||||
config.Flags(flag.CommandLine, "ginkgo", true)
|
||||
GinkgoWriter = writer.New(os.Stdout)
|
||||
}
|
||||
|
||||
//GinkgoWriter implements an io.Writer
|
||||
//When running in verbose mode any writes to GinkgoWriter will be immediately printed
|
||||
//to stdout. Otherwise, GinkgoWriter will buffer any writes produced during the current test and flush them to screen
|
||||
//only if the current test fails.
|
||||
var GinkgoWriter io.Writer
|
||||
|
||||
//The interface by which Ginkgo receives *testing.T
|
||||
type GinkgoTestingT interface {
|
||||
Fail()
|
||||
}
|
||||
|
||||
//GinkgoRandomSeed returns the seed used to randomize spec execution order. It is
|
||||
//useful for seeding your own pseudorandom number generators (PRNGs) to ensure
|
||||
//consistent executions from run to run, where your tests contain variability (for
|
||||
//example, when selecting random test data).
|
||||
func GinkgoRandomSeed() int64 {
|
||||
return config.GinkgoConfig.RandomSeed
|
||||
}
|
||||
|
||||
//GinkgoParallelNode is deprecated, use GinkgoParallelProcess instead
|
||||
func GinkgoParallelNode() int {
|
||||
deprecationTracker.TrackDeprecation(types.Deprecations.ParallelNode(), codelocation.New(1))
|
||||
return GinkgoParallelProcess()
|
||||
}
|
||||
|
||||
//GinkgoParallelProcess returns the parallel process number for the current ginkgo process
|
||||
//The process number is 1-indexed
|
||||
func GinkgoParallelProcess() int {
|
||||
return config.GinkgoConfig.ParallelNode
|
||||
}
|
||||
|
||||
//Some matcher libraries or legacy codebases require a *testing.T
|
||||
//GinkgoT implements an interface analogous to *testing.T and can be used if
|
||||
//the library in question accepts *testing.T through an interface
|
||||
//
|
||||
// For example, with testify:
|
||||
// assert.Equal(GinkgoT(), 123, 123, "they should be equal")
|
||||
//
|
||||
// Or with gomock:
|
||||
// gomock.NewController(GinkgoT())
|
||||
//
|
||||
// GinkgoT() takes an optional offset argument that can be used to get the
|
||||
// correct line number associated with the failure.
|
||||
func GinkgoT(optionalOffset ...int) GinkgoTInterface {
|
||||
offset := 3
|
||||
if len(optionalOffset) > 0 {
|
||||
offset = optionalOffset[0]
|
||||
}
|
||||
failedFunc := func() bool {
|
||||
return CurrentGinkgoTestDescription().Failed
|
||||
}
|
||||
nameFunc := func() string {
|
||||
return CurrentGinkgoTestDescription().FullTestText
|
||||
}
|
||||
return testingtproxy.New(GinkgoWriter, Fail, Skip, failedFunc, nameFunc, offset)
|
||||
}
|
||||
|
||||
//The interface returned by GinkgoT(). This covers most of the methods
|
||||
//in the testing package's T.
|
||||
type GinkgoTInterface interface {
|
||||
Cleanup(func())
|
||||
Setenv(key, value string)
|
||||
Error(args ...interface{})
|
||||
Errorf(format string, args ...interface{})
|
||||
Fail()
|
||||
FailNow()
|
||||
Failed() bool
|
||||
Fatal(args ...interface{})
|
||||
Fatalf(format string, args ...interface{})
|
||||
Helper()
|
||||
Log(args ...interface{})
|
||||
Logf(format string, args ...interface{})
|
||||
Name() string
|
||||
Parallel()
|
||||
Skip(args ...interface{})
|
||||
SkipNow()
|
||||
Skipf(format string, args ...interface{})
|
||||
Skipped() bool
|
||||
TempDir() string
|
||||
}
|
||||
|
||||
//Custom Ginkgo test reporters must implement the Reporter interface.
|
||||
//
|
||||
//The custom reporter is passed in a SuiteSummary when the suite begins and ends,
|
||||
//and a SpecSummary just before a spec begins and just after a spec ends
|
||||
type Reporter reporters.Reporter
|
||||
|
||||
//Asynchronous specs are given a channel of the Done type. You must close or write to the channel
|
||||
//to tell Ginkgo that your async test is done.
|
||||
type Done chan<- interface{}
|
||||
|
||||
//GinkgoTestDescription represents the information about the current running test returned by CurrentGinkgoTestDescription
|
||||
// FullTestText: a concatenation of ComponentTexts and the TestText
|
||||
// ComponentTexts: a list of all texts for the Describes & Contexts leading up to the current test
|
||||
// TestText: the text in the actual It or Measure node
|
||||
// IsMeasurement: true if the current test is a measurement
|
||||
// FileName: the name of the file containing the current test
|
||||
// LineNumber: the line number for the current test
|
||||
// Failed: if the current test has failed, this will be true (useful in an AfterEach)
|
||||
type GinkgoTestDescription struct {
|
||||
FullTestText string
|
||||
ComponentTexts []string
|
||||
TestText string
|
||||
|
||||
IsMeasurement bool
|
||||
|
||||
FileName string
|
||||
LineNumber int
|
||||
|
||||
Failed bool
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
//CurrentGinkgoTestDescripton returns information about the current running test.
|
||||
func CurrentGinkgoTestDescription() GinkgoTestDescription {
|
||||
summary, ok := global.Suite.CurrentRunningSpecSummary()
|
||||
if !ok {
|
||||
return GinkgoTestDescription{}
|
||||
}
|
||||
|
||||
subjectCodeLocation := summary.ComponentCodeLocations[len(summary.ComponentCodeLocations)-1]
|
||||
|
||||
return GinkgoTestDescription{
|
||||
ComponentTexts: summary.ComponentTexts[1:],
|
||||
FullTestText: strings.Join(summary.ComponentTexts[1:], " "),
|
||||
TestText: summary.ComponentTexts[len(summary.ComponentTexts)-1],
|
||||
IsMeasurement: summary.IsMeasurement,
|
||||
FileName: subjectCodeLocation.FileName,
|
||||
LineNumber: subjectCodeLocation.LineNumber,
|
||||
Failed: summary.HasFailureState(),
|
||||
Duration: summary.RunTime,
|
||||
}
|
||||
}
|
||||
|
||||
//Measurement tests receive a Benchmarker.
|
||||
//
|
||||
//You use the Time() function to time how long the passed in body function takes to run
|
||||
//You use the RecordValue() function to track arbitrary numerical measurements.
|
||||
//The RecordValueWithPrecision() function can be used alternatively to provide the unit
|
||||
//and resolution of the numeric measurement.
|
||||
//The optional info argument is passed to the test reporter and can be used to
|
||||
// provide the measurement data to a custom reporter with context.
|
||||
//
|
||||
//See http://onsi.github.io/ginkgo/#benchmark_tests for more details
|
||||
type Benchmarker interface {
|
||||
Time(name string, body func(), info ...interface{}) (elapsedTime time.Duration)
|
||||
RecordValue(name string, value float64, info ...interface{})
|
||||
RecordValueWithPrecision(name string, value float64, units string, precision int, info ...interface{})
|
||||
}
|
||||
|
||||
//RunSpecs is the entry point for the Ginkgo test runner.
|
||||
//You must call this within a Golang testing TestX(t *testing.T) function.
|
||||
//
|
||||
//To bootstrap a test suite you can use the Ginkgo CLI:
|
||||
//
|
||||
// ginkgo bootstrap
|
||||
func RunSpecs(t GinkgoTestingT, description string) bool {
|
||||
specReporters := []Reporter{buildDefaultReporter()}
|
||||
if config.DefaultReporterConfig.ReportFile != "" {
|
||||
reportFile := config.DefaultReporterConfig.ReportFile
|
||||
specReporters[0] = reporters.NewJUnitReporter(reportFile)
|
||||
specReporters = append(specReporters, buildDefaultReporter())
|
||||
}
|
||||
return runSpecsWithCustomReporters(t, description, specReporters)
|
||||
}
|
||||
|
||||
//To run your tests with Ginkgo's default reporter and your custom reporter(s), replace
|
||||
//RunSpecs() with this method.
|
||||
func RunSpecsWithDefaultAndCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool {
|
||||
deprecationTracker.TrackDeprecation(types.Deprecations.CustomReporter())
|
||||
specReporters = append(specReporters, buildDefaultReporter())
|
||||
return runSpecsWithCustomReporters(t, description, specReporters)
|
||||
}
|
||||
|
||||
//To run your tests with your custom reporter(s) (and *not* Ginkgo's default reporter), replace
|
||||
//RunSpecs() with this method. Note that parallel tests will not work correctly without the default reporter
|
||||
func RunSpecsWithCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool {
|
||||
deprecationTracker.TrackDeprecation(types.Deprecations.CustomReporter())
|
||||
return runSpecsWithCustomReporters(t, description, specReporters)
|
||||
}
|
||||
|
||||
func runSpecsWithCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool {
|
||||
writer := GinkgoWriter.(*writer.Writer)
|
||||
writer.SetStream(config.DefaultReporterConfig.Verbose)
|
||||
reporters := make([]reporters.Reporter, len(specReporters))
|
||||
for i, reporter := range specReporters {
|
||||
reporters[i] = reporter
|
||||
}
|
||||
passed, hasFocusedTests := global.Suite.Run(t, description, reporters, writer, config.GinkgoConfig)
|
||||
|
||||
if deprecationTracker.DidTrackDeprecations() {
|
||||
fmt.Fprintln(colorable.NewColorableStderr(), deprecationTracker.DeprecationsReport())
|
||||
}
|
||||
|
||||
if passed && hasFocusedTests && strings.TrimSpace(os.Getenv("GINKGO_EDITOR_INTEGRATION")) == "" {
|
||||
fmt.Println("PASS | FOCUSED")
|
||||
os.Exit(types.GINKGO_FOCUS_EXIT_CODE)
|
||||
}
|
||||
return passed
|
||||
}
|
||||
|
||||
func buildDefaultReporter() Reporter {
|
||||
remoteReportingServer := config.GinkgoConfig.StreamHost
|
||||
if remoteReportingServer == "" {
|
||||
stenographer := stenographer.New(!config.DefaultReporterConfig.NoColor, config.GinkgoConfig.FlakeAttempts > 1, colorable.NewColorableStdout())
|
||||
return reporters.NewDefaultReporter(config.DefaultReporterConfig, stenographer)
|
||||
} else {
|
||||
debugFile := ""
|
||||
if config.GinkgoConfig.DebugParallel {
|
||||
debugFile = fmt.Sprintf("ginkgo-node-%d.log", config.GinkgoConfig.ParallelNode)
|
||||
}
|
||||
return remote.NewForwardingReporter(config.DefaultReporterConfig, remoteReportingServer, &http.Client{}, remote.NewOutputInterceptor(), GinkgoWriter.(*writer.Writer), debugFile)
|
||||
}
|
||||
}
|
||||
|
||||
//Skip notifies Ginkgo that the current spec was skipped.
|
||||
func Skip(message string, callerSkip ...int) {
|
||||
skip := 0
|
||||
if len(callerSkip) > 0 {
|
||||
skip = callerSkip[0]
|
||||
}
|
||||
|
||||
global.Failer.Skip(message, codelocation.New(skip+1))
|
||||
panic(GINKGO_PANIC)
|
||||
}
|
||||
|
||||
//Fail notifies Ginkgo that the current spec has failed. (Gomega will call Fail for you automatically when an assertion fails.)
|
||||
func Fail(message string, callerSkip ...int) {
|
||||
skip := 0
|
||||
if len(callerSkip) > 0 {
|
||||
skip = callerSkip[0]
|
||||
}
|
||||
|
||||
global.Failer.Fail(message, codelocation.New(skip+1))
|
||||
panic(GINKGO_PANIC)
|
||||
}
|
||||
|
||||
//GinkgoRecover should be deferred at the top of any spawned goroutine that (may) call `Fail`
|
||||
//Since Gomega assertions call fail, you should throw a `defer GinkgoRecover()` at the top of any goroutine that
|
||||
//calls out to Gomega
|
||||
//
|
||||
//Here's why: Ginkgo's `Fail` method records the failure and then panics to prevent
|
||||
//further assertions from running. This panic must be recovered. Ginkgo does this for you
|
||||
//if the panic originates in a Ginkgo node (an It, BeforeEach, etc...)
|
||||
//
|
||||
//Unfortunately, if a panic originates on a goroutine *launched* from one of these nodes there's no
|
||||
//way for Ginkgo to rescue the panic. To do this, you must remember to `defer GinkgoRecover()` at the top of such a goroutine.
|
||||
func GinkgoRecover() {
|
||||
e := recover()
|
||||
if e != nil {
|
||||
global.Failer.Panic(codelocation.New(1), e)
|
||||
}
|
||||
}
|
||||
|
||||
//Describe blocks allow you to organize your specs. A Describe block can contain any number of
|
||||
//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks.
|
||||
//
|
||||
//In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally
|
||||
//equivalent. The difference is purely semantic -- you typically Describe the behavior of an object
|
||||
//or method and, within that Describe, outline a number of Contexts and Whens.
|
||||
func Describe(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can focus the tests within a describe block using FDescribe
|
||||
func FDescribe(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark the tests within a describe block as pending using PDescribe
|
||||
func PDescribe(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark the tests within a describe block as pending using XDescribe
|
||||
func XDescribe(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//Context blocks allow you to organize your specs. A Context block can contain any number of
|
||||
//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks.
|
||||
//
|
||||
//In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally
|
||||
//equivalent. The difference is purely semantic -- you typical Describe the behavior of an object
|
||||
//or method and, within that Describe, outline a number of Contexts and Whens.
|
||||
func Context(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can focus the tests within a describe block using FContext
|
||||
func FContext(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark the tests within a describe block as pending using PContext
|
||||
func PContext(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark the tests within a describe block as pending using XContext
|
||||
func XContext(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//When blocks allow you to organize your specs. A When block can contain any number of
|
||||
//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks.
|
||||
//
|
||||
//In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally
|
||||
//equivalent. The difference is purely semantic -- you typical Describe the behavior of an object
|
||||
//or method and, within that Describe, outline a number of Contexts and Whens.
|
||||
func When(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode("when "+text, body, types.FlagTypeNone, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can focus the tests within a describe block using FWhen
|
||||
func FWhen(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode("when "+text, body, types.FlagTypeFocused, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark the tests within a describe block as pending using PWhen
|
||||
func PWhen(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark the tests within a describe block as pending using XWhen
|
||||
func XWhen(text string, body func()) bool {
|
||||
global.Suite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1))
|
||||
return true
|
||||
}
|
||||
|
||||
//It blocks contain your test code and assertions. You cannot nest any other Ginkgo blocks
|
||||
//within an It block.
|
||||
//
|
||||
//Ginkgo will normally run It blocks synchronously. To perform asynchronous tests, pass a
|
||||
//function that accepts a Done channel. When you do this, you can also provide an optional timeout.
|
||||
func It(text string, body interface{}, timeout ...float64) bool {
|
||||
validateBodyFunc(body, codelocation.New(1))
|
||||
global.Suite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can focus individual Its using FIt
|
||||
func FIt(text string, body interface{}, timeout ...float64) bool {
|
||||
validateBodyFunc(body, codelocation.New(1))
|
||||
global.Suite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark Its as pending using PIt
|
||||
func PIt(text string, _ ...interface{}) bool {
|
||||
global.Suite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark Its as pending using XIt
|
||||
func XIt(text string, _ ...interface{}) bool {
|
||||
global.Suite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
|
||||
return true
|
||||
}
|
||||
|
||||
//Specify blocks are aliases for It blocks and allow for more natural wording in situations
|
||||
//which "It" does not fit into a natural sentence flow. All the same protocols apply for Specify blocks
|
||||
//which apply to It blocks.
|
||||
func Specify(text string, body interface{}, timeout ...float64) bool {
|
||||
validateBodyFunc(body, codelocation.New(1))
|
||||
global.Suite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can focus individual Specifys using FSpecify
|
||||
func FSpecify(text string, body interface{}, timeout ...float64) bool {
|
||||
validateBodyFunc(body, codelocation.New(1))
|
||||
global.Suite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...))
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark Specifys as pending using PSpecify
|
||||
func PSpecify(text string, is ...interface{}) bool {
|
||||
global.Suite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark Specifys as pending using XSpecify
|
||||
func XSpecify(text string, is ...interface{}) bool {
|
||||
global.Suite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
|
||||
return true
|
||||
}
|
||||
|
||||
//By allows you to better document large Its.
|
||||
//
|
||||
//Generally you should try to keep your Its short and to the point. This is not always possible, however,
|
||||
//especially in the context of integration tests that capture a particular workflow.
|
||||
//
|
||||
//By allows you to document such flows. By must be called within a runnable node (It, BeforeEach, Measure, etc...)
|
||||
//By will simply log the passed in text to the GinkgoWriter. If By is handed a function it will immediately run the function.
|
||||
func By(text string, callbacks ...func()) {
|
||||
preamble := "\x1b[1mSTEP\x1b[0m"
|
||||
if config.DefaultReporterConfig.NoColor {
|
||||
preamble = "STEP"
|
||||
}
|
||||
fmt.Fprintln(GinkgoWriter, preamble+": "+text)
|
||||
if len(callbacks) == 1 {
|
||||
callbacks[0]()
|
||||
}
|
||||
if len(callbacks) > 1 {
|
||||
panic("just one callback per By, please")
|
||||
}
|
||||
}
|
||||
|
||||
//Measure blocks run the passed in body function repeatedly (determined by the samples argument)
|
||||
//and accumulate metrics provided to the Benchmarker by the body function.
|
||||
//
|
||||
//The body function must have the signature:
|
||||
// func(b Benchmarker)
|
||||
func Measure(text string, body interface{}, samples int) bool {
|
||||
deprecationTracker.TrackDeprecation(types.Deprecations.Measure(), codelocation.New(1))
|
||||
global.Suite.PushMeasureNode(text, body, types.FlagTypeNone, codelocation.New(1), samples)
|
||||
return true
|
||||
}
|
||||
|
||||
//You can focus individual Measures using FMeasure
|
||||
func FMeasure(text string, body interface{}, samples int) bool {
|
||||
deprecationTracker.TrackDeprecation(types.Deprecations.Measure(), codelocation.New(1))
|
||||
global.Suite.PushMeasureNode(text, body, types.FlagTypeFocused, codelocation.New(1), samples)
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark Measurements as pending using PMeasure
|
||||
func PMeasure(text string, _ ...interface{}) bool {
|
||||
deprecationTracker.TrackDeprecation(types.Deprecations.Measure(), codelocation.New(1))
|
||||
global.Suite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0)
|
||||
return true
|
||||
}
|
||||
|
||||
//You can mark Measurements as pending using XMeasure
|
||||
func XMeasure(text string, _ ...interface{}) bool {
|
||||
deprecationTracker.TrackDeprecation(types.Deprecations.Measure(), codelocation.New(1))
|
||||
global.Suite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0)
|
||||
return true
|
||||
}
|
||||
|
||||
//BeforeSuite blocks are run just once before any specs are run. When running in parallel, each
|
||||
//parallel node process will call BeforeSuite.
|
||||
//
|
||||
//BeforeSuite blocks can be made asynchronous by providing a body function that accepts a Done channel
|
||||
//
|
||||
//You may only register *one* BeforeSuite handler per test suite. You typically do so in your bootstrap file at the top level.
|
||||
func BeforeSuite(body interface{}, timeout ...float64) bool {
|
||||
validateBodyFunc(body, codelocation.New(1))
|
||||
global.Suite.SetBeforeSuiteNode(body, codelocation.New(1), parseTimeout(timeout...))
|
||||
return true
|
||||
}
|
||||
|
||||
//AfterSuite blocks are *always* run after all the specs regardless of whether specs have passed or failed.
|
||||
//Moreover, if Ginkgo receives an interrupt signal (^C) it will attempt to run the AfterSuite before exiting.
|
||||
//
|
||||
//When running in parallel, each parallel node process will call AfterSuite.
|
||||
//
|
||||
//AfterSuite blocks can be made asynchronous by providing a body function that accepts a Done channel
|
||||
//
|
||||
//You may only register *one* AfterSuite handler per test suite. You typically do so in your bootstrap file at the top level.
|
||||
func AfterSuite(body interface{}, timeout ...float64) bool {
|
||||
validateBodyFunc(body, codelocation.New(1))
|
||||
global.Suite.SetAfterSuiteNode(body, codelocation.New(1), parseTimeout(timeout...))
|
||||
return true
|
||||
}
|
||||
|
||||
//SynchronizedBeforeSuite blocks are primarily meant to solve the problem of setting up singleton external resources shared across
|
||||
//nodes when running tests in parallel. For example, say you have a shared database that you can only start one instance of that
|
||||
//must be used in your tests. When running in parallel, only one node should set up the database and all other nodes should wait
|
||||
//until that node is done before running.
|
||||
//
|
||||
//SynchronizedBeforeSuite accomplishes this by taking *two* function arguments. The first is only run on parallel node #1. The second is
|
||||
//run on all nodes, but *only* after the first function completes successfully. Ginkgo also makes it possible to send data from the first function (on Node 1)
|
||||
//to the second function (on all the other nodes).
|
||||
//
|
||||
//The functions have the following signatures. The first function (which only runs on node 1) has the signature:
|
||||
//
|
||||
// func() []byte
|
||||
//
|
||||
//or, to run asynchronously:
|
||||
//
|
||||
// func(done Done) []byte
|
||||
//
|
||||
//The byte array returned by the first function is then passed to the second function, which has the signature:
|
||||
//
|
||||
// func(data []byte)
|
||||
//
|
||||
//or, to run asynchronously:
|
||||
//
|
||||
// func(data []byte, done Done)
|
||||
//
|
||||
//Here's a simple pseudo-code example that starts a shared database on Node 1 and shares the database's address with the other nodes:
|
||||
//
|
||||
// var dbClient db.Client
|
||||
// var dbRunner db.Runner
|
||||
//
|
||||
// var _ = SynchronizedBeforeSuite(func() []byte {
|
||||
// dbRunner = db.NewRunner()
|
||||
// err := dbRunner.Start()
|
||||
// Ω(err).ShouldNot(HaveOccurred())
|
||||
// return []byte(dbRunner.URL)
|
||||
// }, func(data []byte) {
|
||||
// dbClient = db.NewClient()
|
||||
// err := dbClient.Connect(string(data))
|
||||
// Ω(err).ShouldNot(HaveOccurred())
|
||||
// })
|
||||
func SynchronizedBeforeSuite(node1Body interface{}, allNodesBody interface{}, timeout ...float64) bool {
|
||||
global.Suite.SetSynchronizedBeforeSuiteNode(
|
||||
node1Body,
|
||||
allNodesBody,
|
||||
codelocation.New(1),
|
||||
parseTimeout(timeout...),
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
//SynchronizedAfterSuite blocks complement the SynchronizedBeforeSuite blocks in solving the problem of setting up
|
||||
//external singleton resources shared across nodes when running tests in parallel.
|
||||
//
|
||||
//SynchronizedAfterSuite accomplishes this by taking *two* function arguments. The first runs on all nodes. The second runs only on parallel node #1
|
||||
//and *only* after all other nodes have finished and exited. This ensures that node 1, and any resources it is running, remain alive until
|
||||
//all other nodes are finished.
|
||||
//
|
||||
//Both functions have the same signature: either func() or func(done Done) to run asynchronously.
|
||||
//
|
||||
//Here's a pseudo-code example that complements that given in SynchronizedBeforeSuite. Here, SynchronizedAfterSuite is used to tear down the shared database
|
||||
//only after all nodes have finished:
|
||||
//
|
||||
// var _ = SynchronizedAfterSuite(func() {
|
||||
// dbClient.Cleanup()
|
||||
// }, func() {
|
||||
// dbRunner.Stop()
|
||||
// })
|
||||
func SynchronizedAfterSuite(allNodesBody interface{}, node1Body interface{}, timeout ...float64) bool {
|
||||
global.Suite.SetSynchronizedAfterSuiteNode(
|
||||
allNodesBody,
|
||||
node1Body,
|
||||
codelocation.New(1),
|
||||
parseTimeout(timeout...),
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
//BeforeEach blocks are run before It blocks. When multiple BeforeEach blocks are defined in nested
|
||||
//Describe and Context blocks the outermost BeforeEach blocks are run first.
|
||||
//
|
||||
//Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts
|
||||
//a Done channel
|
||||
func BeforeEach(body interface{}, timeout ...float64) bool {
|
||||
validateBodyFunc(body, codelocation.New(1))
|
||||
global.Suite.PushBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...))
|
||||
return true
|
||||
}
|
||||
|
||||
//JustBeforeEach blocks are run before It blocks but *after* all BeforeEach blocks. For more details,
|
||||
//read the [documentation](http://onsi.github.io/ginkgo/#separating_creation_and_configuration_)
|
||||
//
|
||||
//Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts
|
||||
//a Done channel
|
||||
func JustBeforeEach(body interface{}, timeout ...float64) bool {
|
||||
validateBodyFunc(body, codelocation.New(1))
|
||||
global.Suite.PushJustBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...))
|
||||
return true
|
||||
}
|
||||
|
||||
//JustAfterEach blocks are run after It blocks but *before* all AfterEach blocks. For more details,
|
||||
//read the [documentation](http://onsi.github.io/ginkgo/#separating_creation_and_configuration_)
|
||||
//
|
||||
//Like It blocks, JustAfterEach blocks can be made asynchronous by providing a body function that accepts
|
||||
//a Done channel
|
||||
func JustAfterEach(body interface{}, timeout ...float64) bool {
|
||||
validateBodyFunc(body, codelocation.New(1))
|
||||
global.Suite.PushJustAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...))
|
||||
return true
|
||||
}
|
||||
|
||||
//AfterEach blocks are run after It blocks. When multiple AfterEach blocks are defined in nested
|
||||
//Describe and Context blocks the innermost AfterEach blocks are run first.
|
||||
//
|
||||
//Like It blocks, AfterEach blocks can be made asynchronous by providing a body function that accepts
|
||||
//a Done channel
|
||||
func AfterEach(body interface{}, timeout ...float64) bool {
|
||||
validateBodyFunc(body, codelocation.New(1))
|
||||
global.Suite.PushAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...))
|
||||
return true
|
||||
}
|
||||
|
||||
func validateBodyFunc(body interface{}, cl types.CodeLocation) {
|
||||
t := reflect.TypeOf(body)
|
||||
if t.Kind() != reflect.Func {
|
||||
return
|
||||
}
|
||||
|
||||
if t.NumOut() > 0 {
|
||||
return
|
||||
}
|
||||
|
||||
if t.NumIn() == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
if t.In(0) == reflect.TypeOf(make(Done)) {
|
||||
deprecationTracker.TrackDeprecation(types.Deprecations.Async(), cl)
|
||||
}
|
||||
}
|
||||
|
||||
func parseTimeout(timeout ...float64) time.Duration {
|
||||
if len(timeout) == 0 {
|
||||
return global.DefaultTimeout
|
||||
} else {
|
||||
return time.Duration(timeout[0] * float64(time.Second))
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package global
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/onsi/ginkgo/internal/failer"
|
||||
"github.com/onsi/ginkgo/internal/suite"
|
||||
)
|
||||
|
||||
const DefaultTimeout = time.Duration(1 * time.Second)
|
||||
|
||||
var Suite *suite.Suite
|
||||
var Failer *failer.Failer
|
||||
|
||||
func init() {
|
||||
InitializeGlobals()
|
||||
}
|
||||
|
||||
func InitializeGlobals() {
|
||||
Failer = failer.New()
|
||||
Suite = suite.New(Failer)
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package specrunner
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func randomID() string {
|
||||
b := make([]byte, 8)
|
||||
_, err := rand.Read(b)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%x-%x-%x-%x", b[0:2], b[2:4], b[4:6], b[6:8])
|
||||
}
|
||||
-411
@@ -1,411 +0,0 @@
|
||||
package specrunner
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/onsi/ginkgo/internal/spec_iterator"
|
||||
|
||||
"github.com/onsi/ginkgo/config"
|
||||
"github.com/onsi/ginkgo/internal/leafnodes"
|
||||
"github.com/onsi/ginkgo/internal/spec"
|
||||
Writer "github.com/onsi/ginkgo/internal/writer"
|
||||
"github.com/onsi/ginkgo/reporters"
|
||||
"github.com/onsi/ginkgo/types"
|
||||
|
||||
"time"
|
||||
)
|
||||
|
||||
type SpecRunner struct {
|
||||
description string
|
||||
beforeSuiteNode leafnodes.SuiteNode
|
||||
iterator spec_iterator.SpecIterator
|
||||
afterSuiteNode leafnodes.SuiteNode
|
||||
reporters []reporters.Reporter
|
||||
startTime time.Time
|
||||
suiteID string
|
||||
runningSpec *spec.Spec
|
||||
writer Writer.WriterInterface
|
||||
config config.GinkgoConfigType
|
||||
interrupted bool
|
||||
processedSpecs []*spec.Spec
|
||||
lock *sync.Mutex
|
||||
}
|
||||
|
||||
func New(description string, beforeSuiteNode leafnodes.SuiteNode, iterator spec_iterator.SpecIterator, afterSuiteNode leafnodes.SuiteNode, reporters []reporters.Reporter, writer Writer.WriterInterface, config config.GinkgoConfigType) *SpecRunner {
|
||||
return &SpecRunner{
|
||||
description: description,
|
||||
beforeSuiteNode: beforeSuiteNode,
|
||||
iterator: iterator,
|
||||
afterSuiteNode: afterSuiteNode,
|
||||
reporters: reporters,
|
||||
writer: writer,
|
||||
config: config,
|
||||
suiteID: randomID(),
|
||||
lock: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) Run() bool {
|
||||
if runner.config.DryRun {
|
||||
runner.performDryRun()
|
||||
return true
|
||||
}
|
||||
|
||||
runner.reportSuiteWillBegin()
|
||||
signalRegistered := make(chan struct{})
|
||||
go runner.registerForInterrupts(signalRegistered)
|
||||
<-signalRegistered
|
||||
|
||||
suitePassed := runner.runBeforeSuite()
|
||||
|
||||
if suitePassed {
|
||||
suitePassed = runner.runSpecs()
|
||||
}
|
||||
|
||||
runner.blockForeverIfInterrupted()
|
||||
|
||||
suitePassed = runner.runAfterSuite() && suitePassed
|
||||
|
||||
runner.reportSuiteDidEnd(suitePassed)
|
||||
|
||||
return suitePassed
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) performDryRun() {
|
||||
runner.reportSuiteWillBegin()
|
||||
|
||||
if runner.beforeSuiteNode != nil {
|
||||
summary := runner.beforeSuiteNode.Summary()
|
||||
summary.State = types.SpecStatePassed
|
||||
runner.reportBeforeSuite(summary)
|
||||
}
|
||||
|
||||
for {
|
||||
spec, err := runner.iterator.Next()
|
||||
if err == spec_iterator.ErrClosed {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Println("failed to iterate over tests:\n" + err.Error())
|
||||
break
|
||||
}
|
||||
|
||||
runner.processedSpecs = append(runner.processedSpecs, spec)
|
||||
|
||||
summary := spec.Summary(runner.suiteID)
|
||||
runner.reportSpecWillRun(summary)
|
||||
if summary.State == types.SpecStateInvalid {
|
||||
summary.State = types.SpecStatePassed
|
||||
}
|
||||
runner.reportSpecDidComplete(summary, false)
|
||||
}
|
||||
|
||||
if runner.afterSuiteNode != nil {
|
||||
summary := runner.afterSuiteNode.Summary()
|
||||
summary.State = types.SpecStatePassed
|
||||
runner.reportAfterSuite(summary)
|
||||
}
|
||||
|
||||
runner.reportSuiteDidEnd(true)
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) runBeforeSuite() bool {
|
||||
if runner.beforeSuiteNode == nil || runner.wasInterrupted() {
|
||||
return true
|
||||
}
|
||||
|
||||
runner.writer.Truncate()
|
||||
conf := runner.config
|
||||
passed := runner.beforeSuiteNode.Run(conf.ParallelNode, conf.ParallelTotal, conf.SyncHost)
|
||||
if !passed {
|
||||
runner.writer.DumpOut()
|
||||
}
|
||||
runner.reportBeforeSuite(runner.beforeSuiteNode.Summary())
|
||||
return passed
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) runAfterSuite() bool {
|
||||
if runner.afterSuiteNode == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
runner.writer.Truncate()
|
||||
conf := runner.config
|
||||
passed := runner.afterSuiteNode.Run(conf.ParallelNode, conf.ParallelTotal, conf.SyncHost)
|
||||
if !passed {
|
||||
runner.writer.DumpOut()
|
||||
}
|
||||
runner.reportAfterSuite(runner.afterSuiteNode.Summary())
|
||||
return passed
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) runSpecs() bool {
|
||||
suiteFailed := false
|
||||
skipRemainingSpecs := false
|
||||
for {
|
||||
spec, err := runner.iterator.Next()
|
||||
if err == spec_iterator.ErrClosed {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Println("failed to iterate over tests:\n" + err.Error())
|
||||
suiteFailed = true
|
||||
break
|
||||
}
|
||||
|
||||
runner.processedSpecs = append(runner.processedSpecs, spec)
|
||||
|
||||
if runner.wasInterrupted() {
|
||||
break
|
||||
}
|
||||
if skipRemainingSpecs {
|
||||
spec.Skip()
|
||||
}
|
||||
|
||||
if !spec.Skipped() && !spec.Pending() {
|
||||
if passed := runner.runSpec(spec); !passed {
|
||||
suiteFailed = true
|
||||
}
|
||||
} else if spec.Pending() && runner.config.FailOnPending {
|
||||
runner.reportSpecWillRun(spec.Summary(runner.suiteID))
|
||||
suiteFailed = true
|
||||
runner.reportSpecDidComplete(spec.Summary(runner.suiteID), spec.Failed())
|
||||
} else {
|
||||
runner.reportSpecWillRun(spec.Summary(runner.suiteID))
|
||||
runner.reportSpecDidComplete(spec.Summary(runner.suiteID), spec.Failed())
|
||||
}
|
||||
|
||||
if spec.Failed() && runner.config.FailFast {
|
||||
skipRemainingSpecs = true
|
||||
}
|
||||
}
|
||||
|
||||
return !suiteFailed
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) runSpec(spec *spec.Spec) (passed bool) {
|
||||
maxAttempts := 1
|
||||
if runner.config.FlakeAttempts > 0 {
|
||||
// uninitialized configs count as 1
|
||||
maxAttempts = runner.config.FlakeAttempts
|
||||
}
|
||||
|
||||
for i := 0; i < maxAttempts; i++ {
|
||||
runner.reportSpecWillRun(spec.Summary(runner.suiteID))
|
||||
runner.runningSpec = spec
|
||||
spec.Run(runner.writer)
|
||||
runner.runningSpec = nil
|
||||
runner.reportSpecDidComplete(spec.Summary(runner.suiteID), spec.Failed())
|
||||
if !spec.Failed() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) CurrentSpecSummary() (*types.SpecSummary, bool) {
|
||||
if runner.runningSpec == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return runner.runningSpec.Summary(runner.suiteID), true
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) registerForInterrupts(signalRegistered chan struct{}) {
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
|
||||
close(signalRegistered)
|
||||
|
||||
<-c
|
||||
signal.Stop(c)
|
||||
runner.markInterrupted()
|
||||
go runner.registerForHardInterrupts()
|
||||
runner.writer.DumpOutWithHeader(`
|
||||
Received interrupt. Emitting contents of GinkgoWriter...
|
||||
---------------------------------------------------------
|
||||
`)
|
||||
if runner.afterSuiteNode != nil {
|
||||
fmt.Fprint(os.Stderr, `
|
||||
---------------------------------------------------------
|
||||
Received interrupt. Running AfterSuite...
|
||||
^C again to terminate immediately
|
||||
`)
|
||||
runner.runAfterSuite()
|
||||
}
|
||||
runner.reportSuiteDidEnd(false)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) registerForHardInterrupts() {
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
<-c
|
||||
fmt.Fprintln(os.Stderr, "\nReceived second interrupt. Shutting down.")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) blockForeverIfInterrupted() {
|
||||
runner.lock.Lock()
|
||||
interrupted := runner.interrupted
|
||||
runner.lock.Unlock()
|
||||
|
||||
if interrupted {
|
||||
select {}
|
||||
}
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) markInterrupted() {
|
||||
runner.lock.Lock()
|
||||
defer runner.lock.Unlock()
|
||||
runner.interrupted = true
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) wasInterrupted() bool {
|
||||
runner.lock.Lock()
|
||||
defer runner.lock.Unlock()
|
||||
return runner.interrupted
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) reportSuiteWillBegin() {
|
||||
runner.startTime = time.Now()
|
||||
summary := runner.suiteWillBeginSummary()
|
||||
for _, reporter := range runner.reporters {
|
||||
reporter.SpecSuiteWillBegin(runner.config, summary)
|
||||
}
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) reportBeforeSuite(summary *types.SetupSummary) {
|
||||
for _, reporter := range runner.reporters {
|
||||
reporter.BeforeSuiteDidRun(summary)
|
||||
}
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) reportAfterSuite(summary *types.SetupSummary) {
|
||||
for _, reporter := range runner.reporters {
|
||||
reporter.AfterSuiteDidRun(summary)
|
||||
}
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) reportSpecWillRun(summary *types.SpecSummary) {
|
||||
runner.writer.Truncate()
|
||||
|
||||
for _, reporter := range runner.reporters {
|
||||
reporter.SpecWillRun(summary)
|
||||
}
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) reportSpecDidComplete(summary *types.SpecSummary, failed bool) {
|
||||
if len(summary.CapturedOutput) == 0 {
|
||||
summary.CapturedOutput = string(runner.writer.Bytes())
|
||||
}
|
||||
for i := len(runner.reporters) - 1; i >= 1; i-- {
|
||||
runner.reporters[i].SpecDidComplete(summary)
|
||||
}
|
||||
|
||||
if failed {
|
||||
runner.writer.DumpOut()
|
||||
}
|
||||
|
||||
runner.reporters[0].SpecDidComplete(summary)
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) reportSuiteDidEnd(success bool) {
|
||||
summary := runner.suiteDidEndSummary(success)
|
||||
summary.RunTime = time.Since(runner.startTime)
|
||||
for _, reporter := range runner.reporters {
|
||||
reporter.SpecSuiteDidEnd(summary)
|
||||
}
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) countSpecsThatRanSatisfying(filter func(ex *spec.Spec) bool) (count int) {
|
||||
count = 0
|
||||
|
||||
for _, spec := range runner.processedSpecs {
|
||||
if filter(spec) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) suiteDidEndSummary(success bool) *types.SuiteSummary {
|
||||
numberOfSpecsThatWillBeRun := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool {
|
||||
return !ex.Skipped() && !ex.Pending()
|
||||
})
|
||||
|
||||
numberOfPendingSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool {
|
||||
return ex.Pending()
|
||||
})
|
||||
|
||||
numberOfSkippedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool {
|
||||
return ex.Skipped()
|
||||
})
|
||||
|
||||
numberOfPassedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool {
|
||||
return ex.Passed()
|
||||
})
|
||||
|
||||
numberOfFlakedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool {
|
||||
return ex.Flaked()
|
||||
})
|
||||
|
||||
numberOfFailedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool {
|
||||
return ex.Failed()
|
||||
})
|
||||
|
||||
if runner.beforeSuiteNode != nil && !runner.beforeSuiteNode.Passed() && !runner.config.DryRun {
|
||||
var known bool
|
||||
numberOfSpecsThatWillBeRun, known = runner.iterator.NumberOfSpecsThatWillBeRunIfKnown()
|
||||
if !known {
|
||||
numberOfSpecsThatWillBeRun = runner.iterator.NumberOfSpecsPriorToIteration()
|
||||
}
|
||||
numberOfFailedSpecs = numberOfSpecsThatWillBeRun
|
||||
}
|
||||
|
||||
return &types.SuiteSummary{
|
||||
SuiteDescription: runner.description,
|
||||
SuiteSucceeded: success,
|
||||
SuiteID: runner.suiteID,
|
||||
|
||||
NumberOfSpecsBeforeParallelization: runner.iterator.NumberOfSpecsPriorToIteration(),
|
||||
NumberOfTotalSpecs: len(runner.processedSpecs),
|
||||
NumberOfSpecsThatWillBeRun: numberOfSpecsThatWillBeRun,
|
||||
NumberOfPendingSpecs: numberOfPendingSpecs,
|
||||
NumberOfSkippedSpecs: numberOfSkippedSpecs,
|
||||
NumberOfPassedSpecs: numberOfPassedSpecs,
|
||||
NumberOfFailedSpecs: numberOfFailedSpecs,
|
||||
NumberOfFlakedSpecs: numberOfFlakedSpecs,
|
||||
}
|
||||
}
|
||||
|
||||
func (runner *SpecRunner) suiteWillBeginSummary() *types.SuiteSummary {
|
||||
numTotal, known := runner.iterator.NumberOfSpecsToProcessIfKnown()
|
||||
if !known {
|
||||
numTotal = -1
|
||||
}
|
||||
|
||||
numToRun, known := runner.iterator.NumberOfSpecsThatWillBeRunIfKnown()
|
||||
if !known {
|
||||
numToRun = -1
|
||||
}
|
||||
|
||||
return &types.SuiteSummary{
|
||||
SuiteDescription: runner.description,
|
||||
SuiteID: runner.suiteID,
|
||||
|
||||
NumberOfSpecsBeforeParallelization: runner.iterator.NumberOfSpecsPriorToIteration(),
|
||||
NumberOfTotalSpecs: numTotal,
|
||||
NumberOfSpecsThatWillBeRun: numToRun,
|
||||
NumberOfPendingSpecs: -1,
|
||||
NumberOfSkippedSpecs: -1,
|
||||
NumberOfPassedSpecs: -1,
|
||||
NumberOfFailedSpecs: -1,
|
||||
NumberOfFlakedSpecs: -1,
|
||||
}
|
||||
}
|
||||
-227
@@ -1,227 +0,0 @@
|
||||
package suite
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/onsi/ginkgo/internal/spec_iterator"
|
||||
|
||||
"github.com/onsi/ginkgo/config"
|
||||
"github.com/onsi/ginkgo/internal/containernode"
|
||||
"github.com/onsi/ginkgo/internal/failer"
|
||||
"github.com/onsi/ginkgo/internal/leafnodes"
|
||||
"github.com/onsi/ginkgo/internal/spec"
|
||||
"github.com/onsi/ginkgo/internal/specrunner"
|
||||
"github.com/onsi/ginkgo/internal/writer"
|
||||
"github.com/onsi/ginkgo/reporters"
|
||||
"github.com/onsi/ginkgo/types"
|
||||
)
|
||||
|
||||
type ginkgoTestingT interface {
|
||||
Fail()
|
||||
}
|
||||
|
||||
type deferredContainerNode struct {
|
||||
text string
|
||||
body func()
|
||||
flag types.FlagType
|
||||
codeLocation types.CodeLocation
|
||||
}
|
||||
|
||||
type Suite struct {
|
||||
topLevelContainer *containernode.ContainerNode
|
||||
currentContainer *containernode.ContainerNode
|
||||
|
||||
deferredContainerNodes []deferredContainerNode
|
||||
|
||||
containerIndex int
|
||||
beforeSuiteNode leafnodes.SuiteNode
|
||||
afterSuiteNode leafnodes.SuiteNode
|
||||
runner *specrunner.SpecRunner
|
||||
failer *failer.Failer
|
||||
running bool
|
||||
expandTopLevelNodes bool
|
||||
}
|
||||
|
||||
func New(failer *failer.Failer) *Suite {
|
||||
topLevelContainer := containernode.New("[Top Level]", types.FlagTypeNone, types.CodeLocation{})
|
||||
|
||||
return &Suite{
|
||||
topLevelContainer: topLevelContainer,
|
||||
currentContainer: topLevelContainer,
|
||||
failer: failer,
|
||||
containerIndex: 1,
|
||||
deferredContainerNodes: []deferredContainerNode{},
|
||||
}
|
||||
}
|
||||
|
||||
func (suite *Suite) Run(t ginkgoTestingT, description string, reporters []reporters.Reporter, writer writer.WriterInterface, config config.GinkgoConfigType) (bool, bool) {
|
||||
if config.ParallelTotal < 1 {
|
||||
panic("ginkgo.parallel.total must be >= 1")
|
||||
}
|
||||
|
||||
if config.ParallelNode > config.ParallelTotal || config.ParallelNode < 1 {
|
||||
panic("ginkgo.parallel.node is one-indexed and must be <= ginkgo.parallel.total")
|
||||
}
|
||||
|
||||
suite.expandTopLevelNodes = true
|
||||
for _, deferredNode := range suite.deferredContainerNodes {
|
||||
suite.PushContainerNode(deferredNode.text, deferredNode.body, deferredNode.flag, deferredNode.codeLocation)
|
||||
}
|
||||
|
||||
r := rand.New(rand.NewSource(config.RandomSeed))
|
||||
suite.topLevelContainer.Shuffle(r)
|
||||
iterator, hasProgrammaticFocus := suite.generateSpecsIterator(description, config)
|
||||
suite.runner = specrunner.New(description, suite.beforeSuiteNode, iterator, suite.afterSuiteNode, reporters, writer, config)
|
||||
|
||||
suite.running = true
|
||||
success := suite.runner.Run()
|
||||
if !success {
|
||||
t.Fail()
|
||||
}
|
||||
return success, hasProgrammaticFocus
|
||||
}
|
||||
|
||||
func (suite *Suite) generateSpecsIterator(description string, config config.GinkgoConfigType) (spec_iterator.SpecIterator, bool) {
|
||||
specsSlice := []*spec.Spec{}
|
||||
suite.topLevelContainer.BackPropagateProgrammaticFocus()
|
||||
for _, collatedNodes := range suite.topLevelContainer.Collate() {
|
||||
specsSlice = append(specsSlice, spec.New(collatedNodes.Subject, collatedNodes.Containers, config.EmitSpecProgress))
|
||||
}
|
||||
|
||||
specs := spec.NewSpecs(specsSlice)
|
||||
specs.RegexScansFilePath = config.RegexScansFilePath
|
||||
|
||||
if config.RandomizeAllSpecs {
|
||||
specs.Shuffle(rand.New(rand.NewSource(config.RandomSeed)))
|
||||
}
|
||||
|
||||
specs.ApplyFocus(description, config.FocusStrings, config.SkipStrings)
|
||||
|
||||
if config.SkipMeasurements {
|
||||
specs.SkipMeasurements()
|
||||
}
|
||||
|
||||
var iterator spec_iterator.SpecIterator
|
||||
|
||||
if config.ParallelTotal > 1 {
|
||||
iterator = spec_iterator.NewParallelIterator(specs.Specs(), config.SyncHost)
|
||||
resp, err := http.Get(config.SyncHost + "/has-counter")
|
||||
if err != nil || resp.StatusCode != http.StatusOK {
|
||||
iterator = spec_iterator.NewShardedParallelIterator(specs.Specs(), config.ParallelTotal, config.ParallelNode)
|
||||
}
|
||||
} else {
|
||||
iterator = spec_iterator.NewSerialIterator(specs.Specs())
|
||||
}
|
||||
|
||||
return iterator, specs.HasProgrammaticFocus()
|
||||
}
|
||||
|
||||
func (suite *Suite) CurrentRunningSpecSummary() (*types.SpecSummary, bool) {
|
||||
if !suite.running {
|
||||
return nil, false
|
||||
}
|
||||
return suite.runner.CurrentSpecSummary()
|
||||
}
|
||||
|
||||
func (suite *Suite) SetBeforeSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) {
|
||||
if suite.beforeSuiteNode != nil {
|
||||
panic("You may only call BeforeSuite once!")
|
||||
}
|
||||
suite.beforeSuiteNode = leafnodes.NewBeforeSuiteNode(body, codeLocation, timeout, suite.failer)
|
||||
}
|
||||
|
||||
func (suite *Suite) SetAfterSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) {
|
||||
if suite.afterSuiteNode != nil {
|
||||
panic("You may only call AfterSuite once!")
|
||||
}
|
||||
suite.afterSuiteNode = leafnodes.NewAfterSuiteNode(body, codeLocation, timeout, suite.failer)
|
||||
}
|
||||
|
||||
func (suite *Suite) SetSynchronizedBeforeSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration) {
|
||||
if suite.beforeSuiteNode != nil {
|
||||
panic("You may only call BeforeSuite once!")
|
||||
}
|
||||
suite.beforeSuiteNode = leafnodes.NewSynchronizedBeforeSuiteNode(bodyA, bodyB, codeLocation, timeout, suite.failer)
|
||||
}
|
||||
|
||||
func (suite *Suite) SetSynchronizedAfterSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration) {
|
||||
if suite.afterSuiteNode != nil {
|
||||
panic("You may only call AfterSuite once!")
|
||||
}
|
||||
suite.afterSuiteNode = leafnodes.NewSynchronizedAfterSuiteNode(bodyA, bodyB, codeLocation, timeout, suite.failer)
|
||||
}
|
||||
|
||||
func (suite *Suite) PushContainerNode(text string, body func(), flag types.FlagType, codeLocation types.CodeLocation) {
|
||||
/*
|
||||
We defer walking the container nodes (which immediately evaluates the `body` function)
|
||||
until `RunSpecs` is called. We do this by storing off the deferred container nodes. Then, when
|
||||
`RunSpecs` is called we actually go through and add the container nodes to the test structure.
|
||||
|
||||
This allows us to defer calling all the `body` functions until _after_ the top level functions
|
||||
have been walked, _after_ func init()s have been called, and _after_ `go test` has called `flag.Parse()`.
|
||||
|
||||
This allows users to load up configuration information in the `TestX` go test hook just before `RunSpecs`
|
||||
is invoked and solves issues like #693 and makes the lifecycle easier to reason about.
|
||||
|
||||
*/
|
||||
if !suite.expandTopLevelNodes {
|
||||
suite.deferredContainerNodes = append(suite.deferredContainerNodes, deferredContainerNode{text, body, flag, codeLocation})
|
||||
return
|
||||
}
|
||||
|
||||
container := containernode.New(text, flag, codeLocation)
|
||||
suite.currentContainer.PushContainerNode(container)
|
||||
|
||||
previousContainer := suite.currentContainer
|
||||
suite.currentContainer = container
|
||||
suite.containerIndex++
|
||||
|
||||
body()
|
||||
|
||||
suite.containerIndex--
|
||||
suite.currentContainer = previousContainer
|
||||
}
|
||||
|
||||
func (suite *Suite) PushItNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, timeout time.Duration) {
|
||||
if suite.running {
|
||||
suite.failer.Fail("You may only call It from within a Describe, Context or When", codeLocation)
|
||||
}
|
||||
suite.currentContainer.PushSubjectNode(leafnodes.NewItNode(text, body, flag, codeLocation, timeout, suite.failer, suite.containerIndex))
|
||||
}
|
||||
|
||||
func (suite *Suite) PushMeasureNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, samples int) {
|
||||
if suite.running {
|
||||
suite.failer.Fail("You may only call Measure from within a Describe, Context or When", codeLocation)
|
||||
}
|
||||
suite.currentContainer.PushSubjectNode(leafnodes.NewMeasureNode(text, body, flag, codeLocation, samples, suite.failer, suite.containerIndex))
|
||||
}
|
||||
|
||||
func (suite *Suite) PushBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) {
|
||||
if suite.running {
|
||||
suite.failer.Fail("You may only call BeforeEach from within a Describe, Context or When", codeLocation)
|
||||
}
|
||||
suite.currentContainer.PushSetupNode(leafnodes.NewBeforeEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex))
|
||||
}
|
||||
|
||||
func (suite *Suite) PushJustBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) {
|
||||
if suite.running {
|
||||
suite.failer.Fail("You may only call JustBeforeEach from within a Describe, Context or When", codeLocation)
|
||||
}
|
||||
suite.currentContainer.PushSetupNode(leafnodes.NewJustBeforeEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex))
|
||||
}
|
||||
|
||||
func (suite *Suite) PushJustAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) {
|
||||
if suite.running {
|
||||
suite.failer.Fail("You may only call JustAfterEach from within a Describe or Context", codeLocation)
|
||||
}
|
||||
suite.currentContainer.PushSetupNode(leafnodes.NewJustAfterEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex))
|
||||
}
|
||||
|
||||
func (suite *Suite) PushAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) {
|
||||
if suite.running {
|
||||
suite.failer.Fail("You may only call AfterEach from within a Describe, Context or When", codeLocation)
|
||||
}
|
||||
suite.currentContainer.PushSetupNode(leafnodes.NewAfterEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex))
|
||||
}
|
||||
-109
@@ -1,109 +0,0 @@
|
||||
package testingtproxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
type failFunc func(message string, callerSkip ...int)
|
||||
type skipFunc func(message string, callerSkip ...int)
|
||||
type failedFunc func() bool
|
||||
type nameFunc func() string
|
||||
|
||||
func New(writer io.Writer, fail failFunc, skip skipFunc, failed failedFunc, name nameFunc, offset int) *ginkgoTestingTProxy {
|
||||
return &ginkgoTestingTProxy{
|
||||
fail: fail,
|
||||
offset: offset,
|
||||
writer: writer,
|
||||
skip: skip,
|
||||
failed: failed,
|
||||
name: name,
|
||||
}
|
||||
}
|
||||
|
||||
type ginkgoTestingTProxy struct {
|
||||
fail failFunc
|
||||
skip skipFunc
|
||||
failed failedFunc
|
||||
name nameFunc
|
||||
offset int
|
||||
writer io.Writer
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Cleanup(func()) {
|
||||
// No-op
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Setenv(kev, value string) {
|
||||
fmt.Println("Setenv is a noop for Ginkgo at the moment but will be implemented in V2")
|
||||
// No-op until Cleanup is implemented
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Error(args ...interface{}) {
|
||||
t.fail(fmt.Sprintln(args...), t.offset)
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Errorf(format string, args ...interface{}) {
|
||||
t.fail(fmt.Sprintf(format, args...), t.offset)
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Fail() {
|
||||
t.fail("failed", t.offset)
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) FailNow() {
|
||||
t.fail("failed", t.offset)
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Failed() bool {
|
||||
return t.failed()
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Fatal(args ...interface{}) {
|
||||
t.fail(fmt.Sprintln(args...), t.offset)
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Fatalf(format string, args ...interface{}) {
|
||||
t.fail(fmt.Sprintf(format, args...), t.offset)
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Helper() {
|
||||
// No-op
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Log(args ...interface{}) {
|
||||
fmt.Fprintln(t.writer, args...)
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Logf(format string, args ...interface{}) {
|
||||
t.Log(fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Name() string {
|
||||
return t.name()
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Parallel() {
|
||||
// No-op
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Skip(args ...interface{}) {
|
||||
t.skip(fmt.Sprintln(args...), t.offset)
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) SkipNow() {
|
||||
t.skip("skip", t.offset)
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Skipf(format string, args ...interface{}) {
|
||||
t.skip(fmt.Sprintf(format, args...), t.offset)
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) Skipped() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (t *ginkgoTestingTProxy) TempDir() string {
|
||||
// No-op
|
||||
return ""
|
||||
}
|
||||
Vendored
-8
@@ -373,9 +373,6 @@ github.com/desertbit/timer
|
||||
# github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f
|
||||
## explicit
|
||||
github.com/dgryski/go-rendezvous
|
||||
# github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
|
||||
## explicit; go 1.20
|
||||
github.com/dhowden/tag
|
||||
# github.com/distribution/reference v0.6.0
|
||||
## explicit; go 1.20
|
||||
github.com/distribution/reference
|
||||
@@ -1204,7 +1201,6 @@ github.com/olekukonko/tablewriter/renderer
|
||||
github.com/olekukonko/tablewriter/tw
|
||||
# github.com/onsi/ginkgo v1.16.5
|
||||
## explicit; go 1.16
|
||||
github.com/onsi/ginkgo
|
||||
github.com/onsi/ginkgo/config
|
||||
github.com/onsi/ginkgo/formatter
|
||||
github.com/onsi/ginkgo/ginkgo
|
||||
@@ -1218,14 +1214,10 @@ github.com/onsi/ginkgo/ginkgo/watch
|
||||
github.com/onsi/ginkgo/internal/codelocation
|
||||
github.com/onsi/ginkgo/internal/containernode
|
||||
github.com/onsi/ginkgo/internal/failer
|
||||
github.com/onsi/ginkgo/internal/global
|
||||
github.com/onsi/ginkgo/internal/leafnodes
|
||||
github.com/onsi/ginkgo/internal/remote
|
||||
github.com/onsi/ginkgo/internal/spec
|
||||
github.com/onsi/ginkgo/internal/spec_iterator
|
||||
github.com/onsi/ginkgo/internal/specrunner
|
||||
github.com/onsi/ginkgo/internal/suite
|
||||
github.com/onsi/ginkgo/internal/testingtproxy
|
||||
github.com/onsi/ginkgo/internal/writer
|
||||
github.com/onsi/ginkgo/reporters
|
||||
github.com/onsi/ginkgo/reporters/stenographer
|
||||
|
||||
Reference in new issue
Block a user