WIP: Save agent roles integration work before CHORUS rebrand
- Agent roles and coordination features - Chat API integration testing - New configuration and workspace management 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1
vendor/github.com/ipfs/go-cid/.gitignore
generated
vendored
Normal file
1
vendor/github.com/ipfs/go-cid/.gitignore
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
cid-fuzz.zip
|
||||
21
vendor/github.com/ipfs/go-cid/LICENSE
generated
vendored
Normal file
21
vendor/github.com/ipfs/go-cid/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Protocol Labs, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
5
vendor/github.com/ipfs/go-cid/Makefile
generated
vendored
Normal file
5
vendor/github.com/ipfs/go-cid/Makefile
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
all: deps
|
||||
|
||||
deps:
|
||||
go get github.com/mattn/goveralls
|
||||
go get golang.org/x/tools/cmd/cover
|
||||
115
vendor/github.com/ipfs/go-cid/README.md
generated
vendored
Normal file
115
vendor/github.com/ipfs/go-cid/README.md
generated
vendored
Normal file
@@ -0,0 +1,115 @@
|
||||
go-cid
|
||||
==================
|
||||
|
||||
[](http://ipn.io)
|
||||
[](http://ipfs.io/)
|
||||
[](http://webchat.freenode.net/?channels=%23ipfs)
|
||||
[](https://github.com/RichardLitt/standard-readme)
|
||||
[](https://godoc.org/github.com/ipfs/go-cid)
|
||||
[](https://coveralls.io/github/ipfs/go-cid?branch=master)
|
||||
[](https://travis-ci.org/ipfs/go-cid)
|
||||
|
||||
> A package to handle content IDs in Go.
|
||||
|
||||
This is an implementation in Go of the [CID spec](https://github.com/ipld/cid).
|
||||
It is used in `go-ipfs` and related packages to refer to a typed hunk of data.
|
||||
|
||||
## Lead Maintainer
|
||||
|
||||
[Eric Myhre](https://github.com/warpfork)
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Install](#install)
|
||||
- [Usage](#usage)
|
||||
- [API](#api)
|
||||
- [Contribute](#contribute)
|
||||
- [License](#license)
|
||||
|
||||
## Install
|
||||
|
||||
`go-cid` is a standard Go module which can be installed with:
|
||||
|
||||
```sh
|
||||
go get github.com/ipfs/go-cid
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Running tests
|
||||
|
||||
Run tests with `go test` from the directory root
|
||||
|
||||
```sh
|
||||
go test
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
#### Parsing string input from users
|
||||
|
||||
```go
|
||||
// Create a cid from a marshaled string
|
||||
c, err := cid.Decode("bafzbeigai3eoy2ccc7ybwjfz5r3rdxqrinwi4rwytly24tdbh6yk7zslrm")
|
||||
if err != nil {...}
|
||||
|
||||
fmt.Println("Got CID: ", c)
|
||||
```
|
||||
|
||||
#### Creating a CID from scratch
|
||||
|
||||
```go
|
||||
|
||||
import (
|
||||
cid "github.com/ipfs/go-cid"
|
||||
mc "github.com/multiformats/go-multicodec"
|
||||
mh "github.com/multiformats/go-multihash"
|
||||
)
|
||||
|
||||
// Create a cid manually by specifying the 'prefix' parameters
|
||||
pref := cid.Prefix{
|
||||
Version: 1,
|
||||
Codec: uint64(mc.Raw),
|
||||
MhType: mh.SHA2_256,
|
||||
MhLength: -1, // default length
|
||||
}
|
||||
|
||||
// And then feed it some data
|
||||
c, err := pref.Sum([]byte("Hello World!"))
|
||||
if err != nil {...}
|
||||
|
||||
fmt.Println("Created CID: ", c)
|
||||
```
|
||||
|
||||
#### Check if two CIDs match
|
||||
|
||||
```go
|
||||
// To test if two cid's are equivalent, be sure to use the 'Equals' method:
|
||||
if c1.Equals(c2) {
|
||||
fmt.Println("These two refer to the same exact data!")
|
||||
}
|
||||
```
|
||||
|
||||
#### Check if some data matches a given CID
|
||||
|
||||
```go
|
||||
// To check if some data matches a given cid,
|
||||
// Get your CIDs prefix, and use that to sum the data in question:
|
||||
other, err := c.Prefix().Sum(mydata)
|
||||
if err != nil {...}
|
||||
|
||||
if !c.Equals(other) {
|
||||
fmt.Println("This data is different.")
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Contribute
|
||||
|
||||
PRs are welcome!
|
||||
|
||||
Small note: If editing the Readme, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification.
|
||||
|
||||
## License
|
||||
|
||||
MIT © Jeromy Johnson
|
||||
74
vendor/github.com/ipfs/go-cid/builder.go
generated
vendored
Normal file
74
vendor/github.com/ipfs/go-cid/builder.go
generated
vendored
Normal file
@@ -0,0 +1,74 @@
|
||||
package cid
|
||||
|
||||
import (
|
||||
mh "github.com/multiformats/go-multihash"
|
||||
)
|
||||
|
||||
type Builder interface {
|
||||
Sum(data []byte) (Cid, error)
|
||||
GetCodec() uint64
|
||||
WithCodec(uint64) Builder
|
||||
}
|
||||
|
||||
type V0Builder struct{}
|
||||
|
||||
type V1Builder struct {
|
||||
Codec uint64
|
||||
MhType uint64
|
||||
MhLength int // MhLength <= 0 means the default length
|
||||
}
|
||||
|
||||
func (p Prefix) GetCodec() uint64 {
|
||||
return p.Codec
|
||||
}
|
||||
|
||||
func (p Prefix) WithCodec(c uint64) Builder {
|
||||
if c == p.Codec {
|
||||
return p
|
||||
}
|
||||
p.Codec = c
|
||||
if c != DagProtobuf {
|
||||
p.Version = 1
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (p V0Builder) Sum(data []byte) (Cid, error) {
|
||||
hash, err := mh.Sum(data, mh.SHA2_256, -1)
|
||||
if err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
return Cid{string(hash)}, nil
|
||||
}
|
||||
|
||||
func (p V0Builder) GetCodec() uint64 {
|
||||
return DagProtobuf
|
||||
}
|
||||
|
||||
func (p V0Builder) WithCodec(c uint64) Builder {
|
||||
if c == DagProtobuf {
|
||||
return p
|
||||
}
|
||||
return V1Builder{Codec: c, MhType: mh.SHA2_256}
|
||||
}
|
||||
|
||||
func (p V1Builder) Sum(data []byte) (Cid, error) {
|
||||
mhLen := p.MhLength
|
||||
if mhLen <= 0 {
|
||||
mhLen = -1
|
||||
}
|
||||
hash, err := mh.Sum(data, p.MhType, mhLen)
|
||||
if err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
return NewCidV1(p.Codec, hash), nil
|
||||
}
|
||||
|
||||
func (p V1Builder) GetCodec() uint64 {
|
||||
return p.Codec
|
||||
}
|
||||
|
||||
func (p V1Builder) WithCodec(c uint64) Builder {
|
||||
p.Codec = c
|
||||
return p
|
||||
}
|
||||
817
vendor/github.com/ipfs/go-cid/cid.go
generated
vendored
Normal file
817
vendor/github.com/ipfs/go-cid/cid.go
generated
vendored
Normal file
@@ -0,0 +1,817 @@
|
||||
// Package cid implements the Content-IDentifiers specification
|
||||
// (https://github.com/ipld/cid) in Go. CIDs are
|
||||
// self-describing content-addressed identifiers useful for
|
||||
// distributed information systems. CIDs are used in the IPFS
|
||||
// (https://ipfs.io) project ecosystem.
|
||||
//
|
||||
// CIDs have two major versions. A CIDv0 corresponds to a multihash of type
|
||||
// DagProtobuf, is deprecated and exists for compatibility reasons. Usually,
|
||||
// CIDv1 should be used.
|
||||
//
|
||||
// A CIDv1 has four parts:
|
||||
//
|
||||
// <cidv1> ::= <multibase-prefix><cid-version><multicodec-packed-content-type><multihash-content-address>
|
||||
//
|
||||
// As shown above, the CID implementation relies heavily on Multiformats,
|
||||
// particularly Multibase
|
||||
// (https://github.com/multiformats/go-multibase), Multicodec
|
||||
// (https://github.com/multiformats/multicodec) and Multihash
|
||||
// implementations (https://github.com/multiformats/go-multihash).
|
||||
package cid
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
mbase "github.com/multiformats/go-multibase"
|
||||
mh "github.com/multiformats/go-multihash"
|
||||
varint "github.com/multiformats/go-varint"
|
||||
)
|
||||
|
||||
// UnsupportedVersionString just holds an error message
|
||||
const UnsupportedVersionString = "<unsupported cid version>"
|
||||
|
||||
// ErrInvalidCid is an error that indicates that a CID is invalid.
|
||||
type ErrInvalidCid struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e ErrInvalidCid) Error() string {
|
||||
return fmt.Sprintf("invalid cid: %s", e.Err)
|
||||
}
|
||||
|
||||
func (e ErrInvalidCid) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
func (e ErrInvalidCid) Is(err error) bool {
|
||||
switch err.(type) {
|
||||
case ErrInvalidCid, *ErrInvalidCid:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrCidTooShort means that the cid passed to decode was not long
|
||||
// enough to be a valid Cid
|
||||
ErrCidTooShort = ErrInvalidCid{errors.New("cid too short")}
|
||||
|
||||
// ErrInvalidEncoding means that selected encoding is not supported
|
||||
// by this Cid version
|
||||
ErrInvalidEncoding = errors.New("invalid base encoding")
|
||||
)
|
||||
|
||||
// Consts below are DEPRECATED and left only for legacy reasons:
|
||||
// <https://github.com/ipfs/go-cid/pull/137>
|
||||
// Modern code should use consts from go-multicodec instead:
|
||||
// <https://github.com/multiformats/go-multicodec>
|
||||
const (
|
||||
// common ones
|
||||
Raw = 0x55
|
||||
DagProtobuf = 0x70 // https://ipld.io/docs/codecs/known/dag-pb/
|
||||
DagCBOR = 0x71 // https://ipld.io/docs/codecs/known/dag-cbor/
|
||||
DagJSON = 0x0129 // https://ipld.io/docs/codecs/known/dag-json/
|
||||
Libp2pKey = 0x72 // https://github.com/libp2p/specs/blob/master/peer-ids/peer-ids.md#peer-ids
|
||||
|
||||
// other
|
||||
GitRaw = 0x78
|
||||
DagJOSE = 0x85 // https://ipld.io/specs/codecs/dag-jose/spec/
|
||||
EthBlock = 0x90
|
||||
EthBlockList = 0x91
|
||||
EthTxTrie = 0x92
|
||||
EthTx = 0x93
|
||||
EthTxReceiptTrie = 0x94
|
||||
EthTxReceipt = 0x95
|
||||
EthStateTrie = 0x96
|
||||
EthAccountSnapshot = 0x97
|
||||
EthStorageTrie = 0x98
|
||||
BitcoinBlock = 0xb0
|
||||
BitcoinTx = 0xb1
|
||||
ZcashBlock = 0xc0
|
||||
ZcashTx = 0xc1
|
||||
DecredBlock = 0xe0
|
||||
DecredTx = 0xe1
|
||||
DashBlock = 0xf0
|
||||
DashTx = 0xf1
|
||||
FilCommitmentUnsealed = 0xf101
|
||||
FilCommitmentSealed = 0xf102
|
||||
)
|
||||
|
||||
// tryNewCidV0 tries to convert a multihash into a CIDv0 CID and returns an
|
||||
// error on failure.
|
||||
func tryNewCidV0(mhash mh.Multihash) (Cid, error) {
|
||||
// Need to make sure hash is valid for CidV0 otherwise we will
|
||||
// incorrectly detect it as CidV1 in the Version() method
|
||||
dec, err := mh.Decode(mhash)
|
||||
if err != nil {
|
||||
return Undef, ErrInvalidCid{err}
|
||||
}
|
||||
if dec.Code != mh.SHA2_256 || dec.Length != 32 {
|
||||
return Undef, ErrInvalidCid{fmt.Errorf("invalid hash for cidv0 %d-%d", dec.Code, dec.Length)}
|
||||
}
|
||||
return Cid{string(mhash)}, nil
|
||||
}
|
||||
|
||||
// NewCidV0 returns a Cid-wrapped multihash.
|
||||
// They exist to allow IPFS to work with Cids while keeping
|
||||
// compatibility with the plain-multihash format used used in IPFS.
|
||||
// NewCidV1 should be used preferentially.
|
||||
//
|
||||
// Panics if the multihash isn't sha2-256.
|
||||
func NewCidV0(mhash mh.Multihash) Cid {
|
||||
c, err := tryNewCidV0(mhash)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// NewCidV1 returns a new Cid using the given multicodec-packed
|
||||
// content type.
|
||||
//
|
||||
// Panics if the multihash is invalid.
|
||||
func NewCidV1(codecType uint64, mhash mh.Multihash) Cid {
|
||||
hashlen := len(mhash)
|
||||
|
||||
// Two 8 bytes (max) numbers plus hash.
|
||||
// We use strings.Builder to only allocate once.
|
||||
var b strings.Builder
|
||||
b.Grow(1 + varint.UvarintSize(codecType) + hashlen)
|
||||
|
||||
b.WriteByte(1)
|
||||
|
||||
var buf [binary.MaxVarintLen64]byte
|
||||
n := varint.PutUvarint(buf[:], codecType)
|
||||
b.Write(buf[:n])
|
||||
|
||||
cn, _ := b.Write(mhash)
|
||||
if cn != hashlen {
|
||||
panic("copy hash length is inconsistent")
|
||||
}
|
||||
|
||||
return Cid{b.String()}
|
||||
}
|
||||
|
||||
var (
|
||||
_ encoding.BinaryMarshaler = Cid{}
|
||||
_ encoding.BinaryUnmarshaler = (*Cid)(nil)
|
||||
_ encoding.TextMarshaler = Cid{}
|
||||
_ encoding.TextUnmarshaler = (*Cid)(nil)
|
||||
)
|
||||
|
||||
// Cid represents a self-describing content addressed
|
||||
// identifier. It is formed by a Version, a Codec (which indicates
|
||||
// a multicodec-packed content type) and a Multihash.
|
||||
type Cid struct{ str string }
|
||||
|
||||
// Undef can be used to represent a nil or undefined Cid, using Cid{}
|
||||
// directly is also acceptable.
|
||||
var Undef = Cid{}
|
||||
|
||||
// Defined returns true if a Cid is defined
|
||||
// Calling any other methods on an undefined Cid will result in
|
||||
// undefined behavior.
|
||||
func (c Cid) Defined() bool {
|
||||
return c.str != ""
|
||||
}
|
||||
|
||||
// Parse is a short-hand function to perform Decode, Cast etc... on
|
||||
// a generic interface{} type.
|
||||
func Parse(v interface{}) (Cid, error) {
|
||||
switch v2 := v.(type) {
|
||||
case string:
|
||||
if strings.Contains(v2, "/ipfs/") {
|
||||
return Decode(strings.Split(v2, "/ipfs/")[1])
|
||||
}
|
||||
return Decode(v2)
|
||||
case []byte:
|
||||
return Cast(v2)
|
||||
case mh.Multihash:
|
||||
return tryNewCidV0(v2)
|
||||
case Cid:
|
||||
return v2, nil
|
||||
default:
|
||||
return Undef, ErrInvalidCid{fmt.Errorf("can't parse %+v as Cid", v2)}
|
||||
}
|
||||
}
|
||||
|
||||
// MustParse calls Parse but will panic on error.
|
||||
func MustParse(v interface{}) Cid {
|
||||
c, err := Parse(v)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Decode parses a Cid-encoded string and returns a Cid object.
|
||||
// For CidV1, a Cid-encoded string is primarily a multibase string:
|
||||
//
|
||||
// <multibase-type-code><base-encoded-string>
|
||||
//
|
||||
// The base-encoded string represents a:
|
||||
//
|
||||
// <version><codec-type><multihash>
|
||||
//
|
||||
// Decode will also detect and parse CidV0 strings. Strings
|
||||
// starting with "Qm" are considered CidV0 and treated directly
|
||||
// as B58-encoded multihashes.
|
||||
func Decode(v string) (Cid, error) {
|
||||
if len(v) < 2 {
|
||||
return Undef, ErrCidTooShort
|
||||
}
|
||||
|
||||
if len(v) == 46 && v[:2] == "Qm" {
|
||||
hash, err := mh.FromB58String(v)
|
||||
if err != nil {
|
||||
return Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
return tryNewCidV0(hash)
|
||||
}
|
||||
|
||||
_, data, err := mbase.Decode(v)
|
||||
if err != nil {
|
||||
return Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
return Cast(data)
|
||||
}
|
||||
|
||||
// Extract the encoding from a Cid. If Decode on the same string did
|
||||
// not return an error neither will this function.
|
||||
func ExtractEncoding(v string) (mbase.Encoding, error) {
|
||||
if len(v) < 2 {
|
||||
return -1, ErrCidTooShort
|
||||
}
|
||||
|
||||
if len(v) == 46 && v[:2] == "Qm" {
|
||||
return mbase.Base58BTC, nil
|
||||
}
|
||||
|
||||
encoding := mbase.Encoding(v[0])
|
||||
|
||||
// check encoding is valid
|
||||
_, err := mbase.NewEncoder(encoding)
|
||||
if err != nil {
|
||||
return -1, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
return encoding, nil
|
||||
}
|
||||
|
||||
// Cast takes a Cid data slice, parses it and returns a Cid.
|
||||
// For CidV1, the data buffer is in the form:
|
||||
//
|
||||
// <version><codec-type><multihash>
|
||||
//
|
||||
// CidV0 are also supported. In particular, data buffers starting
|
||||
// with length 34 bytes, which starts with bytes [18,32...] are considered
|
||||
// binary multihashes.
|
||||
//
|
||||
// Please use decode when parsing a regular Cid string, as Cast does not
|
||||
// expect multibase-encoded data. Cast accepts the output of Cid.Bytes().
|
||||
func Cast(data []byte) (Cid, error) {
|
||||
nr, c, err := CidFromBytes(data)
|
||||
if err != nil {
|
||||
return Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
if nr != len(data) {
|
||||
return Undef, ErrInvalidCid{fmt.Errorf("trailing bytes in data buffer passed to cid Cast")}
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// UnmarshalBinary is equivalent to Cast(). It implements the
|
||||
// encoding.BinaryUnmarshaler interface.
|
||||
func (c *Cid) UnmarshalBinary(data []byte) error {
|
||||
casted, err := Cast(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.str = casted.str
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnmarshalText is equivalent to Decode(). It implements the
|
||||
// encoding.TextUnmarshaler interface.
|
||||
func (c *Cid) UnmarshalText(text []byte) error {
|
||||
decodedCid, err := Decode(string(text))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.str = decodedCid.str
|
||||
return nil
|
||||
}
|
||||
|
||||
// Version returns the Cid version.
|
||||
func (c Cid) Version() uint64 {
|
||||
if len(c.str) == 34 && c.str[0] == 18 && c.str[1] == 32 {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// Type returns the multicodec-packed content type of a Cid.
|
||||
func (c Cid) Type() uint64 {
|
||||
if c.Version() == 0 {
|
||||
return DagProtobuf
|
||||
}
|
||||
_, n, _ := uvarint(c.str)
|
||||
codec, _, _ := uvarint(c.str[n:])
|
||||
return codec
|
||||
}
|
||||
|
||||
// String returns the default string representation of a
|
||||
// Cid. Currently, Base32 is used for CIDV1 as the encoding for the
|
||||
// multibase string, Base58 is used for CIDV0.
|
||||
func (c Cid) String() string {
|
||||
switch c.Version() {
|
||||
case 0:
|
||||
return c.Hash().B58String()
|
||||
case 1:
|
||||
mbstr, err := mbase.Encode(mbase.Base32, c.Bytes())
|
||||
if err != nil {
|
||||
panic("should not error with hardcoded mbase: " + err.Error())
|
||||
}
|
||||
|
||||
return mbstr
|
||||
default:
|
||||
panic("not possible to reach this point")
|
||||
}
|
||||
}
|
||||
|
||||
// String returns the string representation of a Cid
|
||||
// encoded is selected base
|
||||
func (c Cid) StringOfBase(base mbase.Encoding) (string, error) {
|
||||
switch c.Version() {
|
||||
case 0:
|
||||
if base != mbase.Base58BTC {
|
||||
return "", ErrInvalidEncoding
|
||||
}
|
||||
return c.Hash().B58String(), nil
|
||||
case 1:
|
||||
return mbase.Encode(base, c.Bytes())
|
||||
default:
|
||||
panic("not possible to reach this point")
|
||||
}
|
||||
}
|
||||
|
||||
// Encode return the string representation of a Cid in a given base
|
||||
// when applicable. Version 0 Cid's are always in Base58 as they do
|
||||
// not take a multibase prefix.
|
||||
func (c Cid) Encode(base mbase.Encoder) string {
|
||||
switch c.Version() {
|
||||
case 0:
|
||||
return c.Hash().B58String()
|
||||
case 1:
|
||||
return base.Encode(c.Bytes())
|
||||
default:
|
||||
panic("not possible to reach this point")
|
||||
}
|
||||
}
|
||||
|
||||
// Hash returns the multihash contained by a Cid.
|
||||
func (c Cid) Hash() mh.Multihash {
|
||||
bytes := c.Bytes()
|
||||
|
||||
if c.Version() == 0 {
|
||||
return mh.Multihash(bytes)
|
||||
}
|
||||
|
||||
// skip version length
|
||||
_, n1, _ := varint.FromUvarint(bytes)
|
||||
// skip codec length
|
||||
_, n2, _ := varint.FromUvarint(bytes[n1:])
|
||||
|
||||
return mh.Multihash(bytes[n1+n2:])
|
||||
}
|
||||
|
||||
// Bytes returns the byte representation of a Cid.
|
||||
// The output of bytes can be parsed back into a Cid
|
||||
// with Cast().
|
||||
//
|
||||
// If c.Defined() == false, it return a nil slice and may not
|
||||
// be parsable with Cast().
|
||||
func (c Cid) Bytes() []byte {
|
||||
if !c.Defined() {
|
||||
return nil
|
||||
}
|
||||
return []byte(c.str)
|
||||
}
|
||||
|
||||
// ByteLen returns the length of the CID in bytes.
|
||||
// It's equivalent to `len(c.Bytes())`, but works without an allocation,
|
||||
// and should therefore be preferred.
|
||||
//
|
||||
// (See also the WriteTo method for other important operations that work without allocation.)
|
||||
func (c Cid) ByteLen() int {
|
||||
return len(c.str)
|
||||
}
|
||||
|
||||
// WriteBytes writes the CID bytes to the given writer.
|
||||
// This method works without incurring any allocation.
|
||||
//
|
||||
// (See also the ByteLen method for other important operations that work without allocation.)
|
||||
func (c Cid) WriteBytes(w io.Writer) (int, error) {
|
||||
n, err := io.WriteString(w, c.str)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
if n != len(c.str) {
|
||||
return n, fmt.Errorf("failed to write entire cid string")
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// MarshalBinary is equivalent to Bytes(). It implements the
|
||||
// encoding.BinaryMarshaler interface.
|
||||
func (c Cid) MarshalBinary() ([]byte, error) {
|
||||
return c.Bytes(), nil
|
||||
}
|
||||
|
||||
// MarshalText is equivalent to String(). It implements the
|
||||
// encoding.TextMarshaler interface.
|
||||
func (c Cid) MarshalText() ([]byte, error) {
|
||||
return []byte(c.String()), nil
|
||||
}
|
||||
|
||||
// Equals checks that two Cids are the same.
|
||||
// In order for two Cids to be considered equal, the
|
||||
// Version, the Codec and the Multihash must match.
|
||||
func (c Cid) Equals(o Cid) bool {
|
||||
return c == o
|
||||
}
|
||||
|
||||
// UnmarshalJSON parses the JSON representation of a Cid.
|
||||
func (c *Cid) UnmarshalJSON(b []byte) error {
|
||||
if len(b) < 2 {
|
||||
return ErrInvalidCid{fmt.Errorf("invalid cid json blob")}
|
||||
}
|
||||
obj := struct {
|
||||
CidTarget string `json:"/"`
|
||||
}{}
|
||||
objptr := &obj
|
||||
err := json.Unmarshal(b, &objptr)
|
||||
if err != nil {
|
||||
return ErrInvalidCid{err}
|
||||
}
|
||||
if objptr == nil {
|
||||
*c = Cid{}
|
||||
return nil
|
||||
}
|
||||
|
||||
if obj.CidTarget == "" {
|
||||
return ErrInvalidCid{fmt.Errorf("cid was incorrectly formatted")}
|
||||
}
|
||||
|
||||
out, err := Decode(obj.CidTarget)
|
||||
if err != nil {
|
||||
return ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
*c = out
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON procudes a JSON representation of a Cid, which looks as follows:
|
||||
//
|
||||
// { "/": "<cid-string>" }
|
||||
//
|
||||
// Note that this formatting comes from the IPLD specification
|
||||
// (https://github.com/ipld/specs/tree/master/ipld)
|
||||
func (c Cid) MarshalJSON() ([]byte, error) {
|
||||
if !c.Defined() {
|
||||
return []byte("null"), nil
|
||||
}
|
||||
return []byte(fmt.Sprintf("{\"/\":\"%s\"}", c.String())), nil
|
||||
}
|
||||
|
||||
// KeyString returns the binary representation of the Cid as a string
|
||||
func (c Cid) KeyString() string {
|
||||
return c.str
|
||||
}
|
||||
|
||||
// Loggable returns a Loggable (as defined by
|
||||
// https://godoc.org/github.com/ipfs/go-log).
|
||||
func (c Cid) Loggable() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"cid": c,
|
||||
}
|
||||
}
|
||||
|
||||
// Prefix builds and returns a Prefix out of a Cid.
|
||||
func (c Cid) Prefix() Prefix {
|
||||
if c.Version() == 0 {
|
||||
return Prefix{
|
||||
MhType: mh.SHA2_256,
|
||||
MhLength: 32,
|
||||
Version: 0,
|
||||
Codec: DagProtobuf,
|
||||
}
|
||||
}
|
||||
|
||||
offset := 0
|
||||
version, n, _ := uvarint(c.str[offset:])
|
||||
offset += n
|
||||
codec, n, _ := uvarint(c.str[offset:])
|
||||
offset += n
|
||||
mhtype, n, _ := uvarint(c.str[offset:])
|
||||
offset += n
|
||||
mhlen, _, _ := uvarint(c.str[offset:])
|
||||
|
||||
return Prefix{
|
||||
MhType: mhtype,
|
||||
MhLength: int(mhlen),
|
||||
Version: version,
|
||||
Codec: codec,
|
||||
}
|
||||
}
|
||||
|
||||
// Prefix represents all the metadata of a Cid,
|
||||
// that is, the Version, the Codec, the Multihash type
|
||||
// and the Multihash length. It does not contains
|
||||
// any actual content information.
|
||||
// NOTE: The use -1 in MhLength to mean default length is deprecated,
|
||||
//
|
||||
// use the V0Builder or V1Builder structures instead
|
||||
type Prefix struct {
|
||||
Version uint64
|
||||
Codec uint64
|
||||
MhType uint64
|
||||
MhLength int
|
||||
}
|
||||
|
||||
// Sum uses the information in a prefix to perform a multihash.Sum()
|
||||
// and return a newly constructed Cid with the resulting multihash.
|
||||
func (p Prefix) Sum(data []byte) (Cid, error) {
|
||||
length := p.MhLength
|
||||
if p.MhType == mh.IDENTITY {
|
||||
length = -1
|
||||
}
|
||||
|
||||
if p.Version == 0 && (p.MhType != mh.SHA2_256 ||
|
||||
(p.MhLength != 32 && p.MhLength != -1)) {
|
||||
|
||||
return Undef, ErrInvalidCid{fmt.Errorf("invalid v0 prefix")}
|
||||
}
|
||||
|
||||
hash, err := mh.Sum(data, p.MhType, length)
|
||||
if err != nil {
|
||||
return Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
switch p.Version {
|
||||
case 0:
|
||||
return NewCidV0(hash), nil
|
||||
case 1:
|
||||
return NewCidV1(p.Codec, hash), nil
|
||||
default:
|
||||
return Undef, ErrInvalidCid{fmt.Errorf("invalid cid version")}
|
||||
}
|
||||
}
|
||||
|
||||
// Bytes returns a byte representation of a Prefix. It looks like:
|
||||
//
|
||||
// <version><codec><mh-type><mh-length>
|
||||
func (p Prefix) Bytes() []byte {
|
||||
size := varint.UvarintSize(p.Version)
|
||||
size += varint.UvarintSize(p.Codec)
|
||||
size += varint.UvarintSize(p.MhType)
|
||||
size += varint.UvarintSize(uint64(p.MhLength))
|
||||
|
||||
buf := make([]byte, size)
|
||||
n := varint.PutUvarint(buf, p.Version)
|
||||
n += varint.PutUvarint(buf[n:], p.Codec)
|
||||
n += varint.PutUvarint(buf[n:], p.MhType)
|
||||
n += varint.PutUvarint(buf[n:], uint64(p.MhLength))
|
||||
if n != size {
|
||||
panic("size mismatch")
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
// PrefixFromBytes parses a Prefix-byte representation onto a
|
||||
// Prefix.
|
||||
func PrefixFromBytes(buf []byte) (Prefix, error) {
|
||||
r := bytes.NewReader(buf)
|
||||
vers, err := varint.ReadUvarint(r)
|
||||
if err != nil {
|
||||
return Prefix{}, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
codec, err := varint.ReadUvarint(r)
|
||||
if err != nil {
|
||||
return Prefix{}, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
mhtype, err := varint.ReadUvarint(r)
|
||||
if err != nil {
|
||||
return Prefix{}, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
mhlen, err := varint.ReadUvarint(r)
|
||||
if err != nil {
|
||||
return Prefix{}, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
return Prefix{
|
||||
Version: vers,
|
||||
Codec: codec,
|
||||
MhType: mhtype,
|
||||
MhLength: int(mhlen),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func CidFromBytes(data []byte) (int, Cid, error) {
|
||||
if len(data) > 2 && data[0] == mh.SHA2_256 && data[1] == 32 {
|
||||
if len(data) < 34 {
|
||||
return 0, Undef, ErrInvalidCid{fmt.Errorf("not enough bytes for cid v0")}
|
||||
}
|
||||
|
||||
h, err := mh.Cast(data[:34])
|
||||
if err != nil {
|
||||
return 0, Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
return 34, Cid{string(h)}, nil
|
||||
}
|
||||
|
||||
vers, n, err := varint.FromUvarint(data)
|
||||
if err != nil {
|
||||
return 0, Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
if vers != 1 {
|
||||
return 0, Undef, ErrInvalidCid{fmt.Errorf("expected 1 as the cid version number, got: %d", vers)}
|
||||
}
|
||||
|
||||
_, cn, err := varint.FromUvarint(data[n:])
|
||||
if err != nil {
|
||||
return 0, Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
mhnr, _, err := mh.MHFromBytes(data[n+cn:])
|
||||
if err != nil {
|
||||
return 0, Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
l := n + cn + mhnr
|
||||
|
||||
return l, Cid{string(data[0:l])}, nil
|
||||
}
|
||||
|
||||
func toBufByteReader(r io.Reader, dst []byte) *bufByteReader {
|
||||
// If the reader already implements ByteReader, use it directly.
|
||||
// Otherwise, use a fallback that does 1-byte Reads.
|
||||
if br, ok := r.(io.ByteReader); ok {
|
||||
return &bufByteReader{direct: br, dst: dst}
|
||||
}
|
||||
return &bufByteReader{fallback: r, dst: dst}
|
||||
}
|
||||
|
||||
type bufByteReader struct {
|
||||
direct io.ByteReader
|
||||
fallback io.Reader
|
||||
|
||||
dst []byte
|
||||
}
|
||||
|
||||
func (r *bufByteReader) ReadByte() (byte, error) {
|
||||
// The underlying reader has ReadByte; use it.
|
||||
if br := r.direct; br != nil {
|
||||
b, err := br.ReadByte()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
r.dst = append(r.dst, b)
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Fall back to a one-byte Read.
|
||||
// TODO: consider reading straight into dst,
|
||||
// once we have benchmarks and if they prove that to be faster.
|
||||
var p [1]byte
|
||||
if _, err := io.ReadFull(r.fallback, p[:]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
r.dst = append(r.dst, p[0])
|
||||
return p[0], nil
|
||||
}
|
||||
|
||||
// CidFromReader reads a precise number of bytes for a CID from a given reader.
|
||||
// It returns the number of bytes read, the CID, and any error encountered.
|
||||
// The number of bytes read is accurate even if a non-nil error is returned.
|
||||
//
|
||||
// It's recommended to supply a reader that buffers and implements io.ByteReader,
|
||||
// as CidFromReader has to do many single-byte reads to decode varints.
|
||||
// If the argument only implements io.Reader, single-byte Read calls are used instead.
|
||||
//
|
||||
// If the Reader is found to yield zero bytes, an io.EOF error is returned directly, in all
|
||||
// other error cases, an ErrInvalidCid, wrapping the original error, is returned.
|
||||
func CidFromReader(r io.Reader) (int, Cid, error) {
|
||||
// 64 bytes is enough for any CIDv0,
|
||||
// and it's enough for most CIDv1s in practice.
|
||||
// If the digest is too long, we'll allocate more.
|
||||
br := toBufByteReader(r, make([]byte, 0, 64))
|
||||
|
||||
// We read the first varint, to tell if this is a CIDv0 or a CIDv1.
|
||||
// The varint package wants a io.ByteReader, so we must wrap our io.Reader.
|
||||
vers, err := varint.ReadUvarint(br)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
// First-byte read in ReadUvarint errors with io.EOF, so reader has no data.
|
||||
// Subsequent reads with an EOF will return io.ErrUnexpectedEOF and be wrapped here.
|
||||
return 0, Undef, err
|
||||
}
|
||||
return len(br.dst), Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
// If we have a CIDv0, read the rest of the bytes and cast the buffer.
|
||||
if vers == mh.SHA2_256 {
|
||||
if n, err := io.ReadFull(r, br.dst[1:34]); err != nil {
|
||||
return len(br.dst) + n, Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
br.dst = br.dst[:34]
|
||||
h, err := mh.Cast(br.dst)
|
||||
if err != nil {
|
||||
return len(br.dst), Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
return len(br.dst), Cid{string(h)}, nil
|
||||
}
|
||||
|
||||
if vers != 1 {
|
||||
return len(br.dst), Undef, ErrInvalidCid{fmt.Errorf("expected 1 as the cid version number, got: %d", vers)}
|
||||
}
|
||||
|
||||
// CID block encoding multicodec.
|
||||
_, err = varint.ReadUvarint(br)
|
||||
if err != nil {
|
||||
return len(br.dst), Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
// We could replace most of the code below with go-multihash's ReadMultihash.
|
||||
// Note that it would save code, but prevent reusing buffers.
|
||||
// Plus, we already have a ByteReader now.
|
||||
mhStart := len(br.dst)
|
||||
|
||||
// Multihash hash function code.
|
||||
_, err = varint.ReadUvarint(br)
|
||||
if err != nil {
|
||||
return len(br.dst), Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
// Multihash digest length.
|
||||
mhl, err := varint.ReadUvarint(br)
|
||||
if err != nil {
|
||||
return len(br.dst), Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
// Refuse to make large allocations to prevent OOMs due to bugs.
|
||||
const maxDigestAlloc = 32 << 20 // 32MiB
|
||||
if mhl > maxDigestAlloc {
|
||||
return len(br.dst), Undef, ErrInvalidCid{fmt.Errorf("refusing to allocate %d bytes for a digest", mhl)}
|
||||
}
|
||||
|
||||
// Fine to convert mhl to int, given maxDigestAlloc.
|
||||
prefixLength := len(br.dst)
|
||||
cidLength := prefixLength + int(mhl)
|
||||
if cidLength > cap(br.dst) {
|
||||
// If the multihash digest doesn't fit in our initial 64 bytes,
|
||||
// efficiently extend the slice via append+make.
|
||||
br.dst = append(br.dst, make([]byte, cidLength-len(br.dst))...)
|
||||
} else {
|
||||
// The multihash digest fits inside our buffer,
|
||||
// so just extend its capacity.
|
||||
br.dst = br.dst[:cidLength]
|
||||
}
|
||||
|
||||
if n, err := io.ReadFull(r, br.dst[prefixLength:cidLength]); err != nil {
|
||||
// We can't use len(br.dst) here,
|
||||
// as we've only read n bytes past prefixLength.
|
||||
return prefixLength + n, Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
// This simply ensures the multihash is valid.
|
||||
// TODO: consider removing this bit, as it's probably redundant;
|
||||
// for now, it helps ensure consistency with CidFromBytes.
|
||||
_, _, err = mh.MHFromBytes(br.dst[mhStart:])
|
||||
if err != nil {
|
||||
return len(br.dst), Undef, ErrInvalidCid{err}
|
||||
}
|
||||
|
||||
return len(br.dst), Cid{string(br.dst)}, nil
|
||||
}
|
||||
36
vendor/github.com/ipfs/go-cid/cid_fuzz.go
generated
vendored
Normal file
36
vendor/github.com/ipfs/go-cid/cid_fuzz.go
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
//go:build gofuzz
|
||||
|
||||
package cid
|
||||
|
||||
func Fuzz(data []byte) int {
|
||||
cid, err := Cast(data)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
_ = cid.Bytes()
|
||||
_ = cid.String()
|
||||
p := cid.Prefix()
|
||||
_ = p.Bytes()
|
||||
|
||||
if !cid.Equals(cid) {
|
||||
panic("inequality")
|
||||
}
|
||||
|
||||
// json loop
|
||||
json, err := cid.MarshalJSON()
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
cid2 := Cid{}
|
||||
err = cid2.UnmarshalJSON(json)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
if !cid.Equals(cid2) {
|
||||
panic("json loop not equal")
|
||||
}
|
||||
|
||||
return 1
|
||||
}
|
||||
3
vendor/github.com/ipfs/go-cid/codecov.yml
generated
vendored
Normal file
3
vendor/github.com/ipfs/go-cid/codecov.yml
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
coverage:
|
||||
range: "50...100"
|
||||
comment: off
|
||||
28
vendor/github.com/ipfs/go-cid/deprecated.go
generated
vendored
Normal file
28
vendor/github.com/ipfs/go-cid/deprecated.go
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
package cid
|
||||
|
||||
import (
|
||||
mh "github.com/multiformats/go-multihash"
|
||||
)
|
||||
|
||||
// NewPrefixV0 returns a CIDv0 prefix with the specified multihash type.
|
||||
// DEPRECATED: Use V0Builder
|
||||
func NewPrefixV0(mhType uint64) Prefix {
|
||||
return Prefix{
|
||||
MhType: mhType,
|
||||
MhLength: mh.DefaultLengths[mhType],
|
||||
Version: 0,
|
||||
Codec: DagProtobuf,
|
||||
}
|
||||
}
|
||||
|
||||
// NewPrefixV1 returns a CIDv1 prefix with the specified codec and multihash
|
||||
// type.
|
||||
// DEPRECATED: Use V1Builder
|
||||
func NewPrefixV1(codecType uint64, mhType uint64) Prefix {
|
||||
return Prefix{
|
||||
MhType: mhType,
|
||||
MhLength: mh.DefaultLengths[mhType],
|
||||
Version: 1,
|
||||
Codec: codecType,
|
||||
}
|
||||
}
|
||||
65
vendor/github.com/ipfs/go-cid/set.go
generated
vendored
Normal file
65
vendor/github.com/ipfs/go-cid/set.go
generated
vendored
Normal file
@@ -0,0 +1,65 @@
|
||||
package cid
|
||||
|
||||
// Set is a implementation of a set of Cids, that is, a structure
|
||||
// to which holds a single copy of every Cids that is added to it.
|
||||
type Set struct {
|
||||
set map[Cid]struct{}
|
||||
}
|
||||
|
||||
// NewSet initializes and returns a new Set.
|
||||
func NewSet() *Set {
|
||||
return &Set{set: make(map[Cid]struct{})}
|
||||
}
|
||||
|
||||
// Add puts a Cid in the Set.
|
||||
func (s *Set) Add(c Cid) {
|
||||
s.set[c] = struct{}{}
|
||||
}
|
||||
|
||||
// Has returns if the Set contains a given Cid.
|
||||
func (s *Set) Has(c Cid) bool {
|
||||
_, ok := s.set[c]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Remove deletes a Cid from the Set.
|
||||
func (s *Set) Remove(c Cid) {
|
||||
delete(s.set, c)
|
||||
}
|
||||
|
||||
// Len returns how many elements the Set has.
|
||||
func (s *Set) Len() int {
|
||||
return len(s.set)
|
||||
}
|
||||
|
||||
// Keys returns the Cids in the set.
|
||||
func (s *Set) Keys() []Cid {
|
||||
out := make([]Cid, 0, len(s.set))
|
||||
for k := range s.set {
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Visit adds a Cid to the set only if it is
|
||||
// not in it already.
|
||||
func (s *Set) Visit(c Cid) bool {
|
||||
if !s.Has(c) {
|
||||
s.Add(c)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// ForEach allows to run a custom function on each
|
||||
// Cid in the set.
|
||||
func (s *Set) ForEach(f func(c Cid) error) error {
|
||||
for c := range s.set {
|
||||
err := f(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
37
vendor/github.com/ipfs/go-cid/varint.go
generated
vendored
Normal file
37
vendor/github.com/ipfs/go-cid/varint.go
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
package cid
|
||||
|
||||
import (
|
||||
"github.com/multiformats/go-varint"
|
||||
)
|
||||
|
||||
// Version of varint function that works with a string rather than
|
||||
// []byte to avoid unnecessary allocation
|
||||
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license as given at https://golang.org/LICENSE
|
||||
|
||||
// uvarint decodes a uint64 from buf and returns that value and the
|
||||
// number of bytes read (> 0). If an error occurred, then 0 is
|
||||
// returned for both the value and the number of bytes read, and an
|
||||
// error is returned.
|
||||
func uvarint(buf string) (uint64, int, error) {
|
||||
var x uint64
|
||||
var s uint
|
||||
// we have a binary string so we can't use a range loop
|
||||
for i := 0; i < len(buf); i++ {
|
||||
b := buf[i]
|
||||
if b < 0x80 {
|
||||
if i > 9 || i == 9 && b > 1 {
|
||||
return 0, 0, varint.ErrOverflow
|
||||
}
|
||||
if b == 0 && i > 0 {
|
||||
return 0, 0, varint.ErrNotMinimal
|
||||
}
|
||||
return x | uint64(b)<<s, i + 1, nil
|
||||
}
|
||||
x |= uint64(b&0x7f) << s
|
||||
s += 7
|
||||
}
|
||||
return 0, 0, varint.ErrUnderflow
|
||||
}
|
||||
3
vendor/github.com/ipfs/go-cid/version.json
generated
vendored
Normal file
3
vendor/github.com/ipfs/go-cid/version.json
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"version": "v0.4.1"
|
||||
}
|
||||
21
vendor/github.com/ipfs/go-log/v2/LICENSE
generated
vendored
Normal file
21
vendor/github.com/ipfs/go-log/v2/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Juan Batiz-Benet
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
137
vendor/github.com/ipfs/go-log/v2/README.md
generated
vendored
Normal file
137
vendor/github.com/ipfs/go-log/v2/README.md
generated
vendored
Normal file
@@ -0,0 +1,137 @@
|
||||
# go-log
|
||||
|
||||
[](https://protocol.ai)
|
||||
[](https://ipfs.io/)
|
||||
[](https://pkg.go.dev/github.com/ipfs/go-log/v2)
|
||||
|
||||
> The logging library used by go-ipfs
|
||||
|
||||
go-log wraps [zap](https://github.com/uber-go/zap) to provide a logging facade. go-log manages logging
|
||||
instances and allows for their levels to be controlled individually.
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
go get github.com/ipfs/go-log
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Once the package is imported under the name `logging`, an instance of `EventLogger` can be created like so:
|
||||
|
||||
```go
|
||||
var log = logging.Logger("subsystem name")
|
||||
```
|
||||
|
||||
It can then be used to emit log messages in plain printf-style messages at seven standard levels:
|
||||
|
||||
Levels may be set for all loggers:
|
||||
|
||||
```go
|
||||
lvl, err := logging.LevelFromString("error")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
logging.SetAllLoggers(lvl)
|
||||
```
|
||||
|
||||
or individually:
|
||||
|
||||
```go
|
||||
err := logging.SetLogLevel("net:pubsub", "info")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
```
|
||||
|
||||
or by regular expression:
|
||||
|
||||
```go
|
||||
err := logging.SetLogLevelRegex("net:.*", "info")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
This package can be configured through various environment variables.
|
||||
|
||||
#### `GOLOG_LOG_LEVEL`
|
||||
|
||||
Specifies the log-level, both globally and on a per-subsystem basis.
|
||||
|
||||
For example, the following will set the global minimum log level to `error`, but reduce the minimum
|
||||
log level for `subsystem1` to `info` and reduce the minimum log level for `subsystem2` to debug.
|
||||
|
||||
```bash
|
||||
export GOLOG_LOG_LEVEL="error,subsystem1=info,subsystem2=debug"
|
||||
```
|
||||
|
||||
`IPFS_LOGGING` is a deprecated alias for this environment variable.
|
||||
|
||||
#### `GOLOG_FILE`
|
||||
|
||||
Specifies that logs should be written to the specified file. If this option is _not_ specified, logs are written to standard error.
|
||||
|
||||
```bash
|
||||
export GOLOG_FILE="/path/to/my/file.log"
|
||||
```
|
||||
|
||||
#### `GOLOG_OUTPUT`
|
||||
|
||||
Specifies where logging output should be written. Can take one or more of the following values, combined with `+`:
|
||||
|
||||
- `stdout` -- write logs to standard out.
|
||||
- `stderr` -- write logs to standard error.
|
||||
- `file` -- write logs to the file specified by `GOLOG_FILE`
|
||||
|
||||
For example, if you want to log to both a file and standard error:
|
||||
|
||||
```bash
|
||||
export GOLOG_FILE="/path/to/my/file.log"
|
||||
export GOLOG_OUTPUT="stderr+file"
|
||||
```
|
||||
|
||||
Setting _only_ `GOLOG_FILE` will prevent logs from being written to standard error.
|
||||
|
||||
#### `GOLOG_LOG_FMT`
|
||||
|
||||
Specifies the log message format. It supports the following values:
|
||||
|
||||
- `color` -- human readable, colorized (ANSI) output
|
||||
- `nocolor` -- human readable, plain-text output.
|
||||
- `json` -- structured JSON.
|
||||
|
||||
For example, to log structured JSON (for easier parsing):
|
||||
|
||||
```bash
|
||||
export GOLOG_LOG_FMT="json"
|
||||
```
|
||||
|
||||
The logging format defaults to `color` when the output is a terminal, and `nocolor` otherwise.
|
||||
|
||||
`IPFS_LOGGING_FMT` is a deprecated alias for this environment variable.
|
||||
|
||||
#### `GOLOG_LOG_LABELS`
|
||||
|
||||
Specifies a set of labels that should be added to all log messages as comma-separated key-value
|
||||
pairs. For example, the following add `{"app": "example_app", "dc": "sjc-1"}` to every log entry.
|
||||
|
||||
```bash
|
||||
export GOLOG_LOG_LABELS="app=example_app,dc=sjc-1"
|
||||
```
|
||||
|
||||
## Contribute
|
||||
|
||||
Feel free to join in. All welcome. Open an [issue](https://github.com/ipfs/go-log/issues)!
|
||||
|
||||
This repository falls under the IPFS [Code of Conduct](https://github.com/ipfs/community/blob/master/code-of-conduct.md).
|
||||
|
||||
### Want to hack on IPFS?
|
||||
|
||||
[](https://github.com/ipfs/community/blob/master/CONTRIBUTING.md)
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
121
vendor/github.com/ipfs/go-log/v2/core.go
generated
vendored
Normal file
121
vendor/github.com/ipfs/go-log/v2/core.go
generated
vendored
Normal file
@@ -0,0 +1,121 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"go.uber.org/multierr"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
var _ zapcore.Core = (*lockedMultiCore)(nil)
|
||||
|
||||
type lockedMultiCore struct {
|
||||
mu sync.RWMutex // guards mutations to cores slice
|
||||
cores []zapcore.Core
|
||||
}
|
||||
|
||||
func (l *lockedMultiCore) With(fields []zapcore.Field) zapcore.Core {
|
||||
l.mu.RLock()
|
||||
defer l.mu.RUnlock()
|
||||
sub := &lockedMultiCore{
|
||||
cores: make([]zapcore.Core, len(l.cores)),
|
||||
}
|
||||
for i := range l.cores {
|
||||
sub.cores[i] = l.cores[i].With(fields)
|
||||
}
|
||||
return sub
|
||||
}
|
||||
|
||||
func (l *lockedMultiCore) Enabled(lvl zapcore.Level) bool {
|
||||
l.mu.RLock()
|
||||
defer l.mu.RUnlock()
|
||||
for i := range l.cores {
|
||||
if l.cores[i].Enabled(lvl) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (l *lockedMultiCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
|
||||
l.mu.RLock()
|
||||
defer l.mu.RUnlock()
|
||||
for i := range l.cores {
|
||||
ce = l.cores[i].Check(ent, ce)
|
||||
}
|
||||
return ce
|
||||
}
|
||||
|
||||
func (l *lockedMultiCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {
|
||||
l.mu.RLock()
|
||||
defer l.mu.RUnlock()
|
||||
var err error
|
||||
for i := range l.cores {
|
||||
err = multierr.Append(err, l.cores[i].Write(ent, fields))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *lockedMultiCore) Sync() error {
|
||||
l.mu.RLock()
|
||||
defer l.mu.RUnlock()
|
||||
var err error
|
||||
for i := range l.cores {
|
||||
err = multierr.Append(err, l.cores[i].Sync())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *lockedMultiCore) AddCore(core zapcore.Core) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
l.cores = append(l.cores, core)
|
||||
}
|
||||
|
||||
func (l *lockedMultiCore) DeleteCore(core zapcore.Core) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
w := 0
|
||||
for i := 0; i < len(l.cores); i++ {
|
||||
if reflect.DeepEqual(l.cores[i], core) {
|
||||
continue
|
||||
}
|
||||
l.cores[w] = l.cores[i]
|
||||
w++
|
||||
}
|
||||
l.cores = l.cores[:w]
|
||||
}
|
||||
|
||||
func (l *lockedMultiCore) ReplaceCore(original, replacement zapcore.Core) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
for i := 0; i < len(l.cores); i++ {
|
||||
if reflect.DeepEqual(l.cores[i], original) {
|
||||
l.cores[i] = replacement
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newCore(format LogFormat, ws zapcore.WriteSyncer, level LogLevel) zapcore.Core {
|
||||
encCfg := zap.NewProductionEncoderConfig()
|
||||
encCfg.EncodeTime = zapcore.ISO8601TimeEncoder
|
||||
|
||||
var encoder zapcore.Encoder
|
||||
switch format {
|
||||
case PlaintextOutput:
|
||||
encCfg.EncodeLevel = zapcore.CapitalLevelEncoder
|
||||
encoder = zapcore.NewConsoleEncoder(encCfg)
|
||||
case JSONOutput:
|
||||
encoder = zapcore.NewJSONEncoder(encCfg)
|
||||
default:
|
||||
encCfg.EncodeLevel = zapcore.CapitalColorLevelEncoder
|
||||
encoder = zapcore.NewConsoleEncoder(encCfg)
|
||||
}
|
||||
|
||||
return zapcore.NewCore(encoder, ws, zap.NewAtomicLevelAt(zapcore.Level(level)))
|
||||
}
|
||||
30
vendor/github.com/ipfs/go-log/v2/levels.go
generated
vendored
Normal file
30
vendor/github.com/ipfs/go-log/v2/levels.go
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
package log
|
||||
|
||||
import "go.uber.org/zap/zapcore"
|
||||
|
||||
// LogLevel represents a log severity level. Use the package variables as an
|
||||
// enum.
|
||||
type LogLevel zapcore.Level
|
||||
|
||||
var (
|
||||
LevelDebug = LogLevel(zapcore.DebugLevel)
|
||||
LevelInfo = LogLevel(zapcore.InfoLevel)
|
||||
LevelWarn = LogLevel(zapcore.WarnLevel)
|
||||
LevelError = LogLevel(zapcore.ErrorLevel)
|
||||
LevelDPanic = LogLevel(zapcore.DPanicLevel)
|
||||
LevelPanic = LogLevel(zapcore.PanicLevel)
|
||||
LevelFatal = LogLevel(zapcore.FatalLevel)
|
||||
)
|
||||
|
||||
// LevelFromString parses a string-based level and returns the corresponding
|
||||
// LogLevel.
|
||||
//
|
||||
// Supported strings are: DEBUG, INFO, WARN, ERROR, DPANIC, PANIC, FATAL, and
|
||||
// their lower-case forms.
|
||||
//
|
||||
// The returned LogLevel must be discarded if error is not nil.
|
||||
func LevelFromString(level string) (LogLevel, error) {
|
||||
lvl := zapcore.InfoLevel // zero value
|
||||
err := lvl.Set(level)
|
||||
return LogLevel(lvl), err
|
||||
}
|
||||
94
vendor/github.com/ipfs/go-log/v2/log.go
generated
vendored
Normal file
94
vendor/github.com/ipfs/go-log/v2/log.go
generated
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
// Package log is the logging library used by IPFS & libp2p
|
||||
// (https://github.com/ipfs/go-ipfs).
|
||||
package log
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// StandardLogger provides API compatibility with standard printf loggers
|
||||
// eg. go-logging
|
||||
type StandardLogger interface {
|
||||
Debug(args ...interface{})
|
||||
Debugf(format string, args ...interface{})
|
||||
Error(args ...interface{})
|
||||
Errorf(format string, args ...interface{})
|
||||
Fatal(args ...interface{})
|
||||
Fatalf(format string, args ...interface{})
|
||||
Info(args ...interface{})
|
||||
Infof(format string, args ...interface{})
|
||||
Panic(args ...interface{})
|
||||
Panicf(format string, args ...interface{})
|
||||
Warn(args ...interface{})
|
||||
Warnf(format string, args ...interface{})
|
||||
}
|
||||
|
||||
// EventLogger extends the StandardLogger interface to allow for log items
|
||||
// containing structured metadata
|
||||
type EventLogger interface {
|
||||
StandardLogger
|
||||
}
|
||||
|
||||
// Logger retrieves an event logger by name
|
||||
func Logger(system string) *ZapEventLogger {
|
||||
if len(system) == 0 {
|
||||
setuplog := getLogger("setup-logger")
|
||||
setuplog.Error("Missing name parameter")
|
||||
system = "undefined"
|
||||
}
|
||||
|
||||
logger := getLogger(system)
|
||||
skipLogger := logger.Desugar().WithOptions(zap.AddCallerSkip(1)).Sugar()
|
||||
|
||||
return &ZapEventLogger{
|
||||
system: system,
|
||||
SugaredLogger: *logger,
|
||||
skipLogger: *skipLogger,
|
||||
}
|
||||
}
|
||||
|
||||
// ZapEventLogger implements the EventLogger and wraps a go-logging Logger
|
||||
type ZapEventLogger struct {
|
||||
zap.SugaredLogger
|
||||
// used to fix the caller location when calling Warning and Warningf.
|
||||
skipLogger zap.SugaredLogger
|
||||
system string
|
||||
}
|
||||
|
||||
// Warning is for compatibility
|
||||
// Deprecated: use Warn(args ...interface{}) instead
|
||||
func (logger *ZapEventLogger) Warning(args ...interface{}) {
|
||||
logger.skipLogger.Warn(args...)
|
||||
}
|
||||
|
||||
// Warningf is for compatibility
|
||||
// Deprecated: use Warnf(format string, args ...interface{}) instead
|
||||
func (logger *ZapEventLogger) Warningf(format string, args ...interface{}) {
|
||||
logger.skipLogger.Warnf(format, args...)
|
||||
}
|
||||
|
||||
// FormatRFC3339 returns the given time in UTC with RFC3999Nano format.
|
||||
func FormatRFC3339(t time.Time) string {
|
||||
return t.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
|
||||
func WithStacktrace(l *ZapEventLogger, level LogLevel) *ZapEventLogger {
|
||||
copyLogger := *l
|
||||
copyLogger.SugaredLogger = *copyLogger.SugaredLogger.Desugar().
|
||||
WithOptions(zap.AddStacktrace(zapcore.Level(level))).Sugar()
|
||||
copyLogger.skipLogger = *copyLogger.SugaredLogger.Desugar().WithOptions(zap.AddCallerSkip(1)).Sugar()
|
||||
return ©Logger
|
||||
}
|
||||
|
||||
// WithSkip returns a new logger that skips the specified number of stack frames when reporting the
|
||||
// line/file.
|
||||
func WithSkip(l *ZapEventLogger, skip int) *ZapEventLogger {
|
||||
copyLogger := *l
|
||||
copyLogger.SugaredLogger = *copyLogger.SugaredLogger.Desugar().
|
||||
WithOptions(zap.AddCallerSkip(skip)).Sugar()
|
||||
copyLogger.skipLogger = *copyLogger.SugaredLogger.Desugar().WithOptions(zap.AddCallerSkip(1)).Sugar()
|
||||
return ©Logger
|
||||
}
|
||||
12
vendor/github.com/ipfs/go-log/v2/path_other.go
generated
vendored
Normal file
12
vendor/github.com/ipfs/go-log/v2/path_other.go
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package log
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func normalizePath(p string) (string, error) {
|
||||
return filepath.Abs(p)
|
||||
}
|
||||
36
vendor/github.com/ipfs/go-log/v2/path_windows.go
generated
vendored
Normal file
36
vendor/github.com/ipfs/go-log/v2/path_windows.go
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package log
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func normalizePath(p string) (string, error) {
|
||||
if p == "" {
|
||||
return "", fmt.Errorf("path empty")
|
||||
}
|
||||
p, err := filepath.Abs(p)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Is this _really_ an absolute path?
|
||||
if !strings.HasPrefix(p, "\\\\") {
|
||||
// It's a drive: path!
|
||||
// Return a UNC path.
|
||||
p = "\\\\%3F\\" + p
|
||||
}
|
||||
|
||||
// This will return file:////?/c:/foobar
|
||||
//
|
||||
// Why? Because:
|
||||
// 1. Go will choke on file://c:/ because the "domain" includes a :.
|
||||
// 2. Windows will choke on file:///c:/ because the path will be
|
||||
// /c:/... which is _relative_ to the current drive.
|
||||
//
|
||||
// This path (a) has no "domain" and (b) starts with a slash. Yay!
|
||||
return "file://" + filepath.ToSlash(p), nil
|
||||
}
|
||||
90
vendor/github.com/ipfs/go-log/v2/pipe.go
generated
vendored
Normal file
90
vendor/github.com/ipfs/go-log/v2/pipe.go
generated
vendored
Normal file
@@ -0,0 +1,90 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"go.uber.org/multierr"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// A PipeReader is a reader that reads from the logger. It is synchronous
|
||||
// so blocking on read will affect logging performance.
|
||||
type PipeReader struct {
|
||||
r *io.PipeReader
|
||||
closer io.Closer
|
||||
core zapcore.Core
|
||||
}
|
||||
|
||||
// Read implements the standard Read interface
|
||||
func (p *PipeReader) Read(data []byte) (int, error) {
|
||||
return p.r.Read(data)
|
||||
}
|
||||
|
||||
// Close unregisters the reader from the logger.
|
||||
func (p *PipeReader) Close() error {
|
||||
if p.core != nil {
|
||||
loggerCore.DeleteCore(p.core)
|
||||
}
|
||||
return multierr.Append(p.core.Sync(), p.closer.Close())
|
||||
}
|
||||
|
||||
// NewPipeReader creates a new in-memory reader that reads from all loggers
|
||||
// The caller must call Close on the returned reader when done.
|
||||
//
|
||||
// By default, it:
|
||||
//
|
||||
// 1. Logs JSON. This can be changed by passing the PipeFormat option.
|
||||
// 2. Logs everything that would otherwise be logged to the "primary" log
|
||||
// output. That is, everything enabled by SetLogLevel. The minimum log level
|
||||
// can be increased by passing the PipeLevel option.
|
||||
func NewPipeReader(opts ...PipeReaderOption) *PipeReader {
|
||||
opt := pipeReaderOptions{
|
||||
format: JSONOutput,
|
||||
level: LevelDebug,
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
o.setOption(&opt)
|
||||
}
|
||||
|
||||
r, w := io.Pipe()
|
||||
|
||||
p := &PipeReader{
|
||||
r: r,
|
||||
closer: w,
|
||||
core: newCore(opt.format, zapcore.AddSync(w), opt.level),
|
||||
}
|
||||
|
||||
loggerCore.AddCore(p.core)
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
type pipeReaderOptions struct {
|
||||
format LogFormat
|
||||
level LogLevel
|
||||
}
|
||||
|
||||
type PipeReaderOption interface {
|
||||
setOption(*pipeReaderOptions)
|
||||
}
|
||||
|
||||
type pipeReaderOptionFunc func(*pipeReaderOptions)
|
||||
|
||||
func (p pipeReaderOptionFunc) setOption(o *pipeReaderOptions) {
|
||||
p(o)
|
||||
}
|
||||
|
||||
// PipeFormat sets the output format of the pipe reader
|
||||
func PipeFormat(format LogFormat) PipeReaderOption {
|
||||
return pipeReaderOptionFunc(func(o *pipeReaderOptions) {
|
||||
o.format = format
|
||||
})
|
||||
}
|
||||
|
||||
// PipeLevel sets the log level of logs sent to the pipe reader.
|
||||
func PipeLevel(level LogLevel) PipeReaderOption {
|
||||
return pipeReaderOptionFunc(func(o *pipeReaderOptions) {
|
||||
o.level = level
|
||||
})
|
||||
}
|
||||
400
vendor/github.com/ipfs/go-log/v2/setup.go
generated
vendored
Normal file
400
vendor/github.com/ipfs/go-log/v2/setup.go
generated
vendored
Normal file
@@ -0,0 +1,400 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/mattn/go-isatty"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
var config Config
|
||||
|
||||
func init() {
|
||||
SetupLogging(configFromEnv())
|
||||
}
|
||||
|
||||
// Logging environment variables
|
||||
const (
|
||||
// IPFS_* prefixed env vars kept for backwards compatibility
|
||||
// for this release. They will not be available in the next
|
||||
// release.
|
||||
//
|
||||
// GOLOG_* env vars take precedences over IPFS_* env vars.
|
||||
envIPFSLogging = "IPFS_LOGGING"
|
||||
envIPFSLoggingFmt = "IPFS_LOGGING_FMT"
|
||||
|
||||
envLogging = "GOLOG_LOG_LEVEL"
|
||||
envLoggingFmt = "GOLOG_LOG_FMT"
|
||||
|
||||
envLoggingFile = "GOLOG_FILE" // /path/to/file
|
||||
envLoggingURL = "GOLOG_URL" // url that will be processed by sink in the zap
|
||||
|
||||
envLoggingOutput = "GOLOG_OUTPUT" // possible values: stdout|stderr|file combine multiple values with '+'
|
||||
envLoggingLabels = "GOLOG_LOG_LABELS" // comma-separated key-value pairs, i.e. "app=example_app,dc=sjc-1"
|
||||
)
|
||||
|
||||
type LogFormat int
|
||||
|
||||
const (
|
||||
ColorizedOutput LogFormat = iota
|
||||
PlaintextOutput
|
||||
JSONOutput
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
// Format overrides the format of the log output. Defaults to ColorizedOutput
|
||||
Format LogFormat
|
||||
|
||||
// Level is the default minimum enabled logging level.
|
||||
Level LogLevel
|
||||
|
||||
// SubsystemLevels are the default levels per-subsystem. When unspecified, defaults to Level.
|
||||
SubsystemLevels map[string]LogLevel
|
||||
|
||||
// Stderr indicates whether logs should be written to stderr.
|
||||
Stderr bool
|
||||
|
||||
// Stdout indicates whether logs should be written to stdout.
|
||||
Stdout bool
|
||||
|
||||
// File is a path to a file that logs will be written to.
|
||||
File string
|
||||
|
||||
// URL with schema supported by zap. Use zap.RegisterSink
|
||||
URL string
|
||||
|
||||
// Labels is a set of key-values to apply to all loggers
|
||||
Labels map[string]string
|
||||
}
|
||||
|
||||
// ErrNoSuchLogger is returned when the util pkg is asked for a non existant logger
|
||||
var ErrNoSuchLogger = errors.New("error: No such logger")
|
||||
|
||||
var loggerMutex sync.RWMutex // guards access to global logger state
|
||||
|
||||
// loggers is the set of loggers in the system
|
||||
var loggers = make(map[string]*zap.SugaredLogger)
|
||||
var levels = make(map[string]zap.AtomicLevel)
|
||||
|
||||
// primaryFormat is the format of the primary core used for logging
|
||||
var primaryFormat LogFormat = ColorizedOutput
|
||||
|
||||
// defaultLevel is the default log level
|
||||
var defaultLevel LogLevel = LevelError
|
||||
|
||||
// primaryCore is the primary logging core
|
||||
var primaryCore zapcore.Core
|
||||
|
||||
// loggerCore is the base for all loggers created by this package
|
||||
var loggerCore = &lockedMultiCore{}
|
||||
|
||||
// GetConfig returns a copy of the saved config. It can be inspected, modified,
|
||||
// and re-applied using a subsequent call to SetupLogging().
|
||||
func GetConfig() Config {
|
||||
return config
|
||||
}
|
||||
|
||||
// SetupLogging will initialize the logger backend and set the flags.
|
||||
// TODO calling this in `init` pushes all configuration to env variables
|
||||
// - move it out of `init`? then we need to change all the code (js-ipfs, go-ipfs) to call this explicitly
|
||||
// - have it look for a config file? need to define what that is
|
||||
func SetupLogging(cfg Config) {
|
||||
loggerMutex.Lock()
|
||||
defer loggerMutex.Unlock()
|
||||
|
||||
config = cfg
|
||||
|
||||
primaryFormat = cfg.Format
|
||||
defaultLevel = cfg.Level
|
||||
|
||||
outputPaths := []string{}
|
||||
|
||||
if cfg.Stderr {
|
||||
outputPaths = append(outputPaths, "stderr")
|
||||
}
|
||||
if cfg.Stdout {
|
||||
outputPaths = append(outputPaths, "stdout")
|
||||
}
|
||||
|
||||
// check if we log to a file
|
||||
if len(cfg.File) > 0 {
|
||||
if path, err := normalizePath(cfg.File); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "failed to resolve log path '%q', logging to %s\n", cfg.File, outputPaths)
|
||||
} else {
|
||||
outputPaths = append(outputPaths, path)
|
||||
}
|
||||
}
|
||||
if len(cfg.URL) > 0 {
|
||||
outputPaths = append(outputPaths, cfg.URL)
|
||||
}
|
||||
|
||||
ws, _, err := zap.Open(outputPaths...)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("unable to open logging output: %v", err))
|
||||
}
|
||||
|
||||
newPrimaryCore := newCore(primaryFormat, ws, LevelDebug) // the main core needs to log everything.
|
||||
|
||||
for k, v := range cfg.Labels {
|
||||
newPrimaryCore = newPrimaryCore.With([]zap.Field{zap.String(k, v)})
|
||||
}
|
||||
|
||||
setPrimaryCore(newPrimaryCore)
|
||||
setAllLoggers(defaultLevel)
|
||||
|
||||
for name, level := range cfg.SubsystemLevels {
|
||||
if leveler, ok := levels[name]; ok {
|
||||
leveler.SetLevel(zapcore.Level(level))
|
||||
} else {
|
||||
levels[name] = zap.NewAtomicLevelAt(zapcore.Level(level))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SetPrimaryCore changes the primary logging core. If the SetupLogging was
|
||||
// called then the previously configured core will be replaced.
|
||||
func SetPrimaryCore(core zapcore.Core) {
|
||||
loggerMutex.Lock()
|
||||
defer loggerMutex.Unlock()
|
||||
|
||||
setPrimaryCore(core)
|
||||
}
|
||||
|
||||
func setPrimaryCore(core zapcore.Core) {
|
||||
if primaryCore != nil {
|
||||
loggerCore.ReplaceCore(primaryCore, core)
|
||||
} else {
|
||||
loggerCore.AddCore(core)
|
||||
}
|
||||
primaryCore = core
|
||||
}
|
||||
|
||||
// SetDebugLogging calls SetAllLoggers with logging.DEBUG
|
||||
func SetDebugLogging() {
|
||||
SetAllLoggers(LevelDebug)
|
||||
}
|
||||
|
||||
// SetAllLoggers changes the logging level of all loggers to lvl
|
||||
func SetAllLoggers(lvl LogLevel) {
|
||||
loggerMutex.RLock()
|
||||
defer loggerMutex.RUnlock()
|
||||
|
||||
setAllLoggers(lvl)
|
||||
}
|
||||
|
||||
func setAllLoggers(lvl LogLevel) {
|
||||
for _, l := range levels {
|
||||
l.SetLevel(zapcore.Level(lvl))
|
||||
}
|
||||
}
|
||||
|
||||
// SetLogLevel changes the log level of a specific subsystem
|
||||
// name=="*" changes all subsystems
|
||||
func SetLogLevel(name, level string) error {
|
||||
lvl, err := LevelFromString(level)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// wildcard, change all
|
||||
if name == "*" {
|
||||
SetAllLoggers(lvl)
|
||||
return nil
|
||||
}
|
||||
|
||||
loggerMutex.RLock()
|
||||
defer loggerMutex.RUnlock()
|
||||
|
||||
// Check if we have a logger by that name
|
||||
if _, ok := levels[name]; !ok {
|
||||
return ErrNoSuchLogger
|
||||
}
|
||||
|
||||
levels[name].SetLevel(zapcore.Level(lvl))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetLogLevelRegex sets all loggers to level `l` that match expression `e`.
|
||||
// An error is returned if `e` fails to compile.
|
||||
func SetLogLevelRegex(e, l string) error {
|
||||
lvl, err := LevelFromString(l)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rem, err := regexp.Compile(e)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
loggerMutex.Lock()
|
||||
defer loggerMutex.Unlock()
|
||||
for name := range loggers {
|
||||
if rem.MatchString(name) {
|
||||
levels[name].SetLevel(zapcore.Level(lvl))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSubsystems returns a slice containing the
|
||||
// names of the current loggers
|
||||
func GetSubsystems() []string {
|
||||
loggerMutex.RLock()
|
||||
defer loggerMutex.RUnlock()
|
||||
subs := make([]string, 0, len(loggers))
|
||||
|
||||
for k := range loggers {
|
||||
subs = append(subs, k)
|
||||
}
|
||||
return subs
|
||||
}
|
||||
|
||||
func getLogger(name string) *zap.SugaredLogger {
|
||||
loggerMutex.Lock()
|
||||
defer loggerMutex.Unlock()
|
||||
log, ok := loggers[name]
|
||||
if !ok {
|
||||
level, ok := levels[name]
|
||||
if !ok {
|
||||
level = zap.NewAtomicLevelAt(zapcore.Level(defaultLevel))
|
||||
levels[name] = level
|
||||
}
|
||||
log = zap.New(loggerCore).
|
||||
WithOptions(
|
||||
zap.IncreaseLevel(level),
|
||||
zap.AddCaller(),
|
||||
).
|
||||
Named(name).
|
||||
Sugar()
|
||||
|
||||
loggers[name] = log
|
||||
}
|
||||
|
||||
return log
|
||||
}
|
||||
|
||||
// configFromEnv returns a Config with defaults populated using environment variables.
|
||||
func configFromEnv() Config {
|
||||
cfg := Config{
|
||||
Format: ColorizedOutput,
|
||||
Stderr: true,
|
||||
Level: LevelError,
|
||||
SubsystemLevels: map[string]LogLevel{},
|
||||
Labels: map[string]string{},
|
||||
}
|
||||
|
||||
format := os.Getenv(envLoggingFmt)
|
||||
if format == "" {
|
||||
format = os.Getenv(envIPFSLoggingFmt)
|
||||
}
|
||||
|
||||
var noExplicitFormat bool
|
||||
|
||||
switch format {
|
||||
case "color":
|
||||
cfg.Format = ColorizedOutput
|
||||
case "nocolor":
|
||||
cfg.Format = PlaintextOutput
|
||||
case "json":
|
||||
cfg.Format = JSONOutput
|
||||
default:
|
||||
if format != "" {
|
||||
fmt.Fprintf(os.Stderr, "ignoring unrecognized log format '%s'\n", format)
|
||||
}
|
||||
noExplicitFormat = true
|
||||
}
|
||||
|
||||
lvl := os.Getenv(envLogging)
|
||||
if lvl == "" {
|
||||
lvl = os.Getenv(envIPFSLogging)
|
||||
}
|
||||
if lvl != "" {
|
||||
for _, kvs := range strings.Split(lvl, ",") {
|
||||
kv := strings.SplitN(kvs, "=", 2)
|
||||
lvl, err := LevelFromString(kv[len(kv)-1])
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error setting log level %q: %s\n", kvs, err)
|
||||
continue
|
||||
}
|
||||
switch len(kv) {
|
||||
case 1:
|
||||
cfg.Level = lvl
|
||||
case 2:
|
||||
cfg.SubsystemLevels[kv[0]] = lvl
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cfg.File = os.Getenv(envLoggingFile)
|
||||
// Disable stderr logging when a file is specified
|
||||
// https://github.com/ipfs/go-log/issues/83
|
||||
if cfg.File != "" {
|
||||
cfg.Stderr = false
|
||||
}
|
||||
|
||||
cfg.URL = os.Getenv(envLoggingURL)
|
||||
output := os.Getenv(envLoggingOutput)
|
||||
outputOptions := strings.Split(output, "+")
|
||||
for _, opt := range outputOptions {
|
||||
switch opt {
|
||||
case "stdout":
|
||||
cfg.Stdout = true
|
||||
case "stderr":
|
||||
cfg.Stderr = true
|
||||
case "file":
|
||||
if cfg.File == "" {
|
||||
fmt.Fprint(os.Stderr, "please specify a GOLOG_FILE value to write to")
|
||||
}
|
||||
case "url":
|
||||
if cfg.URL == "" {
|
||||
fmt.Fprint(os.Stderr, "please specify a GOLOG_URL value to write to")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check that neither of the requested Std* nor the file are TTYs
|
||||
// At this stage (configFromEnv) we do not have a uniform list to examine yet
|
||||
if noExplicitFormat &&
|
||||
!(cfg.Stdout && isTerm(os.Stdout)) &&
|
||||
!(cfg.Stderr && isTerm(os.Stderr)) &&
|
||||
// check this last: expensive
|
||||
!(cfg.File != "" && pathIsTerm(cfg.File)) {
|
||||
cfg.Format = PlaintextOutput
|
||||
}
|
||||
|
||||
labels := os.Getenv(envLoggingLabels)
|
||||
if labels != "" {
|
||||
labelKVs := strings.Split(labels, ",")
|
||||
for _, label := range labelKVs {
|
||||
kv := strings.Split(label, "=")
|
||||
if len(kv) != 2 {
|
||||
fmt.Fprint(os.Stderr, "invalid label k=v: ", label)
|
||||
continue
|
||||
}
|
||||
cfg.Labels[kv[0]] = kv[1]
|
||||
}
|
||||
}
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
func isTerm(f *os.File) bool {
|
||||
return isatty.IsTerminal(f.Fd()) || isatty.IsCygwinTerminal(f.Fd())
|
||||
}
|
||||
|
||||
func pathIsTerm(p string) bool {
|
||||
// !!!no!!! O_CREAT, if we fail - we fail
|
||||
f, err := os.OpenFile(p, os.O_WRONLY, 0)
|
||||
if f != nil {
|
||||
defer f.Close() // nolint:errcheck
|
||||
}
|
||||
return err == nil && isTerm(f)
|
||||
}
|
||||
3
vendor/github.com/ipfs/go-log/v2/version.json
generated
vendored
Normal file
3
vendor/github.com/ipfs/go-log/v2/version.json
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"version": "v2.5.0"
|
||||
}
|
||||
Reference in New Issue
Block a user