repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
gobuffalo/pop | connection.go | Open | func (c *Connection) Open() error {
if c.Store != nil {
return nil
}
if c.Dialect == nil {
return errors.New("invalid connection instance")
}
details := c.Dialect.Details()
db, err := sqlx.Open(details.Dialect, c.Dialect.URL())
if err != nil {
return errors.Wrap(err, "could not open database connection")
}
db.SetMaxOpenConns(details.Pool)
db.SetMaxIdleConns(details.IdlePool)
c.Store = &dB{db}
if d, ok := c.Dialect.(afterOpenable); ok {
err = d.AfterOpen(c)
if err != nil {
c.Store = nil
}
}
return errors.Wrap(err, "could not open database connection")
} | go | func (c *Connection) Open() error {
if c.Store != nil {
return nil
}
if c.Dialect == nil {
return errors.New("invalid connection instance")
}
details := c.Dialect.Details()
db, err := sqlx.Open(details.Dialect, c.Dialect.URL())
if err != nil {
return errors.Wrap(err, "could not open database connection")
}
db.SetMaxOpenConns(details.Pool)
db.SetMaxIdleConns(details.IdlePool)
c.Store = &dB{db}
if d, ok := c.Dialect.(afterOpenable); ok {
err = d.AfterOpen(c)
if err != nil {
c.Store = nil
}
}
return errors.Wrap(err, "could not open database connection")
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"Open",
"(",
")",
"error",
"{",
"if",
"c",
".",
"Store",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"c",
".",
"Dialect",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"invalid co... | // Open creates a new datasource connection | [
"Open",
"creates",
"a",
"new",
"datasource",
"connection"
] | 9eeaaa184b5e2f2d98ba1a306447621f64bc1826 | https://github.com/gobuffalo/pop/blob/9eeaaa184b5e2f2d98ba1a306447621f64bc1826/connection.go#L89-L112 | train |
gobuffalo/pop | connection.go | Transaction | func (c *Connection) Transaction(fn func(tx *Connection) error) error {
return c.Dialect.Lock(func() error {
var dberr error
cn, err := c.NewTransaction()
if err != nil {
return err
}
err = fn(cn)
if err != nil {
dberr = cn.TX.Rollback()
} else {
dberr = cn.TX.Commit()
}
if err != nil {
return errors.WithStack(err)
}
return errors.Wrap(dberr, "error committing or rolling back transaction")
})
} | go | func (c *Connection) Transaction(fn func(tx *Connection) error) error {
return c.Dialect.Lock(func() error {
var dberr error
cn, err := c.NewTransaction()
if err != nil {
return err
}
err = fn(cn)
if err != nil {
dberr = cn.TX.Rollback()
} else {
dberr = cn.TX.Commit()
}
if err != nil {
return errors.WithStack(err)
}
return errors.Wrap(dberr, "error committing or rolling back transaction")
})
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"Transaction",
"(",
"fn",
"func",
"(",
"tx",
"*",
"Connection",
")",
"error",
")",
"error",
"{",
"return",
"c",
".",
"Dialect",
".",
"Lock",
"(",
"func",
"(",
")",
"error",
"{",
"var",
"dberr",
"error",
"\n... | // Transaction will start a new transaction on the connection. If the inner function
// returns an error then the transaction will be rolled back, otherwise the transaction
// will automatically commit at the end. | [
"Transaction",
"will",
"start",
"a",
"new",
"transaction",
"on",
"the",
"connection",
".",
"If",
"the",
"inner",
"function",
"returns",
"an",
"error",
"then",
"the",
"transaction",
"will",
"be",
"rolled",
"back",
"otherwise",
"the",
"transaction",
"will",
"aut... | 9eeaaa184b5e2f2d98ba1a306447621f64bc1826 | https://github.com/gobuffalo/pop/blob/9eeaaa184b5e2f2d98ba1a306447621f64bc1826/connection.go#L122-L141 | train |
gobuffalo/pop | connection.go | Rollback | func (c *Connection) Rollback(fn func(tx *Connection)) error {
cn, err := c.NewTransaction()
if err != nil {
return err
}
fn(cn)
return cn.TX.Rollback()
} | go | func (c *Connection) Rollback(fn func(tx *Connection)) error {
cn, err := c.NewTransaction()
if err != nil {
return err
}
fn(cn)
return cn.TX.Rollback()
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"Rollback",
"(",
"fn",
"func",
"(",
"tx",
"*",
"Connection",
")",
")",
"error",
"{",
"cn",
",",
"err",
":=",
"c",
".",
"NewTransaction",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n... | // Rollback will open a new transaction and automatically rollback that transaction
// when the inner function returns, regardless. This can be useful for tests, etc... | [
"Rollback",
"will",
"open",
"a",
"new",
"transaction",
"and",
"automatically",
"rollback",
"that",
"transaction",
"when",
"the",
"inner",
"function",
"returns",
"regardless",
".",
"This",
"can",
"be",
"useful",
"for",
"tests",
"etc",
"..."
] | 9eeaaa184b5e2f2d98ba1a306447621f64bc1826 | https://github.com/gobuffalo/pop/blob/9eeaaa184b5e2f2d98ba1a306447621f64bc1826/connection.go#L145-L152 | train |
gobuffalo/pop | connection.go | NewTransaction | func (c *Connection) NewTransaction() (*Connection, error) {
var cn *Connection
if c.TX == nil {
tx, err := c.Store.Transaction()
if err != nil {
return cn, errors.Wrap(err, "couldn't start a new transaction")
}
cn = &Connection{
ID: randx.String(30),
Store: tx,
Dialect: c.Dialect,
TX: tx,
}
} else {
cn = c
}
return cn, nil
} | go | func (c *Connection) NewTransaction() (*Connection, error) {
var cn *Connection
if c.TX == nil {
tx, err := c.Store.Transaction()
if err != nil {
return cn, errors.Wrap(err, "couldn't start a new transaction")
}
cn = &Connection{
ID: randx.String(30),
Store: tx,
Dialect: c.Dialect,
TX: tx,
}
} else {
cn = c
}
return cn, nil
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"NewTransaction",
"(",
")",
"(",
"*",
"Connection",
",",
"error",
")",
"{",
"var",
"cn",
"*",
"Connection",
"\n",
"if",
"c",
".",
"TX",
"==",
"nil",
"{",
"tx",
",",
"err",
":=",
"c",
".",
"Store",
".",
... | // NewTransaction starts a new transaction on the connection | [
"NewTransaction",
"starts",
"a",
"new",
"transaction",
"on",
"the",
"connection"
] | 9eeaaa184b5e2f2d98ba1a306447621f64bc1826 | https://github.com/gobuffalo/pop/blob/9eeaaa184b5e2f2d98ba1a306447621f64bc1826/connection.go#L155-L172 | train |
gobuffalo/pop | columns/tags.go | Find | func (t Tags) Find(name string) Tag {
for _, popTag := range t {
if popTag.Name == name {
return popTag
}
}
return Tag{}
} | go | func (t Tags) Find(name string) Tag {
for _, popTag := range t {
if popTag.Name == name {
return popTag
}
}
return Tag{}
} | [
"func",
"(",
"t",
"Tags",
")",
"Find",
"(",
"name",
"string",
")",
"Tag",
"{",
"for",
"_",
",",
"popTag",
":=",
"range",
"t",
"{",
"if",
"popTag",
".",
"Name",
"==",
"name",
"{",
"return",
"popTag",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"Tag",
... | // Find find for a specific tag with the name passed as
// a param. returns an empty Tag in case it is not found. | [
"Find",
"find",
"for",
"a",
"specific",
"tag",
"with",
"the",
"name",
"passed",
"as",
"a",
"param",
".",
"returns",
"an",
"empty",
"Tag",
"in",
"case",
"it",
"is",
"not",
"found",
"."
] | 9eeaaa184b5e2f2d98ba1a306447621f64bc1826 | https://github.com/gobuffalo/pop/blob/9eeaaa184b5e2f2d98ba1a306447621f64bc1826/columns/tags.go#L32-L39 | train |
gobuffalo/pop | columns/tags.go | TagsFor | func TagsFor(field reflect.StructField) Tags {
pTags := Tags{}
for _, tag := range strings.Fields(tags) {
if valTag := field.Tag.Get(tag); valTag != "" {
pTags = append(pTags, Tag{valTag, tag})
}
}
if len(pTags) == 0 {
pTags = append(pTags, Tag{field.Name, "db"})
}
return pTags
} | go | func TagsFor(field reflect.StructField) Tags {
pTags := Tags{}
for _, tag := range strings.Fields(tags) {
if valTag := field.Tag.Get(tag); valTag != "" {
pTags = append(pTags, Tag{valTag, tag})
}
}
if len(pTags) == 0 {
pTags = append(pTags, Tag{field.Name, "db"})
}
return pTags
} | [
"func",
"TagsFor",
"(",
"field",
"reflect",
".",
"StructField",
")",
"Tags",
"{",
"pTags",
":=",
"Tags",
"{",
"}",
"\n",
"for",
"_",
",",
"tag",
":=",
"range",
"strings",
".",
"Fields",
"(",
"tags",
")",
"{",
"if",
"valTag",
":=",
"field",
".",
"Ta... | // TagsFor is a function which returns all tags defined
// in model field. | [
"TagsFor",
"is",
"a",
"function",
"which",
"returns",
"all",
"tags",
"defined",
"in",
"model",
"field",
"."
] | 9eeaaa184b5e2f2d98ba1a306447621f64bc1826 | https://github.com/gobuffalo/pop/blob/9eeaaa184b5e2f2d98ba1a306447621f64bc1826/columns/tags.go#L43-L55 | train |
gobuffalo/pop | slices/string.go | Scan | func (s *String) Scan(src interface{}) error {
ss := pq.StringArray(*s)
err := ss.Scan(src)
*s = String(ss)
return err
} | go | func (s *String) Scan(src interface{}) error {
ss := pq.StringArray(*s)
err := ss.Scan(src)
*s = String(ss)
return err
} | [
"func",
"(",
"s",
"*",
"String",
")",
"Scan",
"(",
"src",
"interface",
"{",
"}",
")",
"error",
"{",
"ss",
":=",
"pq",
".",
"StringArray",
"(",
"*",
"s",
")",
"\n",
"err",
":=",
"ss",
".",
"Scan",
"(",
"src",
")",
"\n",
"*",
"s",
"=",
"String"... | // Scan implements the sql.Scanner interface.
// It allows to read the string slice from the database value. | [
"Scan",
"implements",
"the",
"sql",
".",
"Scanner",
"interface",
".",
"It",
"allows",
"to",
"read",
"the",
"string",
"slice",
"from",
"the",
"database",
"value",
"."
] | 9eeaaa184b5e2f2d98ba1a306447621f64bc1826 | https://github.com/gobuffalo/pop/blob/9eeaaa184b5e2f2d98ba1a306447621f64bc1826/slices/string.go#L26-L31 | train |
gobuffalo/pop | slices/string.go | Value | func (s String) Value() (driver.Value, error) {
ss := pq.StringArray(s)
return ss.Value()
} | go | func (s String) Value() (driver.Value, error) {
ss := pq.StringArray(s)
return ss.Value()
} | [
"func",
"(",
"s",
"String",
")",
"Value",
"(",
")",
"(",
"driver",
".",
"Value",
",",
"error",
")",
"{",
"ss",
":=",
"pq",
".",
"StringArray",
"(",
"s",
")",
"\n",
"return",
"ss",
".",
"Value",
"(",
")",
"\n",
"}"
] | // Value implements the driver.Valuer interface.
// It allows to convert the string slice to a driver.value. | [
"Value",
"implements",
"the",
"driver",
".",
"Valuer",
"interface",
".",
"It",
"allows",
"to",
"convert",
"the",
"string",
"slice",
"to",
"a",
"driver",
".",
"value",
"."
] | 9eeaaa184b5e2f2d98ba1a306447621f64bc1826 | https://github.com/gobuffalo/pop/blob/9eeaaa184b5e2f2d98ba1a306447621f64bc1826/slices/string.go#L35-L38 | train |
gobuffalo/pop | slices/string.go | UnmarshalJSON | func (s *String) UnmarshalJSON(data []byte) error {
var ss pq.StringArray
if err := json.Unmarshal(data, &ss); err != nil {
return err
}
*s = String(ss)
return nil
} | go | func (s *String) UnmarshalJSON(data []byte) error {
var ss pq.StringArray
if err := json.Unmarshal(data, &ss); err != nil {
return err
}
*s = String(ss)
return nil
} | [
"func",
"(",
"s",
"*",
"String",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"ss",
"pq",
".",
"StringArray",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"ss",
")",
";",
"err",
"!=",... | // UnmarshalJSON will unmarshall JSON value into
// the string slice representation of this value. | [
"UnmarshalJSON",
"will",
"unmarshall",
"JSON",
"value",
"into",
"the",
"string",
"slice",
"representation",
"of",
"this",
"value",
"."
] | 9eeaaa184b5e2f2d98ba1a306447621f64bc1826 | https://github.com/gobuffalo/pop/blob/9eeaaa184b5e2f2d98ba1a306447621f64bc1826/slices/string.go#L42-L49 | train |
gobuffalo/pop | slices/string.go | UnmarshalText | func (s *String) UnmarshalText(text []byte) error {
r := csv.NewReader(bytes.NewReader(text))
var words []string
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return err
}
words = append(words, record...)
}
*s = String(words)
return nil
} | go | func (s *String) UnmarshalText(text []byte) error {
r := csv.NewReader(bytes.NewReader(text))
var words []string
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return err
}
words = append(words, record...)
}
*s = String(words)
return nil
} | [
"func",
"(",
"s",
"*",
"String",
")",
"UnmarshalText",
"(",
"text",
"[",
"]",
"byte",
")",
"error",
"{",
"r",
":=",
"csv",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"text",
")",
")",
"\n",
"var",
"words",
"[",
"]",
"string",
"\n",
"f... | // UnmarshalText will unmarshall text value into
// the string slice representation of this value. | [
"UnmarshalText",
"will",
"unmarshall",
"text",
"value",
"into",
"the",
"string",
"slice",
"representation",
"of",
"this",
"value",
"."
] | 9eeaaa184b5e2f2d98ba1a306447621f64bc1826 | https://github.com/gobuffalo/pop/blob/9eeaaa184b5e2f2d98ba1a306447621f64bc1826/slices/string.go#L53-L71 | train |
valyala/quicktemplate | parser/parser.go | Parse | func Parse(w io.Writer, r io.Reader, filename, pkg string) error {
p := &parser{
s: newScanner(r, filename),
w: w,
packageName: pkg,
}
return p.parseTemplate()
} | go | func Parse(w io.Writer, r io.Reader, filename, pkg string) error {
p := &parser{
s: newScanner(r, filename),
w: w,
packageName: pkg,
}
return p.parseTemplate()
} | [
"func",
"Parse",
"(",
"w",
"io",
".",
"Writer",
",",
"r",
"io",
".",
"Reader",
",",
"filename",
",",
"pkg",
"string",
")",
"error",
"{",
"p",
":=",
"&",
"parser",
"{",
"s",
":",
"newScanner",
"(",
"r",
",",
"filename",
")",
",",
"w",
":",
"w",
... | // Parse parses the contents of the supplied reader, writing generated code to
// the supplied writer. Uses filename as the source file for line comments, and
// pkg as the Go package name. | [
"Parse",
"parses",
"the",
"contents",
"of",
"the",
"supplied",
"reader",
"writing",
"generated",
"code",
"to",
"the",
"supplied",
"writer",
".",
"Uses",
"filename",
"as",
"the",
"source",
"file",
"for",
"line",
"comments",
"and",
"pkg",
"as",
"the",
"Go",
... | 480e8b93a60078dd620fcf4b2591f4d6422e3fc1 | https://github.com/valyala/quicktemplate/blob/480e8b93a60078dd620fcf4b2591f4d6422e3fc1/parser/parser.go#L31-L38 | train |
valyala/quicktemplate | writer.go | AcquireWriter | func AcquireWriter(w io.Writer) *Writer {
v := writerPool.Get()
if v == nil {
qw := &Writer{}
qw.e.w = &htmlEscapeWriter{}
v = qw
}
qw := v.(*Writer)
qw.e.w.(*htmlEscapeWriter).w = w
qw.n.w = w
return qw
} | go | func AcquireWriter(w io.Writer) *Writer {
v := writerPool.Get()
if v == nil {
qw := &Writer{}
qw.e.w = &htmlEscapeWriter{}
v = qw
}
qw := v.(*Writer)
qw.e.w.(*htmlEscapeWriter).w = w
qw.n.w = w
return qw
} | [
"func",
"AcquireWriter",
"(",
"w",
"io",
".",
"Writer",
")",
"*",
"Writer",
"{",
"v",
":=",
"writerPool",
".",
"Get",
"(",
")",
"\n",
"if",
"v",
"==",
"nil",
"{",
"qw",
":=",
"&",
"Writer",
"{",
"}",
"\n",
"qw",
".",
"e",
".",
"w",
"=",
"&",
... | // AcquireWriter returns new writer from the pool.
//
// Return unneeded writer to the pool by calling ReleaseWriter
// in order to reduce memory allocations. | [
"AcquireWriter",
"returns",
"new",
"writer",
"from",
"the",
"pool",
".",
"Return",
"unneeded",
"writer",
"to",
"the",
"pool",
"by",
"calling",
"ReleaseWriter",
"in",
"order",
"to",
"reduce",
"memory",
"allocations",
"."
] | 480e8b93a60078dd620fcf4b2591f4d6422e3fc1 | https://github.com/valyala/quicktemplate/blob/480e8b93a60078dd620fcf4b2591f4d6422e3fc1/writer.go#L37-L48 | train |
valyala/quicktemplate | writer.go | ReleaseWriter | func ReleaseWriter(qw *Writer) {
hw := qw.e.w.(*htmlEscapeWriter)
hw.w = nil
qw.e.Reset()
qw.e.w = hw
qw.n.Reset()
writerPool.Put(qw)
} | go | func ReleaseWriter(qw *Writer) {
hw := qw.e.w.(*htmlEscapeWriter)
hw.w = nil
qw.e.Reset()
qw.e.w = hw
qw.n.Reset()
writerPool.Put(qw)
} | [
"func",
"ReleaseWriter",
"(",
"qw",
"*",
"Writer",
")",
"{",
"hw",
":=",
"qw",
".",
"e",
".",
"w",
".",
"(",
"*",
"htmlEscapeWriter",
")",
"\n",
"hw",
".",
"w",
"=",
"nil",
"\n",
"qw",
".",
"e",
".",
"Reset",
"(",
")",
"\n",
"qw",
".",
"e",
... | // ReleaseWriter returns the writer to the pool.
//
// Do not access released writer, otherwise data races may occur. | [
"ReleaseWriter",
"returns",
"the",
"writer",
"to",
"the",
"pool",
".",
"Do",
"not",
"access",
"released",
"writer",
"otherwise",
"data",
"races",
"may",
"occur",
"."
] | 480e8b93a60078dd620fcf4b2591f4d6422e3fc1 | https://github.com/valyala/quicktemplate/blob/480e8b93a60078dd620fcf4b2591f4d6422e3fc1/writer.go#L53-L62 | train |
valyala/quicktemplate | writer.go | D | func (w *QWriter) D(n int) {
bb, ok := w.w.(*ByteBuffer)
if ok {
bb.B = strconv.AppendInt(bb.B, int64(n), 10)
} else {
w.b = strconv.AppendInt(w.b[:0], int64(n), 10)
w.Write(w.b)
}
} | go | func (w *QWriter) D(n int) {
bb, ok := w.w.(*ByteBuffer)
if ok {
bb.B = strconv.AppendInt(bb.B, int64(n), 10)
} else {
w.b = strconv.AppendInt(w.b[:0], int64(n), 10)
w.Write(w.b)
}
} | [
"func",
"(",
"w",
"*",
"QWriter",
")",
"D",
"(",
"n",
"int",
")",
"{",
"bb",
",",
"ok",
":=",
"w",
".",
"w",
".",
"(",
"*",
"ByteBuffer",
")",
"\n",
"if",
"ok",
"{",
"bb",
".",
"B",
"=",
"strconv",
".",
"AppendInt",
"(",
"bb",
".",
"B",
"... | // D writes n to w. | [
"D",
"writes",
"n",
"to",
"w",
"."
] | 480e8b93a60078dd620fcf4b2591f4d6422e3fc1 | https://github.com/valyala/quicktemplate/blob/480e8b93a60078dd620fcf4b2591f4d6422e3fc1/writer.go#L107-L115 | train |
valyala/quicktemplate | writer.go | F | func (w *QWriter) F(f float64) {
n := int(f)
if float64(n) == f {
// Fast path - just int.
w.D(n)
return
}
// Slow path.
w.FPrec(f, -1)
} | go | func (w *QWriter) F(f float64) {
n := int(f)
if float64(n) == f {
// Fast path - just int.
w.D(n)
return
}
// Slow path.
w.FPrec(f, -1)
} | [
"func",
"(",
"w",
"*",
"QWriter",
")",
"F",
"(",
"f",
"float64",
")",
"{",
"n",
":=",
"int",
"(",
"f",
")",
"\n",
"if",
"float64",
"(",
"n",
")",
"==",
"f",
"{",
"w",
".",
"D",
"(",
"n",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"... | // F writes f to w. | [
"F",
"writes",
"f",
"to",
"w",
"."
] | 480e8b93a60078dd620fcf4b2591f4d6422e3fc1 | https://github.com/valyala/quicktemplate/blob/480e8b93a60078dd620fcf4b2591f4d6422e3fc1/writer.go#L118-L128 | train |
valyala/quicktemplate | writer.go | FPrec | func (w *QWriter) FPrec(f float64, prec int) {
bb, ok := w.w.(*ByteBuffer)
if ok {
bb.B = strconv.AppendFloat(bb.B, f, 'f', prec, 64)
} else {
w.b = strconv.AppendFloat(w.b[:0], f, 'f', prec, 64)
w.Write(w.b)
}
} | go | func (w *QWriter) FPrec(f float64, prec int) {
bb, ok := w.w.(*ByteBuffer)
if ok {
bb.B = strconv.AppendFloat(bb.B, f, 'f', prec, 64)
} else {
w.b = strconv.AppendFloat(w.b[:0], f, 'f', prec, 64)
w.Write(w.b)
}
} | [
"func",
"(",
"w",
"*",
"QWriter",
")",
"FPrec",
"(",
"f",
"float64",
",",
"prec",
"int",
")",
"{",
"bb",
",",
"ok",
":=",
"w",
".",
"w",
".",
"(",
"*",
"ByteBuffer",
")",
"\n",
"if",
"ok",
"{",
"bb",
".",
"B",
"=",
"strconv",
".",
"AppendFloa... | // FPrec writes f to w using the given floating point precision. | [
"FPrec",
"writes",
"f",
"to",
"w",
"using",
"the",
"given",
"floating",
"point",
"precision",
"."
] | 480e8b93a60078dd620fcf4b2591f4d6422e3fc1 | https://github.com/valyala/quicktemplate/blob/480e8b93a60078dd620fcf4b2591f4d6422e3fc1/writer.go#L131-L139 | train |
valyala/quicktemplate | writer.go | Q | func (w *QWriter) Q(s string) {
w.Write(strQuote)
writeJSONString(w, s)
w.Write(strQuote)
} | go | func (w *QWriter) Q(s string) {
w.Write(strQuote)
writeJSONString(w, s)
w.Write(strQuote)
} | [
"func",
"(",
"w",
"*",
"QWriter",
")",
"Q",
"(",
"s",
"string",
")",
"{",
"w",
".",
"Write",
"(",
"strQuote",
")",
"\n",
"writeJSONString",
"(",
"w",
",",
"s",
")",
"\n",
"w",
".",
"Write",
"(",
"strQuote",
")",
"\n",
"}"
] | // Q writes quoted json-safe s to w. | [
"Q",
"writes",
"quoted",
"json",
"-",
"safe",
"s",
"to",
"w",
"."
] | 480e8b93a60078dd620fcf4b2591f4d6422e3fc1 | https://github.com/valyala/quicktemplate/blob/480e8b93a60078dd620fcf4b2591f4d6422e3fc1/writer.go#L142-L146 | train |
valyala/quicktemplate | writer.go | U | func (w *QWriter) U(s string) {
bb, ok := w.w.(*ByteBuffer)
if ok {
bb.B = appendURLEncode(bb.B, s)
} else {
w.b = appendURLEncode(w.b[:0], s)
w.Write(w.b)
}
} | go | func (w *QWriter) U(s string) {
bb, ok := w.w.(*ByteBuffer)
if ok {
bb.B = appendURLEncode(bb.B, s)
} else {
w.b = appendURLEncode(w.b[:0], s)
w.Write(w.b)
}
} | [
"func",
"(",
"w",
"*",
"QWriter",
")",
"U",
"(",
"s",
"string",
")",
"{",
"bb",
",",
"ok",
":=",
"w",
".",
"w",
".",
"(",
"*",
"ByteBuffer",
")",
"\n",
"if",
"ok",
"{",
"bb",
".",
"B",
"=",
"appendURLEncode",
"(",
"bb",
".",
"B",
",",
"s",
... | // U writes url-encoded s to w. | [
"U",
"writes",
"url",
"-",
"encoded",
"s",
"to",
"w",
"."
] | 480e8b93a60078dd620fcf4b2591f4d6422e3fc1 | https://github.com/valyala/quicktemplate/blob/480e8b93a60078dd620fcf4b2591f4d6422e3fc1/writer.go#L175-L183 | train |
docker/distribution | registry/storage/driver/base/regulator.go | GetLimitFromParameter | func GetLimitFromParameter(param interface{}, min, def uint64) (uint64, error) {
limit := def
switch v := param.(type) {
case string:
var err error
if limit, err = strconv.ParseUint(v, 0, 64); err != nil {
return limit, fmt.Errorf("parameter must be an integer, '%v' invalid", param)
}
case uint64:
limit = v
case int, int32, int64:
val := reflect.ValueOf(v).Convert(reflect.TypeOf(param)).Int()
// if param is negative casting to uint64 will wrap around and
// give you the hugest thread limit ever. Let's be sensible, here
if val > 0 {
limit = uint64(val)
} else {
limit = min
}
case uint, uint32:
limit = reflect.ValueOf(v).Convert(reflect.TypeOf(param)).Uint()
case nil:
// use the default
default:
return 0, fmt.Errorf("invalid value '%#v'", param)
}
if limit < min {
return min, nil
}
return limit, nil
} | go | func GetLimitFromParameter(param interface{}, min, def uint64) (uint64, error) {
limit := def
switch v := param.(type) {
case string:
var err error
if limit, err = strconv.ParseUint(v, 0, 64); err != nil {
return limit, fmt.Errorf("parameter must be an integer, '%v' invalid", param)
}
case uint64:
limit = v
case int, int32, int64:
val := reflect.ValueOf(v).Convert(reflect.TypeOf(param)).Int()
// if param is negative casting to uint64 will wrap around and
// give you the hugest thread limit ever. Let's be sensible, here
if val > 0 {
limit = uint64(val)
} else {
limit = min
}
case uint, uint32:
limit = reflect.ValueOf(v).Convert(reflect.TypeOf(param)).Uint()
case nil:
// use the default
default:
return 0, fmt.Errorf("invalid value '%#v'", param)
}
if limit < min {
return min, nil
}
return limit, nil
} | [
"func",
"GetLimitFromParameter",
"(",
"param",
"interface",
"{",
"}",
",",
"min",
",",
"def",
"uint64",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"limit",
":=",
"def",
"\n",
"switch",
"v",
":=",
"param",
".",
"(",
"type",
")",
"{",
"case",
"string"... | // GetLimitFromParameter takes an interface type as decoded from the YAML
// configuration and returns a uint64 representing the maximum number of
// concurrent calls given a minimum limit and default.
//
// If the parameter supplied is of an invalid type this returns an error. | [
"GetLimitFromParameter",
"takes",
"an",
"interface",
"type",
"as",
"decoded",
"from",
"the",
"YAML",
"configuration",
"and",
"returns",
"a",
"uint64",
"representing",
"the",
"maximum",
"number",
"of",
"concurrent",
"calls",
"given",
"a",
"minimum",
"limit",
"and",... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/regulator.go#L26-L59 | train |
docker/distribution | registry/storage/driver/base/regulator.go | NewRegulator | func NewRegulator(driver storagedriver.StorageDriver, limit uint64) storagedriver.StorageDriver {
return ®ulator{
StorageDriver: driver,
Cond: sync.NewCond(&sync.Mutex{}),
available: limit,
}
} | go | func NewRegulator(driver storagedriver.StorageDriver, limit uint64) storagedriver.StorageDriver {
return ®ulator{
StorageDriver: driver,
Cond: sync.NewCond(&sync.Mutex{}),
available: limit,
}
} | [
"func",
"NewRegulator",
"(",
"driver",
"storagedriver",
".",
"StorageDriver",
",",
"limit",
"uint64",
")",
"storagedriver",
".",
"StorageDriver",
"{",
"return",
"&",
"regulator",
"{",
"StorageDriver",
":",
"driver",
",",
"Cond",
":",
"sync",
".",
"NewCond",
"(... | // NewRegulator wraps the given driver and is used to regulate concurrent calls
// to the given storage driver to a maximum of the given limit. This is useful
// for storage drivers that would otherwise create an unbounded number of OS
// threads if allowed to be called unregulated. | [
"NewRegulator",
"wraps",
"the",
"given",
"driver",
"and",
"is",
"used",
"to",
"regulate",
"concurrent",
"calls",
"to",
"the",
"given",
"storage",
"driver",
"to",
"a",
"maximum",
"of",
"the",
"given",
"limit",
".",
"This",
"is",
"useful",
"for",
"storage",
... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/regulator.go#L65-L71 | train |
docker/distribution | registry/storage/driver/base/regulator.go | Name | func (r *regulator) Name() string {
r.enter()
defer r.exit()
return r.StorageDriver.Name()
} | go | func (r *regulator) Name() string {
r.enter()
defer r.exit()
return r.StorageDriver.Name()
} | [
"func",
"(",
"r",
"*",
"regulator",
")",
"Name",
"(",
")",
"string",
"{",
"r",
".",
"enter",
"(",
")",
"\n",
"defer",
"r",
".",
"exit",
"(",
")",
"\n",
"return",
"r",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"\n",
"}"
] | // Name returns the human-readable "name" of the driver, useful in error
// messages and logging. By convention, this will just be the registration
// name, but drivers may provide other information here. | [
"Name",
"returns",
"the",
"human",
"-",
"readable",
"name",
"of",
"the",
"driver",
"useful",
"in",
"error",
"messages",
"and",
"logging",
".",
"By",
"convention",
"this",
"will",
"just",
"be",
"the",
"registration",
"name",
"but",
"drivers",
"may",
"provide"... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/regulator.go#L92-L97 | train |
docker/distribution | registry/storage/driver/base/regulator.go | Writer | func (r *regulator) Writer(ctx context.Context, path string, append bool) (storagedriver.FileWriter, error) {
r.enter()
defer r.exit()
return r.StorageDriver.Writer(ctx, path, append)
} | go | func (r *regulator) Writer(ctx context.Context, path string, append bool) (storagedriver.FileWriter, error) {
r.enter()
defer r.exit()
return r.StorageDriver.Writer(ctx, path, append)
} | [
"func",
"(",
"r",
"*",
"regulator",
")",
"Writer",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"append",
"bool",
")",
"(",
"storagedriver",
".",
"FileWriter",
",",
"error",
")",
"{",
"r",
".",
"enter",
"(",
")",
"\n",
"defer",
... | // Writer stores the contents of the provided io.ReadCloser at a
// location designated by the given path.
// May be used to resume writing a stream by providing a nonzero offset.
// The offset must be no larger than the CurrentSize for this path. | [
"Writer",
"stores",
"the",
"contents",
"of",
"the",
"provided",
"io",
".",
"ReadCloser",
"at",
"a",
"location",
"designated",
"by",
"the",
"given",
"path",
".",
"May",
"be",
"used",
"to",
"resume",
"writing",
"a",
"stream",
"by",
"providing",
"a",
"nonzero... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/regulator.go#L131-L136 | train |
docker/distribution | registry/storage/driver/base/regulator.go | URLFor | func (r *regulator) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
r.enter()
defer r.exit()
return r.StorageDriver.URLFor(ctx, path, options)
} | go | func (r *regulator) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
r.enter()
defer r.exit()
return r.StorageDriver.URLFor(ctx, path, options)
} | [
"func",
"(",
"r",
"*",
"regulator",
")",
"URLFor",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"r",
".",
"enter",
"(",
... | // URLFor returns a URL which may be used to retrieve the content stored at
// the given path, possibly using the given options.
// May return an ErrUnsupportedMethod in certain StorageDriver
// implementations. | [
"URLFor",
"returns",
"a",
"URL",
"which",
"may",
"be",
"used",
"to",
"retrieve",
"the",
"content",
"stored",
"at",
"the",
"given",
"path",
"possibly",
"using",
"the",
"given",
"options",
".",
"May",
"return",
"an",
"ErrUnsupportedMethod",
"in",
"certain",
"S... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/regulator.go#L179-L184 | train |
docker/distribution | registry/storage/driver/swift/swift.go | URLFor | func (d *driver) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
if d.SecretKey == "" {
return "", storagedriver.ErrUnsupportedMethod{}
}
methodString := "GET"
method, ok := options["method"]
if ok {
if methodString, ok = method.(string); !ok {
return "", storagedriver.ErrUnsupportedMethod{}
}
}
if methodString == "HEAD" {
// A "HEAD" request on a temporary URL is allowed if the
// signature was generated with "GET", "POST" or "PUT"
methodString = "GET"
}
supported := false
for _, method := range d.TempURLMethods {
if method == methodString {
supported = true
break
}
}
if !supported {
return "", storagedriver.ErrUnsupportedMethod{}
}
expiresTime := time.Now().Add(20 * time.Minute)
expires, ok := options["expiry"]
if ok {
et, ok := expires.(time.Time)
if ok {
expiresTime = et
}
}
tempURL := d.Conn.ObjectTempUrl(d.Container, d.swiftPath(path), d.SecretKey, methodString, expiresTime)
if d.AccessKey != "" {
// On HP Cloud, the signature must be in the form of tenant_id:access_key:signature
url, _ := url.Parse(tempURL)
query := url.Query()
query.Set("temp_url_sig", fmt.Sprintf("%s:%s:%s", d.Conn.TenantId, d.AccessKey, query.Get("temp_url_sig")))
url.RawQuery = query.Encode()
tempURL = url.String()
}
return tempURL, nil
} | go | func (d *driver) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
if d.SecretKey == "" {
return "", storagedriver.ErrUnsupportedMethod{}
}
methodString := "GET"
method, ok := options["method"]
if ok {
if methodString, ok = method.(string); !ok {
return "", storagedriver.ErrUnsupportedMethod{}
}
}
if methodString == "HEAD" {
// A "HEAD" request on a temporary URL is allowed if the
// signature was generated with "GET", "POST" or "PUT"
methodString = "GET"
}
supported := false
for _, method := range d.TempURLMethods {
if method == methodString {
supported = true
break
}
}
if !supported {
return "", storagedriver.ErrUnsupportedMethod{}
}
expiresTime := time.Now().Add(20 * time.Minute)
expires, ok := options["expiry"]
if ok {
et, ok := expires.(time.Time)
if ok {
expiresTime = et
}
}
tempURL := d.Conn.ObjectTempUrl(d.Container, d.swiftPath(path), d.SecretKey, methodString, expiresTime)
if d.AccessKey != "" {
// On HP Cloud, the signature must be in the form of tenant_id:access_key:signature
url, _ := url.Parse(tempURL)
query := url.Query()
query.Set("temp_url_sig", fmt.Sprintf("%s:%s:%s", d.Conn.TenantId, d.AccessKey, query.Get("temp_url_sig")))
url.RawQuery = query.Encode()
tempURL = url.String()
}
return tempURL, nil
} | [
"func",
"(",
"d",
"*",
"driver",
")",
"URLFor",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"d",
".",
"SecretKey",... | // URLFor returns a URL which may be used to retrieve the content stored at the given path. | [
"URLFor",
"returns",
"a",
"URL",
"which",
"may",
"be",
"used",
"to",
"retrieve",
"the",
"content",
"stored",
"at",
"the",
"given",
"path",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/swift/swift.go#L606-L658 | train |
docker/distribution | manifest/schema2/manifest.go | References | func (m Manifest) References() []distribution.Descriptor {
references := make([]distribution.Descriptor, 0, 1+len(m.Layers))
references = append(references, m.Config)
references = append(references, m.Layers...)
return references
} | go | func (m Manifest) References() []distribution.Descriptor {
references := make([]distribution.Descriptor, 0, 1+len(m.Layers))
references = append(references, m.Config)
references = append(references, m.Layers...)
return references
} | [
"func",
"(",
"m",
"Manifest",
")",
"References",
"(",
")",
"[",
"]",
"distribution",
".",
"Descriptor",
"{",
"references",
":=",
"make",
"(",
"[",
"]",
"distribution",
".",
"Descriptor",
",",
"0",
",",
"1",
"+",
"len",
"(",
"m",
".",
"Layers",
")",
... | // References returns the descriptors of this manifests references. | [
"References",
"returns",
"the",
"descriptors",
"of",
"this",
"manifests",
"references",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema2/manifest.go#L75-L80 | train |
docker/distribution | manifest/schema2/manifest.go | FromStruct | func FromStruct(m Manifest) (*DeserializedManifest, error) {
var deserialized DeserializedManifest
deserialized.Manifest = m
var err error
deserialized.canonical, err = json.MarshalIndent(&m, "", " ")
return &deserialized, err
} | go | func FromStruct(m Manifest) (*DeserializedManifest, error) {
var deserialized DeserializedManifest
deserialized.Manifest = m
var err error
deserialized.canonical, err = json.MarshalIndent(&m, "", " ")
return &deserialized, err
} | [
"func",
"FromStruct",
"(",
"m",
"Manifest",
")",
"(",
"*",
"DeserializedManifest",
",",
"error",
")",
"{",
"var",
"deserialized",
"DeserializedManifest",
"\n",
"deserialized",
".",
"Manifest",
"=",
"m",
"\n",
"var",
"err",
"error",
"\n",
"deserialized",
".",
... | // FromStruct takes a Manifest structure, marshals it to JSON, and returns a
// DeserializedManifest which contains the manifest and its JSON representation. | [
"FromStruct",
"takes",
"a",
"Manifest",
"structure",
"marshals",
"it",
"to",
"JSON",
"and",
"returns",
"a",
"DeserializedManifest",
"which",
"contains",
"the",
"manifest",
"and",
"its",
"JSON",
"representation",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema2/manifest.go#L98-L105 | train |
docker/distribution | manifest/schema2/manifest.go | MarshalJSON | func (m *DeserializedManifest) MarshalJSON() ([]byte, error) {
if len(m.canonical) > 0 {
return m.canonical, nil
}
return nil, errors.New("JSON representation not initialized in DeserializedManifest")
} | go | func (m *DeserializedManifest) MarshalJSON() ([]byte, error) {
if len(m.canonical) > 0 {
return m.canonical, nil
}
return nil, errors.New("JSON representation not initialized in DeserializedManifest")
} | [
"func",
"(",
"m",
"*",
"DeserializedManifest",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"m",
".",
"canonical",
")",
">",
"0",
"{",
"return",
"m",
".",
"canonical",
",",
"nil",
"\n",
"}",
"\n",... | // MarshalJSON returns the contents of canonical. If canonical is empty,
// marshals the inner contents. | [
"MarshalJSON",
"returns",
"the",
"contents",
"of",
"canonical",
".",
"If",
"canonical",
"is",
"empty",
"marshals",
"the",
"inner",
"contents",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema2/manifest.go#L132-L138 | train |
docker/distribution | registry/storage/blobwriter_resumable.go | resumeDigest | func (bw *blobWriter) resumeDigest(ctx context.Context) error {
if !bw.resumableDigestEnabled {
return errResumableDigestNotAvailable
}
h, ok := bw.digester.Hash().(encoding.BinaryUnmarshaler)
if !ok {
return errResumableDigestNotAvailable
}
offset := bw.fileWriter.Size()
if offset == bw.written {
// State of digester is already at the requested offset.
return nil
}
// List hash states from storage backend.
var hashStateMatch hashStateEntry
hashStates, err := bw.getStoredHashStates(ctx)
if err != nil {
return fmt.Errorf("unable to get stored hash states with offset %d: %s", offset, err)
}
// Find the highest stored hashState with offset equal to
// the requested offset.
for _, hashState := range hashStates {
if hashState.offset == offset {
hashStateMatch = hashState
break // Found an exact offset match.
}
}
if hashStateMatch.offset == 0 {
// No need to load any state, just reset the hasher.
h.(hash.Hash).Reset()
} else {
storedState, err := bw.driver.GetContent(ctx, hashStateMatch.path)
if err != nil {
return err
}
if err = h.UnmarshalBinary(storedState); err != nil {
return err
}
bw.written = hashStateMatch.offset
}
// Mind the gap.
if gapLen := offset - bw.written; gapLen > 0 {
return errResumableDigestNotAvailable
}
return nil
} | go | func (bw *blobWriter) resumeDigest(ctx context.Context) error {
if !bw.resumableDigestEnabled {
return errResumableDigestNotAvailable
}
h, ok := bw.digester.Hash().(encoding.BinaryUnmarshaler)
if !ok {
return errResumableDigestNotAvailable
}
offset := bw.fileWriter.Size()
if offset == bw.written {
// State of digester is already at the requested offset.
return nil
}
// List hash states from storage backend.
var hashStateMatch hashStateEntry
hashStates, err := bw.getStoredHashStates(ctx)
if err != nil {
return fmt.Errorf("unable to get stored hash states with offset %d: %s", offset, err)
}
// Find the highest stored hashState with offset equal to
// the requested offset.
for _, hashState := range hashStates {
if hashState.offset == offset {
hashStateMatch = hashState
break // Found an exact offset match.
}
}
if hashStateMatch.offset == 0 {
// No need to load any state, just reset the hasher.
h.(hash.Hash).Reset()
} else {
storedState, err := bw.driver.GetContent(ctx, hashStateMatch.path)
if err != nil {
return err
}
if err = h.UnmarshalBinary(storedState); err != nil {
return err
}
bw.written = hashStateMatch.offset
}
// Mind the gap.
if gapLen := offset - bw.written; gapLen > 0 {
return errResumableDigestNotAvailable
}
return nil
} | [
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"resumeDigest",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"!",
"bw",
".",
"resumableDigestEnabled",
"{",
"return",
"errResumableDigestNotAvailable",
"\n",
"}",
"\n",
"h",
",",
"ok",
":=",
"bw... | // resumeDigest attempts to restore the state of the internal hash function
// by loading the most recent saved hash state equal to the current size of the blob. | [
"resumeDigest",
"attempts",
"to",
"restore",
"the",
"state",
"of",
"the",
"internal",
"hash",
"function",
"by",
"loading",
"the",
"most",
"recent",
"saved",
"hash",
"state",
"equal",
"to",
"the",
"current",
"size",
"of",
"the",
"blob",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter_resumable.go#L19-L72 | train |
docker/distribution | registry/storage/blobwriter_resumable.go | getStoredHashStates | func (bw *blobWriter) getStoredHashStates(ctx context.Context) ([]hashStateEntry, error) {
uploadHashStatePathPrefix, err := pathFor(uploadHashStatePathSpec{
name: bw.blobStore.repository.Named().String(),
id: bw.id,
alg: bw.digester.Digest().Algorithm(),
list: true,
})
if err != nil {
return nil, err
}
paths, err := bw.blobStore.driver.List(ctx, uploadHashStatePathPrefix)
if err != nil {
if _, ok := err.(storagedriver.PathNotFoundError); !ok {
return nil, err
}
// Treat PathNotFoundError as no entries.
paths = nil
}
hashStateEntries := make([]hashStateEntry, 0, len(paths))
for _, p := range paths {
pathSuffix := path.Base(p)
// The suffix should be the offset.
offset, err := strconv.ParseInt(pathSuffix, 0, 64)
if err != nil {
logrus.Errorf("unable to parse offset from upload state path %q: %s", p, err)
}
hashStateEntries = append(hashStateEntries, hashStateEntry{offset: offset, path: p})
}
return hashStateEntries, nil
} | go | func (bw *blobWriter) getStoredHashStates(ctx context.Context) ([]hashStateEntry, error) {
uploadHashStatePathPrefix, err := pathFor(uploadHashStatePathSpec{
name: bw.blobStore.repository.Named().String(),
id: bw.id,
alg: bw.digester.Digest().Algorithm(),
list: true,
})
if err != nil {
return nil, err
}
paths, err := bw.blobStore.driver.List(ctx, uploadHashStatePathPrefix)
if err != nil {
if _, ok := err.(storagedriver.PathNotFoundError); !ok {
return nil, err
}
// Treat PathNotFoundError as no entries.
paths = nil
}
hashStateEntries := make([]hashStateEntry, 0, len(paths))
for _, p := range paths {
pathSuffix := path.Base(p)
// The suffix should be the offset.
offset, err := strconv.ParseInt(pathSuffix, 0, 64)
if err != nil {
logrus.Errorf("unable to parse offset from upload state path %q: %s", p, err)
}
hashStateEntries = append(hashStateEntries, hashStateEntry{offset: offset, path: p})
}
return hashStateEntries, nil
} | [
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"getStoredHashStates",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"[",
"]",
"hashStateEntry",
",",
"error",
")",
"{",
"uploadHashStatePathPrefix",
",",
"err",
":=",
"pathFor",
"(",
"uploadHashStatePathSpec",
"{"... | // getStoredHashStates returns a slice of hashStateEntries for this upload. | [
"getStoredHashStates",
"returns",
"a",
"slice",
"of",
"hashStateEntries",
"for",
"this",
"upload",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter_resumable.go#L80-L115 | train |
docker/distribution | registry/storage/catalog.go | Repositories | func (reg *registry) Repositories(ctx context.Context, repos []string, last string) (n int, err error) {
var finishedWalk bool
var foundRepos []string
if len(repos) == 0 {
return 0, errors.New("no space in slice")
}
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return 0, err
}
err = reg.blobStore.driver.Walk(ctx, root, func(fileInfo driver.FileInfo) error {
err := handleRepository(fileInfo, root, last, func(repoPath string) error {
foundRepos = append(foundRepos, repoPath)
return nil
})
if err != nil {
return err
}
// if we've filled our array, no need to walk any further
if len(foundRepos) == len(repos) {
finishedWalk = true
return driver.ErrSkipDir
}
return nil
})
n = copy(repos, foundRepos)
if err != nil {
return n, err
} else if !finishedWalk {
// We didn't fill buffer. No more records are available.
return n, io.EOF
}
return n, err
} | go | func (reg *registry) Repositories(ctx context.Context, repos []string, last string) (n int, err error) {
var finishedWalk bool
var foundRepos []string
if len(repos) == 0 {
return 0, errors.New("no space in slice")
}
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return 0, err
}
err = reg.blobStore.driver.Walk(ctx, root, func(fileInfo driver.FileInfo) error {
err := handleRepository(fileInfo, root, last, func(repoPath string) error {
foundRepos = append(foundRepos, repoPath)
return nil
})
if err != nil {
return err
}
// if we've filled our array, no need to walk any further
if len(foundRepos) == len(repos) {
finishedWalk = true
return driver.ErrSkipDir
}
return nil
})
n = copy(repos, foundRepos)
if err != nil {
return n, err
} else if !finishedWalk {
// We didn't fill buffer. No more records are available.
return n, io.EOF
}
return n, err
} | [
"func",
"(",
"reg",
"*",
"registry",
")",
"Repositories",
"(",
"ctx",
"context",
".",
"Context",
",",
"repos",
"[",
"]",
"string",
",",
"last",
"string",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"var",
"finishedWalk",
"bool",
"\n",
"var",... | // Returns a list, or partial list, of repositories in the registry.
// Because it's a quite expensive operation, it should only be used when building up
// an initial set of repositories. | [
"Returns",
"a",
"list",
"or",
"partial",
"list",
"of",
"repositories",
"in",
"the",
"registry",
".",
"Because",
"it",
"s",
"a",
"quite",
"expensive",
"operation",
"it",
"should",
"only",
"be",
"used",
"when",
"building",
"up",
"an",
"initial",
"set",
"of",... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/catalog.go#L17-L58 | train |
docker/distribution | registry/storage/catalog.go | Enumerate | func (reg *registry) Enumerate(ctx context.Context, ingester func(string) error) error {
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
err = reg.blobStore.driver.Walk(ctx, root, func(fileInfo driver.FileInfo) error {
return handleRepository(fileInfo, root, "", ingester)
})
return err
} | go | func (reg *registry) Enumerate(ctx context.Context, ingester func(string) error) error {
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
err = reg.blobStore.driver.Walk(ctx, root, func(fileInfo driver.FileInfo) error {
return handleRepository(fileInfo, root, "", ingester)
})
return err
} | [
"func",
"(",
"reg",
"*",
"registry",
")",
"Enumerate",
"(",
"ctx",
"context",
".",
"Context",
",",
"ingester",
"func",
"(",
"string",
")",
"error",
")",
"error",
"{",
"root",
",",
"err",
":=",
"pathFor",
"(",
"repositoriesRootPathSpec",
"{",
"}",
")",
... | // Enumerate applies ingester to each repository | [
"Enumerate",
"applies",
"ingester",
"to",
"each",
"repository"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/catalog.go#L61-L72 | train |
docker/distribution | registry/storage/catalog.go | Remove | func (reg *registry) Remove(ctx context.Context, name reference.Named) error {
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
repoDir := path.Join(root, name.Name())
return reg.driver.Delete(ctx, repoDir)
} | go | func (reg *registry) Remove(ctx context.Context, name reference.Named) error {
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
repoDir := path.Join(root, name.Name())
return reg.driver.Delete(ctx, repoDir)
} | [
"func",
"(",
"reg",
"*",
"registry",
")",
"Remove",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"reference",
".",
"Named",
")",
"error",
"{",
"root",
",",
"err",
":=",
"pathFor",
"(",
"repositoriesRootPathSpec",
"{",
"}",
")",
"\n",
"if",
"err"... | // Remove removes a repository from storage | [
"Remove",
"removes",
"a",
"repository",
"from",
"storage"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/catalog.go#L75-L82 | train |
docker/distribution | registry/storage/catalog.go | compareReplaceInline | func compareReplaceInline(s1, s2 string, old, new byte) int {
// TODO(stevvooe): We are missing an optimization when the s1 and s2 have
// the exact same slice header. It will make the code unsafe but can
// provide some extra performance.
l := len(s1)
if len(s2) < l {
l = len(s2)
}
for i := 0; i < l; i++ {
c1, c2 := s1[i], s2[i]
if c1 == old {
c1 = new
}
if c2 == old {
c2 = new
}
if c1 < c2 {
return -1
}
if c1 > c2 {
return +1
}
}
if len(s1) < len(s2) {
return -1
}
if len(s1) > len(s2) {
return +1
}
return 0
} | go | func compareReplaceInline(s1, s2 string, old, new byte) int {
// TODO(stevvooe): We are missing an optimization when the s1 and s2 have
// the exact same slice header. It will make the code unsafe but can
// provide some extra performance.
l := len(s1)
if len(s2) < l {
l = len(s2)
}
for i := 0; i < l; i++ {
c1, c2 := s1[i], s2[i]
if c1 == old {
c1 = new
}
if c2 == old {
c2 = new
}
if c1 < c2 {
return -1
}
if c1 > c2 {
return +1
}
}
if len(s1) < len(s2) {
return -1
}
if len(s1) > len(s2) {
return +1
}
return 0
} | [
"func",
"compareReplaceInline",
"(",
"s1",
",",
"s2",
"string",
",",
"old",
",",
"new",
"byte",
")",
"int",
"{",
"l",
":=",
"len",
"(",
"s1",
")",
"\n",
"if",
"len",
"(",
"s2",
")",
"<",
"l",
"{",
"l",
"=",
"len",
"(",
"s2",
")",
"\n",
"}",
... | // compareReplaceInline modifies runtime.cmpstring to replace old with new
// during a byte-wise comparison. | [
"compareReplaceInline",
"modifies",
"runtime",
".",
"cmpstring",
"to",
"replace",
"old",
"with",
"new",
"during",
"a",
"byte",
"-",
"wise",
"comparison",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/catalog.go#L95-L133 | train |
docker/distribution | registry/storage/catalog.go | handleRepository | func handleRepository(fileInfo driver.FileInfo, root, last string, fn func(repoPath string) error) error {
filePath := fileInfo.Path()
// lop the base path off
repo := filePath[len(root)+1:]
_, file := path.Split(repo)
if file == "_layers" {
repo = strings.TrimSuffix(repo, "/_layers")
if lessPath(last, repo) {
if err := fn(repo); err != nil {
return err
}
}
return driver.ErrSkipDir
} else if strings.HasPrefix(file, "_") {
return driver.ErrSkipDir
}
return nil
} | go | func handleRepository(fileInfo driver.FileInfo, root, last string, fn func(repoPath string) error) error {
filePath := fileInfo.Path()
// lop the base path off
repo := filePath[len(root)+1:]
_, file := path.Split(repo)
if file == "_layers" {
repo = strings.TrimSuffix(repo, "/_layers")
if lessPath(last, repo) {
if err := fn(repo); err != nil {
return err
}
}
return driver.ErrSkipDir
} else if strings.HasPrefix(file, "_") {
return driver.ErrSkipDir
}
return nil
} | [
"func",
"handleRepository",
"(",
"fileInfo",
"driver",
".",
"FileInfo",
",",
"root",
",",
"last",
"string",
",",
"fn",
"func",
"(",
"repoPath",
"string",
")",
"error",
")",
"error",
"{",
"filePath",
":=",
"fileInfo",
".",
"Path",
"(",
")",
"\n",
"repo",
... | // handleRepository calls function fn with a repository path if fileInfo
// has a path of a repository under root and that it is lexographically
// after last. Otherwise, it will return ErrSkipDir. This should be used
// with Walk to do handling with repositories in a storage. | [
"handleRepository",
"calls",
"function",
"fn",
"with",
"a",
"repository",
"path",
"if",
"fileInfo",
"has",
"a",
"path",
"of",
"a",
"repository",
"under",
"root",
"and",
"that",
"it",
"is",
"lexographically",
"after",
"last",
".",
"Otherwise",
"it",
"will",
"... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/catalog.go#L139-L159 | train |
docker/distribution | registry/storage/driver/middleware/cloudfront/middleware.go | URLFor | func (lh *cloudFrontStorageMiddleware) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
// TODO(endophage): currently only supports S3
keyer, ok := lh.StorageDriver.(S3BucketKeyer)
if !ok {
dcontext.GetLogger(ctx).Warn("the CloudFront middleware does not support this backend storage driver")
return lh.StorageDriver.URLFor(ctx, path, options)
}
if eligibleForS3(ctx, lh.awsIPs) {
return lh.StorageDriver.URLFor(ctx, path, options)
}
// Get signed cloudfront url.
cfURL, err := lh.urlSigner.Sign(lh.baseURL+keyer.S3BucketKey(path), time.Now().Add(lh.duration))
if err != nil {
return "", err
}
return cfURL, nil
} | go | func (lh *cloudFrontStorageMiddleware) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
// TODO(endophage): currently only supports S3
keyer, ok := lh.StorageDriver.(S3BucketKeyer)
if !ok {
dcontext.GetLogger(ctx).Warn("the CloudFront middleware does not support this backend storage driver")
return lh.StorageDriver.URLFor(ctx, path, options)
}
if eligibleForS3(ctx, lh.awsIPs) {
return lh.StorageDriver.URLFor(ctx, path, options)
}
// Get signed cloudfront url.
cfURL, err := lh.urlSigner.Sign(lh.baseURL+keyer.S3BucketKey(path), time.Now().Add(lh.duration))
if err != nil {
return "", err
}
return cfURL, nil
} | [
"func",
"(",
"lh",
"*",
"cloudFrontStorageMiddleware",
")",
"URLFor",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"keyer",
"... | // URLFor attempts to find a url which may be used to retrieve the file at the given path.
// Returns an error if the file cannot be found. | [
"URLFor",
"attempts",
"to",
"find",
"a",
"url",
"which",
"may",
"be",
"used",
"to",
"retrieve",
"the",
"file",
"at",
"the",
"given",
"path",
".",
"Returns",
"an",
"error",
"if",
"the",
"file",
"cannot",
"be",
"found",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/middleware.go#L187-L205 | train |
docker/distribution | registry/storage/paths.go | digestFromPath | func digestFromPath(digestPath string) (digest.Digest, error) {
digestPath = strings.TrimSuffix(digestPath, "/data")
dir, hex := path.Split(digestPath)
dir = path.Dir(dir)
dir, next := path.Split(dir)
// next is either the algorithm OR the first two characters in the hex string
var algo string
if next == hex[:2] {
algo = path.Base(dir)
} else {
algo = next
}
dgst := digest.NewDigestFromHex(algo, hex)
return dgst, dgst.Validate()
} | go | func digestFromPath(digestPath string) (digest.Digest, error) {
digestPath = strings.TrimSuffix(digestPath, "/data")
dir, hex := path.Split(digestPath)
dir = path.Dir(dir)
dir, next := path.Split(dir)
// next is either the algorithm OR the first two characters in the hex string
var algo string
if next == hex[:2] {
algo = path.Base(dir)
} else {
algo = next
}
dgst := digest.NewDigestFromHex(algo, hex)
return dgst, dgst.Validate()
} | [
"func",
"digestFromPath",
"(",
"digestPath",
"string",
")",
"(",
"digest",
".",
"Digest",
",",
"error",
")",
"{",
"digestPath",
"=",
"strings",
".",
"TrimSuffix",
"(",
"digestPath",
",",
"\"/data\"",
")",
"\n",
"dir",
",",
"hex",
":=",
"path",
".",
"Spli... | // Reconstructs a digest from a path | [
"Reconstructs",
"a",
"digest",
"from",
"a",
"path"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/paths.go#L460-L477 | train |
docker/distribution | registry/storage/blobwriter.go | Commit | func (bw *blobWriter) Commit(ctx context.Context, desc distribution.Descriptor) (distribution.Descriptor, error) {
dcontext.GetLogger(ctx).Debug("(*blobWriter).Commit")
if err := bw.fileWriter.Commit(); err != nil {
return distribution.Descriptor{}, err
}
bw.Close()
desc.Size = bw.Size()
canonical, err := bw.validateBlob(ctx, desc)
if err != nil {
return distribution.Descriptor{}, err
}
if err := bw.moveBlob(ctx, canonical); err != nil {
return distribution.Descriptor{}, err
}
if err := bw.blobStore.linkBlob(ctx, canonical, desc.Digest); err != nil {
return distribution.Descriptor{}, err
}
if err := bw.removeResources(ctx); err != nil {
return distribution.Descriptor{}, err
}
err = bw.blobStore.blobAccessController.SetDescriptor(ctx, canonical.Digest, canonical)
if err != nil {
return distribution.Descriptor{}, err
}
bw.committed = true
return canonical, nil
} | go | func (bw *blobWriter) Commit(ctx context.Context, desc distribution.Descriptor) (distribution.Descriptor, error) {
dcontext.GetLogger(ctx).Debug("(*blobWriter).Commit")
if err := bw.fileWriter.Commit(); err != nil {
return distribution.Descriptor{}, err
}
bw.Close()
desc.Size = bw.Size()
canonical, err := bw.validateBlob(ctx, desc)
if err != nil {
return distribution.Descriptor{}, err
}
if err := bw.moveBlob(ctx, canonical); err != nil {
return distribution.Descriptor{}, err
}
if err := bw.blobStore.linkBlob(ctx, canonical, desc.Digest); err != nil {
return distribution.Descriptor{}, err
}
if err := bw.removeResources(ctx); err != nil {
return distribution.Descriptor{}, err
}
err = bw.blobStore.blobAccessController.SetDescriptor(ctx, canonical.Digest, canonical)
if err != nil {
return distribution.Descriptor{}, err
}
bw.committed = true
return canonical, nil
} | [
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"Commit",
"(",
"ctx",
"context",
".",
"Context",
",",
"desc",
"distribution",
".",
"Descriptor",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")"... | // Commit marks the upload as completed, returning a valid descriptor. The
// final size and digest are checked against the first descriptor provided. | [
"Commit",
"marks",
"the",
"upload",
"as",
"completed",
"returning",
"a",
"valid",
"descriptor",
".",
"The",
"final",
"size",
"and",
"digest",
"are",
"checked",
"against",
"the",
"first",
"descriptor",
"provided",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter.go#L59-L93 | train |
docker/distribution | registry/storage/blobwriter.go | Cancel | func (bw *blobWriter) Cancel(ctx context.Context) error {
dcontext.GetLogger(ctx).Debug("(*blobWriter).Cancel")
if err := bw.fileWriter.Cancel(); err != nil {
return err
}
if err := bw.Close(); err != nil {
dcontext.GetLogger(ctx).Errorf("error closing blobwriter: %s", err)
}
return bw.removeResources(ctx)
} | go | func (bw *blobWriter) Cancel(ctx context.Context) error {
dcontext.GetLogger(ctx).Debug("(*blobWriter).Cancel")
if err := bw.fileWriter.Cancel(); err != nil {
return err
}
if err := bw.Close(); err != nil {
dcontext.GetLogger(ctx).Errorf("error closing blobwriter: %s", err)
}
return bw.removeResources(ctx)
} | [
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"Cancel",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"(*blobWriter).Cancel\"",
")",
"\n",
"if",
"err",
":=",
"bw",
".",
"fileW... | // Cancel the blob upload process, releasing any resources associated with
// the writer and canceling the operation. | [
"Cancel",
"the",
"blob",
"upload",
"process",
"releasing",
"any",
"resources",
"associated",
"with",
"the",
"writer",
"and",
"canceling",
"the",
"operation",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter.go#L97-L108 | train |
docker/distribution | registry/storage/blobwriter.go | moveBlob | func (bw *blobWriter) moveBlob(ctx context.Context, desc distribution.Descriptor) error {
blobPath, err := pathFor(blobDataPathSpec{
digest: desc.Digest,
})
if err != nil {
return err
}
// Check for existence
if _, err := bw.blobStore.driver.Stat(ctx, blobPath); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
break // ensure that it doesn't exist.
default:
return err
}
} else {
// If the path exists, we can assume that the content has already
// been uploaded, since the blob storage is content-addressable.
// While it may be corrupted, detection of such corruption belongs
// elsewhere.
return nil
}
// If no data was received, we may not actually have a file on disk. Check
// the size here and write a zero-length file to blobPath if this is the
// case. For the most part, this should only ever happen with zero-length
// blobs.
if _, err := bw.blobStore.driver.Stat(ctx, bw.path); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
// HACK(stevvooe): This is slightly dangerous: if we verify above,
// get a hash, then the underlying file is deleted, we risk moving
// a zero-length blob into a nonzero-length blob location. To
// prevent this horrid thing, we employ the hack of only allowing
// to this happen for the digest of an empty blob.
if desc.Digest == digestSha256Empty {
return bw.blobStore.driver.PutContent(ctx, blobPath, []byte{})
}
// We let this fail during the move below.
logrus.
WithField("upload.id", bw.ID()).
WithField("digest", desc.Digest).Warnf("attempted to move zero-length content with non-zero digest")
default:
return err // unrelated error
}
}
// TODO(stevvooe): We should also write the mediatype when executing this move.
return bw.blobStore.driver.Move(ctx, bw.path, blobPath)
} | go | func (bw *blobWriter) moveBlob(ctx context.Context, desc distribution.Descriptor) error {
blobPath, err := pathFor(blobDataPathSpec{
digest: desc.Digest,
})
if err != nil {
return err
}
// Check for existence
if _, err := bw.blobStore.driver.Stat(ctx, blobPath); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
break // ensure that it doesn't exist.
default:
return err
}
} else {
// If the path exists, we can assume that the content has already
// been uploaded, since the blob storage is content-addressable.
// While it may be corrupted, detection of such corruption belongs
// elsewhere.
return nil
}
// If no data was received, we may not actually have a file on disk. Check
// the size here and write a zero-length file to blobPath if this is the
// case. For the most part, this should only ever happen with zero-length
// blobs.
if _, err := bw.blobStore.driver.Stat(ctx, bw.path); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
// HACK(stevvooe): This is slightly dangerous: if we verify above,
// get a hash, then the underlying file is deleted, we risk moving
// a zero-length blob into a nonzero-length blob location. To
// prevent this horrid thing, we employ the hack of only allowing
// to this happen for the digest of an empty blob.
if desc.Digest == digestSha256Empty {
return bw.blobStore.driver.PutContent(ctx, blobPath, []byte{})
}
// We let this fail during the move below.
logrus.
WithField("upload.id", bw.ID()).
WithField("digest", desc.Digest).Warnf("attempted to move zero-length content with non-zero digest")
default:
return err // unrelated error
}
}
// TODO(stevvooe): We should also write the mediatype when executing this move.
return bw.blobStore.driver.Move(ctx, bw.path, blobPath)
} | [
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"moveBlob",
"(",
"ctx",
"context",
".",
"Context",
",",
"desc",
"distribution",
".",
"Descriptor",
")",
"error",
"{",
"blobPath",
",",
"err",
":=",
"pathFor",
"(",
"blobDataPathSpec",
"{",
"digest",
":",
"desc",
... | // moveBlob moves the data into its final, hash-qualified destination,
// identified by dgst. The layer should be validated before commencing the
// move. | [
"moveBlob",
"moves",
"the",
"data",
"into",
"its",
"final",
"hash",
"-",
"qualified",
"destination",
"identified",
"by",
"dgst",
".",
"The",
"layer",
"should",
"be",
"validated",
"before",
"commencing",
"the",
"move",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter.go#L295-L348 | train |
docker/distribution | registry/storage/blobwriter.go | removeResources | func (bw *blobWriter) removeResources(ctx context.Context) error {
dataPath, err := pathFor(uploadDataPathSpec{
name: bw.blobStore.repository.Named().Name(),
id: bw.id,
})
if err != nil {
return err
}
// Resolve and delete the containing directory, which should include any
// upload related files.
dirPath := path.Dir(dataPath)
if err := bw.blobStore.driver.Delete(ctx, dirPath); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
break // already gone!
default:
// This should be uncommon enough such that returning an error
// should be okay. At this point, the upload should be mostly
// complete, but perhaps the backend became unaccessible.
dcontext.GetLogger(ctx).Errorf("unable to delete layer upload resources %q: %v", dirPath, err)
return err
}
}
return nil
} | go | func (bw *blobWriter) removeResources(ctx context.Context) error {
dataPath, err := pathFor(uploadDataPathSpec{
name: bw.blobStore.repository.Named().Name(),
id: bw.id,
})
if err != nil {
return err
}
// Resolve and delete the containing directory, which should include any
// upload related files.
dirPath := path.Dir(dataPath)
if err := bw.blobStore.driver.Delete(ctx, dirPath); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
break // already gone!
default:
// This should be uncommon enough such that returning an error
// should be okay. At this point, the upload should be mostly
// complete, but perhaps the backend became unaccessible.
dcontext.GetLogger(ctx).Errorf("unable to delete layer upload resources %q: %v", dirPath, err)
return err
}
}
return nil
} | [
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"removeResources",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"dataPath",
",",
"err",
":=",
"pathFor",
"(",
"uploadDataPathSpec",
"{",
"name",
":",
"bw",
".",
"blobStore",
".",
"repository",
".",
... | // removeResources should clean up all resources associated with the upload
// instance. An error will be returned if the clean up cannot proceed. If the
// resources are already not present, no error will be returned. | [
"removeResources",
"should",
"clean",
"up",
"all",
"resources",
"associated",
"with",
"the",
"upload",
"instance",
".",
"An",
"error",
"will",
"be",
"returned",
"if",
"the",
"clean",
"up",
"cannot",
"proceed",
".",
"If",
"the",
"resources",
"are",
"already",
... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter.go#L353-L380 | train |
docker/distribution | manifest/schema1/verify.go | Verify | func Verify(sm *SignedManifest) ([]libtrust.PublicKey, error) {
js, err := libtrust.ParsePrettySignature(sm.all, "signatures")
if err != nil {
logrus.WithField("err", err).Debugf("(*SignedManifest).Verify")
return nil, err
}
return js.Verify()
} | go | func Verify(sm *SignedManifest) ([]libtrust.PublicKey, error) {
js, err := libtrust.ParsePrettySignature(sm.all, "signatures")
if err != nil {
logrus.WithField("err", err).Debugf("(*SignedManifest).Verify")
return nil, err
}
return js.Verify()
} | [
"func",
"Verify",
"(",
"sm",
"*",
"SignedManifest",
")",
"(",
"[",
"]",
"libtrust",
".",
"PublicKey",
",",
"error",
")",
"{",
"js",
",",
"err",
":=",
"libtrust",
".",
"ParsePrettySignature",
"(",
"sm",
".",
"all",
",",
"\"signatures\"",
")",
"\n",
"if"... | // Verify verifies the signature of the signed manifest returning the public
// keys used during signing. | [
"Verify",
"verifies",
"the",
"signature",
"of",
"the",
"signed",
"manifest",
"returning",
"the",
"public",
"keys",
"used",
"during",
"signing",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/verify.go#L12-L20 | train |
docker/distribution | manifest/schema1/verify.go | VerifyChains | func VerifyChains(sm *SignedManifest, ca *x509.CertPool) ([][]*x509.Certificate, error) {
js, err := libtrust.ParsePrettySignature(sm.all, "signatures")
if err != nil {
return nil, err
}
return js.VerifyChains(ca)
} | go | func VerifyChains(sm *SignedManifest, ca *x509.CertPool) ([][]*x509.Certificate, error) {
js, err := libtrust.ParsePrettySignature(sm.all, "signatures")
if err != nil {
return nil, err
}
return js.VerifyChains(ca)
} | [
"func",
"VerifyChains",
"(",
"sm",
"*",
"SignedManifest",
",",
"ca",
"*",
"x509",
".",
"CertPool",
")",
"(",
"[",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"js",
",",
"err",
":=",
"libtrust",
".",
"ParsePrettySignature",
... | // VerifyChains verifies the signature of the signed manifest against the
// certificate pool returning the list of verified chains. Signatures without
// an x509 chain are not checked. | [
"VerifyChains",
"verifies",
"the",
"signature",
"of",
"the",
"signed",
"manifest",
"against",
"the",
"certificate",
"pool",
"returning",
"the",
"list",
"of",
"verified",
"chains",
".",
"Signatures",
"without",
"an",
"x509",
"chain",
"are",
"not",
"checked",
"."
... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/verify.go#L25-L32 | train |
docker/distribution | registry/proxy/proxyauth.go | configureAuth | func configureAuth(username, password, remoteURL string) (auth.CredentialStore, error) {
creds := map[string]userpass{}
authURLs, err := getAuthURLs(remoteURL)
if err != nil {
return nil, err
}
for _, url := range authURLs {
context.GetLogger(context.Background()).Infof("Discovered token authentication URL: %s", url)
creds[url] = userpass{
username: username,
password: password,
}
}
return credentials{creds: creds}, nil
} | go | func configureAuth(username, password, remoteURL string) (auth.CredentialStore, error) {
creds := map[string]userpass{}
authURLs, err := getAuthURLs(remoteURL)
if err != nil {
return nil, err
}
for _, url := range authURLs {
context.GetLogger(context.Background()).Infof("Discovered token authentication URL: %s", url)
creds[url] = userpass{
username: username,
password: password,
}
}
return credentials{creds: creds}, nil
} | [
"func",
"configureAuth",
"(",
"username",
",",
"password",
",",
"remoteURL",
"string",
")",
"(",
"auth",
".",
"CredentialStore",
",",
"error",
")",
"{",
"creds",
":=",
"map",
"[",
"string",
"]",
"userpass",
"{",
"}",
"\n",
"authURLs",
",",
"err",
":=",
... | // configureAuth stores credentials for challenge responses | [
"configureAuth",
"stores",
"credentials",
"for",
"challenge",
"responses"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxyauth.go#L38-L55 | train |
docker/distribution | registry/storage/driver/inmemory/mfs.go | add | func (d *dir) add(n node) {
if d.children == nil {
d.children = make(map[string]node)
}
d.children[n.name()] = n
d.mod = time.Now()
} | go | func (d *dir) add(n node) {
if d.children == nil {
d.children = make(map[string]node)
}
d.children[n.name()] = n
d.mod = time.Now()
} | [
"func",
"(",
"d",
"*",
"dir",
")",
"add",
"(",
"n",
"node",
")",
"{",
"if",
"d",
".",
"children",
"==",
"nil",
"{",
"d",
".",
"children",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"node",
")",
"\n",
"}",
"\n",
"d",
".",
"children",
"[",
... | // add places the node n into dir d. | [
"add",
"places",
"the",
"node",
"n",
"into",
"dir",
"d",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/inmemory/mfs.go#L42-L49 | train |
docker/distribution | registry/storage/driver/inmemory/mfs.go | mkfile | func (d *dir) mkfile(p string) (*file, error) {
n := d.find(p)
if n.path() == p {
if n.isdir() {
return nil, errIsDir
}
return n.(*file), nil
}
dirpath, filename := path.Split(p)
// Make any non-existent directories
n, err := d.mkdirs(dirpath)
if err != nil {
return nil, err
}
dd := n.(*dir)
n = &file{
common: common{
p: path.Join(dd.path(), filename),
mod: time.Now(),
},
}
dd.add(n)
return n.(*file), nil
} | go | func (d *dir) mkfile(p string) (*file, error) {
n := d.find(p)
if n.path() == p {
if n.isdir() {
return nil, errIsDir
}
return n.(*file), nil
}
dirpath, filename := path.Split(p)
// Make any non-existent directories
n, err := d.mkdirs(dirpath)
if err != nil {
return nil, err
}
dd := n.(*dir)
n = &file{
common: common{
p: path.Join(dd.path(), filename),
mod: time.Now(),
},
}
dd.add(n)
return n.(*file), nil
} | [
"func",
"(",
"d",
"*",
"dir",
")",
"mkfile",
"(",
"p",
"string",
")",
"(",
"*",
"file",
",",
"error",
")",
"{",
"n",
":=",
"d",
".",
"find",
"(",
"p",
")",
"\n",
"if",
"n",
".",
"path",
"(",
")",
"==",
"p",
"{",
"if",
"n",
".",
"isdir",
... | // mkfile or return the existing one. returns an error if it exists and is a
// directory. Essentially, this is open or create. | [
"mkfile",
"or",
"return",
"the",
"existing",
"one",
".",
"returns",
"an",
"error",
"if",
"it",
"exists",
"and",
"is",
"a",
"directory",
".",
"Essentially",
"this",
"is",
"open",
"or",
"create",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/inmemory/mfs.go#L111-L138 | train |
docker/distribution | registry/storage/driver/inmemory/mfs.go | mkdirs | func (d *dir) mkdirs(p string) (*dir, error) {
p = normalize(p)
n := d.find(p)
if !n.isdir() {
// Found something there
return nil, errIsNotDir
}
if n.path() == p {
return n.(*dir), nil
}
dd := n.(*dir)
relative := strings.Trim(strings.TrimPrefix(p, n.path()), "/")
if relative == "" {
return dd, nil
}
components := strings.Split(relative, "/")
for _, component := range components {
d, err := dd.mkdir(component)
if err != nil {
// This should actually never happen, since there are no children.
return nil, err
}
dd = d
}
return dd, nil
} | go | func (d *dir) mkdirs(p string) (*dir, error) {
p = normalize(p)
n := d.find(p)
if !n.isdir() {
// Found something there
return nil, errIsNotDir
}
if n.path() == p {
return n.(*dir), nil
}
dd := n.(*dir)
relative := strings.Trim(strings.TrimPrefix(p, n.path()), "/")
if relative == "" {
return dd, nil
}
components := strings.Split(relative, "/")
for _, component := range components {
d, err := dd.mkdir(component)
if err != nil {
// This should actually never happen, since there are no children.
return nil, err
}
dd = d
}
return dd, nil
} | [
"func",
"(",
"d",
"*",
"dir",
")",
"mkdirs",
"(",
"p",
"string",
")",
"(",
"*",
"dir",
",",
"error",
")",
"{",
"p",
"=",
"normalize",
"(",
"p",
")",
"\n",
"n",
":=",
"d",
".",
"find",
"(",
"p",
")",
"\n",
"if",
"!",
"n",
".",
"isdir",
"("... | // mkdirs creates any missing directory entries in p and returns the result. | [
"mkdirs",
"creates",
"any",
"missing",
"directory",
"entries",
"in",
"p",
"and",
"returns",
"the",
"result",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/inmemory/mfs.go#L141-L175 | train |
docker/distribution | registry/storage/driver/inmemory/mfs.go | mkdir | func (d *dir) mkdir(name string) (*dir, error) {
if name == "" {
return nil, fmt.Errorf("invalid dirname")
}
_, ok := d.children[name]
if ok {
return nil, errExists
}
child := &dir{
common: common{
p: path.Join(d.path(), name),
mod: time.Now(),
},
}
d.add(child)
d.mod = time.Now()
return child, nil
} | go | func (d *dir) mkdir(name string) (*dir, error) {
if name == "" {
return nil, fmt.Errorf("invalid dirname")
}
_, ok := d.children[name]
if ok {
return nil, errExists
}
child := &dir{
common: common{
p: path.Join(d.path(), name),
mod: time.Now(),
},
}
d.add(child)
d.mod = time.Now()
return child, nil
} | [
"func",
"(",
"d",
"*",
"dir",
")",
"mkdir",
"(",
"name",
"string",
")",
"(",
"*",
"dir",
",",
"error",
")",
"{",
"if",
"name",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"invalid dirname\"",
")",
"\n",
"}",
"\n",
"_",
... | // mkdir creates a child directory under d with the given name. | [
"mkdir",
"creates",
"a",
"child",
"directory",
"under",
"d",
"with",
"the",
"given",
"name",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/inmemory/mfs.go#L178-L198 | train |
docker/distribution | registry/client/repository.go | checkHTTPRedirect | func checkHTTPRedirect(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
if len(via) > 0 {
for headerName, headerVals := range via[0].Header {
if headerName != "Accept" && headerName != "Range" {
continue
}
for _, val := range headerVals {
// Don't add to redirected request if redirected
// request already has a header with the same
// name and value.
hasValue := false
for _, existingVal := range req.Header[headerName] {
if existingVal == val {
hasValue = true
break
}
}
if !hasValue {
req.Header.Add(headerName, val)
}
}
}
}
return nil
} | go | func checkHTTPRedirect(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
if len(via) > 0 {
for headerName, headerVals := range via[0].Header {
if headerName != "Accept" && headerName != "Range" {
continue
}
for _, val := range headerVals {
// Don't add to redirected request if redirected
// request already has a header with the same
// name and value.
hasValue := false
for _, existingVal := range req.Header[headerName] {
if existingVal == val {
hasValue = true
break
}
}
if !hasValue {
req.Header.Add(headerName, val)
}
}
}
}
return nil
} | [
"func",
"checkHTTPRedirect",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"via",
"[",
"]",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"if",
"len",
"(",
"via",
")",
">=",
"10",
"{",
"return",
"errors",
".",
"New",
"(",
"\"stopped after 10 redirect... | // checkHTTPRedirect is a callback that can manipulate redirected HTTP
// requests. It is used to preserve Accept and Range headers. | [
"checkHTTPRedirect",
"is",
"a",
"callback",
"that",
"can",
"manipulate",
"redirected",
"HTTP",
"requests",
".",
"It",
"is",
"used",
"to",
"preserve",
"Accept",
"and",
"Range",
"headers",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L33-L62 | train |
docker/distribution | registry/client/repository.go | NewRegistry | func NewRegistry(baseURL string, transport http.RoundTripper) (Registry, error) {
ub, err := v2.NewURLBuilderFromString(baseURL, false)
if err != nil {
return nil, err
}
client := &http.Client{
Transport: transport,
Timeout: 1 * time.Minute,
CheckRedirect: checkHTTPRedirect,
}
return ®istry{
client: client,
ub: ub,
}, nil
} | go | func NewRegistry(baseURL string, transport http.RoundTripper) (Registry, error) {
ub, err := v2.NewURLBuilderFromString(baseURL, false)
if err != nil {
return nil, err
}
client := &http.Client{
Transport: transport,
Timeout: 1 * time.Minute,
CheckRedirect: checkHTTPRedirect,
}
return ®istry{
client: client,
ub: ub,
}, nil
} | [
"func",
"NewRegistry",
"(",
"baseURL",
"string",
",",
"transport",
"http",
".",
"RoundTripper",
")",
"(",
"Registry",
",",
"error",
")",
"{",
"ub",
",",
"err",
":=",
"v2",
".",
"NewURLBuilderFromString",
"(",
"baseURL",
",",
"false",
")",
"\n",
"if",
"er... | // NewRegistry creates a registry namespace which can be used to get a listing of repositories | [
"NewRegistry",
"creates",
"a",
"registry",
"namespace",
"which",
"can",
"be",
"used",
"to",
"get",
"a",
"listing",
"of",
"repositories"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L65-L81 | train |
docker/distribution | registry/client/repository.go | Repositories | func (r *registry) Repositories(ctx context.Context, entries []string, last string) (int, error) {
var numFilled int
var returnErr error
values := buildCatalogValues(len(entries), last)
u, err := r.ub.BuildCatalogURL(values)
if err != nil {
return 0, err
}
resp, err := r.client.Get(u)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if SuccessStatus(resp.StatusCode) {
var ctlg struct {
Repositories []string `json:"repositories"`
}
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&ctlg); err != nil {
return 0, err
}
for cnt := range ctlg.Repositories {
entries[cnt] = ctlg.Repositories[cnt]
}
numFilled = len(ctlg.Repositories)
link := resp.Header.Get("Link")
if link == "" {
returnErr = io.EOF
}
} else {
return 0, HandleErrorResponse(resp)
}
return numFilled, returnErr
} | go | func (r *registry) Repositories(ctx context.Context, entries []string, last string) (int, error) {
var numFilled int
var returnErr error
values := buildCatalogValues(len(entries), last)
u, err := r.ub.BuildCatalogURL(values)
if err != nil {
return 0, err
}
resp, err := r.client.Get(u)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if SuccessStatus(resp.StatusCode) {
var ctlg struct {
Repositories []string `json:"repositories"`
}
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&ctlg); err != nil {
return 0, err
}
for cnt := range ctlg.Repositories {
entries[cnt] = ctlg.Repositories[cnt]
}
numFilled = len(ctlg.Repositories)
link := resp.Header.Get("Link")
if link == "" {
returnErr = io.EOF
}
} else {
return 0, HandleErrorResponse(resp)
}
return numFilled, returnErr
} | [
"func",
"(",
"r",
"*",
"registry",
")",
"Repositories",
"(",
"ctx",
"context",
".",
"Context",
",",
"entries",
"[",
"]",
"string",
",",
"last",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"var",
"numFilled",
"int",
"\n",
"var",
"returnErr",
"e... | // Repositories returns a lexigraphically sorted catalog given a base URL. The 'entries' slice will be filled up to the size
// of the slice, starting at the value provided in 'last'. The number of entries will be returned along with io.EOF if there
// are no more entries | [
"Repositories",
"returns",
"a",
"lexigraphically",
"sorted",
"catalog",
"given",
"a",
"base",
"URL",
".",
"The",
"entries",
"slice",
"will",
"be",
"filled",
"up",
"to",
"the",
"size",
"of",
"the",
"slice",
"starting",
"at",
"the",
"value",
"provided",
"in",
... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L91-L131 | train |
docker/distribution | registry/client/repository.go | NewRepository | func NewRepository(name reference.Named, baseURL string, transport http.RoundTripper) (distribution.Repository, error) {
ub, err := v2.NewURLBuilderFromString(baseURL, false)
if err != nil {
return nil, err
}
client := &http.Client{
Transport: transport,
CheckRedirect: checkHTTPRedirect,
// TODO(dmcgowan): create cookie jar
}
return &repository{
client: client,
ub: ub,
name: name,
}, nil
} | go | func NewRepository(name reference.Named, baseURL string, transport http.RoundTripper) (distribution.Repository, error) {
ub, err := v2.NewURLBuilderFromString(baseURL, false)
if err != nil {
return nil, err
}
client := &http.Client{
Transport: transport,
CheckRedirect: checkHTTPRedirect,
// TODO(dmcgowan): create cookie jar
}
return &repository{
client: client,
ub: ub,
name: name,
}, nil
} | [
"func",
"NewRepository",
"(",
"name",
"reference",
".",
"Named",
",",
"baseURL",
"string",
",",
"transport",
"http",
".",
"RoundTripper",
")",
"(",
"distribution",
".",
"Repository",
",",
"error",
")",
"{",
"ub",
",",
"err",
":=",
"v2",
".",
"NewURLBuilder... | // NewRepository creates a new Repository for the given repository name and base URL. | [
"NewRepository",
"creates",
"a",
"new",
"Repository",
"for",
"the",
"given",
"repository",
"name",
"and",
"base",
"URL",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L134-L151 | train |
docker/distribution | registry/client/repository.go | Get | func (t *tags) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
ref, err := reference.WithTag(t.name, tag)
if err != nil {
return distribution.Descriptor{}, err
}
u, err := t.ub.BuildManifestURL(ref)
if err != nil {
return distribution.Descriptor{}, err
}
newRequest := func(method string) (*http.Response, error) {
req, err := http.NewRequest(method, u, nil)
if err != nil {
return nil, err
}
for _, t := range distribution.ManifestMediaTypes() {
req.Header.Add("Accept", t)
}
resp, err := t.client.Do(req)
return resp, err
}
resp, err := newRequest("HEAD")
if err != nil {
return distribution.Descriptor{}, err
}
defer resp.Body.Close()
switch {
case resp.StatusCode >= 200 && resp.StatusCode < 400 && len(resp.Header.Get("Docker-Content-Digest")) > 0:
// if the response is a success AND a Docker-Content-Digest can be retrieved from the headers
return descriptorFromResponse(resp)
default:
// if the response is an error - there will be no body to decode.
// Issue a GET request:
// - for data from a server that does not handle HEAD
// - to get error details in case of a failure
resp, err = newRequest("GET")
if err != nil {
return distribution.Descriptor{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 400 {
return descriptorFromResponse(resp)
}
return distribution.Descriptor{}, HandleErrorResponse(resp)
}
} | go | func (t *tags) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
ref, err := reference.WithTag(t.name, tag)
if err != nil {
return distribution.Descriptor{}, err
}
u, err := t.ub.BuildManifestURL(ref)
if err != nil {
return distribution.Descriptor{}, err
}
newRequest := func(method string) (*http.Response, error) {
req, err := http.NewRequest(method, u, nil)
if err != nil {
return nil, err
}
for _, t := range distribution.ManifestMediaTypes() {
req.Header.Add("Accept", t)
}
resp, err := t.client.Do(req)
return resp, err
}
resp, err := newRequest("HEAD")
if err != nil {
return distribution.Descriptor{}, err
}
defer resp.Body.Close()
switch {
case resp.StatusCode >= 200 && resp.StatusCode < 400 && len(resp.Header.Get("Docker-Content-Digest")) > 0:
// if the response is a success AND a Docker-Content-Digest can be retrieved from the headers
return descriptorFromResponse(resp)
default:
// if the response is an error - there will be no body to decode.
// Issue a GET request:
// - for data from a server that does not handle HEAD
// - to get error details in case of a failure
resp, err = newRequest("GET")
if err != nil {
return distribution.Descriptor{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 400 {
return descriptorFromResponse(resp)
}
return distribution.Descriptor{}, HandleErrorResponse(resp)
}
} | [
"func",
"(",
"t",
"*",
"tags",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"tag",
"string",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"ref",
",",
"err",
":=",
"reference",
".",
"WithTag",
"(",
"t",
".",
"name"... | // Get issues a HEAD request for a Manifest against its named endpoint in order
// to construct a descriptor for the tag. If the registry doesn't support HEADing
// a manifest, fallback to GET. | [
"Get",
"issues",
"a",
"HEAD",
"request",
"for",
"a",
"Manifest",
"against",
"its",
"named",
"endpoint",
"in",
"order",
"to",
"construct",
"a",
"descriptor",
"for",
"the",
"tag",
".",
"If",
"the",
"registry",
"doesn",
"t",
"support",
"HEADing",
"a",
"manife... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L299-L348 | train |
docker/distribution | registry/client/repository.go | Put | func (ms *manifests) Put(ctx context.Context, m distribution.Manifest, options ...distribution.ManifestServiceOption) (digest.Digest, error) {
ref := ms.name
var tagged bool
for _, option := range options {
if opt, ok := option.(distribution.WithTagOption); ok {
var err error
ref, err = reference.WithTag(ref, opt.Tag)
if err != nil {
return "", err
}
tagged = true
} else {
err := option.Apply(ms)
if err != nil {
return "", err
}
}
}
mediaType, p, err := m.Payload()
if err != nil {
return "", err
}
if !tagged {
// generate a canonical digest and Put by digest
_, d, err := distribution.UnmarshalManifest(mediaType, p)
if err != nil {
return "", err
}
ref, err = reference.WithDigest(ref, d.Digest)
if err != nil {
return "", err
}
}
manifestURL, err := ms.ub.BuildManifestURL(ref)
if err != nil {
return "", err
}
putRequest, err := http.NewRequest("PUT", manifestURL, bytes.NewReader(p))
if err != nil {
return "", err
}
putRequest.Header.Set("Content-Type", mediaType)
resp, err := ms.client.Do(putRequest)
if err != nil {
return "", err
}
defer resp.Body.Close()
if SuccessStatus(resp.StatusCode) {
dgstHeader := resp.Header.Get("Docker-Content-Digest")
dgst, err := digest.Parse(dgstHeader)
if err != nil {
return "", err
}
return dgst, nil
}
return "", HandleErrorResponse(resp)
} | go | func (ms *manifests) Put(ctx context.Context, m distribution.Manifest, options ...distribution.ManifestServiceOption) (digest.Digest, error) {
ref := ms.name
var tagged bool
for _, option := range options {
if opt, ok := option.(distribution.WithTagOption); ok {
var err error
ref, err = reference.WithTag(ref, opt.Tag)
if err != nil {
return "", err
}
tagged = true
} else {
err := option.Apply(ms)
if err != nil {
return "", err
}
}
}
mediaType, p, err := m.Payload()
if err != nil {
return "", err
}
if !tagged {
// generate a canonical digest and Put by digest
_, d, err := distribution.UnmarshalManifest(mediaType, p)
if err != nil {
return "", err
}
ref, err = reference.WithDigest(ref, d.Digest)
if err != nil {
return "", err
}
}
manifestURL, err := ms.ub.BuildManifestURL(ref)
if err != nil {
return "", err
}
putRequest, err := http.NewRequest("PUT", manifestURL, bytes.NewReader(p))
if err != nil {
return "", err
}
putRequest.Header.Set("Content-Type", mediaType)
resp, err := ms.client.Do(putRequest)
if err != nil {
return "", err
}
defer resp.Body.Close()
if SuccessStatus(resp.StatusCode) {
dgstHeader := resp.Header.Get("Docker-Content-Digest")
dgst, err := digest.Parse(dgstHeader)
if err != nil {
return "", err
}
return dgst, nil
}
return "", HandleErrorResponse(resp)
} | [
"func",
"(",
"ms",
"*",
"manifests",
")",
"Put",
"(",
"ctx",
"context",
".",
"Context",
",",
"m",
"distribution",
".",
"Manifest",
",",
"options",
"...",
"distribution",
".",
"ManifestServiceOption",
")",
"(",
"digest",
".",
"Digest",
",",
"error",
")",
... | // Put puts a manifest. A tag can be specified using an options parameter which uses some shared state to hold the
// tag name in order to build the correct upload URL. | [
"Put",
"puts",
"a",
"manifest",
".",
"A",
"tag",
"can",
"be",
"specified",
"using",
"an",
"options",
"parameter",
"which",
"uses",
"some",
"shared",
"state",
"to",
"hold",
"the",
"tag",
"name",
"in",
"order",
"to",
"build",
"the",
"correct",
"upload",
"U... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L514-L579 | train |
docker/distribution | registry/client/repository.go | WithMountFrom | func WithMountFrom(ref reference.Canonical) distribution.BlobCreateOption {
return optionFunc(func(v interface{}) error {
opts, ok := v.(*distribution.CreateOptions)
if !ok {
return fmt.Errorf("unexpected options type: %T", v)
}
opts.Mount.ShouldMount = true
opts.Mount.From = ref
return nil
})
} | go | func WithMountFrom(ref reference.Canonical) distribution.BlobCreateOption {
return optionFunc(func(v interface{}) error {
opts, ok := v.(*distribution.CreateOptions)
if !ok {
return fmt.Errorf("unexpected options type: %T", v)
}
opts.Mount.ShouldMount = true
opts.Mount.From = ref
return nil
})
} | [
"func",
"WithMountFrom",
"(",
"ref",
"reference",
".",
"Canonical",
")",
"distribution",
".",
"BlobCreateOption",
"{",
"return",
"optionFunc",
"(",
"func",
"(",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"opts",
",",
"ok",
":=",
"v",
".",
"(",
"*",
... | // WithMountFrom returns a BlobCreateOption which designates that the blob should be
// mounted from the given canonical reference. | [
"WithMountFrom",
"returns",
"a",
"BlobCreateOption",
"which",
"designates",
"that",
"the",
"blob",
"should",
"be",
"mounted",
"from",
"the",
"given",
"canonical",
"reference",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L704-L716 | train |
docker/distribution | registry/client/auth/session.go | String | func (rs RepositoryScope) String() string {
repoType := "repository"
// Keep existing format for image class to maintain backwards compatibility
// with authorization servers which do not support the expanded grammar.
if rs.Class != "" && rs.Class != "image" {
repoType = fmt.Sprintf("%s(%s)", repoType, rs.Class)
}
return fmt.Sprintf("%s:%s:%s", repoType, rs.Repository, strings.Join(rs.Actions, ","))
} | go | func (rs RepositoryScope) String() string {
repoType := "repository"
// Keep existing format for image class to maintain backwards compatibility
// with authorization servers which do not support the expanded grammar.
if rs.Class != "" && rs.Class != "image" {
repoType = fmt.Sprintf("%s(%s)", repoType, rs.Class)
}
return fmt.Sprintf("%s:%s:%s", repoType, rs.Repository, strings.Join(rs.Actions, ","))
} | [
"func",
"(",
"rs",
"RepositoryScope",
")",
"String",
"(",
")",
"string",
"{",
"repoType",
":=",
"\"repository\"",
"\n",
"if",
"rs",
".",
"Class",
"!=",
"\"\"",
"&&",
"rs",
".",
"Class",
"!=",
"\"image\"",
"{",
"repoType",
"=",
"fmt",
".",
"Sprintf",
"(... | // String returns the string representation of the repository
// using the scope grammar | [
"String",
"returns",
"the",
"string",
"representation",
"of",
"the",
"repository",
"using",
"the",
"scope",
"grammar"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/session.go#L155-L163 | train |
docker/distribution | registry/client/auth/session.go | String | func (rs RegistryScope) String() string {
return fmt.Sprintf("registry:%s:%s", rs.Name, strings.Join(rs.Actions, ","))
} | go | func (rs RegistryScope) String() string {
return fmt.Sprintf("registry:%s:%s", rs.Name, strings.Join(rs.Actions, ","))
} | [
"func",
"(",
"rs",
"RegistryScope",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"registry:%s:%s\"",
",",
"rs",
".",
"Name",
",",
"strings",
".",
"Join",
"(",
"rs",
".",
"Actions",
",",
"\",\"",
")",
")",
"\n",
"}"
... | // String returns the string representation of the user
// using the scope grammar | [
"String",
"returns",
"the",
"string",
"representation",
"of",
"the",
"user",
"using",
"the",
"scope",
"grammar"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/session.go#L174-L176 | train |
docker/distribution | registry/client/auth/session.go | NewTokenHandler | func NewTokenHandler(transport http.RoundTripper, creds CredentialStore, scope string, actions ...string) AuthenticationHandler {
// Create options...
return NewTokenHandlerWithOptions(TokenHandlerOptions{
Transport: transport,
Credentials: creds,
Scopes: []Scope{
RepositoryScope{
Repository: scope,
Actions: actions,
},
},
})
} | go | func NewTokenHandler(transport http.RoundTripper, creds CredentialStore, scope string, actions ...string) AuthenticationHandler {
// Create options...
return NewTokenHandlerWithOptions(TokenHandlerOptions{
Transport: transport,
Credentials: creds,
Scopes: []Scope{
RepositoryScope{
Repository: scope,
Actions: actions,
},
},
})
} | [
"func",
"NewTokenHandler",
"(",
"transport",
"http",
".",
"RoundTripper",
",",
"creds",
"CredentialStore",
",",
"scope",
"string",
",",
"actions",
"...",
"string",
")",
"AuthenticationHandler",
"{",
"return",
"NewTokenHandlerWithOptions",
"(",
"TokenHandlerOptions",
"... | // NewTokenHandler creates a new AuthenicationHandler which supports
// fetching tokens from a remote token server. | [
"NewTokenHandler",
"creates",
"a",
"new",
"AuthenicationHandler",
"which",
"supports",
"fetching",
"tokens",
"from",
"a",
"remote",
"token",
"server",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/session.go#L210-L222 | train |
docker/distribution | registry/client/auth/session.go | NewTokenHandlerWithOptions | func NewTokenHandlerWithOptions(options TokenHandlerOptions) AuthenticationHandler {
handler := &tokenHandler{
transport: options.Transport,
creds: options.Credentials,
offlineAccess: options.OfflineAccess,
forceOAuth: options.ForceOAuth,
clientID: options.ClientID,
scopes: options.Scopes,
clock: realClock{},
logger: options.Logger,
}
return handler
} | go | func NewTokenHandlerWithOptions(options TokenHandlerOptions) AuthenticationHandler {
handler := &tokenHandler{
transport: options.Transport,
creds: options.Credentials,
offlineAccess: options.OfflineAccess,
forceOAuth: options.ForceOAuth,
clientID: options.ClientID,
scopes: options.Scopes,
clock: realClock{},
logger: options.Logger,
}
return handler
} | [
"func",
"NewTokenHandlerWithOptions",
"(",
"options",
"TokenHandlerOptions",
")",
"AuthenticationHandler",
"{",
"handler",
":=",
"&",
"tokenHandler",
"{",
"transport",
":",
"options",
".",
"Transport",
",",
"creds",
":",
"options",
".",
"Credentials",
",",
"offlineA... | // NewTokenHandlerWithOptions creates a new token handler using the provided
// options structure. | [
"NewTokenHandlerWithOptions",
"creates",
"a",
"new",
"token",
"handler",
"using",
"the",
"provided",
"options",
"structure",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/session.go#L226-L239 | train |
docker/distribution | registry/proxy/proxymetrics.go | BlobPull | func (pmc *proxyMetricsCollector) BlobPull(bytesPulled uint64) {
atomic.AddUint64(&pmc.blobMetrics.Misses, 1)
atomic.AddUint64(&pmc.blobMetrics.BytesPulled, bytesPulled)
} | go | func (pmc *proxyMetricsCollector) BlobPull(bytesPulled uint64) {
atomic.AddUint64(&pmc.blobMetrics.Misses, 1)
atomic.AddUint64(&pmc.blobMetrics.BytesPulled, bytesPulled)
} | [
"func",
"(",
"pmc",
"*",
"proxyMetricsCollector",
")",
"BlobPull",
"(",
"bytesPulled",
"uint64",
")",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"blobMetrics",
".",
"Misses",
",",
"1",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
... | // BlobPull tracks metrics about blobs pulled into the cache | [
"BlobPull",
"tracks",
"metrics",
"about",
"blobs",
"pulled",
"into",
"the",
"cache"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxymetrics.go#L24-L27 | train |
docker/distribution | registry/proxy/proxymetrics.go | BlobPush | func (pmc *proxyMetricsCollector) BlobPush(bytesPushed uint64) {
atomic.AddUint64(&pmc.blobMetrics.Requests, 1)
atomic.AddUint64(&pmc.blobMetrics.Hits, 1)
atomic.AddUint64(&pmc.blobMetrics.BytesPushed, bytesPushed)
} | go | func (pmc *proxyMetricsCollector) BlobPush(bytesPushed uint64) {
atomic.AddUint64(&pmc.blobMetrics.Requests, 1)
atomic.AddUint64(&pmc.blobMetrics.Hits, 1)
atomic.AddUint64(&pmc.blobMetrics.BytesPushed, bytesPushed)
} | [
"func",
"(",
"pmc",
"*",
"proxyMetricsCollector",
")",
"BlobPush",
"(",
"bytesPushed",
"uint64",
")",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"blobMetrics",
".",
"Requests",
",",
"1",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",... | // BlobPush tracks metrics about blobs pushed to clients | [
"BlobPush",
"tracks",
"metrics",
"about",
"blobs",
"pushed",
"to",
"clients"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxymetrics.go#L30-L34 | train |
docker/distribution | registry/proxy/proxymetrics.go | ManifestPull | func (pmc *proxyMetricsCollector) ManifestPull(bytesPulled uint64) {
atomic.AddUint64(&pmc.manifestMetrics.Misses, 1)
atomic.AddUint64(&pmc.manifestMetrics.BytesPulled, bytesPulled)
} | go | func (pmc *proxyMetricsCollector) ManifestPull(bytesPulled uint64) {
atomic.AddUint64(&pmc.manifestMetrics.Misses, 1)
atomic.AddUint64(&pmc.manifestMetrics.BytesPulled, bytesPulled)
} | [
"func",
"(",
"pmc",
"*",
"proxyMetricsCollector",
")",
"ManifestPull",
"(",
"bytesPulled",
"uint64",
")",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"manifestMetrics",
".",
"Misses",
",",
"1",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
... | // ManifestPull tracks metrics related to Manifests pulled into the cache | [
"ManifestPull",
"tracks",
"metrics",
"related",
"to",
"Manifests",
"pulled",
"into",
"the",
"cache"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxymetrics.go#L37-L40 | train |
docker/distribution | registry/proxy/proxymetrics.go | ManifestPush | func (pmc *proxyMetricsCollector) ManifestPush(bytesPushed uint64) {
atomic.AddUint64(&pmc.manifestMetrics.Requests, 1)
atomic.AddUint64(&pmc.manifestMetrics.Hits, 1)
atomic.AddUint64(&pmc.manifestMetrics.BytesPushed, bytesPushed)
} | go | func (pmc *proxyMetricsCollector) ManifestPush(bytesPushed uint64) {
atomic.AddUint64(&pmc.manifestMetrics.Requests, 1)
atomic.AddUint64(&pmc.manifestMetrics.Hits, 1)
atomic.AddUint64(&pmc.manifestMetrics.BytesPushed, bytesPushed)
} | [
"func",
"(",
"pmc",
"*",
"proxyMetricsCollector",
")",
"ManifestPush",
"(",
"bytesPushed",
"uint64",
")",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"manifestMetrics",
".",
"Requests",
",",
"1",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
... | // ManifestPush tracks metrics about manifests pushed to clients | [
"ManifestPush",
"tracks",
"metrics",
"about",
"manifests",
"pushed",
"to",
"clients"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxymetrics.go#L43-L47 | train |
docker/distribution | registry/storage/driver/middleware/alicdn/middleware.go | URLFor | func (ac *aliCDNStorageMiddleware) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
if ac.StorageDriver.Name() != "oss" {
dcontext.GetLogger(ctx).Warn("the AliCDN middleware does not support this backend storage driver")
return ac.StorageDriver.URLFor(ctx, path, options)
}
acURL, err := ac.urlSigner.Sign(ac.baseURL+path, time.Now().Add(ac.duration))
if err != nil {
return "", err
}
return acURL, nil
} | go | func (ac *aliCDNStorageMiddleware) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
if ac.StorageDriver.Name() != "oss" {
dcontext.GetLogger(ctx).Warn("the AliCDN middleware does not support this backend storage driver")
return ac.StorageDriver.URLFor(ctx, path, options)
}
acURL, err := ac.urlSigner.Sign(ac.baseURL+path, time.Now().Add(ac.duration))
if err != nil {
return "", err
}
return acURL, nil
} | [
"func",
"(",
"ac",
"*",
"aliCDNStorageMiddleware",
")",
"URLFor",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"ac",
... | // URLFor attempts to find a url which may be used to retrieve the file at the given path. | [
"URLFor",
"attempts",
"to",
"find",
"a",
"url",
"which",
"may",
"be",
"used",
"to",
"retrieve",
"the",
"file",
"at",
"the",
"given",
"path",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/alicdn/middleware.go#L100-L111 | train |
docker/distribution | health/api/api.go | DownHandler | func DownHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
updater.Update(errors.New("manual Check"))
} else {
w.WriteHeader(http.StatusNotFound)
}
} | go | func DownHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
updater.Update(errors.New("manual Check"))
} else {
w.WriteHeader(http.StatusNotFound)
}
} | [
"func",
"DownHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"==",
"\"POST\"",
"{",
"updater",
".",
"Update",
"(",
"errors",
".",
"New",
"(",
"\"manual Check\"",
")",
")",
... | // DownHandler registers a manual_http_status that always returns an Error | [
"DownHandler",
"registers",
"a",
"manual_http_status",
"that",
"always",
"returns",
"an",
"Error"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/api/api.go#L15-L21 | train |
docker/distribution | health/api/api.go | UpHandler | func UpHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
updater.Update(nil)
} else {
w.WriteHeader(http.StatusNotFound)
}
} | go | func UpHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
updater.Update(nil)
} else {
w.WriteHeader(http.StatusNotFound)
}
} | [
"func",
"UpHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"==",
"\"POST\"",
"{",
"updater",
".",
"Update",
"(",
"nil",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"WriteHeade... | // UpHandler registers a manual_http_status that always returns nil | [
"UpHandler",
"registers",
"a",
"manual_http_status",
"that",
"always",
"returns",
"nil"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/api/api.go#L24-L30 | train |
docker/distribution | health/api/api.go | init | func init() {
health.Register("manual_http_status", updater)
http.HandleFunc("/debug/health/down", DownHandler)
http.HandleFunc("/debug/health/up", UpHandler)
} | go | func init() {
health.Register("manual_http_status", updater)
http.HandleFunc("/debug/health/down", DownHandler)
http.HandleFunc("/debug/health/up", UpHandler)
} | [
"func",
"init",
"(",
")",
"{",
"health",
".",
"Register",
"(",
"\"manual_http_status\"",
",",
"updater",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"/debug/health/down\"",
",",
"DownHandler",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"/debug/health/up\"",
... | // init sets up the two endpoints to bring the service up and down | [
"init",
"sets",
"up",
"the",
"two",
"endpoints",
"to",
"bring",
"the",
"service",
"up",
"and",
"down"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/api/api.go#L33-L37 | train |
docker/distribution | health/checks/checks.go | HTTPChecker | func HTTPChecker(r string, statusCode int, timeout time.Duration, headers http.Header) health.Checker {
return health.CheckFunc(func() error {
client := http.Client{
Timeout: timeout,
}
req, err := http.NewRequest("HEAD", r, nil)
if err != nil {
return errors.New("error creating request: " + r)
}
for headerName, headerValues := range headers {
for _, headerValue := range headerValues {
req.Header.Add(headerName, headerValue)
}
}
response, err := client.Do(req)
if err != nil {
return errors.New("error while checking: " + r)
}
if response.StatusCode != statusCode {
return errors.New("downstream service returned unexpected status: " + strconv.Itoa(response.StatusCode))
}
return nil
})
} | go | func HTTPChecker(r string, statusCode int, timeout time.Duration, headers http.Header) health.Checker {
return health.CheckFunc(func() error {
client := http.Client{
Timeout: timeout,
}
req, err := http.NewRequest("HEAD", r, nil)
if err != nil {
return errors.New("error creating request: " + r)
}
for headerName, headerValues := range headers {
for _, headerValue := range headerValues {
req.Header.Add(headerName, headerValue)
}
}
response, err := client.Do(req)
if err != nil {
return errors.New("error while checking: " + r)
}
if response.StatusCode != statusCode {
return errors.New("downstream service returned unexpected status: " + strconv.Itoa(response.StatusCode))
}
return nil
})
} | [
"func",
"HTTPChecker",
"(",
"r",
"string",
",",
"statusCode",
"int",
",",
"timeout",
"time",
".",
"Duration",
",",
"headers",
"http",
".",
"Header",
")",
"health",
".",
"Checker",
"{",
"return",
"health",
".",
"CheckFunc",
"(",
"func",
"(",
")",
"error",... | // HTTPChecker does a HEAD request and verifies that the HTTP status code
// returned matches statusCode. | [
"HTTPChecker",
"does",
"a",
"HEAD",
"request",
"and",
"verifies",
"that",
"the",
"HTTP",
"status",
"code",
"returned",
"matches",
"statusCode",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/checks/checks.go#L38-L61 | train |
docker/distribution | health/checks/checks.go | TCPChecker | func TCPChecker(addr string, timeout time.Duration) health.Checker {
return health.CheckFunc(func() error {
conn, err := net.DialTimeout("tcp", addr, timeout)
if err != nil {
return errors.New("connection to " + addr + " failed")
}
conn.Close()
return nil
})
} | go | func TCPChecker(addr string, timeout time.Duration) health.Checker {
return health.CheckFunc(func() error {
conn, err := net.DialTimeout("tcp", addr, timeout)
if err != nil {
return errors.New("connection to " + addr + " failed")
}
conn.Close()
return nil
})
} | [
"func",
"TCPChecker",
"(",
"addr",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"health",
".",
"Checker",
"{",
"return",
"health",
".",
"CheckFunc",
"(",
"func",
"(",
")",
"error",
"{",
"conn",
",",
"err",
":=",
"net",
".",
"DialTimeout",
"(... | // TCPChecker attempts to open a TCP connection. | [
"TCPChecker",
"attempts",
"to",
"open",
"a",
"TCP",
"connection",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/checks/checks.go#L64-L73 | train |
docker/distribution | registry/storage/manifeststore.go | Delete | func (ms *manifestStore) Delete(ctx context.Context, dgst digest.Digest) error {
dcontext.GetLogger(ms.ctx).Debug("(*manifestStore).Delete")
return ms.blobStore.Delete(ctx, dgst)
} | go | func (ms *manifestStore) Delete(ctx context.Context, dgst digest.Digest) error {
dcontext.GetLogger(ms.ctx).Debug("(*manifestStore).Delete")
return ms.blobStore.Delete(ctx, dgst)
} | [
"func",
"(",
"ms",
"*",
"manifestStore",
")",
"Delete",
"(",
"ctx",
"context",
".",
"Context",
",",
"dgst",
"digest",
".",
"Digest",
")",
"error",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ms",
".",
"ctx",
")",
".",
"Debug",
"(",
"\"(*manifestStore).Delet... | // Delete removes the revision of the specified manifest. | [
"Delete",
"removes",
"the",
"revision",
"of",
"the",
"specified",
"manifest",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/manifeststore.go#L147-L150 | train |
docker/distribution | registry/middleware/registry/middleware.go | Register | func Register(name string, initFunc InitFunc) error {
if middlewares == nil {
middlewares = make(map[string]InitFunc)
}
if _, exists := middlewares[name]; exists {
return fmt.Errorf("name already registered: %s", name)
}
middlewares[name] = initFunc
return nil
} | go | func Register(name string, initFunc InitFunc) error {
if middlewares == nil {
middlewares = make(map[string]InitFunc)
}
if _, exists := middlewares[name]; exists {
return fmt.Errorf("name already registered: %s", name)
}
middlewares[name] = initFunc
return nil
} | [
"func",
"Register",
"(",
"name",
"string",
",",
"initFunc",
"InitFunc",
")",
"error",
"{",
"if",
"middlewares",
"==",
"nil",
"{",
"middlewares",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"InitFunc",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"exists",
... | // Register is used to register an InitFunc for
// a RegistryMiddleware backend with the given name. | [
"Register",
"is",
"used",
"to",
"register",
"an",
"InitFunc",
"for",
"a",
"RegistryMiddleware",
"backend",
"with",
"the",
"given",
"name",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/middleware/registry/middleware.go#L20-L31 | train |
docker/distribution | registry/middleware/registry/middleware.go | Get | func Get(ctx context.Context, name string, options map[string]interface{}, registry distribution.Namespace) (distribution.Namespace, error) {
if middlewares != nil {
if initFunc, exists := middlewares[name]; exists {
return initFunc(ctx, registry, options)
}
}
return nil, fmt.Errorf("no registry middleware registered with name: %s", name)
} | go | func Get(ctx context.Context, name string, options map[string]interface{}, registry distribution.Namespace) (distribution.Namespace, error) {
if middlewares != nil {
if initFunc, exists := middlewares[name]; exists {
return initFunc(ctx, registry, options)
}
}
return nil, fmt.Errorf("no registry middleware registered with name: %s", name)
} | [
"func",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"registry",
"distribution",
".",
"Namespace",
")",
"(",
"distribution",
".",
"Namespace",
",",
"error",
")... | // Get constructs a RegistryMiddleware with the given options using the named backend. | [
"Get",
"constructs",
"a",
"RegistryMiddleware",
"with",
"the",
"given",
"options",
"using",
"the",
"named",
"backend",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/middleware/registry/middleware.go#L34-L42 | train |
docker/distribution | registry/middleware/registry/middleware.go | RegisterOptions | func RegisterOptions(options ...storage.RegistryOption) error {
registryoptions = append(registryoptions, options...)
return nil
} | go | func RegisterOptions(options ...storage.RegistryOption) error {
registryoptions = append(registryoptions, options...)
return nil
} | [
"func",
"RegisterOptions",
"(",
"options",
"...",
"storage",
".",
"RegistryOption",
")",
"error",
"{",
"registryoptions",
"=",
"append",
"(",
"registryoptions",
",",
"options",
"...",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // RegisterOptions adds more options to RegistryOption list. Options get applied before
// any other configuration-based options. | [
"RegisterOptions",
"adds",
"more",
"options",
"to",
"RegistryOption",
"list",
".",
"Options",
"get",
"applied",
"before",
"any",
"other",
"configuration",
"-",
"based",
"options",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/middleware/registry/middleware.go#L46-L49 | train |
docker/distribution | reference/reference.go | Domain | func Domain(named Named) string {
if r, ok := named.(namedRepository); ok {
return r.Domain()
}
domain, _ := splitDomain(named.Name())
return domain
} | go | func Domain(named Named) string {
if r, ok := named.(namedRepository); ok {
return r.Domain()
}
domain, _ := splitDomain(named.Name())
return domain
} | [
"func",
"Domain",
"(",
"named",
"Named",
")",
"string",
"{",
"if",
"r",
",",
"ok",
":=",
"named",
".",
"(",
"namedRepository",
")",
";",
"ok",
"{",
"return",
"r",
".",
"Domain",
"(",
")",
"\n",
"}",
"\n",
"domain",
",",
"_",
":=",
"splitDomain",
... | // Domain returns the domain part of the Named reference | [
"Domain",
"returns",
"the",
"domain",
"part",
"of",
"the",
"Named",
"reference"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/reference.go#L149-L155 | train |
docker/distribution | reference/reference.go | Path | func Path(named Named) (name string) {
if r, ok := named.(namedRepository); ok {
return r.Path()
}
_, path := splitDomain(named.Name())
return path
} | go | func Path(named Named) (name string) {
if r, ok := named.(namedRepository); ok {
return r.Path()
}
_, path := splitDomain(named.Name())
return path
} | [
"func",
"Path",
"(",
"named",
"Named",
")",
"(",
"name",
"string",
")",
"{",
"if",
"r",
",",
"ok",
":=",
"named",
".",
"(",
"namedRepository",
")",
";",
"ok",
"{",
"return",
"r",
".",
"Path",
"(",
")",
"\n",
"}",
"\n",
"_",
",",
"path",
":=",
... | // Path returns the name without the domain part of the Named reference | [
"Path",
"returns",
"the",
"name",
"without",
"the",
"domain",
"part",
"of",
"the",
"Named",
"reference"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/reference.go#L158-L164 | train |
docker/distribution | reference/reference.go | TrimNamed | func TrimNamed(ref Named) Named {
domain, path := SplitHostname(ref)
return repository{
domain: domain,
path: path,
}
} | go | func TrimNamed(ref Named) Named {
domain, path := SplitHostname(ref)
return repository{
domain: domain,
path: path,
}
} | [
"func",
"TrimNamed",
"(",
"ref",
"Named",
")",
"Named",
"{",
"domain",
",",
"path",
":=",
"SplitHostname",
"(",
"ref",
")",
"\n",
"return",
"repository",
"{",
"domain",
":",
"domain",
",",
"path",
":",
"path",
",",
"}",
"\n",
"}"
] | // TrimNamed removes any tag or digest from the named reference. | [
"TrimNamed",
"removes",
"any",
"tag",
"or",
"digest",
"from",
"the",
"named",
"reference",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/reference.go#L322-L328 | train |
docker/distribution | registry/storage/cache/cachecheck/suite.go | CheckBlobDescriptorCache | func CheckBlobDescriptorCache(t *testing.T, provider cache.BlobDescriptorCacheProvider) {
ctx := context.Background()
checkBlobDescriptorCacheEmptyRepository(ctx, t, provider)
checkBlobDescriptorCacheSetAndRead(ctx, t, provider)
checkBlobDescriptorCacheClear(ctx, t, provider)
} | go | func CheckBlobDescriptorCache(t *testing.T, provider cache.BlobDescriptorCacheProvider) {
ctx := context.Background()
checkBlobDescriptorCacheEmptyRepository(ctx, t, provider)
checkBlobDescriptorCacheSetAndRead(ctx, t, provider)
checkBlobDescriptorCacheClear(ctx, t, provider)
} | [
"func",
"CheckBlobDescriptorCache",
"(",
"t",
"*",
"testing",
".",
"T",
",",
"provider",
"cache",
".",
"BlobDescriptorCacheProvider",
")",
"{",
"ctx",
":=",
"context",
".",
"Background",
"(",
")",
"\n",
"checkBlobDescriptorCacheEmptyRepository",
"(",
"ctx",
",",
... | // CheckBlobDescriptorCache takes a cache implementation through a common set
// of operations. If adding new tests, please add them here so new
// implementations get the benefit. This should be used for unit tests. | [
"CheckBlobDescriptorCache",
"takes",
"a",
"cache",
"implementation",
"through",
"a",
"common",
"set",
"of",
"operations",
".",
"If",
"adding",
"new",
"tests",
"please",
"add",
"them",
"here",
"so",
"new",
"implementations",
"get",
"the",
"benefit",
".",
"This",
... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/cachecheck/suite.go#L16-L22 | train |
docker/distribution | registry/storage/vacuum.go | RemoveBlob | func (v Vacuum) RemoveBlob(dgst string) error {
d, err := digest.Parse(dgst)
if err != nil {
return err
}
blobPath, err := pathFor(blobPathSpec{digest: d})
if err != nil {
return err
}
dcontext.GetLogger(v.ctx).Infof("Deleting blob: %s", blobPath)
err = v.driver.Delete(v.ctx, blobPath)
if err != nil {
return err
}
return nil
} | go | func (v Vacuum) RemoveBlob(dgst string) error {
d, err := digest.Parse(dgst)
if err != nil {
return err
}
blobPath, err := pathFor(blobPathSpec{digest: d})
if err != nil {
return err
}
dcontext.GetLogger(v.ctx).Infof("Deleting blob: %s", blobPath)
err = v.driver.Delete(v.ctx, blobPath)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"v",
"Vacuum",
")",
"RemoveBlob",
"(",
"dgst",
"string",
")",
"error",
"{",
"d",
",",
"err",
":=",
"digest",
".",
"Parse",
"(",
"dgst",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"blobPath",
",",
"err... | // RemoveBlob removes a blob from the filesystem | [
"RemoveBlob",
"removes",
"a",
"blob",
"from",
"the",
"filesystem"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/vacuum.go#L32-L51 | train |
docker/distribution | registry/storage/vacuum.go | RemoveManifest | func (v Vacuum) RemoveManifest(name string, dgst digest.Digest, tags []string) error {
// remove a tag manifest reference, in case of not found continue to next one
for _, tag := range tags {
tagsPath, err := pathFor(manifestTagIndexEntryPathSpec{name: name, revision: dgst, tag: tag})
if err != nil {
return err
}
_, err = v.driver.Stat(v.ctx, tagsPath)
if err != nil {
switch err := err.(type) {
case driver.PathNotFoundError:
continue
default:
return err
}
}
dcontext.GetLogger(v.ctx).Infof("deleting manifest tag reference: %s", tagsPath)
err = v.driver.Delete(v.ctx, tagsPath)
if err != nil {
return err
}
}
manifestPath, err := pathFor(manifestRevisionPathSpec{name: name, revision: dgst})
if err != nil {
return err
}
dcontext.GetLogger(v.ctx).Infof("deleting manifest: %s", manifestPath)
return v.driver.Delete(v.ctx, manifestPath)
} | go | func (v Vacuum) RemoveManifest(name string, dgst digest.Digest, tags []string) error {
// remove a tag manifest reference, in case of not found continue to next one
for _, tag := range tags {
tagsPath, err := pathFor(manifestTagIndexEntryPathSpec{name: name, revision: dgst, tag: tag})
if err != nil {
return err
}
_, err = v.driver.Stat(v.ctx, tagsPath)
if err != nil {
switch err := err.(type) {
case driver.PathNotFoundError:
continue
default:
return err
}
}
dcontext.GetLogger(v.ctx).Infof("deleting manifest tag reference: %s", tagsPath)
err = v.driver.Delete(v.ctx, tagsPath)
if err != nil {
return err
}
}
manifestPath, err := pathFor(manifestRevisionPathSpec{name: name, revision: dgst})
if err != nil {
return err
}
dcontext.GetLogger(v.ctx).Infof("deleting manifest: %s", manifestPath)
return v.driver.Delete(v.ctx, manifestPath)
} | [
"func",
"(",
"v",
"Vacuum",
")",
"RemoveManifest",
"(",
"name",
"string",
",",
"dgst",
"digest",
".",
"Digest",
",",
"tags",
"[",
"]",
"string",
")",
"error",
"{",
"for",
"_",
",",
"tag",
":=",
"range",
"tags",
"{",
"tagsPath",
",",
"err",
":=",
"p... | // RemoveManifest removes a manifest from the filesystem | [
"RemoveManifest",
"removes",
"a",
"manifest",
"from",
"the",
"filesystem"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/vacuum.go#L54-L85 | train |
docker/distribution | registry/storage/vacuum.go | RemoveRepository | func (v Vacuum) RemoveRepository(repoName string) error {
rootForRepository, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
repoDir := path.Join(rootForRepository, repoName)
dcontext.GetLogger(v.ctx).Infof("Deleting repo: %s", repoDir)
err = v.driver.Delete(v.ctx, repoDir)
if err != nil {
return err
}
return nil
} | go | func (v Vacuum) RemoveRepository(repoName string) error {
rootForRepository, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
repoDir := path.Join(rootForRepository, repoName)
dcontext.GetLogger(v.ctx).Infof("Deleting repo: %s", repoDir)
err = v.driver.Delete(v.ctx, repoDir)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"v",
"Vacuum",
")",
"RemoveRepository",
"(",
"repoName",
"string",
")",
"error",
"{",
"rootForRepository",
",",
"err",
":=",
"pathFor",
"(",
"repositoriesRootPathSpec",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",... | // RemoveRepository removes a repository directory from the
// filesystem | [
"RemoveRepository",
"removes",
"a",
"repository",
"directory",
"from",
"the",
"filesystem"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/vacuum.go#L89-L102 | train |
docker/distribution | registry/proxy/proxytagservice.go | Get | func (pt proxyTagService) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
err := pt.authChallenger.tryEstablishChallenges(ctx)
if err == nil {
desc, err := pt.remoteTags.Get(ctx, tag)
if err == nil {
err := pt.localTags.Tag(ctx, tag, desc)
if err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
}
}
desc, err := pt.localTags.Get(ctx, tag)
if err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
} | go | func (pt proxyTagService) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
err := pt.authChallenger.tryEstablishChallenges(ctx)
if err == nil {
desc, err := pt.remoteTags.Get(ctx, tag)
if err == nil {
err := pt.localTags.Tag(ctx, tag, desc)
if err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
}
}
desc, err := pt.localTags.Get(ctx, tag)
if err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
} | [
"func",
"(",
"pt",
"proxyTagService",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"tag",
"string",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"err",
":=",
"pt",
".",
"authChallenger",
".",
"tryEstablishChallenges",
"("... | // Get attempts to get the most recent digest for the tag by checking the remote
// tag service first and then caching it locally. If the remote is unavailable
// the local association is returned | [
"Get",
"attempts",
"to",
"get",
"the",
"most",
"recent",
"digest",
"for",
"the",
"tag",
"by",
"checking",
"the",
"remote",
"tag",
"service",
"first",
"and",
"then",
"caching",
"it",
"locally",
".",
"If",
"the",
"remote",
"is",
"unavailable",
"the",
"local"... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxytagservice.go#L21-L39 | train |
docker/distribution | configuration/configuration.go | UnmarshalYAML | func (version *Version) UnmarshalYAML(unmarshal func(interface{}) error) error {
var versionString string
err := unmarshal(&versionString)
if err != nil {
return err
}
newVersion := Version(versionString)
if _, err := newVersion.major(); err != nil {
return err
}
if _, err := newVersion.minor(); err != nil {
return err
}
*version = newVersion
return nil
} | go | func (version *Version) UnmarshalYAML(unmarshal func(interface{}) error) error {
var versionString string
err := unmarshal(&versionString)
if err != nil {
return err
}
newVersion := Version(versionString)
if _, err := newVersion.major(); err != nil {
return err
}
if _, err := newVersion.minor(); err != nil {
return err
}
*version = newVersion
return nil
} | [
"func",
"(",
"version",
"*",
"Version",
")",
"UnmarshalYAML",
"(",
"unmarshal",
"func",
"(",
"interface",
"{",
"}",
")",
"error",
")",
"error",
"{",
"var",
"versionString",
"string",
"\n",
"err",
":=",
"unmarshal",
"(",
"&",
"versionString",
")",
"\n",
"... | // UnmarshalYAML implements the yaml.Unmarshaler interface
// Unmarshals a string of the form X.Y into a Version, validating that X and Y can represent unsigned integers | [
"UnmarshalYAML",
"implements",
"the",
"yaml",
".",
"Unmarshaler",
"interface",
"Unmarshals",
"a",
"string",
"of",
"the",
"form",
"X",
".",
"Y",
"into",
"a",
"Version",
"validating",
"that",
"X",
"and",
"Y",
"can",
"represent",
"unsigned",
"integers"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/configuration/configuration.go#L353-L371 | train |
docker/distribution | configuration/configuration.go | UnmarshalYAML | func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {
var loglevelString string
err := unmarshal(&loglevelString)
if err != nil {
return err
}
loglevelString = strings.ToLower(loglevelString)
switch loglevelString {
case "error", "warn", "info", "debug":
default:
return fmt.Errorf("invalid loglevel %s Must be one of [error, warn, info, debug]", loglevelString)
}
*loglevel = Loglevel(loglevelString)
return nil
} | go | func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {
var loglevelString string
err := unmarshal(&loglevelString)
if err != nil {
return err
}
loglevelString = strings.ToLower(loglevelString)
switch loglevelString {
case "error", "warn", "info", "debug":
default:
return fmt.Errorf("invalid loglevel %s Must be one of [error, warn, info, debug]", loglevelString)
}
*loglevel = Loglevel(loglevelString)
return nil
} | [
"func",
"(",
"loglevel",
"*",
"Loglevel",
")",
"UnmarshalYAML",
"(",
"unmarshal",
"func",
"(",
"interface",
"{",
"}",
")",
"error",
")",
"error",
"{",
"var",
"loglevelString",
"string",
"\n",
"err",
":=",
"unmarshal",
"(",
"&",
"loglevelString",
")",
"\n",... | // UnmarshalYAML implements the yaml.Umarshaler interface
// Unmarshals a string into a Loglevel, lowercasing the string and validating that it represents a
// valid loglevel | [
"UnmarshalYAML",
"implements",
"the",
"yaml",
".",
"Umarshaler",
"interface",
"Unmarshals",
"a",
"string",
"into",
"a",
"Loglevel",
"lowercasing",
"the",
"string",
"and",
"validating",
"that",
"it",
"represents",
"a",
"valid",
"loglevel"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/configuration/configuration.go#L383-L399 | train |
docker/distribution | configuration/configuration.go | Type | func (storage Storage) Type() string {
var storageType []string
// Return only key in this map
for k := range storage {
switch k {
case "maintenance":
// allow configuration of maintenance
case "cache":
// allow configuration of caching
case "delete":
// allow configuration of delete
case "redirect":
// allow configuration of redirect
default:
storageType = append(storageType, k)
}
}
if len(storageType) > 1 {
panic("multiple storage drivers specified in configuration or environment: " + strings.Join(storageType, ", "))
}
if len(storageType) == 1 {
return storageType[0]
}
return ""
} | go | func (storage Storage) Type() string {
var storageType []string
// Return only key in this map
for k := range storage {
switch k {
case "maintenance":
// allow configuration of maintenance
case "cache":
// allow configuration of caching
case "delete":
// allow configuration of delete
case "redirect":
// allow configuration of redirect
default:
storageType = append(storageType, k)
}
}
if len(storageType) > 1 {
panic("multiple storage drivers specified in configuration or environment: " + strings.Join(storageType, ", "))
}
if len(storageType) == 1 {
return storageType[0]
}
return ""
} | [
"func",
"(",
"storage",
"Storage",
")",
"Type",
"(",
")",
"string",
"{",
"var",
"storageType",
"[",
"]",
"string",
"\n",
"for",
"k",
":=",
"range",
"storage",
"{",
"switch",
"k",
"{",
"case",
"\"maintenance\"",
":",
"case",
"\"cache\"",
":",
"case",
"\... | // Type returns the storage driver type, such as filesystem or s3 | [
"Type",
"returns",
"the",
"storage",
"driver",
"type",
"such",
"as",
"filesystem",
"or",
"s3"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/configuration/configuration.go#L408-L433 | train |
docker/distribution | uuid/uuid.go | Generate | func Generate() (u UUID) {
const (
// ensures we backoff for less than 450ms total. Use the following to
// select new value, in units of 10ms:
// n*(n+1)/2 = d -> n^2 + n - 2d -> n = (sqrt(8d + 1) - 1)/2
maxretries = 9
backoff = time.Millisecond * 10
)
var (
totalBackoff time.Duration
count int
retries int
)
for {
// This should never block but the read may fail. Because of this,
// we just try to read the random number generator until we get
// something. This is a very rare condition but may happen.
b := time.Duration(retries) * backoff
time.Sleep(b)
totalBackoff += b
n, err := io.ReadFull(rand.Reader, u[count:])
if err != nil {
if retryOnError(err) && retries < maxretries {
count += n
retries++
Loggerf("error generating version 4 uuid, retrying: %v", err)
continue
}
// Any other errors represent a system problem. What did someone
// do to /dev/urandom?
panic(fmt.Errorf("error reading random number generator, retried for %v: %v", totalBackoff.String(), err))
}
break
}
u[6] = (u[6] & 0x0f) | 0x40 // set version byte
u[8] = (u[8] & 0x3f) | 0x80 // set high order byte 0b10{8,9,a,b}
return u
} | go | func Generate() (u UUID) {
const (
// ensures we backoff for less than 450ms total. Use the following to
// select new value, in units of 10ms:
// n*(n+1)/2 = d -> n^2 + n - 2d -> n = (sqrt(8d + 1) - 1)/2
maxretries = 9
backoff = time.Millisecond * 10
)
var (
totalBackoff time.Duration
count int
retries int
)
for {
// This should never block but the read may fail. Because of this,
// we just try to read the random number generator until we get
// something. This is a very rare condition but may happen.
b := time.Duration(retries) * backoff
time.Sleep(b)
totalBackoff += b
n, err := io.ReadFull(rand.Reader, u[count:])
if err != nil {
if retryOnError(err) && retries < maxretries {
count += n
retries++
Loggerf("error generating version 4 uuid, retrying: %v", err)
continue
}
// Any other errors represent a system problem. What did someone
// do to /dev/urandom?
panic(fmt.Errorf("error reading random number generator, retried for %v: %v", totalBackoff.String(), err))
}
break
}
u[6] = (u[6] & 0x0f) | 0x40 // set version byte
u[8] = (u[8] & 0x3f) | 0x80 // set high order byte 0b10{8,9,a,b}
return u
} | [
"func",
"Generate",
"(",
")",
"(",
"u",
"UUID",
")",
"{",
"const",
"(",
"maxretries",
"=",
"9",
"\n",
"backoff",
"=",
"time",
".",
"Millisecond",
"*",
"10",
"\n",
")",
"\n",
"var",
"(",
"totalBackoff",
"time",
".",
"Duration",
"\n",
"count",
"int",
... | // Generate creates a new, version 4 uuid. | [
"Generate",
"creates",
"a",
"new",
"version",
"4",
"uuid",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/uuid/uuid.go#L40-L84 | train |
docker/distribution | uuid/uuid.go | Parse | func Parse(s string) (u UUID, err error) {
if len(s) != 36 {
return UUID{}, ErrUUIDInvalid
}
// create stack addresses for each section of the uuid.
p := make([][]byte, 5)
if _, err := fmt.Sscanf(s, format, &p[0], &p[1], &p[2], &p[3], &p[4]); err != nil {
return u, err
}
copy(u[0:4], p[0])
copy(u[4:6], p[1])
copy(u[6:8], p[2])
copy(u[8:10], p[3])
copy(u[10:16], p[4])
return
} | go | func Parse(s string) (u UUID, err error) {
if len(s) != 36 {
return UUID{}, ErrUUIDInvalid
}
// create stack addresses for each section of the uuid.
p := make([][]byte, 5)
if _, err := fmt.Sscanf(s, format, &p[0], &p[1], &p[2], &p[3], &p[4]); err != nil {
return u, err
}
copy(u[0:4], p[0])
copy(u[4:6], p[1])
copy(u[6:8], p[2])
copy(u[8:10], p[3])
copy(u[10:16], p[4])
return
} | [
"func",
"Parse",
"(",
"s",
"string",
")",
"(",
"u",
"UUID",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"s",
")",
"!=",
"36",
"{",
"return",
"UUID",
"{",
"}",
",",
"ErrUUIDInvalid",
"\n",
"}",
"\n",
"p",
":=",
"make",
"(",
"[",
"]",
"[",... | // Parse attempts to extract a uuid from the string or returns an error. | [
"Parse",
"attempts",
"to",
"extract",
"a",
"uuid",
"from",
"the",
"string",
"or",
"returns",
"an",
"error",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/uuid/uuid.go#L87-L106 | train |
docker/distribution | registry/storage/driver/s3-aws/s3.go | New | func New(params DriverParameters) (*Driver, error) {
if !params.V4Auth &&
(params.RegionEndpoint == "" ||
strings.Contains(params.RegionEndpoint, "s3.amazonaws.com")) {
return nil, fmt.Errorf("on Amazon S3 this storage driver can only be used with v4 authentication")
}
awsConfig := aws.NewConfig()
sess, err := session.NewSession()
if err != nil {
return nil, fmt.Errorf("failed to create new session: %v", err)
}
creds := credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{
Value: credentials.Value{
AccessKeyID: params.AccessKey,
SecretAccessKey: params.SecretKey,
SessionToken: params.SessionToken,
},
},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{},
&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess)},
})
if params.RegionEndpoint != "" {
awsConfig.WithS3ForcePathStyle(true)
awsConfig.WithEndpoint(params.RegionEndpoint)
}
awsConfig.WithCredentials(creds)
awsConfig.WithRegion(params.Region)
awsConfig.WithDisableSSL(!params.Secure)
if params.UserAgent != "" || params.SkipVerify {
httpTransport := http.DefaultTransport
if params.SkipVerify {
httpTransport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
if params.UserAgent != "" {
awsConfig.WithHTTPClient(&http.Client{
Transport: transport.NewTransport(httpTransport, transport.NewHeaderRequestModifier(http.Header{http.CanonicalHeaderKey("User-Agent"): []string{params.UserAgent}})),
})
} else {
awsConfig.WithHTTPClient(&http.Client{
Transport: transport.NewTransport(httpTransport),
})
}
}
sess, err = session.NewSession(awsConfig)
if err != nil {
return nil, fmt.Errorf("failed to create new session with aws config: %v", err)
}
s3obj := s3.New(sess)
// enable S3 compatible signature v2 signing instead
if !params.V4Auth {
setv2Handlers(s3obj)
}
// TODO Currently multipart uploads have no timestamps, so this would be unwise
// if you initiated a new s3driver while another one is running on the same bucket.
// multis, _, err := bucket.ListMulti("", "")
// if err != nil {
// return nil, err
// }
// for _, multi := range multis {
// err := multi.Abort()
// //TODO appropriate to do this error checking?
// if err != nil {
// return nil, err
// }
// }
d := &driver{
S3: s3obj,
Bucket: params.Bucket,
ChunkSize: params.ChunkSize,
Encrypt: params.Encrypt,
KeyID: params.KeyID,
MultipartCopyChunkSize: params.MultipartCopyChunkSize,
MultipartCopyMaxConcurrency: params.MultipartCopyMaxConcurrency,
MultipartCopyThresholdSize: params.MultipartCopyThresholdSize,
RootDirectory: params.RootDirectory,
StorageClass: params.StorageClass,
ObjectACL: params.ObjectACL,
}
return &Driver{
baseEmbed: baseEmbed{
Base: base.Base{
StorageDriver: d,
},
},
}, nil
} | go | func New(params DriverParameters) (*Driver, error) {
if !params.V4Auth &&
(params.RegionEndpoint == "" ||
strings.Contains(params.RegionEndpoint, "s3.amazonaws.com")) {
return nil, fmt.Errorf("on Amazon S3 this storage driver can only be used with v4 authentication")
}
awsConfig := aws.NewConfig()
sess, err := session.NewSession()
if err != nil {
return nil, fmt.Errorf("failed to create new session: %v", err)
}
creds := credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{
Value: credentials.Value{
AccessKeyID: params.AccessKey,
SecretAccessKey: params.SecretKey,
SessionToken: params.SessionToken,
},
},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{},
&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess)},
})
if params.RegionEndpoint != "" {
awsConfig.WithS3ForcePathStyle(true)
awsConfig.WithEndpoint(params.RegionEndpoint)
}
awsConfig.WithCredentials(creds)
awsConfig.WithRegion(params.Region)
awsConfig.WithDisableSSL(!params.Secure)
if params.UserAgent != "" || params.SkipVerify {
httpTransport := http.DefaultTransport
if params.SkipVerify {
httpTransport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
if params.UserAgent != "" {
awsConfig.WithHTTPClient(&http.Client{
Transport: transport.NewTransport(httpTransport, transport.NewHeaderRequestModifier(http.Header{http.CanonicalHeaderKey("User-Agent"): []string{params.UserAgent}})),
})
} else {
awsConfig.WithHTTPClient(&http.Client{
Transport: transport.NewTransport(httpTransport),
})
}
}
sess, err = session.NewSession(awsConfig)
if err != nil {
return nil, fmt.Errorf("failed to create new session with aws config: %v", err)
}
s3obj := s3.New(sess)
// enable S3 compatible signature v2 signing instead
if !params.V4Auth {
setv2Handlers(s3obj)
}
// TODO Currently multipart uploads have no timestamps, so this would be unwise
// if you initiated a new s3driver while another one is running on the same bucket.
// multis, _, err := bucket.ListMulti("", "")
// if err != nil {
// return nil, err
// }
// for _, multi := range multis {
// err := multi.Abort()
// //TODO appropriate to do this error checking?
// if err != nil {
// return nil, err
// }
// }
d := &driver{
S3: s3obj,
Bucket: params.Bucket,
ChunkSize: params.ChunkSize,
Encrypt: params.Encrypt,
KeyID: params.KeyID,
MultipartCopyChunkSize: params.MultipartCopyChunkSize,
MultipartCopyMaxConcurrency: params.MultipartCopyMaxConcurrency,
MultipartCopyThresholdSize: params.MultipartCopyThresholdSize,
RootDirectory: params.RootDirectory,
StorageClass: params.StorageClass,
ObjectACL: params.ObjectACL,
}
return &Driver{
baseEmbed: baseEmbed{
Base: base.Base{
StorageDriver: d,
},
},
}, nil
} | [
"func",
"New",
"(",
"params",
"DriverParameters",
")",
"(",
"*",
"Driver",
",",
"error",
")",
"{",
"if",
"!",
"params",
".",
"V4Auth",
"&&",
"(",
"params",
".",
"RegionEndpoint",
"==",
"\"\"",
"||",
"strings",
".",
"Contains",
"(",
"params",
".",
"Regi... | // New constructs a new Driver with the given AWS credentials, region, encryption flag, and
// bucketName | [
"New",
"constructs",
"a",
"new",
"Driver",
"with",
"the",
"given",
"AWS",
"credentials",
"region",
"encryption",
"flag",
"and",
"bucketName"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/s3-aws/s3.go#L400-L499 | train |
docker/distribution | registry/storage/driver/s3-aws/s3.go | Delete | func (d *driver) Delete(ctx context.Context, path string) error {
s3Objects := make([]*s3.ObjectIdentifier, 0, listMax)
s3Path := d.s3Path(path)
listObjectsInput := &s3.ListObjectsInput{
Bucket: aws.String(d.Bucket),
Prefix: aws.String(s3Path),
}
ListLoop:
for {
// list all the objects
resp, err := d.S3.ListObjects(listObjectsInput)
// resp.Contents can only be empty on the first call
// if there were no more results to return after the first call, resp.IsTruncated would have been false
// and the loop would be exited without recalling ListObjects
if err != nil || len(resp.Contents) == 0 {
return storagedriver.PathNotFoundError{Path: path}
}
for _, key := range resp.Contents {
// Stop if we encounter a key that is not a subpath (so that deleting "/a" does not delete "/ab").
if len(*key.Key) > len(s3Path) && (*key.Key)[len(s3Path)] != '/' {
break ListLoop
}
s3Objects = append(s3Objects, &s3.ObjectIdentifier{
Key: key.Key,
})
}
// resp.Contents must have at least one element or we would have returned not found
listObjectsInput.Marker = resp.Contents[len(resp.Contents)-1].Key
// from the s3 api docs, IsTruncated "specifies whether (true) or not (false) all of the results were returned"
// if everything has been returned, break
if resp.IsTruncated == nil || !*resp.IsTruncated {
break
}
}
// need to chunk objects into groups of 1000 per s3 restrictions
total := len(s3Objects)
for i := 0; i < total; i += 1000 {
_, err := d.S3.DeleteObjects(&s3.DeleteObjectsInput{
Bucket: aws.String(d.Bucket),
Delete: &s3.Delete{
Objects: s3Objects[i:min(i+1000, total)],
Quiet: aws.Bool(false),
},
})
if err != nil {
return err
}
}
return nil
} | go | func (d *driver) Delete(ctx context.Context, path string) error {
s3Objects := make([]*s3.ObjectIdentifier, 0, listMax)
s3Path := d.s3Path(path)
listObjectsInput := &s3.ListObjectsInput{
Bucket: aws.String(d.Bucket),
Prefix: aws.String(s3Path),
}
ListLoop:
for {
// list all the objects
resp, err := d.S3.ListObjects(listObjectsInput)
// resp.Contents can only be empty on the first call
// if there were no more results to return after the first call, resp.IsTruncated would have been false
// and the loop would be exited without recalling ListObjects
if err != nil || len(resp.Contents) == 0 {
return storagedriver.PathNotFoundError{Path: path}
}
for _, key := range resp.Contents {
// Stop if we encounter a key that is not a subpath (so that deleting "/a" does not delete "/ab").
if len(*key.Key) > len(s3Path) && (*key.Key)[len(s3Path)] != '/' {
break ListLoop
}
s3Objects = append(s3Objects, &s3.ObjectIdentifier{
Key: key.Key,
})
}
// resp.Contents must have at least one element or we would have returned not found
listObjectsInput.Marker = resp.Contents[len(resp.Contents)-1].Key
// from the s3 api docs, IsTruncated "specifies whether (true) or not (false) all of the results were returned"
// if everything has been returned, break
if resp.IsTruncated == nil || !*resp.IsTruncated {
break
}
}
// need to chunk objects into groups of 1000 per s3 restrictions
total := len(s3Objects)
for i := 0; i < total; i += 1000 {
_, err := d.S3.DeleteObjects(&s3.DeleteObjectsInput{
Bucket: aws.String(d.Bucket),
Delete: &s3.Delete{
Objects: s3Objects[i:min(i+1000, total)],
Quiet: aws.Bool(false),
},
})
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"d",
"*",
"driver",
")",
"Delete",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"error",
"{",
"s3Objects",
":=",
"make",
"(",
"[",
"]",
"*",
"s3",
".",
"ObjectIdentifier",
",",
"0",
",",
"listMax",
")",
"\n",
"s3P... | // Delete recursively deletes all objects stored at "path" and its subpaths.
// We must be careful since S3 does not guarantee read after delete consistency | [
"Delete",
"recursively",
"deletes",
"all",
"objects",
"stored",
"at",
"path",
"and",
"its",
"subpaths",
".",
"We",
"must",
"be",
"careful",
"since",
"S3",
"does",
"not",
"guarantee",
"read",
"after",
"delete",
"consistency"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/s3-aws/s3.go#L808-L862 | train |
docker/distribution | registry/storage/driver/s3-aws/s3.go | S3BucketKey | func (d *Driver) S3BucketKey(path string) string {
return d.StorageDriver.(*driver).s3Path(path)
} | go | func (d *Driver) S3BucketKey(path string) string {
return d.StorageDriver.(*driver).s3Path(path)
} | [
"func",
"(",
"d",
"*",
"Driver",
")",
"S3BucketKey",
"(",
"path",
"string",
")",
"string",
"{",
"return",
"d",
".",
"StorageDriver",
".",
"(",
"*",
"driver",
")",
".",
"s3Path",
"(",
"path",
")",
"\n",
"}"
] | // S3BucketKey returns the s3 bucket key for the given storage driver path. | [
"S3BucketKey",
"returns",
"the",
"s3",
"bucket",
"key",
"for",
"the",
"given",
"storage",
"driver",
"path",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/s3-aws/s3.go#L1040-L1042 | train |
docker/distribution | registry/storage/cache/cachedblobdescriptorstore.go | NewCachedBlobStatter | func NewCachedBlobStatter(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService) distribution.BlobDescriptorService {
return &cachedBlobStatter{
cache: cache,
backend: backend,
}
} | go | func NewCachedBlobStatter(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService) distribution.BlobDescriptorService {
return &cachedBlobStatter{
cache: cache,
backend: backend,
}
} | [
"func",
"NewCachedBlobStatter",
"(",
"cache",
"distribution",
".",
"BlobDescriptorService",
",",
"backend",
"distribution",
".",
"BlobDescriptorService",
")",
"distribution",
".",
"BlobDescriptorService",
"{",
"return",
"&",
"cachedBlobStatter",
"{",
"cache",
":",
"cach... | // NewCachedBlobStatter creates a new statter which prefers a cache and
// falls back to a backend. | [
"NewCachedBlobStatter",
"creates",
"a",
"new",
"statter",
"which",
"prefers",
"a",
"cache",
"and",
"falls",
"back",
"to",
"a",
"backend",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/cachedblobdescriptorstore.go#L49-L54 | train |
docker/distribution | registry/storage/cache/cachedblobdescriptorstore.go | NewCachedBlobStatterWithMetrics | func NewCachedBlobStatterWithMetrics(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService, tracker MetricsTracker) distribution.BlobStatter {
return &cachedBlobStatter{
cache: cache,
backend: backend,
tracker: tracker,
}
} | go | func NewCachedBlobStatterWithMetrics(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService, tracker MetricsTracker) distribution.BlobStatter {
return &cachedBlobStatter{
cache: cache,
backend: backend,
tracker: tracker,
}
} | [
"func",
"NewCachedBlobStatterWithMetrics",
"(",
"cache",
"distribution",
".",
"BlobDescriptorService",
",",
"backend",
"distribution",
".",
"BlobDescriptorService",
",",
"tracker",
"MetricsTracker",
")",
"distribution",
".",
"BlobStatter",
"{",
"return",
"&",
"cachedBlobS... | // NewCachedBlobStatterWithMetrics creates a new statter which prefers a cache and
// falls back to a backend. Hits and misses will send to the tracker. | [
"NewCachedBlobStatterWithMetrics",
"creates",
"a",
"new",
"statter",
"which",
"prefers",
"a",
"cache",
"and",
"falls",
"back",
"to",
"a",
"backend",
".",
"Hits",
"and",
"misses",
"will",
"send",
"to",
"the",
"tracker",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/cachedblobdescriptorstore.go#L58-L64 | train |
docker/distribution | context/version.go | WithVersion | func WithVersion(ctx context.Context, version string) context.Context {
ctx = context.WithValue(ctx, versionKey{}, version)
// push a new logger onto the stack
return WithLogger(ctx, GetLogger(ctx, versionKey{}))
} | go | func WithVersion(ctx context.Context, version string) context.Context {
ctx = context.WithValue(ctx, versionKey{}, version)
// push a new logger onto the stack
return WithLogger(ctx, GetLogger(ctx, versionKey{}))
} | [
"func",
"WithVersion",
"(",
"ctx",
"context",
".",
"Context",
",",
"version",
"string",
")",
"context",
".",
"Context",
"{",
"ctx",
"=",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"versionKey",
"{",
"}",
",",
"version",
")",
"\n",
"return",
"WithLogge... | // WithVersion stores the application version in the context. The new context
// gets a logger to ensure log messages are marked with the application
// version. | [
"WithVersion",
"stores",
"the",
"application",
"version",
"in",
"the",
"context",
".",
"The",
"new",
"context",
"gets",
"a",
"logger",
"to",
"ensure",
"log",
"messages",
"are",
"marked",
"with",
"the",
"application",
"version",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/version.go#L12-L16 | train |
docker/distribution | registry/storage/driver/middleware/cloudfront/s3filter.go | newAWSIPs | func newAWSIPs(host string, updateFrequency time.Duration, awsRegion []string) *awsIPs {
ips := &awsIPs{
host: host,
updateFrequency: updateFrequency,
awsRegion: awsRegion,
updaterStopChan: make(chan bool),
}
if err := ips.tryUpdate(); err != nil {
dcontext.GetLogger(context.Background()).WithError(err).Warn("failed to update AWS IP")
}
go ips.updater()
return ips
} | go | func newAWSIPs(host string, updateFrequency time.Duration, awsRegion []string) *awsIPs {
ips := &awsIPs{
host: host,
updateFrequency: updateFrequency,
awsRegion: awsRegion,
updaterStopChan: make(chan bool),
}
if err := ips.tryUpdate(); err != nil {
dcontext.GetLogger(context.Background()).WithError(err).Warn("failed to update AWS IP")
}
go ips.updater()
return ips
} | [
"func",
"newAWSIPs",
"(",
"host",
"string",
",",
"updateFrequency",
"time",
".",
"Duration",
",",
"awsRegion",
"[",
"]",
"string",
")",
"*",
"awsIPs",
"{",
"ips",
":=",
"&",
"awsIPs",
"{",
"host",
":",
"host",
",",
"updateFrequency",
":",
"updateFrequency"... | // newAWSIPs returns a New awsIP object.
// If awsRegion is `nil`, it accepts any region. Otherwise, it only allow the regions specified | [
"newAWSIPs",
"returns",
"a",
"New",
"awsIP",
"object",
".",
"If",
"awsRegion",
"is",
"nil",
"it",
"accepts",
"any",
"region",
".",
"Otherwise",
"it",
"only",
"allow",
"the",
"regions",
"specified"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L26-L38 | train |
docker/distribution | registry/storage/driver/middleware/cloudfront/s3filter.go | tryUpdate | func (s *awsIPs) tryUpdate() error {
response, err := fetchAWSIPs(s.host)
if err != nil {
return err
}
var ipv4 []net.IPNet
var ipv6 []net.IPNet
processAddress := func(output *[]net.IPNet, prefix string, region string) {
regionAllowed := false
if len(s.awsRegion) > 0 {
for _, ar := range s.awsRegion {
if strings.ToLower(region) == ar {
regionAllowed = true
break
}
}
} else {
regionAllowed = true
}
_, network, err := net.ParseCIDR(prefix)
if err != nil {
dcontext.GetLoggerWithFields(dcontext.Background(), map[interface{}]interface{}{
"cidr": prefix,
}).Error("unparseable cidr")
return
}
if regionAllowed {
*output = append(*output, *network)
}
}
for _, prefix := range response.Prefixes {
processAddress(&ipv4, prefix.IPV4Prefix, prefix.Region)
}
for _, prefix := range response.V6Prefixes {
processAddress(&ipv6, prefix.IPV6Prefix, prefix.Region)
}
s.mutex.Lock()
defer s.mutex.Unlock()
// Update each attr of awsips atomically.
s.ipv4 = ipv4
s.ipv6 = ipv6
s.initialized = true
return nil
} | go | func (s *awsIPs) tryUpdate() error {
response, err := fetchAWSIPs(s.host)
if err != nil {
return err
}
var ipv4 []net.IPNet
var ipv6 []net.IPNet
processAddress := func(output *[]net.IPNet, prefix string, region string) {
regionAllowed := false
if len(s.awsRegion) > 0 {
for _, ar := range s.awsRegion {
if strings.ToLower(region) == ar {
regionAllowed = true
break
}
}
} else {
regionAllowed = true
}
_, network, err := net.ParseCIDR(prefix)
if err != nil {
dcontext.GetLoggerWithFields(dcontext.Background(), map[interface{}]interface{}{
"cidr": prefix,
}).Error("unparseable cidr")
return
}
if regionAllowed {
*output = append(*output, *network)
}
}
for _, prefix := range response.Prefixes {
processAddress(&ipv4, prefix.IPV4Prefix, prefix.Region)
}
for _, prefix := range response.V6Prefixes {
processAddress(&ipv6, prefix.IPV6Prefix, prefix.Region)
}
s.mutex.Lock()
defer s.mutex.Unlock()
// Update each attr of awsips atomically.
s.ipv4 = ipv4
s.ipv6 = ipv6
s.initialized = true
return nil
} | [
"func",
"(",
"s",
"*",
"awsIPs",
")",
"tryUpdate",
"(",
")",
"error",
"{",
"response",
",",
"err",
":=",
"fetchAWSIPs",
"(",
"s",
".",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"ipv4",
"[",
"]",
... | // tryUpdate attempts to download the new set of ip addresses.
// tryUpdate must be thread safe with contains | [
"tryUpdate",
"attempts",
"to",
"download",
"the",
"new",
"set",
"of",
"ip",
"addresses",
".",
"tryUpdate",
"must",
"be",
"thread",
"safe",
"with",
"contains"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L84-L132 | train |
docker/distribution | registry/storage/driver/middleware/cloudfront/s3filter.go | updater | func (s *awsIPs) updater() {
defer close(s.updaterStopChan)
for {
time.Sleep(s.updateFrequency)
select {
case <-s.updaterStopChan:
dcontext.GetLogger(context.Background()).Info("aws ip updater received stop signal")
return
default:
err := s.tryUpdate()
if err != nil {
dcontext.GetLogger(context.Background()).WithError(err).Error("git AWS IP")
}
}
}
} | go | func (s *awsIPs) updater() {
defer close(s.updaterStopChan)
for {
time.Sleep(s.updateFrequency)
select {
case <-s.updaterStopChan:
dcontext.GetLogger(context.Background()).Info("aws ip updater received stop signal")
return
default:
err := s.tryUpdate()
if err != nil {
dcontext.GetLogger(context.Background()).WithError(err).Error("git AWS IP")
}
}
}
} | [
"func",
"(",
"s",
"*",
"awsIPs",
")",
"updater",
"(",
")",
"{",
"defer",
"close",
"(",
"s",
".",
"updaterStopChan",
")",
"\n",
"for",
"{",
"time",
".",
"Sleep",
"(",
"s",
".",
"updateFrequency",
")",
"\n",
"select",
"{",
"case",
"<-",
"s",
".",
"... | // This function is meant to be run in a background goroutine.
// It will periodically update the ips from aws. | [
"This",
"function",
"is",
"meant",
"to",
"be",
"run",
"in",
"a",
"background",
"goroutine",
".",
"It",
"will",
"periodically",
"update",
"the",
"ips",
"from",
"aws",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L136-L151 | train |
docker/distribution | registry/storage/driver/middleware/cloudfront/s3filter.go | getCandidateNetworks | func (s *awsIPs) getCandidateNetworks(ip net.IP) []net.IPNet {
s.mutex.RLock()
defer s.mutex.RUnlock()
if ip.To4() != nil {
return s.ipv4
} else if ip.To16() != nil {
return s.ipv6
} else {
dcontext.GetLoggerWithFields(dcontext.Background(), map[interface{}]interface{}{
"ip": ip,
}).Error("unknown ip address format")
// assume mismatch, pass through cloudfront
return nil
}
} | go | func (s *awsIPs) getCandidateNetworks(ip net.IP) []net.IPNet {
s.mutex.RLock()
defer s.mutex.RUnlock()
if ip.To4() != nil {
return s.ipv4
} else if ip.To16() != nil {
return s.ipv6
} else {
dcontext.GetLoggerWithFields(dcontext.Background(), map[interface{}]interface{}{
"ip": ip,
}).Error("unknown ip address format")
// assume mismatch, pass through cloudfront
return nil
}
} | [
"func",
"(",
"s",
"*",
"awsIPs",
")",
"getCandidateNetworks",
"(",
"ip",
"net",
".",
"IP",
")",
"[",
"]",
"net",
".",
"IPNet",
"{",
"s",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"if... | // getCandidateNetworks returns either the ipv4 or ipv6 networks
// that were last read from aws. The networks returned
// have the same type as the ip address provided. | [
"getCandidateNetworks",
"returns",
"either",
"the",
"ipv4",
"or",
"ipv6",
"networks",
"that",
"were",
"last",
"read",
"from",
"aws",
".",
"The",
"networks",
"returned",
"have",
"the",
"same",
"type",
"as",
"the",
"ip",
"address",
"provided",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L156-L170 | train |
docker/distribution | registry/storage/driver/middleware/cloudfront/s3filter.go | contains | func (s *awsIPs) contains(ip net.IP) bool {
networks := s.getCandidateNetworks(ip)
for _, network := range networks {
if network.Contains(ip) {
return true
}
}
return false
} | go | func (s *awsIPs) contains(ip net.IP) bool {
networks := s.getCandidateNetworks(ip)
for _, network := range networks {
if network.Contains(ip) {
return true
}
}
return false
} | [
"func",
"(",
"s",
"*",
"awsIPs",
")",
"contains",
"(",
"ip",
"net",
".",
"IP",
")",
"bool",
"{",
"networks",
":=",
"s",
".",
"getCandidateNetworks",
"(",
"ip",
")",
"\n",
"for",
"_",
",",
"network",
":=",
"range",
"networks",
"{",
"if",
"network",
... | // Contains determines whether the host is within aws. | [
"Contains",
"determines",
"whether",
"the",
"host",
"is",
"within",
"aws",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L173-L181 | train |
docker/distribution | registry/storage/driver/middleware/cloudfront/s3filter.go | parseIPFromRequest | func parseIPFromRequest(ctx context.Context) (net.IP, error) {
request, err := dcontext.GetRequest(ctx)
if err != nil {
return nil, err
}
ipStr := dcontext.RemoteIP(request)
ip := net.ParseIP(ipStr)
if ip == nil {
return nil, fmt.Errorf("invalid ip address from requester: %s", ipStr)
}
return ip, nil
} | go | func parseIPFromRequest(ctx context.Context) (net.IP, error) {
request, err := dcontext.GetRequest(ctx)
if err != nil {
return nil, err
}
ipStr := dcontext.RemoteIP(request)
ip := net.ParseIP(ipStr)
if ip == nil {
return nil, fmt.Errorf("invalid ip address from requester: %s", ipStr)
}
return ip, nil
} | [
"func",
"parseIPFromRequest",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"net",
".",
"IP",
",",
"error",
")",
"{",
"request",
",",
"err",
":=",
"dcontext",
".",
"GetRequest",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil"... | // parseIPFromRequest attempts to extract the ip address of the
// client that made the request | [
"parseIPFromRequest",
"attempts",
"to",
"extract",
"the",
"ip",
"address",
"of",
"the",
"client",
"that",
"made",
"the",
"request"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L185-L197 | train |
docker/distribution | registry/storage/driver/middleware/cloudfront/s3filter.go | eligibleForS3 | func eligibleForS3(ctx context.Context, awsIPs *awsIPs) bool {
if awsIPs != nil && awsIPs.initialized {
if addr, err := parseIPFromRequest(ctx); err == nil {
request, err := dcontext.GetRequest(ctx)
if err != nil {
dcontext.GetLogger(ctx).Warnf("the CloudFront middleware cannot parse the request: %s", err)
} else {
loggerField := map[interface{}]interface{}{
"user-client": request.UserAgent(),
"ip": dcontext.RemoteIP(request),
}
if awsIPs.contains(addr) {
dcontext.GetLoggerWithFields(ctx, loggerField).Info("request from the allowed AWS region, skipping CloudFront")
return true
}
dcontext.GetLoggerWithFields(ctx, loggerField).Warn("request not from the allowed AWS region, fallback to CloudFront")
}
} else {
dcontext.GetLogger(ctx).WithError(err).Warn("failed to parse ip address from context, fallback to CloudFront")
}
}
return false
} | go | func eligibleForS3(ctx context.Context, awsIPs *awsIPs) bool {
if awsIPs != nil && awsIPs.initialized {
if addr, err := parseIPFromRequest(ctx); err == nil {
request, err := dcontext.GetRequest(ctx)
if err != nil {
dcontext.GetLogger(ctx).Warnf("the CloudFront middleware cannot parse the request: %s", err)
} else {
loggerField := map[interface{}]interface{}{
"user-client": request.UserAgent(),
"ip": dcontext.RemoteIP(request),
}
if awsIPs.contains(addr) {
dcontext.GetLoggerWithFields(ctx, loggerField).Info("request from the allowed AWS region, skipping CloudFront")
return true
}
dcontext.GetLoggerWithFields(ctx, loggerField).Warn("request not from the allowed AWS region, fallback to CloudFront")
}
} else {
dcontext.GetLogger(ctx).WithError(err).Warn("failed to parse ip address from context, fallback to CloudFront")
}
}
return false
} | [
"func",
"eligibleForS3",
"(",
"ctx",
"context",
".",
"Context",
",",
"awsIPs",
"*",
"awsIPs",
")",
"bool",
"{",
"if",
"awsIPs",
"!=",
"nil",
"&&",
"awsIPs",
".",
"initialized",
"{",
"if",
"addr",
",",
"err",
":=",
"parseIPFromRequest",
"(",
"ctx",
")",
... | // eligibleForS3 checks if a request is eligible for using S3 directly
// Return true only when the IP belongs to a specific aws region and user-agent is docker | [
"eligibleForS3",
"checks",
"if",
"a",
"request",
"is",
"eligible",
"for",
"using",
"S3",
"directly",
"Return",
"true",
"only",
"when",
"the",
"IP",
"belongs",
"to",
"a",
"specific",
"aws",
"region",
"and",
"user",
"-",
"agent",
"is",
"docker"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L201-L223 | train |
docker/distribution | registry/storage/cache/redis/redis.go | RepositoryScoped | func (rbds *redisBlobDescriptorService) RepositoryScoped(repo string) (distribution.BlobDescriptorService, error) {
if _, err := reference.ParseNormalizedNamed(repo); err != nil {
return nil, err
}
return &repositoryScopedRedisBlobDescriptorService{
repo: repo,
upstream: rbds,
}, nil
} | go | func (rbds *redisBlobDescriptorService) RepositoryScoped(repo string) (distribution.BlobDescriptorService, error) {
if _, err := reference.ParseNormalizedNamed(repo); err != nil {
return nil, err
}
return &repositoryScopedRedisBlobDescriptorService{
repo: repo,
upstream: rbds,
}, nil
} | [
"func",
"(",
"rbds",
"*",
"redisBlobDescriptorService",
")",
"RepositoryScoped",
"(",
"repo",
"string",
")",
"(",
"distribution",
".",
"BlobDescriptorService",
",",
"error",
")",
"{",
"if",
"_",
",",
"err",
":=",
"reference",
".",
"ParseNormalizedNamed",
"(",
... | // RepositoryScoped returns the scoped cache. | [
"RepositoryScoped",
"returns",
"the",
"scoped",
"cache",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L43-L52 | train |
docker/distribution | registry/storage/cache/redis/redis.go | Stat | func (rbds *redisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
if err := dgst.Validate(); err != nil {
return distribution.Descriptor{}, err
}
conn := rbds.pool.Get()
defer conn.Close()
return rbds.stat(ctx, conn, dgst)
} | go | func (rbds *redisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
if err := dgst.Validate(); err != nil {
return distribution.Descriptor{}, err
}
conn := rbds.pool.Get()
defer conn.Close()
return rbds.stat(ctx, conn, dgst)
} | [
"func",
"(",
"rbds",
"*",
"redisBlobDescriptorService",
")",
"Stat",
"(",
"ctx",
"context",
".",
"Context",
",",
"dgst",
"digest",
".",
"Digest",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"if",
"err",
":=",
"dgst",
".",
"Valida... | // Stat retrieves the descriptor data from the redis hash entry. | [
"Stat",
"retrieves",
"the",
"descriptor",
"data",
"from",
"the",
"redis",
"hash",
"entry",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L55-L64 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.