repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
francoispqt/gojay | encode_sqlnull.go | SQLNullFloat64KeyOmitEmpty | func (enc *Encoder) SQLNullFloat64KeyOmitEmpty(key string, v *sql.NullFloat64) {
if v != nil && v.Valid && v.Float64 != 0 {
enc.Float64KeyOmitEmpty(key, v.Float64)
}
} | go | func (enc *Encoder) SQLNullFloat64KeyOmitEmpty(key string, v *sql.NullFloat64) {
if v != nil && v.Valid && v.Float64 != 0 {
enc.Float64KeyOmitEmpty(key, v.Float64)
}
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"SQLNullFloat64KeyOmitEmpty",
"(",
"key",
"string",
",",
"v",
"*",
"sql",
".",
"NullFloat64",
")",
"{",
"if",
"v",
"!=",
"nil",
"&&",
"v",
".",
"Valid",
"&&",
"v",
".",
"Float64",
"!=",
"0",
"{",
"enc",
".",
"Float64KeyOmitEmpty",
"(",
"key",
",",
"v",
".",
"Float64",
")",
"\n",
"}",
"\n",
"}"
] | // SQLNullFloat64KeyOmitEmpty adds a string to be encoded or skips it if it is zero value.
// Must be used inside an object as it will encode a key | [
"SQLNullFloat64KeyOmitEmpty",
"adds",
"a",
"string",
"to",
"be",
"encoded",
"or",
"skips",
"it",
"if",
"it",
"is",
"zero",
"value",
".",
"Must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_sqlnull.go#L275-L279 | train |
francoispqt/gojay | encode_sqlnull.go | SQLNullFloat64KeyNullEmpty | func (enc *Encoder) SQLNullFloat64KeyNullEmpty(key string, v *sql.NullFloat64) {
if v != nil && v.Valid {
enc.Float64KeyNullEmpty(key, v.Float64)
}
} | go | func (enc *Encoder) SQLNullFloat64KeyNullEmpty(key string, v *sql.NullFloat64) {
if v != nil && v.Valid {
enc.Float64KeyNullEmpty(key, v.Float64)
}
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"SQLNullFloat64KeyNullEmpty",
"(",
"key",
"string",
",",
"v",
"*",
"sql",
".",
"NullFloat64",
")",
"{",
"if",
"v",
"!=",
"nil",
"&&",
"v",
".",
"Valid",
"{",
"enc",
".",
"Float64KeyNullEmpty",
"(",
"key",
",",
"v",
".",
"Float64",
")",
"\n",
"}",
"\n",
"}"
] | // SQLNullFloat64KeyNullEmpty adds a string to be encoded or skips it if it is zero value.
// Must be used inside an object as it will encode a key | [
"SQLNullFloat64KeyNullEmpty",
"adds",
"a",
"string",
"to",
"be",
"encoded",
"or",
"skips",
"it",
"if",
"it",
"is",
"zero",
"value",
".",
"Must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_sqlnull.go#L283-L287 | train |
francoispqt/gojay | encode_sqlnull.go | EncodeSQLNullBool | func (enc *Encoder) EncodeSQLNullBool(v *sql.NullBool) error {
if enc.isPooled == 1 {
panic(InvalidUsagePooledEncoderError("Invalid usage of pooled encoder"))
}
_, _ = enc.encodeBool(v.Bool)
_, err := enc.Write()
if err != nil {
enc.err = err
return err
}
return nil
} | go | func (enc *Encoder) EncodeSQLNullBool(v *sql.NullBool) error {
if enc.isPooled == 1 {
panic(InvalidUsagePooledEncoderError("Invalid usage of pooled encoder"))
}
_, _ = enc.encodeBool(v.Bool)
_, err := enc.Write()
if err != nil {
enc.err = err
return err
}
return nil
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"EncodeSQLNullBool",
"(",
"v",
"*",
"sql",
".",
"NullBool",
")",
"error",
"{",
"if",
"enc",
".",
"isPooled",
"==",
"1",
"{",
"panic",
"(",
"InvalidUsagePooledEncoderError",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"_",
",",
"_",
"=",
"enc",
".",
"encodeBool",
"(",
"v",
".",
"Bool",
")",
"\n",
"_",
",",
"err",
":=",
"enc",
".",
"Write",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"enc",
".",
"err",
"=",
"err",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // NullBool
// EncodeSQLNullBool encodes a string to | [
"NullBool",
"EncodeSQLNullBool",
"encodes",
"a",
"string",
"to"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_sqlnull.go#L292-L303 | train |
francoispqt/gojay | encode_sqlnull.go | AddSQLNullBoolKey | func (enc *Encoder) AddSQLNullBoolKey(key string, v *sql.NullBool) {
enc.BoolKey(key, v.Bool)
} | go | func (enc *Encoder) AddSQLNullBoolKey(key string, v *sql.NullBool) {
enc.BoolKey(key, v.Bool)
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"AddSQLNullBoolKey",
"(",
"key",
"string",
",",
"v",
"*",
"sql",
".",
"NullBool",
")",
"{",
"enc",
".",
"BoolKey",
"(",
"key",
",",
"v",
".",
"Bool",
")",
"\n",
"}"
] | // AddSQLNullBoolKey adds a string to be encoded, must be used inside an object as it will encode a key | [
"AddSQLNullBoolKey",
"adds",
"a",
"string",
"to",
"be",
"encoded",
"must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_sqlnull.go#L319-L321 | train |
francoispqt/gojay | encode_sqlnull.go | SQLNullBool | func (enc *Encoder) SQLNullBool(v *sql.NullBool) {
enc.Bool(v.Bool)
} | go | func (enc *Encoder) SQLNullBool(v *sql.NullBool) {
enc.Bool(v.Bool)
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"SQLNullBool",
"(",
"v",
"*",
"sql",
".",
"NullBool",
")",
"{",
"enc",
".",
"Bool",
"(",
"v",
".",
"Bool",
")",
"\n",
"}"
] | // SQLNullBool adds a string to be encoded, must be used inside an object as it will encode a key | [
"SQLNullBool",
"adds",
"a",
"string",
"to",
"be",
"encoded",
"must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_sqlnull.go#L340-L342 | train |
francoispqt/gojay | encode_sqlnull.go | SQLNullBoolOmitEmpty | func (enc *Encoder) SQLNullBoolOmitEmpty(v *sql.NullBool) {
if v != nil && v.Valid && v.Bool != false {
enc.Bool(v.Bool)
}
} | go | func (enc *Encoder) SQLNullBoolOmitEmpty(v *sql.NullBool) {
if v != nil && v.Valid && v.Bool != false {
enc.Bool(v.Bool)
}
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"SQLNullBoolOmitEmpty",
"(",
"v",
"*",
"sql",
".",
"NullBool",
")",
"{",
"if",
"v",
"!=",
"nil",
"&&",
"v",
".",
"Valid",
"&&",
"v",
".",
"Bool",
"!=",
"false",
"{",
"enc",
".",
"Bool",
"(",
"v",
".",
"Bool",
")",
"\n",
"}",
"\n",
"}"
] | // SQLNullBoolOmitEmpty adds a string to be encoded, must be used inside an object as it will encode a key | [
"SQLNullBoolOmitEmpty",
"adds",
"a",
"string",
"to",
"be",
"encoded",
"must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_sqlnull.go#L345-L349 | train |
francoispqt/gojay | encode_sqlnull.go | SQLNullBoolNullEmpty | func (enc *Encoder) SQLNullBoolNullEmpty(v *sql.NullBool) {
if v != nil && v.Valid {
enc.BoolNullEmpty(v.Bool)
}
} | go | func (enc *Encoder) SQLNullBoolNullEmpty(v *sql.NullBool) {
if v != nil && v.Valid {
enc.BoolNullEmpty(v.Bool)
}
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"SQLNullBoolNullEmpty",
"(",
"v",
"*",
"sql",
".",
"NullBool",
")",
"{",
"if",
"v",
"!=",
"nil",
"&&",
"v",
".",
"Valid",
"{",
"enc",
".",
"BoolNullEmpty",
"(",
"v",
".",
"Bool",
")",
"\n",
"}",
"\n",
"}"
] | // SQLNullBoolNullEmpty adds a string to be encoded, must be used inside an object as it will encode a key | [
"SQLNullBoolNullEmpty",
"adds",
"a",
"string",
"to",
"be",
"encoded",
"must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_sqlnull.go#L352-L356 | train |
francoispqt/gojay | encode_sqlnull.go | SQLNullBoolKeyOmitEmpty | func (enc *Encoder) SQLNullBoolKeyOmitEmpty(key string, v *sql.NullBool) {
if v != nil && v.Valid && v.Bool != false {
enc.BoolKeyOmitEmpty(key, v.Bool)
}
} | go | func (enc *Encoder) SQLNullBoolKeyOmitEmpty(key string, v *sql.NullBool) {
if v != nil && v.Valid && v.Bool != false {
enc.BoolKeyOmitEmpty(key, v.Bool)
}
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"SQLNullBoolKeyOmitEmpty",
"(",
"key",
"string",
",",
"v",
"*",
"sql",
".",
"NullBool",
")",
"{",
"if",
"v",
"!=",
"nil",
"&&",
"v",
".",
"Valid",
"&&",
"v",
".",
"Bool",
"!=",
"false",
"{",
"enc",
".",
"BoolKeyOmitEmpty",
"(",
"key",
",",
"v",
".",
"Bool",
")",
"\n",
"}",
"\n",
"}"
] | // SQLNullBoolKeyOmitEmpty adds a string to be encoded or skips it if it is zero value.
// Must be used inside an object as it will encode a key | [
"SQLNullBoolKeyOmitEmpty",
"adds",
"a",
"string",
"to",
"be",
"encoded",
"or",
"skips",
"it",
"if",
"it",
"is",
"zero",
"value",
".",
"Must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_sqlnull.go#L365-L369 | train |
francoispqt/gojay | encode_sqlnull.go | SQLNullBoolKeyNullEmpty | func (enc *Encoder) SQLNullBoolKeyNullEmpty(key string, v *sql.NullBool) {
if v != nil && v.Valid {
enc.BoolKeyNullEmpty(key, v.Bool)
}
} | go | func (enc *Encoder) SQLNullBoolKeyNullEmpty(key string, v *sql.NullBool) {
if v != nil && v.Valid {
enc.BoolKeyNullEmpty(key, v.Bool)
}
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"SQLNullBoolKeyNullEmpty",
"(",
"key",
"string",
",",
"v",
"*",
"sql",
".",
"NullBool",
")",
"{",
"if",
"v",
"!=",
"nil",
"&&",
"v",
".",
"Valid",
"{",
"enc",
".",
"BoolKeyNullEmpty",
"(",
"key",
",",
"v",
".",
"Bool",
")",
"\n",
"}",
"\n",
"}"
] | // SQLNullBoolKeyNullEmpty adds a string to be encoded or skips it if it is zero value.
// Must be used inside an object as it will encode a key | [
"SQLNullBoolKeyNullEmpty",
"adds",
"a",
"string",
"to",
"be",
"encoded",
"or",
"skips",
"it",
"if",
"it",
"is",
"zero",
"value",
".",
"Must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_sqlnull.go#L373-L377 | train |
francoispqt/gojay | encode_null.go | Null | func (enc *Encoder) Null() {
enc.grow(5)
r := enc.getPreviousRune()
if r != '[' {
enc.writeByte(',')
}
enc.writeBytes(nullBytes)
} | go | func (enc *Encoder) Null() {
enc.grow(5)
r := enc.getPreviousRune()
if r != '[' {
enc.writeByte(',')
}
enc.writeBytes(nullBytes)
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"Null",
"(",
")",
"{",
"enc",
".",
"grow",
"(",
"5",
")",
"\n",
"r",
":=",
"enc",
".",
"getPreviousRune",
"(",
")",
"\n",
"if",
"r",
"!=",
"'['",
"{",
"enc",
".",
"writeByte",
"(",
"','",
")",
"\n",
"}",
"\n",
"enc",
".",
"writeBytes",
"(",
"nullBytes",
")",
"\n",
"}"
] | // Null adds a `null` to be encoded. Must be used while encoding an array.` | [
"Null",
"adds",
"a",
"null",
"to",
"be",
"encoded",
".",
"Must",
"be",
"used",
"while",
"encoding",
"an",
"array",
"."
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_null.go#L9-L16 | train |
francoispqt/gojay | encode_null.go | NullKey | func (enc *Encoder) NullKey(key string) {
if enc.hasKeys {
if !enc.keyExists(key) {
return
}
}
enc.grow(5 + len(key))
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKey)
enc.writeBytes(nullBytes)
} | go | func (enc *Encoder) NullKey(key string) {
if enc.hasKeys {
if !enc.keyExists(key) {
return
}
}
enc.grow(5 + len(key))
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKey)
enc.writeBytes(nullBytes)
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"NullKey",
"(",
"key",
"string",
")",
"{",
"if",
"enc",
".",
"hasKeys",
"{",
"if",
"!",
"enc",
".",
"keyExists",
"(",
"key",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"enc",
".",
"grow",
"(",
"5",
"+",
"len",
"(",
"key",
")",
")",
"\n",
"r",
":=",
"enc",
".",
"getPreviousRune",
"(",
")",
"\n",
"if",
"r",
"!=",
"'{'",
"{",
"enc",
".",
"writeByte",
"(",
"','",
")",
"\n",
"}",
"\n",
"enc",
".",
"writeByte",
"(",
"'\"'",
")",
"\n",
"enc",
".",
"writeStringEscape",
"(",
"key",
")",
"\n",
"enc",
".",
"writeBytes",
"(",
"objKey",
")",
"\n",
"enc",
".",
"writeBytes",
"(",
"nullBytes",
")",
"\n",
"}"
] | // NullKey adds a `null` to be encoded. Must be used while encoding an array.` | [
"NullKey",
"adds",
"a",
"null",
"to",
"be",
"encoded",
".",
"Must",
"be",
"used",
"while",
"encoding",
"an",
"array",
"."
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_null.go#L24-L39 | train |
francoispqt/gojay | encode_object.go | EncodeObject | func (enc *Encoder) EncodeObject(v MarshalerJSONObject) error {
if enc.isPooled == 1 {
panic(InvalidUsagePooledEncoderError("Invalid usage of pooled encoder"))
}
_, err := enc.encodeObject(v)
if err != nil {
enc.err = err
return err
}
_, err = enc.Write()
if err != nil {
enc.err = err
return err
}
return nil
} | go | func (enc *Encoder) EncodeObject(v MarshalerJSONObject) error {
if enc.isPooled == 1 {
panic(InvalidUsagePooledEncoderError("Invalid usage of pooled encoder"))
}
_, err := enc.encodeObject(v)
if err != nil {
enc.err = err
return err
}
_, err = enc.Write()
if err != nil {
enc.err = err
return err
}
return nil
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"EncodeObject",
"(",
"v",
"MarshalerJSONObject",
")",
"error",
"{",
"if",
"enc",
".",
"isPooled",
"==",
"1",
"{",
"panic",
"(",
"InvalidUsagePooledEncoderError",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"enc",
".",
"encodeObject",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"enc",
".",
"err",
"=",
"err",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"enc",
".",
"Write",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"enc",
".",
"err",
"=",
"err",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // EncodeObject encodes an object to JSON | [
"EncodeObject",
"encodes",
"an",
"object",
"to",
"JSON"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_object.go#L9-L24 | train |
francoispqt/gojay | encode_object.go | EncodeObjectKeys | func (enc *Encoder) EncodeObjectKeys(v MarshalerJSONObject, keys []string) error {
if enc.isPooled == 1 {
panic(InvalidUsagePooledEncoderError("Invalid usage of pooled encoder"))
}
enc.hasKeys = true
enc.keys = keys
_, err := enc.encodeObject(v)
if err != nil {
enc.err = err
return err
}
_, err = enc.Write()
if err != nil {
enc.err = err
return err
}
return nil
} | go | func (enc *Encoder) EncodeObjectKeys(v MarshalerJSONObject, keys []string) error {
if enc.isPooled == 1 {
panic(InvalidUsagePooledEncoderError("Invalid usage of pooled encoder"))
}
enc.hasKeys = true
enc.keys = keys
_, err := enc.encodeObject(v)
if err != nil {
enc.err = err
return err
}
_, err = enc.Write()
if err != nil {
enc.err = err
return err
}
return nil
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"EncodeObjectKeys",
"(",
"v",
"MarshalerJSONObject",
",",
"keys",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"enc",
".",
"isPooled",
"==",
"1",
"{",
"panic",
"(",
"InvalidUsagePooledEncoderError",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"enc",
".",
"hasKeys",
"=",
"true",
"\n",
"enc",
".",
"keys",
"=",
"keys",
"\n",
"_",
",",
"err",
":=",
"enc",
".",
"encodeObject",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"enc",
".",
"err",
"=",
"err",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"enc",
".",
"Write",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"enc",
".",
"err",
"=",
"err",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // EncodeObjectKeys encodes an object to JSON | [
"EncodeObjectKeys",
"encodes",
"an",
"object",
"to",
"JSON"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_object.go#L27-L44 | train |
francoispqt/gojay | encode_object.go | AddObjectKey | func (enc *Encoder) AddObjectKey(key string, v MarshalerJSONObject) {
enc.ObjectKey(key, v)
} | go | func (enc *Encoder) AddObjectKey(key string, v MarshalerJSONObject) {
enc.ObjectKey(key, v)
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"AddObjectKey",
"(",
"key",
"string",
",",
"v",
"MarshalerJSONObject",
")",
"{",
"enc",
".",
"ObjectKey",
"(",
"key",
",",
"v",
")",
"\n",
"}"
] | // AddObjectKey adds a struct to be encoded, must be used inside an object as it will encode a key
// value must implement MarshalerJSONObject | [
"AddObjectKey",
"adds",
"a",
"struct",
"to",
"be",
"encoded",
"must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key",
"value",
"must",
"implement",
"MarshalerJSONObject"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_object.go#L82-L84 | train |
francoispqt/gojay | encode_object.go | ObjectKey | func (enc *Encoder) ObjectKey(key string, v MarshalerJSONObject) {
if enc.hasKeys {
if !enc.keyExists(key) {
return
}
}
if v.IsNil() {
enc.grow(2 + len(key))
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKeyObj)
enc.writeByte('}')
return
}
enc.grow(5 + len(key))
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKeyObj)
var origHasKeys = enc.hasKeys
var origKeys = enc.keys
enc.hasKeys = false
enc.keys = nil
v.MarshalJSONObject(enc)
enc.hasKeys = origHasKeys
enc.keys = origKeys
enc.writeByte('}')
} | go | func (enc *Encoder) ObjectKey(key string, v MarshalerJSONObject) {
if enc.hasKeys {
if !enc.keyExists(key) {
return
}
}
if v.IsNil() {
enc.grow(2 + len(key))
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKeyObj)
enc.writeByte('}')
return
}
enc.grow(5 + len(key))
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKeyObj)
var origHasKeys = enc.hasKeys
var origKeys = enc.keys
enc.hasKeys = false
enc.keys = nil
v.MarshalJSONObject(enc)
enc.hasKeys = origHasKeys
enc.keys = origKeys
enc.writeByte('}')
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"ObjectKey",
"(",
"key",
"string",
",",
"v",
"MarshalerJSONObject",
")",
"{",
"if",
"enc",
".",
"hasKeys",
"{",
"if",
"!",
"enc",
".",
"keyExists",
"(",
"key",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"v",
".",
"IsNil",
"(",
")",
"{",
"enc",
".",
"grow",
"(",
"2",
"+",
"len",
"(",
"key",
")",
")",
"\n",
"r",
":=",
"enc",
".",
"getPreviousRune",
"(",
")",
"\n",
"if",
"r",
"!=",
"'{'",
"{",
"enc",
".",
"writeByte",
"(",
"','",
")",
"\n",
"}",
"\n",
"enc",
".",
"writeByte",
"(",
"'\"'",
")",
"\n",
"enc",
".",
"writeStringEscape",
"(",
"key",
")",
"\n",
"enc",
".",
"writeBytes",
"(",
"objKeyObj",
")",
"\n",
"enc",
".",
"writeByte",
"(",
"'}'",
")",
"\n",
"return",
"\n",
"}",
"\n",
"enc",
".",
"grow",
"(",
"5",
"+",
"len",
"(",
"key",
")",
")",
"\n",
"r",
":=",
"enc",
".",
"getPreviousRune",
"(",
")",
"\n",
"if",
"r",
"!=",
"'{'",
"{",
"enc",
".",
"writeByte",
"(",
"','",
")",
"\n",
"}",
"\n",
"enc",
".",
"writeByte",
"(",
"'\"'",
")",
"\n",
"enc",
".",
"writeStringEscape",
"(",
"key",
")",
"\n",
"enc",
".",
"writeBytes",
"(",
"objKeyObj",
")",
"\n\n",
"var",
"origHasKeys",
"=",
"enc",
".",
"hasKeys",
"\n",
"var",
"origKeys",
"=",
"enc",
".",
"keys",
"\n",
"enc",
".",
"hasKeys",
"=",
"false",
"\n",
"enc",
".",
"keys",
"=",
"nil",
"\n\n",
"v",
".",
"MarshalJSONObject",
"(",
"enc",
")",
"\n\n",
"enc",
".",
"hasKeys",
"=",
"origHasKeys",
"\n",
"enc",
".",
"keys",
"=",
"origKeys",
"\n\n",
"enc",
".",
"writeByte",
"(",
"'}'",
")",
"\n",
"}"
] | // ObjectKey adds a struct to be encoded, must be used inside an object as it will encode a key
// value must implement MarshalerJSONObject | [
"ObjectKey",
"adds",
"a",
"struct",
"to",
"be",
"encoded",
"must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key",
"value",
"must",
"implement",
"MarshalerJSONObject"
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_object.go#L223-L261 | train |
francoispqt/gojay | encode_object.go | ObjectKeyWithKeys | func (enc *Encoder) ObjectKeyWithKeys(key string, value MarshalerJSONObject, keys []string) {
if enc.hasKeys {
if !enc.keyExists(key) {
return
}
}
if value.IsNil() {
enc.grow(2 + len(key))
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKeyObj)
enc.writeByte('}')
return
}
enc.grow(5 + len(key))
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKeyObj)
var origKeys = enc.keys
var origHasKeys = enc.hasKeys
enc.hasKeys = true
enc.keys = keys
value.MarshalJSONObject(enc)
enc.hasKeys = origHasKeys
enc.keys = origKeys
enc.writeByte('}')
} | go | func (enc *Encoder) ObjectKeyWithKeys(key string, value MarshalerJSONObject, keys []string) {
if enc.hasKeys {
if !enc.keyExists(key) {
return
}
}
if value.IsNil() {
enc.grow(2 + len(key))
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKeyObj)
enc.writeByte('}')
return
}
enc.grow(5 + len(key))
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKeyObj)
var origKeys = enc.keys
var origHasKeys = enc.hasKeys
enc.hasKeys = true
enc.keys = keys
value.MarshalJSONObject(enc)
enc.hasKeys = origHasKeys
enc.keys = origKeys
enc.writeByte('}')
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"ObjectKeyWithKeys",
"(",
"key",
"string",
",",
"value",
"MarshalerJSONObject",
",",
"keys",
"[",
"]",
"string",
")",
"{",
"if",
"enc",
".",
"hasKeys",
"{",
"if",
"!",
"enc",
".",
"keyExists",
"(",
"key",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"value",
".",
"IsNil",
"(",
")",
"{",
"enc",
".",
"grow",
"(",
"2",
"+",
"len",
"(",
"key",
")",
")",
"\n",
"r",
":=",
"enc",
".",
"getPreviousRune",
"(",
")",
"\n",
"if",
"r",
"!=",
"'{'",
"{",
"enc",
".",
"writeByte",
"(",
"','",
")",
"\n",
"}",
"\n",
"enc",
".",
"writeByte",
"(",
"'\"'",
")",
"\n",
"enc",
".",
"writeStringEscape",
"(",
"key",
")",
"\n",
"enc",
".",
"writeBytes",
"(",
"objKeyObj",
")",
"\n",
"enc",
".",
"writeByte",
"(",
"'}'",
")",
"\n",
"return",
"\n",
"}",
"\n",
"enc",
".",
"grow",
"(",
"5",
"+",
"len",
"(",
"key",
")",
")",
"\n",
"r",
":=",
"enc",
".",
"getPreviousRune",
"(",
")",
"\n",
"if",
"r",
"!=",
"'{'",
"{",
"enc",
".",
"writeByte",
"(",
"','",
")",
"\n",
"}",
"\n",
"enc",
".",
"writeByte",
"(",
"'\"'",
")",
"\n",
"enc",
".",
"writeStringEscape",
"(",
"key",
")",
"\n",
"enc",
".",
"writeBytes",
"(",
"objKeyObj",
")",
"\n",
"var",
"origKeys",
"=",
"enc",
".",
"keys",
"\n",
"var",
"origHasKeys",
"=",
"enc",
".",
"hasKeys",
"\n",
"enc",
".",
"hasKeys",
"=",
"true",
"\n",
"enc",
".",
"keys",
"=",
"keys",
"\n",
"value",
".",
"MarshalJSONObject",
"(",
"enc",
")",
"\n",
"enc",
".",
"hasKeys",
"=",
"origHasKeys",
"\n",
"enc",
".",
"keys",
"=",
"origKeys",
"\n",
"enc",
".",
"writeByte",
"(",
"'}'",
")",
"\n",
"}"
] | // ObjectKeyWithKeys adds a struct to be encoded, must be used inside an object as it will encode a key.
// Value must implement MarshalerJSONObject. It will only encode the keys in keys. | [
"ObjectKeyWithKeys",
"adds",
"a",
"struct",
"to",
"be",
"encoded",
"must",
"be",
"used",
"inside",
"an",
"object",
"as",
"it",
"will",
"encode",
"a",
"key",
".",
"Value",
"must",
"implement",
"MarshalerJSONObject",
".",
"It",
"will",
"only",
"encode",
"the",
"keys",
"in",
"keys",
"."
] | e46791d21b5e950e35a725e34cbee72354cc7d10 | https://github.com/francoispqt/gojay/blob/e46791d21b5e950e35a725e34cbee72354cc7d10/encode_object.go#L265-L299 | train |
golang/snappy | encode.go | Encode | func Encode(dst, src []byte) []byte {
if n := MaxEncodedLen(len(src)); n < 0 {
panic(ErrTooLarge)
} else if len(dst) < n {
dst = make([]byte, n)
}
// The block starts with the varint-encoded length of the decompressed bytes.
d := binary.PutUvarint(dst, uint64(len(src)))
for len(src) > 0 {
p := src
src = nil
if len(p) > maxBlockSize {
p, src = p[:maxBlockSize], p[maxBlockSize:]
}
if len(p) < minNonLiteralBlockSize {
d += emitLiteral(dst[d:], p)
} else {
d += encodeBlock(dst[d:], p)
}
}
return dst[:d]
} | go | func Encode(dst, src []byte) []byte {
if n := MaxEncodedLen(len(src)); n < 0 {
panic(ErrTooLarge)
} else if len(dst) < n {
dst = make([]byte, n)
}
// The block starts with the varint-encoded length of the decompressed bytes.
d := binary.PutUvarint(dst, uint64(len(src)))
for len(src) > 0 {
p := src
src = nil
if len(p) > maxBlockSize {
p, src = p[:maxBlockSize], p[maxBlockSize:]
}
if len(p) < minNonLiteralBlockSize {
d += emitLiteral(dst[d:], p)
} else {
d += encodeBlock(dst[d:], p)
}
}
return dst[:d]
} | [
"func",
"Encode",
"(",
"dst",
",",
"src",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"if",
"n",
":=",
"MaxEncodedLen",
"(",
"len",
"(",
"src",
")",
")",
";",
"n",
"<",
"0",
"{",
"panic",
"(",
"ErrTooLarge",
")",
"\n",
"}",
"else",
"if",
"len",
"(",
"dst",
")",
"<",
"n",
"{",
"dst",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"n",
")",
"\n",
"}",
"\n\n",
"// The block starts with the varint-encoded length of the decompressed bytes.",
"d",
":=",
"binary",
".",
"PutUvarint",
"(",
"dst",
",",
"uint64",
"(",
"len",
"(",
"src",
")",
")",
")",
"\n\n",
"for",
"len",
"(",
"src",
")",
">",
"0",
"{",
"p",
":=",
"src",
"\n",
"src",
"=",
"nil",
"\n",
"if",
"len",
"(",
"p",
")",
">",
"maxBlockSize",
"{",
"p",
",",
"src",
"=",
"p",
"[",
":",
"maxBlockSize",
"]",
",",
"p",
"[",
"maxBlockSize",
":",
"]",
"\n",
"}",
"\n",
"if",
"len",
"(",
"p",
")",
"<",
"minNonLiteralBlockSize",
"{",
"d",
"+=",
"emitLiteral",
"(",
"dst",
"[",
"d",
":",
"]",
",",
"p",
")",
"\n",
"}",
"else",
"{",
"d",
"+=",
"encodeBlock",
"(",
"dst",
"[",
"d",
":",
"]",
",",
"p",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"dst",
"[",
":",
"d",
"]",
"\n",
"}"
] | // Encode returns the encoded form of src. The returned slice may be a sub-
// slice of dst if dst was large enough to hold the entire encoded block.
// Otherwise, a newly allocated slice will be returned.
//
// The dst and src must not overlap. It is valid to pass a nil dst. | [
"Encode",
"returns",
"the",
"encoded",
"form",
"of",
"src",
".",
"The",
"returned",
"slice",
"may",
"be",
"a",
"sub",
"-",
"slice",
"of",
"dst",
"if",
"dst",
"was",
"large",
"enough",
"to",
"hold",
"the",
"entire",
"encoded",
"block",
".",
"Otherwise",
"a",
"newly",
"allocated",
"slice",
"will",
"be",
"returned",
".",
"The",
"dst",
"and",
"src",
"must",
"not",
"overlap",
".",
"It",
"is",
"valid",
"to",
"pass",
"a",
"nil",
"dst",
"."
] | 2a8bb927dd31d8daada140a5d09578521ce5c36a | https://github.com/golang/snappy/blob/2a8bb927dd31d8daada140a5d09578521ce5c36a/encode.go#L18-L41 | train |
golang/snappy | encode.go | MaxEncodedLen | func MaxEncodedLen(srcLen int) int {
n := uint64(srcLen)
if n > 0xffffffff {
return -1
}
// Compressed data can be defined as:
// compressed := item* literal*
// item := literal* copy
//
// The trailing literal sequence has a space blowup of at most 62/60
// since a literal of length 60 needs one tag byte + one extra byte
// for length information.
//
// Item blowup is trickier to measure. Suppose the "copy" op copies
// 4 bytes of data. Because of a special check in the encoding code,
// we produce a 4-byte copy only if the offset is < 65536. Therefore
// the copy op takes 3 bytes to encode, and this type of item leads
// to at most the 62/60 blowup for representing literals.
//
// Suppose the "copy" op copies 5 bytes of data. If the offset is big
// enough, it will take 5 bytes to encode the copy op. Therefore the
// worst case here is a one-byte literal followed by a five-byte copy.
// That is, 6 bytes of input turn into 7 bytes of "compressed" data.
//
// This last factor dominates the blowup, so the final estimate is:
n = 32 + n + n/6
if n > 0xffffffff {
return -1
}
return int(n)
} | go | func MaxEncodedLen(srcLen int) int {
n := uint64(srcLen)
if n > 0xffffffff {
return -1
}
// Compressed data can be defined as:
// compressed := item* literal*
// item := literal* copy
//
// The trailing literal sequence has a space blowup of at most 62/60
// since a literal of length 60 needs one tag byte + one extra byte
// for length information.
//
// Item blowup is trickier to measure. Suppose the "copy" op copies
// 4 bytes of data. Because of a special check in the encoding code,
// we produce a 4-byte copy only if the offset is < 65536. Therefore
// the copy op takes 3 bytes to encode, and this type of item leads
// to at most the 62/60 blowup for representing literals.
//
// Suppose the "copy" op copies 5 bytes of data. If the offset is big
// enough, it will take 5 bytes to encode the copy op. Therefore the
// worst case here is a one-byte literal followed by a five-byte copy.
// That is, 6 bytes of input turn into 7 bytes of "compressed" data.
//
// This last factor dominates the blowup, so the final estimate is:
n = 32 + n + n/6
if n > 0xffffffff {
return -1
}
return int(n)
} | [
"func",
"MaxEncodedLen",
"(",
"srcLen",
"int",
")",
"int",
"{",
"n",
":=",
"uint64",
"(",
"srcLen",
")",
"\n",
"if",
"n",
">",
"0xffffffff",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"// Compressed data can be defined as:",
"// compressed := item* literal*",
"// item := literal* copy",
"//",
"// The trailing literal sequence has a space blowup of at most 62/60",
"// since a literal of length 60 needs one tag byte + one extra byte",
"// for length information.",
"//",
"// Item blowup is trickier to measure. Suppose the \"copy\" op copies",
"// 4 bytes of data. Because of a special check in the encoding code,",
"// we produce a 4-byte copy only if the offset is < 65536. Therefore",
"// the copy op takes 3 bytes to encode, and this type of item leads",
"// to at most the 62/60 blowup for representing literals.",
"//",
"// Suppose the \"copy\" op copies 5 bytes of data. If the offset is big",
"// enough, it will take 5 bytes to encode the copy op. Therefore the",
"// worst case here is a one-byte literal followed by a five-byte copy.",
"// That is, 6 bytes of input turn into 7 bytes of \"compressed\" data.",
"//",
"// This last factor dominates the blowup, so the final estimate is:",
"n",
"=",
"32",
"+",
"n",
"+",
"n",
"/",
"6",
"\n",
"if",
"n",
">",
"0xffffffff",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"return",
"int",
"(",
"n",
")",
"\n",
"}"
] | // MaxEncodedLen returns the maximum length of a snappy block, given its
// uncompressed length.
//
// It will return a negative value if srcLen is too large to encode. | [
"MaxEncodedLen",
"returns",
"the",
"maximum",
"length",
"of",
"a",
"snappy",
"block",
"given",
"its",
"uncompressed",
"length",
".",
"It",
"will",
"return",
"a",
"negative",
"value",
"if",
"srcLen",
"is",
"too",
"large",
"to",
"encode",
"."
] | 2a8bb927dd31d8daada140a5d09578521ce5c36a | https://github.com/golang/snappy/blob/2a8bb927dd31d8daada140a5d09578521ce5c36a/encode.go#L76-L106 | train |
golang/snappy | encode.go | Close | func (w *Writer) Close() error {
w.Flush()
ret := w.err
if w.err == nil {
w.err = errClosed
}
return ret
} | go | func (w *Writer) Close() error {
w.Flush()
ret := w.err
if w.err == nil {
w.err = errClosed
}
return ret
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Close",
"(",
")",
"error",
"{",
"w",
".",
"Flush",
"(",
")",
"\n",
"ret",
":=",
"w",
".",
"err",
"\n",
"if",
"w",
".",
"err",
"==",
"nil",
"{",
"w",
".",
"err",
"=",
"errClosed",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // Close calls Flush and then closes the Writer. | [
"Close",
"calls",
"Flush",
"and",
"then",
"closes",
"the",
"Writer",
"."
] | 2a8bb927dd31d8daada140a5d09578521ce5c36a | https://github.com/golang/snappy/blob/2a8bb927dd31d8daada140a5d09578521ce5c36a/encode.go#L278-L285 | train |
golang/snappy | decode.go | Decode | func Decode(dst, src []byte) ([]byte, error) {
dLen, s, err := decodedLen(src)
if err != nil {
return nil, err
}
if dLen <= len(dst) {
dst = dst[:dLen]
} else {
dst = make([]byte, dLen)
}
switch decode(dst, src[s:]) {
case 0:
return dst, nil
case decodeErrCodeUnsupportedLiteralLength:
return nil, errUnsupportedLiteralLength
}
return nil, ErrCorrupt
} | go | func Decode(dst, src []byte) ([]byte, error) {
dLen, s, err := decodedLen(src)
if err != nil {
return nil, err
}
if dLen <= len(dst) {
dst = dst[:dLen]
} else {
dst = make([]byte, dLen)
}
switch decode(dst, src[s:]) {
case 0:
return dst, nil
case decodeErrCodeUnsupportedLiteralLength:
return nil, errUnsupportedLiteralLength
}
return nil, ErrCorrupt
} | [
"func",
"Decode",
"(",
"dst",
",",
"src",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"dLen",
",",
"s",
",",
"err",
":=",
"decodedLen",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"dLen",
"<=",
"len",
"(",
"dst",
")",
"{",
"dst",
"=",
"dst",
"[",
":",
"dLen",
"]",
"\n",
"}",
"else",
"{",
"dst",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"dLen",
")",
"\n",
"}",
"\n",
"switch",
"decode",
"(",
"dst",
",",
"src",
"[",
"s",
":",
"]",
")",
"{",
"case",
"0",
":",
"return",
"dst",
",",
"nil",
"\n",
"case",
"decodeErrCodeUnsupportedLiteralLength",
":",
"return",
"nil",
",",
"errUnsupportedLiteralLength",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ErrCorrupt",
"\n",
"}"
] | // Decode returns the decoded form of src. The returned slice may be a sub-
// slice of dst if dst was large enough to hold the entire decoded block.
// Otherwise, a newly allocated slice will be returned.
//
// The dst and src must not overlap. It is valid to pass a nil dst. | [
"Decode",
"returns",
"the",
"decoded",
"form",
"of",
"src",
".",
"The",
"returned",
"slice",
"may",
"be",
"a",
"sub",
"-",
"slice",
"of",
"dst",
"if",
"dst",
"was",
"large",
"enough",
"to",
"hold",
"the",
"entire",
"decoded",
"block",
".",
"Otherwise",
"a",
"newly",
"allocated",
"slice",
"will",
"be",
"returned",
".",
"The",
"dst",
"and",
"src",
"must",
"not",
"overlap",
".",
"It",
"is",
"valid",
"to",
"pass",
"a",
"nil",
"dst",
"."
] | 2a8bb927dd31d8daada140a5d09578521ce5c36a | https://github.com/golang/snappy/blob/2a8bb927dd31d8daada140a5d09578521ce5c36a/decode.go#L55-L72 | train |
coreos/go-iptables | iptables/iptables.go | IsNotExist | func (e *Error) IsNotExist() bool {
return e.ExitStatus() == 1 &&
(e.msg == fmt.Sprintf("%s: Bad rule (does a matching rule exist in that chain?).\n", getIptablesCommand(e.proto)) ||
e.msg == fmt.Sprintf("%s: No chain/target/match by that name.\n", getIptablesCommand(e.proto)))
} | go | func (e *Error) IsNotExist() bool {
return e.ExitStatus() == 1 &&
(e.msg == fmt.Sprintf("%s: Bad rule (does a matching rule exist in that chain?).\n", getIptablesCommand(e.proto)) ||
e.msg == fmt.Sprintf("%s: No chain/target/match by that name.\n", getIptablesCommand(e.proto)))
} | [
"func",
"(",
"e",
"*",
"Error",
")",
"IsNotExist",
"(",
")",
"bool",
"{",
"return",
"e",
".",
"ExitStatus",
"(",
")",
"==",
"1",
"&&",
"(",
"e",
".",
"msg",
"==",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"getIptablesCommand",
"(",
"e",
".",
"proto",
")",
")",
"||",
"e",
".",
"msg",
"==",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"getIptablesCommand",
"(",
"e",
".",
"proto",
")",
")",
")",
"\n",
"}"
] | // IsNotExist returns true if the error is due to the chain or rule not existing | [
"IsNotExist",
"returns",
"true",
"if",
"the",
"error",
"is",
"due",
"to",
"the",
"chain",
"or",
"rule",
"not",
"existing"
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L50-L54 | train |
coreos/go-iptables | iptables/iptables.go | NewWithProtocol | func NewWithProtocol(proto Protocol) (*IPTables, error) {
path, err := exec.LookPath(getIptablesCommand(proto))
if err != nil {
return nil, err
}
vstring, err := getIptablesVersionString(path)
v1, v2, v3, mode, err := extractIptablesVersion(vstring)
checkPresent, waitPresent, randomFullyPresent := getIptablesCommandSupport(v1, v2, v3)
ipt := IPTables{
path: path,
proto: proto,
hasCheck: checkPresent,
hasWait: waitPresent,
hasRandomFully: randomFullyPresent,
v1: v1,
v2: v2,
v3: v3,
mode: mode,
}
return &ipt, nil
} | go | func NewWithProtocol(proto Protocol) (*IPTables, error) {
path, err := exec.LookPath(getIptablesCommand(proto))
if err != nil {
return nil, err
}
vstring, err := getIptablesVersionString(path)
v1, v2, v3, mode, err := extractIptablesVersion(vstring)
checkPresent, waitPresent, randomFullyPresent := getIptablesCommandSupport(v1, v2, v3)
ipt := IPTables{
path: path,
proto: proto,
hasCheck: checkPresent,
hasWait: waitPresent,
hasRandomFully: randomFullyPresent,
v1: v1,
v2: v2,
v3: v3,
mode: mode,
}
return &ipt, nil
} | [
"func",
"NewWithProtocol",
"(",
"proto",
"Protocol",
")",
"(",
"*",
"IPTables",
",",
"error",
")",
"{",
"path",
",",
"err",
":=",
"exec",
".",
"LookPath",
"(",
"getIptablesCommand",
"(",
"proto",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"vstring",
",",
"err",
":=",
"getIptablesVersionString",
"(",
"path",
")",
"\n",
"v1",
",",
"v2",
",",
"v3",
",",
"mode",
",",
"err",
":=",
"extractIptablesVersion",
"(",
"vstring",
")",
"\n\n",
"checkPresent",
",",
"waitPresent",
",",
"randomFullyPresent",
":=",
"getIptablesCommandSupport",
"(",
"v1",
",",
"v2",
",",
"v3",
")",
"\n\n",
"ipt",
":=",
"IPTables",
"{",
"path",
":",
"path",
",",
"proto",
":",
"proto",
",",
"hasCheck",
":",
"checkPresent",
",",
"hasWait",
":",
"waitPresent",
",",
"hasRandomFully",
":",
"randomFullyPresent",
",",
"v1",
":",
"v1",
",",
"v2",
":",
"v2",
",",
"v3",
":",
"v3",
",",
"mode",
":",
"mode",
",",
"}",
"\n",
"return",
"&",
"ipt",
",",
"nil",
"\n",
"}"
] | // New creates a new IPTables for the given proto.
// The proto will determine which command is used, either "iptables" or "ip6tables". | [
"New",
"creates",
"a",
"new",
"IPTables",
"for",
"the",
"given",
"proto",
".",
"The",
"proto",
"will",
"determine",
"which",
"command",
"is",
"used",
"either",
"iptables",
"or",
"ip6tables",
"."
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L84-L106 | train |
coreos/go-iptables | iptables/iptables.go | ListChains | func (ipt *IPTables) ListChains(table string) ([]string, error) {
args := []string{"-t", table, "-S"}
result, err := ipt.executeList(args)
if err != nil {
return nil, err
}
// Iterate over rules to find all default (-P) and user-specified (-N) chains.
// Chains definition always come before rules.
// Format is the following:
// -P OUTPUT ACCEPT
// -N Custom
var chains []string
for _, val := range result {
if strings.HasPrefix(val, "-P") || strings.HasPrefix(val, "-N") {
chains = append(chains, strings.Fields(val)[1])
} else {
break
}
}
return chains, nil
} | go | func (ipt *IPTables) ListChains(table string) ([]string, error) {
args := []string{"-t", table, "-S"}
result, err := ipt.executeList(args)
if err != nil {
return nil, err
}
// Iterate over rules to find all default (-P) and user-specified (-N) chains.
// Chains definition always come before rules.
// Format is the following:
// -P OUTPUT ACCEPT
// -N Custom
var chains []string
for _, val := range result {
if strings.HasPrefix(val, "-P") || strings.HasPrefix(val, "-N") {
chains = append(chains, strings.Fields(val)[1])
} else {
break
}
}
return chains, nil
} | [
"func",
"(",
"ipt",
"*",
"IPTables",
")",
"ListChains",
"(",
"table",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"args",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"table",
",",
"\"",
"\"",
"}",
"\n\n",
"result",
",",
"err",
":=",
"ipt",
".",
"executeList",
"(",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Iterate over rules to find all default (-P) and user-specified (-N) chains.",
"// Chains definition always come before rules.",
"// Format is the following:",
"// -P OUTPUT ACCEPT",
"// -N Custom",
"var",
"chains",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"val",
":=",
"range",
"result",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"val",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"HasPrefix",
"(",
"val",
",",
"\"",
"\"",
")",
"{",
"chains",
"=",
"append",
"(",
"chains",
",",
"strings",
".",
"Fields",
"(",
"val",
")",
"[",
"1",
"]",
")",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"chains",
",",
"nil",
"\n",
"}"
] | // ListChains returns a slice containing the name of each chain in the specified table. | [
"ListChains",
"returns",
"a",
"slice",
"containing",
"the",
"name",
"of",
"each",
"chain",
"in",
"the",
"specified",
"table",
"."
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L177-L199 | train |
coreos/go-iptables | iptables/iptables.go | Stats | func (ipt *IPTables) Stats(table, chain string) ([][]string, error) {
args := []string{"-t", table, "-L", chain, "-n", "-v", "-x"}
lines, err := ipt.executeList(args)
if err != nil {
return nil, err
}
appendSubnet := func(addr string) string {
if strings.IndexByte(addr, byte('/')) < 0 {
if strings.IndexByte(addr, '.') < 0 {
return addr + "/128"
}
return addr + "/32"
}
return addr
}
ipv6 := ipt.proto == ProtocolIPv6
rows := [][]string{}
for i, line := range lines {
// Skip over chain name and field header
if i < 2 {
continue
}
// Fields:
// 0=pkts 1=bytes 2=target 3=prot 4=opt 5=in 6=out 7=source 8=destination 9=options
line = strings.TrimSpace(line)
fields := strings.Fields(line)
// The ip6tables verbose output cannot be naively split due to the default "opt"
// field containing 2 single spaces.
if ipv6 {
// Check if field 6 is "opt" or "source" address
dest := fields[6]
ip, _, _ := net.ParseCIDR(dest)
if ip == nil {
ip = net.ParseIP(dest)
}
// If we detected a CIDR or IP, the "opt" field is empty.. insert it.
if ip != nil {
f := []string{}
f = append(f, fields[:4]...)
f = append(f, " ") // Empty "opt" field for ip6tables
f = append(f, fields[4:]...)
fields = f
}
}
// Adjust "source" and "destination" to include netmask, to match regular
// List output
fields[7] = appendSubnet(fields[7])
fields[8] = appendSubnet(fields[8])
// Combine "options" fields 9... into a single space-delimited field.
options := fields[9:]
fields = fields[:9]
fields = append(fields, strings.Join(options, " "))
rows = append(rows, fields)
}
return rows, nil
} | go | func (ipt *IPTables) Stats(table, chain string) ([][]string, error) {
args := []string{"-t", table, "-L", chain, "-n", "-v", "-x"}
lines, err := ipt.executeList(args)
if err != nil {
return nil, err
}
appendSubnet := func(addr string) string {
if strings.IndexByte(addr, byte('/')) < 0 {
if strings.IndexByte(addr, '.') < 0 {
return addr + "/128"
}
return addr + "/32"
}
return addr
}
ipv6 := ipt.proto == ProtocolIPv6
rows := [][]string{}
for i, line := range lines {
// Skip over chain name and field header
if i < 2 {
continue
}
// Fields:
// 0=pkts 1=bytes 2=target 3=prot 4=opt 5=in 6=out 7=source 8=destination 9=options
line = strings.TrimSpace(line)
fields := strings.Fields(line)
// The ip6tables verbose output cannot be naively split due to the default "opt"
// field containing 2 single spaces.
if ipv6 {
// Check if field 6 is "opt" or "source" address
dest := fields[6]
ip, _, _ := net.ParseCIDR(dest)
if ip == nil {
ip = net.ParseIP(dest)
}
// If we detected a CIDR or IP, the "opt" field is empty.. insert it.
if ip != nil {
f := []string{}
f = append(f, fields[:4]...)
f = append(f, " ") // Empty "opt" field for ip6tables
f = append(f, fields[4:]...)
fields = f
}
}
// Adjust "source" and "destination" to include netmask, to match regular
// List output
fields[7] = appendSubnet(fields[7])
fields[8] = appendSubnet(fields[8])
// Combine "options" fields 9... into a single space-delimited field.
options := fields[9:]
fields = fields[:9]
fields = append(fields, strings.Join(options, " "))
rows = append(rows, fields)
}
return rows, nil
} | [
"func",
"(",
"ipt",
"*",
"IPTables",
")",
"Stats",
"(",
"table",
",",
"chain",
"string",
")",
"(",
"[",
"]",
"[",
"]",
"string",
",",
"error",
")",
"{",
"args",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"table",
",",
"\"",
"\"",
",",
"chain",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"lines",
",",
"err",
":=",
"ipt",
".",
"executeList",
"(",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"appendSubnet",
":=",
"func",
"(",
"addr",
"string",
")",
"string",
"{",
"if",
"strings",
".",
"IndexByte",
"(",
"addr",
",",
"byte",
"(",
"'/'",
")",
")",
"<",
"0",
"{",
"if",
"strings",
".",
"IndexByte",
"(",
"addr",
",",
"'.'",
")",
"<",
"0",
"{",
"return",
"addr",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"addr",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"addr",
"\n",
"}",
"\n\n",
"ipv6",
":=",
"ipt",
".",
"proto",
"==",
"ProtocolIPv6",
"\n\n",
"rows",
":=",
"[",
"]",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
",",
"line",
":=",
"range",
"lines",
"{",
"// Skip over chain name and field header",
"if",
"i",
"<",
"2",
"{",
"continue",
"\n",
"}",
"\n\n",
"// Fields:",
"// 0=pkts 1=bytes 2=target 3=prot 4=opt 5=in 6=out 7=source 8=destination 9=options",
"line",
"=",
"strings",
".",
"TrimSpace",
"(",
"line",
")",
"\n",
"fields",
":=",
"strings",
".",
"Fields",
"(",
"line",
")",
"\n\n",
"// The ip6tables verbose output cannot be naively split due to the default \"opt\"",
"// field containing 2 single spaces.",
"if",
"ipv6",
"{",
"// Check if field 6 is \"opt\" or \"source\" address",
"dest",
":=",
"fields",
"[",
"6",
"]",
"\n",
"ip",
",",
"_",
",",
"_",
":=",
"net",
".",
"ParseCIDR",
"(",
"dest",
")",
"\n",
"if",
"ip",
"==",
"nil",
"{",
"ip",
"=",
"net",
".",
"ParseIP",
"(",
"dest",
")",
"\n",
"}",
"\n\n",
"// If we detected a CIDR or IP, the \"opt\" field is empty.. insert it.",
"if",
"ip",
"!=",
"nil",
"{",
"f",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"f",
"=",
"append",
"(",
"f",
",",
"fields",
"[",
":",
"4",
"]",
"...",
")",
"\n",
"f",
"=",
"append",
"(",
"f",
",",
"\"",
"\"",
")",
"// Empty \"opt\" field for ip6tables",
"\n",
"f",
"=",
"append",
"(",
"f",
",",
"fields",
"[",
"4",
":",
"]",
"...",
")",
"\n",
"fields",
"=",
"f",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Adjust \"source\" and \"destination\" to include netmask, to match regular",
"// List output",
"fields",
"[",
"7",
"]",
"=",
"appendSubnet",
"(",
"fields",
"[",
"7",
"]",
")",
"\n",
"fields",
"[",
"8",
"]",
"=",
"appendSubnet",
"(",
"fields",
"[",
"8",
"]",
")",
"\n\n",
"// Combine \"options\" fields 9... into a single space-delimited field.",
"options",
":=",
"fields",
"[",
"9",
":",
"]",
"\n",
"fields",
"=",
"fields",
"[",
":",
"9",
"]",
"\n",
"fields",
"=",
"append",
"(",
"fields",
",",
"strings",
".",
"Join",
"(",
"options",
",",
"\"",
"\"",
")",
")",
"\n",
"rows",
"=",
"append",
"(",
"rows",
",",
"fields",
")",
"\n",
"}",
"\n",
"return",
"rows",
",",
"nil",
"\n",
"}"
] | // Stats lists rules including the byte and packet counts | [
"Stats",
"lists",
"rules",
"including",
"the",
"byte",
"and",
"packet",
"counts"
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L202-L265 | train |
coreos/go-iptables | iptables/iptables.go | NewChain | func (ipt *IPTables) NewChain(table, chain string) error {
return ipt.run("-t", table, "-N", chain)
} | go | func (ipt *IPTables) NewChain(table, chain string) error {
return ipt.run("-t", table, "-N", chain)
} | [
"func",
"(",
"ipt",
"*",
"IPTables",
")",
"NewChain",
"(",
"table",
",",
"chain",
"string",
")",
"error",
"{",
"return",
"ipt",
".",
"run",
"(",
"\"",
"\"",
",",
"table",
",",
"\"",
"\"",
",",
"chain",
")",
"\n",
"}"
] | // NewChain creates a new chain in the specified table.
// If the chain already exists, it will result in an error. | [
"NewChain",
"creates",
"a",
"new",
"chain",
"in",
"the",
"specified",
"table",
".",
"If",
"the",
"chain",
"already",
"exists",
"it",
"will",
"result",
"in",
"an",
"error",
"."
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L301-L303 | train |
coreos/go-iptables | iptables/iptables.go | RenameChain | func (ipt *IPTables) RenameChain(table, oldChain, newChain string) error {
return ipt.run("-t", table, "-E", oldChain, newChain)
} | go | func (ipt *IPTables) RenameChain(table, oldChain, newChain string) error {
return ipt.run("-t", table, "-E", oldChain, newChain)
} | [
"func",
"(",
"ipt",
"*",
"IPTables",
")",
"RenameChain",
"(",
"table",
",",
"oldChain",
",",
"newChain",
"string",
")",
"error",
"{",
"return",
"ipt",
".",
"run",
"(",
"\"",
"\"",
",",
"table",
",",
"\"",
"\"",
",",
"oldChain",
",",
"newChain",
")",
"\n",
"}"
] | // RenameChain renames the old chain to the new one. | [
"RenameChain",
"renames",
"the",
"old",
"chain",
"to",
"the",
"new",
"one",
"."
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L330-L332 | train |
coreos/go-iptables | iptables/iptables.go | DeleteChain | func (ipt *IPTables) DeleteChain(table, chain string) error {
return ipt.run("-t", table, "-X", chain)
} | go | func (ipt *IPTables) DeleteChain(table, chain string) error {
return ipt.run("-t", table, "-X", chain)
} | [
"func",
"(",
"ipt",
"*",
"IPTables",
")",
"DeleteChain",
"(",
"table",
",",
"chain",
"string",
")",
"error",
"{",
"return",
"ipt",
".",
"run",
"(",
"\"",
"\"",
",",
"table",
",",
"\"",
"\"",
",",
"chain",
")",
"\n",
"}"
] | // DeleteChain deletes the chain in the specified table.
// The chain must be empty | [
"DeleteChain",
"deletes",
"the",
"chain",
"in",
"the",
"specified",
"table",
".",
"The",
"chain",
"must",
"be",
"empty"
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L336-L338 | train |
coreos/go-iptables | iptables/iptables.go | ChangePolicy | func (ipt *IPTables) ChangePolicy(table, chain, target string) error {
return ipt.run("-t", table, "-P", chain, target)
} | go | func (ipt *IPTables) ChangePolicy(table, chain, target string) error {
return ipt.run("-t", table, "-P", chain, target)
} | [
"func",
"(",
"ipt",
"*",
"IPTables",
")",
"ChangePolicy",
"(",
"table",
",",
"chain",
",",
"target",
"string",
")",
"error",
"{",
"return",
"ipt",
".",
"run",
"(",
"\"",
"\"",
",",
"table",
",",
"\"",
"\"",
",",
"chain",
",",
"target",
")",
"\n",
"}"
] | // ChangePolicy changes policy on chain to target | [
"ChangePolicy",
"changes",
"policy",
"on",
"chain",
"to",
"target"
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L341-L343 | train |
coreos/go-iptables | iptables/iptables.go | GetIptablesVersion | func (ipt *IPTables) GetIptablesVersion() (int, int, int) {
return ipt.v1, ipt.v2, ipt.v3
} | go | func (ipt *IPTables) GetIptablesVersion() (int, int, int) {
return ipt.v1, ipt.v2, ipt.v3
} | [
"func",
"(",
"ipt",
"*",
"IPTables",
")",
"GetIptablesVersion",
"(",
")",
"(",
"int",
",",
"int",
",",
"int",
")",
"{",
"return",
"ipt",
".",
"v1",
",",
"ipt",
".",
"v2",
",",
"ipt",
".",
"v3",
"\n",
"}"
] | // Return version components of the underlying iptables command | [
"Return",
"version",
"components",
"of",
"the",
"underlying",
"iptables",
"command"
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L351-L353 | train |
coreos/go-iptables | iptables/iptables.go | run | func (ipt *IPTables) run(args ...string) error {
return ipt.runWithOutput(args, nil)
} | go | func (ipt *IPTables) run(args ...string) error {
return ipt.runWithOutput(args, nil)
} | [
"func",
"(",
"ipt",
"*",
"IPTables",
")",
"run",
"(",
"args",
"...",
"string",
")",
"error",
"{",
"return",
"ipt",
".",
"runWithOutput",
"(",
"args",
",",
"nil",
")",
"\n",
"}"
] | // run runs an iptables command with the given arguments, ignoring
// any stdout output | [
"run",
"runs",
"an",
"iptables",
"command",
"with",
"the",
"given",
"arguments",
"ignoring",
"any",
"stdout",
"output"
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L357-L359 | train |
coreos/go-iptables | iptables/iptables.go | runWithOutput | func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
args = append([]string{ipt.path}, args...)
if ipt.hasWait {
args = append(args, "--wait")
} else {
fmu, err := newXtablesFileLock()
if err != nil {
return err
}
ul, err := fmu.tryLock()
if err != nil {
return err
}
defer ul.Unlock()
}
var stderr bytes.Buffer
cmd := exec.Cmd{
Path: ipt.path,
Args: args,
Stdout: stdout,
Stderr: &stderr,
}
if err := cmd.Run(); err != nil {
switch e := err.(type) {
case *exec.ExitError:
return &Error{*e, cmd, stderr.String(), ipt.proto, nil}
default:
return err
}
}
return nil
} | go | func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
args = append([]string{ipt.path}, args...)
if ipt.hasWait {
args = append(args, "--wait")
} else {
fmu, err := newXtablesFileLock()
if err != nil {
return err
}
ul, err := fmu.tryLock()
if err != nil {
return err
}
defer ul.Unlock()
}
var stderr bytes.Buffer
cmd := exec.Cmd{
Path: ipt.path,
Args: args,
Stdout: stdout,
Stderr: &stderr,
}
if err := cmd.Run(); err != nil {
switch e := err.(type) {
case *exec.ExitError:
return &Error{*e, cmd, stderr.String(), ipt.proto, nil}
default:
return err
}
}
return nil
} | [
"func",
"(",
"ipt",
"*",
"IPTables",
")",
"runWithOutput",
"(",
"args",
"[",
"]",
"string",
",",
"stdout",
"io",
".",
"Writer",
")",
"error",
"{",
"args",
"=",
"append",
"(",
"[",
"]",
"string",
"{",
"ipt",
".",
"path",
"}",
",",
"args",
"...",
")",
"\n",
"if",
"ipt",
".",
"hasWait",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"fmu",
",",
"err",
":=",
"newXtablesFileLock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ul",
",",
"err",
":=",
"fmu",
".",
"tryLock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"ul",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n\n",
"var",
"stderr",
"bytes",
".",
"Buffer",
"\n",
"cmd",
":=",
"exec",
".",
"Cmd",
"{",
"Path",
":",
"ipt",
".",
"path",
",",
"Args",
":",
"args",
",",
"Stdout",
":",
"stdout",
",",
"Stderr",
":",
"&",
"stderr",
",",
"}",
"\n\n",
"if",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"switch",
"e",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"*",
"exec",
".",
"ExitError",
":",
"return",
"&",
"Error",
"{",
"*",
"e",
",",
"cmd",
",",
"stderr",
".",
"String",
"(",
")",
",",
"ipt",
".",
"proto",
",",
"nil",
"}",
"\n",
"default",
":",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // runWithOutput runs an iptables command with the given arguments,
// writing any stdout output to the given writer | [
"runWithOutput",
"runs",
"an",
"iptables",
"command",
"with",
"the",
"given",
"arguments",
"writing",
"any",
"stdout",
"output",
"to",
"the",
"given",
"writer"
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L363-L397 | train |
coreos/go-iptables | iptables/iptables.go | filterRuleOutput | func filterRuleOutput(rule string) string {
out := rule
// work around an output difference in nftables mode where counters
// are output in iptables-save format, rather than iptables -S format
// The string begins with "[0:0]"
//
// Fixes #49
if groups := counterRegex.FindStringSubmatch(out); groups != nil {
// drop the brackets
out = out[len(groups[0]):]
out = fmt.Sprintf("%s -c %s %s", out, groups[1], groups[2])
}
return out
} | go | func filterRuleOutput(rule string) string {
out := rule
// work around an output difference in nftables mode where counters
// are output in iptables-save format, rather than iptables -S format
// The string begins with "[0:0]"
//
// Fixes #49
if groups := counterRegex.FindStringSubmatch(out); groups != nil {
// drop the brackets
out = out[len(groups[0]):]
out = fmt.Sprintf("%s -c %s %s", out, groups[1], groups[2])
}
return out
} | [
"func",
"filterRuleOutput",
"(",
"rule",
"string",
")",
"string",
"{",
"out",
":=",
"rule",
"\n\n",
"// work around an output difference in nftables mode where counters",
"// are output in iptables-save format, rather than iptables -S format",
"// The string begins with \"[0:0]\"",
"//",
"// Fixes #49",
"if",
"groups",
":=",
"counterRegex",
".",
"FindStringSubmatch",
"(",
"out",
")",
";",
"groups",
"!=",
"nil",
"{",
"// drop the brackets",
"out",
"=",
"out",
"[",
"len",
"(",
"groups",
"[",
"0",
"]",
")",
":",
"]",
"\n",
"out",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"out",
",",
"groups",
"[",
"1",
"]",
",",
"groups",
"[",
"2",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"out",
"\n",
"}"
] | // filterRuleOutput works around some inconsistencies in output.
// For example, when iptables is in legacy vs. nftables mode, it produces
// different results. | [
"filterRuleOutput",
"works",
"around",
"some",
"inconsistencies",
"in",
"output",
".",
"For",
"example",
"when",
"iptables",
"is",
"in",
"legacy",
"vs",
".",
"nftables",
"mode",
"it",
"produces",
"different",
"results",
"."
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/iptables.go#L517-L532 | train |
coreos/go-iptables | iptables/lock.go | Unlock | func (l *fileLock) Unlock() error {
defer l.mu.Unlock()
return syscall.Close(l.fd)
} | go | func (l *fileLock) Unlock() error {
defer l.mu.Unlock()
return syscall.Close(l.fd)
} | [
"func",
"(",
"l",
"*",
"fileLock",
")",
"Unlock",
"(",
")",
"error",
"{",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"syscall",
".",
"Close",
"(",
"l",
".",
"fd",
")",
"\n",
"}"
] | // Unlock closes the underlying file, which implicitly unlocks it as well. It
// also unlocks the associated mutex. | [
"Unlock",
"closes",
"the",
"underlying",
"file",
"which",
"implicitly",
"unlocks",
"it",
"as",
"well",
".",
"It",
"also",
"unlocks",
"the",
"associated",
"mutex",
"."
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/lock.go#L71-L74 | train |
coreos/go-iptables | iptables/lock.go | newXtablesFileLock | func newXtablesFileLock() (*fileLock, error) {
fd, err := syscall.Open(xtablesLockFilePath, os.O_CREATE, defaultFilePerm)
if err != nil {
return nil, err
}
return &fileLock{fd: fd}, nil
} | go | func newXtablesFileLock() (*fileLock, error) {
fd, err := syscall.Open(xtablesLockFilePath, os.O_CREATE, defaultFilePerm)
if err != nil {
return nil, err
}
return &fileLock{fd: fd}, nil
} | [
"func",
"newXtablesFileLock",
"(",
")",
"(",
"*",
"fileLock",
",",
"error",
")",
"{",
"fd",
",",
"err",
":=",
"syscall",
".",
"Open",
"(",
"xtablesLockFilePath",
",",
"os",
".",
"O_CREATE",
",",
"defaultFilePerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"fileLock",
"{",
"fd",
":",
"fd",
"}",
",",
"nil",
"\n",
"}"
] | // newXtablesFileLock opens a new lock on the xtables lockfile without
// acquiring the lock | [
"newXtablesFileLock",
"opens",
"a",
"new",
"lock",
"on",
"the",
"xtables",
"lockfile",
"without",
"acquiring",
"the",
"lock"
] | 78b5fff24e6df8886ef8eca9411f683a884349a5 | https://github.com/coreos/go-iptables/blob/78b5fff24e6df8886ef8eca9411f683a884349a5/iptables/lock.go#L78-L84 | train |
edsrzf/mmap-go | mmap.go | Map | func Map(f *os.File, prot, flags int) (MMap, error) {
return MapRegion(f, -1, prot, flags, 0)
} | go | func Map(f *os.File, prot, flags int) (MMap, error) {
return MapRegion(f, -1, prot, flags, 0)
} | [
"func",
"Map",
"(",
"f",
"*",
"os",
".",
"File",
",",
"prot",
",",
"flags",
"int",
")",
"(",
"MMap",
",",
"error",
")",
"{",
"return",
"MapRegion",
"(",
"f",
",",
"-",
"1",
",",
"prot",
",",
"flags",
",",
"0",
")",
"\n",
"}"
] | // Map maps an entire file into memory.
// If ANON is set in flags, f is ignored. | [
"Map",
"maps",
"an",
"entire",
"file",
"into",
"memory",
".",
"If",
"ANON",
"is",
"set",
"in",
"flags",
"f",
"is",
"ignored",
"."
] | 904c4ced31cdffe19e971afa0b3d319ff06d9c72 | https://github.com/edsrzf/mmap-go/blob/904c4ced31cdffe19e971afa0b3d319ff06d9c72/mmap.go#L48-L50 | train |
edsrzf/mmap-go | mmap.go | MapRegion | func MapRegion(f *os.File, length int, prot, flags int, offset int64) (MMap, error) {
if offset%int64(os.Getpagesize()) != 0 {
return nil, errors.New("offset parameter must be a multiple of the system's page size")
}
var fd uintptr
if flags&ANON == 0 {
fd = uintptr(f.Fd())
if length < 0 {
fi, err := f.Stat()
if err != nil {
return nil, err
}
length = int(fi.Size())
}
} else {
if length <= 0 {
return nil, errors.New("anonymous mapping requires non-zero length")
}
fd = ^uintptr(0)
}
return mmap(length, uintptr(prot), uintptr(flags), fd, offset)
} | go | func MapRegion(f *os.File, length int, prot, flags int, offset int64) (MMap, error) {
if offset%int64(os.Getpagesize()) != 0 {
return nil, errors.New("offset parameter must be a multiple of the system's page size")
}
var fd uintptr
if flags&ANON == 0 {
fd = uintptr(f.Fd())
if length < 0 {
fi, err := f.Stat()
if err != nil {
return nil, err
}
length = int(fi.Size())
}
} else {
if length <= 0 {
return nil, errors.New("anonymous mapping requires non-zero length")
}
fd = ^uintptr(0)
}
return mmap(length, uintptr(prot), uintptr(flags), fd, offset)
} | [
"func",
"MapRegion",
"(",
"f",
"*",
"os",
".",
"File",
",",
"length",
"int",
",",
"prot",
",",
"flags",
"int",
",",
"offset",
"int64",
")",
"(",
"MMap",
",",
"error",
")",
"{",
"if",
"offset",
"%",
"int64",
"(",
"os",
".",
"Getpagesize",
"(",
")",
")",
"!=",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"fd",
"uintptr",
"\n",
"if",
"flags",
"&",
"ANON",
"==",
"0",
"{",
"fd",
"=",
"uintptr",
"(",
"f",
".",
"Fd",
"(",
")",
")",
"\n",
"if",
"length",
"<",
"0",
"{",
"fi",
",",
"err",
":=",
"f",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"length",
"=",
"int",
"(",
"fi",
".",
"Size",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"length",
"<=",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"fd",
"=",
"^",
"uintptr",
"(",
"0",
")",
"\n",
"}",
"\n",
"return",
"mmap",
"(",
"length",
",",
"uintptr",
"(",
"prot",
")",
",",
"uintptr",
"(",
"flags",
")",
",",
"fd",
",",
"offset",
")",
"\n",
"}"
] | // MapRegion maps part of a file into memory.
// The offset parameter must be a multiple of the system's page size.
// If length < 0, the entire file will be mapped.
// If ANON is set in flags, f is ignored. | [
"MapRegion",
"maps",
"part",
"of",
"a",
"file",
"into",
"memory",
".",
"The",
"offset",
"parameter",
"must",
"be",
"a",
"multiple",
"of",
"the",
"system",
"s",
"page",
"size",
".",
"If",
"length",
"<",
"0",
"the",
"entire",
"file",
"will",
"be",
"mapped",
".",
"If",
"ANON",
"is",
"set",
"in",
"flags",
"f",
"is",
"ignored",
"."
] | 904c4ced31cdffe19e971afa0b3d319ff06d9c72 | https://github.com/edsrzf/mmap-go/blob/904c4ced31cdffe19e971afa0b3d319ff06d9c72/mmap.go#L56-L78 | train |
matrix-org/gomatrix | events.go | Body | func (event *Event) Body() (body string, ok bool) {
value, exists := event.Content["body"]
if !exists {
return
}
body, ok = value.(string)
return
} | go | func (event *Event) Body() (body string, ok bool) {
value, exists := event.Content["body"]
if !exists {
return
}
body, ok = value.(string)
return
} | [
"func",
"(",
"event",
"*",
"Event",
")",
"Body",
"(",
")",
"(",
"body",
"string",
",",
"ok",
"bool",
")",
"{",
"value",
",",
"exists",
":=",
"event",
".",
"Content",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"exists",
"{",
"return",
"\n",
"}",
"\n",
"body",
",",
"ok",
"=",
"value",
".",
"(",
"string",
")",
"\n",
"return",
"\n",
"}"
] | // Body returns the value of the "body" key in the event content if it is
// present and is a string. | [
"Body",
"returns",
"the",
"value",
"of",
"the",
"body",
"key",
"in",
"the",
"event",
"content",
"if",
"it",
"is",
"present",
"and",
"is",
"a",
"string",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/events.go#L23-L30 | train |
matrix-org/gomatrix | events.go | MessageType | func (event *Event) MessageType() (msgtype string, ok bool) {
value, exists := event.Content["msgtype"]
if !exists {
return
}
msgtype, ok = value.(string)
return
} | go | func (event *Event) MessageType() (msgtype string, ok bool) {
value, exists := event.Content["msgtype"]
if !exists {
return
}
msgtype, ok = value.(string)
return
} | [
"func",
"(",
"event",
"*",
"Event",
")",
"MessageType",
"(",
")",
"(",
"msgtype",
"string",
",",
"ok",
"bool",
")",
"{",
"value",
",",
"exists",
":=",
"event",
".",
"Content",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"exists",
"{",
"return",
"\n",
"}",
"\n",
"msgtype",
",",
"ok",
"=",
"value",
".",
"(",
"string",
")",
"\n",
"return",
"\n",
"}"
] | // MessageType returns the value of the "msgtype" key in the event content if
// it is present and is a string. | [
"MessageType",
"returns",
"the",
"value",
"of",
"the",
"msgtype",
"key",
"in",
"the",
"event",
"content",
"if",
"it",
"is",
"present",
"and",
"is",
"a",
"string",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/events.go#L34-L41 | train |
matrix-org/gomatrix | events.go | GetHTMLMessage | func GetHTMLMessage(msgtype, htmlText string) HTMLMessage {
return HTMLMessage{
Body: html.UnescapeString(htmlRegex.ReplaceAllLiteralString(htmlText, "")),
MsgType: msgtype,
Format: "org.matrix.custom.html",
FormattedBody: htmlText,
}
} | go | func GetHTMLMessage(msgtype, htmlText string) HTMLMessage {
return HTMLMessage{
Body: html.UnescapeString(htmlRegex.ReplaceAllLiteralString(htmlText, "")),
MsgType: msgtype,
Format: "org.matrix.custom.html",
FormattedBody: htmlText,
}
} | [
"func",
"GetHTMLMessage",
"(",
"msgtype",
",",
"htmlText",
"string",
")",
"HTMLMessage",
"{",
"return",
"HTMLMessage",
"{",
"Body",
":",
"html",
".",
"UnescapeString",
"(",
"htmlRegex",
".",
"ReplaceAllLiteralString",
"(",
"htmlText",
",",
"\"",
"\"",
")",
")",
",",
"MsgType",
":",
"msgtype",
",",
"Format",
":",
"\"",
"\"",
",",
"FormattedBody",
":",
"htmlText",
",",
"}",
"\n",
"}"
] | // GetHTMLMessage returns an HTMLMessage with the body set to a stripped version of the provided HTML, in addition
// to the provided HTML. | [
"GetHTMLMessage",
"returns",
"an",
"HTMLMessage",
"with",
"the",
"body",
"set",
"to",
"a",
"stripped",
"version",
"of",
"the",
"provided",
"HTML",
"in",
"addition",
"to",
"the",
"provided",
"HTML",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/events.go#L106-L113 | train |
matrix-org/gomatrix | room.go | GetMembershipState | func (room Room) GetMembershipState(userID string) string {
state := "leave"
event := room.GetStateEvent("m.room.member", userID)
if event != nil {
membershipState, found := event.Content["membership"]
if found {
mState, isString := membershipState.(string)
if isString {
state = mState
}
}
}
return state
} | go | func (room Room) GetMembershipState(userID string) string {
state := "leave"
event := room.GetStateEvent("m.room.member", userID)
if event != nil {
membershipState, found := event.Content["membership"]
if found {
mState, isString := membershipState.(string)
if isString {
state = mState
}
}
}
return state
} | [
"func",
"(",
"room",
"Room",
")",
"GetMembershipState",
"(",
"userID",
"string",
")",
"string",
"{",
"state",
":=",
"\"",
"\"",
"\n",
"event",
":=",
"room",
".",
"GetStateEvent",
"(",
"\"",
"\"",
",",
"userID",
")",
"\n",
"if",
"event",
"!=",
"nil",
"{",
"membershipState",
",",
"found",
":=",
"event",
".",
"Content",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"found",
"{",
"mState",
",",
"isString",
":=",
"membershipState",
".",
"(",
"string",
")",
"\n",
"if",
"isString",
"{",
"state",
"=",
"mState",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"state",
"\n",
"}"
] | // GetMembershipState returns the membership state of the given user ID in this room. If there is
// no entry for this member, 'leave' is returned for consistency with left users. | [
"GetMembershipState",
"returns",
"the",
"membership",
"state",
"of",
"the",
"given",
"user",
"ID",
"in",
"this",
"room",
".",
"If",
"there",
"is",
"no",
"entry",
"for",
"this",
"member",
"leave",
"is",
"returned",
"for",
"consistency",
"with",
"left",
"users",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/room.go#L28-L41 | train |
matrix-org/gomatrix | room.go | NewRoom | func NewRoom(roomID string) *Room {
// Init the State map and return a pointer to the Room
return &Room{
ID: roomID,
State: make(map[string]map[string]*Event),
}
} | go | func NewRoom(roomID string) *Room {
// Init the State map and return a pointer to the Room
return &Room{
ID: roomID,
State: make(map[string]map[string]*Event),
}
} | [
"func",
"NewRoom",
"(",
"roomID",
"string",
")",
"*",
"Room",
"{",
"// Init the State map and return a pointer to the Room",
"return",
"&",
"Room",
"{",
"ID",
":",
"roomID",
",",
"State",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"*",
"Event",
")",
",",
"}",
"\n",
"}"
] | // NewRoom creates a new Room with the given ID | [
"NewRoom",
"creates",
"a",
"new",
"Room",
"with",
"the",
"given",
"ID"
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/room.go#L44-L50 | train |
matrix-org/gomatrix | responses.go | HasSingleStageFlow | func (r RespUserInteractive) HasSingleStageFlow(stageName string) bool {
for _, f := range r.Flows {
if len(f.Stages) == 1 && f.Stages[0] == stageName {
return true
}
}
return false
} | go | func (r RespUserInteractive) HasSingleStageFlow(stageName string) bool {
for _, f := range r.Flows {
if len(f.Stages) == 1 && f.Stages[0] == stageName {
return true
}
}
return false
} | [
"func",
"(",
"r",
"RespUserInteractive",
")",
"HasSingleStageFlow",
"(",
"stageName",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"r",
".",
"Flows",
"{",
"if",
"len",
"(",
"f",
".",
"Stages",
")",
"==",
"1",
"&&",
"f",
".",
"Stages",
"[",
"0",
"]",
"==",
"stageName",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // HasSingleStageFlow returns true if there exists at least 1 Flow with a single stage of stageName. | [
"HasSingleStageFlow",
"returns",
"true",
"if",
"there",
"exists",
"at",
"least",
"1",
"Flow",
"with",
"a",
"single",
"stage",
"of",
"stageName",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/responses.go#L94-L101 | train |
matrix-org/gomatrix | client.go | SetCredentials | func (cli *Client) SetCredentials(userID, accessToken string) {
cli.AccessToken = accessToken
cli.UserID = userID
} | go | func (cli *Client) SetCredentials(userID, accessToken string) {
cli.AccessToken = accessToken
cli.UserID = userID
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"SetCredentials",
"(",
"userID",
",",
"accessToken",
"string",
")",
"{",
"cli",
".",
"AccessToken",
"=",
"accessToken",
"\n",
"cli",
".",
"UserID",
"=",
"userID",
"\n",
"}"
] | // SetCredentials sets the user ID and access token on this client instance. | [
"SetCredentials",
"sets",
"the",
"user",
"ID",
"and",
"access",
"token",
"on",
"this",
"client",
"instance",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/client.go#L99-L102 | train |
matrix-org/gomatrix | client.go | MakeRequest | func (cli *Client) MakeRequest(method string, httpURL string, reqBody interface{}, resBody interface{}) ([]byte, error) {
var req *http.Request
var err error
if reqBody != nil {
var jsonStr []byte
jsonStr, err = json.Marshal(reqBody)
if err != nil {
return nil, err
}
req, err = http.NewRequest(method, httpURL, bytes.NewBuffer(jsonStr))
} else {
req, err = http.NewRequest(method, httpURL, nil)
}
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
res, err := cli.Client.Do(req)
if res != nil {
defer res.Body.Close()
}
if err != nil {
return nil, err
}
contents, err := ioutil.ReadAll(res.Body)
if res.StatusCode/100 != 2 { // not 2xx
var wrap error
var respErr RespError
if _ = json.Unmarshal(contents, &respErr); respErr.ErrCode != "" {
wrap = respErr
}
// If we failed to decode as RespError, don't just drop the HTTP body, include it in the
// HTTP error instead (e.g proxy errors which return HTML).
msg := "Failed to " + method + " JSON to " + req.URL.Path
if wrap == nil {
msg = msg + ": " + string(contents)
}
return contents, HTTPError{
Code: res.StatusCode,
Message: msg,
WrappedError: wrap,
}
}
if err != nil {
return nil, err
}
if resBody != nil {
if err = json.Unmarshal(contents, &resBody); err != nil {
return nil, err
}
}
return contents, nil
} | go | func (cli *Client) MakeRequest(method string, httpURL string, reqBody interface{}, resBody interface{}) ([]byte, error) {
var req *http.Request
var err error
if reqBody != nil {
var jsonStr []byte
jsonStr, err = json.Marshal(reqBody)
if err != nil {
return nil, err
}
req, err = http.NewRequest(method, httpURL, bytes.NewBuffer(jsonStr))
} else {
req, err = http.NewRequest(method, httpURL, nil)
}
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
res, err := cli.Client.Do(req)
if res != nil {
defer res.Body.Close()
}
if err != nil {
return nil, err
}
contents, err := ioutil.ReadAll(res.Body)
if res.StatusCode/100 != 2 { // not 2xx
var wrap error
var respErr RespError
if _ = json.Unmarshal(contents, &respErr); respErr.ErrCode != "" {
wrap = respErr
}
// If we failed to decode as RespError, don't just drop the HTTP body, include it in the
// HTTP error instead (e.g proxy errors which return HTML).
msg := "Failed to " + method + " JSON to " + req.URL.Path
if wrap == nil {
msg = msg + ": " + string(contents)
}
return contents, HTTPError{
Code: res.StatusCode,
Message: msg,
WrappedError: wrap,
}
}
if err != nil {
return nil, err
}
if resBody != nil {
if err = json.Unmarshal(contents, &resBody); err != nil {
return nil, err
}
}
return contents, nil
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"MakeRequest",
"(",
"method",
"string",
",",
"httpURL",
"string",
",",
"reqBody",
"interface",
"{",
"}",
",",
"resBody",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"req",
"*",
"http",
".",
"Request",
"\n",
"var",
"err",
"error",
"\n",
"if",
"reqBody",
"!=",
"nil",
"{",
"var",
"jsonStr",
"[",
"]",
"byte",
"\n",
"jsonStr",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"reqBody",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"req",
",",
"err",
"=",
"http",
".",
"NewRequest",
"(",
"method",
",",
"httpURL",
",",
"bytes",
".",
"NewBuffer",
"(",
"jsonStr",
")",
")",
"\n",
"}",
"else",
"{",
"req",
",",
"err",
"=",
"http",
".",
"NewRequest",
"(",
"method",
",",
"httpURL",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"res",
",",
"err",
":=",
"cli",
".",
"Client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"res",
"!=",
"nil",
"{",
"defer",
"res",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"contents",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"res",
".",
"Body",
")",
"\n",
"if",
"res",
".",
"StatusCode",
"/",
"100",
"!=",
"2",
"{",
"// not 2xx",
"var",
"wrap",
"error",
"\n",
"var",
"respErr",
"RespError",
"\n",
"if",
"_",
"=",
"json",
".",
"Unmarshal",
"(",
"contents",
",",
"&",
"respErr",
")",
";",
"respErr",
".",
"ErrCode",
"!=",
"\"",
"\"",
"{",
"wrap",
"=",
"respErr",
"\n",
"}",
"\n\n",
"// If we failed to decode as RespError, don't just drop the HTTP body, include it in the",
"// HTTP error instead (e.g proxy errors which return HTML).",
"msg",
":=",
"\"",
"\"",
"+",
"method",
"+",
"\"",
"\"",
"+",
"req",
".",
"URL",
".",
"Path",
"\n",
"if",
"wrap",
"==",
"nil",
"{",
"msg",
"=",
"msg",
"+",
"\"",
"\"",
"+",
"string",
"(",
"contents",
")",
"\n",
"}",
"\n\n",
"return",
"contents",
",",
"HTTPError",
"{",
"Code",
":",
"res",
".",
"StatusCode",
",",
"Message",
":",
"msg",
",",
"WrappedError",
":",
"wrap",
",",
"}",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"resBody",
"!=",
"nil",
"{",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"contents",
",",
"&",
"resBody",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"contents",
",",
"nil",
"\n",
"}"
] | // MakeRequest makes a JSON HTTP request to the given URL.
// If "resBody" is not nil, the response body will be json.Unmarshalled into it.
//
// Returns the HTTP body as bytes on 2xx with a nil error. Returns an error if the response is not 2xx along
// with the HTTP body bytes if it got that far. This error is an HTTPError which includes the returned
// HTTP status code and possibly a RespError as the WrappedError, if the HTTP body could be decoded as a RespError. | [
"MakeRequest",
"makes",
"a",
"JSON",
"HTTP",
"request",
"to",
"the",
"given",
"URL",
".",
"If",
"resBody",
"is",
"not",
"nil",
"the",
"response",
"body",
"will",
"be",
"json",
".",
"Unmarshalled",
"into",
"it",
".",
"Returns",
"the",
"HTTP",
"body",
"as",
"bytes",
"on",
"2xx",
"with",
"a",
"nil",
"error",
".",
"Returns",
"an",
"error",
"if",
"the",
"response",
"is",
"not",
"2xx",
"along",
"with",
"the",
"HTTP",
"body",
"bytes",
"if",
"it",
"got",
"that",
"far",
".",
"This",
"error",
"is",
"an",
"HTTPError",
"which",
"includes",
"the",
"returned",
"HTTP",
"status",
"code",
"and",
"possibly",
"a",
"RespError",
"as",
"the",
"WrappedError",
"if",
"the",
"HTTP",
"body",
"could",
"be",
"decoded",
"as",
"a",
"RespError",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/client.go#L191-L248 | train |
matrix-org/gomatrix | client.go | UploadLink | func (cli *Client) UploadLink(link string) (*RespMediaUpload, error) {
res, err := cli.Client.Get(link)
if res != nil {
defer res.Body.Close()
}
if err != nil {
return nil, err
}
return cli.UploadToContentRepo(res.Body, res.Header.Get("Content-Type"), res.ContentLength)
} | go | func (cli *Client) UploadLink(link string) (*RespMediaUpload, error) {
res, err := cli.Client.Get(link)
if res != nil {
defer res.Body.Close()
}
if err != nil {
return nil, err
}
return cli.UploadToContentRepo(res.Body, res.Header.Get("Content-Type"), res.ContentLength)
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"UploadLink",
"(",
"link",
"string",
")",
"(",
"*",
"RespMediaUpload",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"cli",
".",
"Client",
".",
"Get",
"(",
"link",
")",
"\n",
"if",
"res",
"!=",
"nil",
"{",
"defer",
"res",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"cli",
".",
"UploadToContentRepo",
"(",
"res",
".",
"Body",
",",
"res",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"res",
".",
"ContentLength",
")",
"\n",
"}"
] | // UploadLink uploads an HTTP URL and then returns an MXC URI. | [
"UploadLink",
"uploads",
"an",
"HTTP",
"URL",
"and",
"then",
"returns",
"an",
"MXC",
"URI",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/client.go#L587-L596 | train |
matrix-org/gomatrix | client.go | NewClient | func NewClient(homeserverURL, userID, accessToken string) (*Client, error) {
hsURL, err := url.Parse(homeserverURL)
if err != nil {
return nil, err
}
// By default, use an in-memory store which will never save filter ids / next batch tokens to disk.
// The client will work with this storer: it just won't remember across restarts.
// In practice, a database backend should be used.
store := NewInMemoryStore()
cli := Client{
AccessToken: accessToken,
HomeserverURL: hsURL,
UserID: userID,
Prefix: "/_matrix/client/r0",
Syncer: NewDefaultSyncer(userID, store),
Store: store,
}
// By default, use the default HTTP client.
cli.Client = http.DefaultClient
return &cli, nil
} | go | func NewClient(homeserverURL, userID, accessToken string) (*Client, error) {
hsURL, err := url.Parse(homeserverURL)
if err != nil {
return nil, err
}
// By default, use an in-memory store which will never save filter ids / next batch tokens to disk.
// The client will work with this storer: it just won't remember across restarts.
// In practice, a database backend should be used.
store := NewInMemoryStore()
cli := Client{
AccessToken: accessToken,
HomeserverURL: hsURL,
UserID: userID,
Prefix: "/_matrix/client/r0",
Syncer: NewDefaultSyncer(userID, store),
Store: store,
}
// By default, use the default HTTP client.
cli.Client = http.DefaultClient
return &cli, nil
} | [
"func",
"NewClient",
"(",
"homeserverURL",
",",
"userID",
",",
"accessToken",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"hsURL",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"homeserverURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// By default, use an in-memory store which will never save filter ids / next batch tokens to disk.",
"// The client will work with this storer: it just won't remember across restarts.",
"// In practice, a database backend should be used.",
"store",
":=",
"NewInMemoryStore",
"(",
")",
"\n",
"cli",
":=",
"Client",
"{",
"AccessToken",
":",
"accessToken",
",",
"HomeserverURL",
":",
"hsURL",
",",
"UserID",
":",
"userID",
",",
"Prefix",
":",
"\"",
"\"",
",",
"Syncer",
":",
"NewDefaultSyncer",
"(",
"userID",
",",
"store",
")",
",",
"Store",
":",
"store",
",",
"}",
"\n",
"// By default, use the default HTTP client.",
"cli",
".",
"Client",
"=",
"http",
".",
"DefaultClient",
"\n\n",
"return",
"&",
"cli",
",",
"nil",
"\n",
"}"
] | // NewClient creates a new Matrix Client ready for syncing | [
"NewClient",
"creates",
"a",
"new",
"Matrix",
"Client",
"ready",
"for",
"syncing"
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/client.go#L687-L708 | train |
matrix-org/gomatrix | userids.go | escape | func escape(buf *bytes.Buffer, b byte) {
buf.WriteByte('_')
if b == '_' {
buf.WriteByte('_') // another _
} else {
buf.WriteByte(b + 0x20) // ASCII shift A-Z to a-z
}
} | go | func escape(buf *bytes.Buffer, b byte) {
buf.WriteByte('_')
if b == '_' {
buf.WriteByte('_') // another _
} else {
buf.WriteByte(b + 0x20) // ASCII shift A-Z to a-z
}
} | [
"func",
"escape",
"(",
"buf",
"*",
"bytes",
".",
"Buffer",
",",
"b",
"byte",
")",
"{",
"buf",
".",
"WriteByte",
"(",
"'_'",
")",
"\n",
"if",
"b",
"==",
"'_'",
"{",
"buf",
".",
"WriteByte",
"(",
"'_'",
")",
"// another _",
"\n",
"}",
"else",
"{",
"buf",
".",
"WriteByte",
"(",
"b",
"+",
"0x20",
")",
"// ASCII shift A-Z to a-z",
"\n",
"}",
"\n",
"}"
] | // escape the given alpha character and writes it to the buffer | [
"escape",
"the",
"given",
"alpha",
"character",
"and",
"writes",
"it",
"to",
"the",
"buffer"
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/userids.go#L22-L29 | train |
matrix-org/gomatrix | sync.go | NewDefaultSyncer | func NewDefaultSyncer(userID string, store Storer) *DefaultSyncer {
return &DefaultSyncer{
UserID: userID,
Store: store,
listeners: make(map[string][]OnEventListener),
}
} | go | func NewDefaultSyncer(userID string, store Storer) *DefaultSyncer {
return &DefaultSyncer{
UserID: userID,
Store: store,
listeners: make(map[string][]OnEventListener),
}
} | [
"func",
"NewDefaultSyncer",
"(",
"userID",
"string",
",",
"store",
"Storer",
")",
"*",
"DefaultSyncer",
"{",
"return",
"&",
"DefaultSyncer",
"{",
"UserID",
":",
"userID",
",",
"Store",
":",
"store",
",",
"listeners",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"OnEventListener",
")",
",",
"}",
"\n",
"}"
] | // NewDefaultSyncer returns an instantiated DefaultSyncer | [
"NewDefaultSyncer",
"returns",
"an",
"instantiated",
"DefaultSyncer"
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/sync.go#L35-L41 | train |
matrix-org/gomatrix | sync.go | OnEventType | func (s *DefaultSyncer) OnEventType(eventType string, callback OnEventListener) {
_, exists := s.listeners[eventType]
if !exists {
s.listeners[eventType] = []OnEventListener{}
}
s.listeners[eventType] = append(s.listeners[eventType], callback)
} | go | func (s *DefaultSyncer) OnEventType(eventType string, callback OnEventListener) {
_, exists := s.listeners[eventType]
if !exists {
s.listeners[eventType] = []OnEventListener{}
}
s.listeners[eventType] = append(s.listeners[eventType], callback)
} | [
"func",
"(",
"s",
"*",
"DefaultSyncer",
")",
"OnEventType",
"(",
"eventType",
"string",
",",
"callback",
"OnEventListener",
")",
"{",
"_",
",",
"exists",
":=",
"s",
".",
"listeners",
"[",
"eventType",
"]",
"\n",
"if",
"!",
"exists",
"{",
"s",
".",
"listeners",
"[",
"eventType",
"]",
"=",
"[",
"]",
"OnEventListener",
"{",
"}",
"\n",
"}",
"\n",
"s",
".",
"listeners",
"[",
"eventType",
"]",
"=",
"append",
"(",
"s",
".",
"listeners",
"[",
"eventType",
"]",
",",
"callback",
")",
"\n",
"}"
] | // OnEventType allows callers to be notified when there are new events for the given event type.
// There are no duplicate checks. | [
"OnEventType",
"allows",
"callers",
"to",
"be",
"notified",
"when",
"there",
"are",
"new",
"events",
"for",
"the",
"given",
"event",
"type",
".",
"There",
"are",
"no",
"duplicate",
"checks",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/sync.go#L91-L97 | train |
matrix-org/gomatrix | sync.go | shouldProcessResponse | func (s *DefaultSyncer) shouldProcessResponse(resp *RespSync, since string) bool {
if since == "" {
return false
}
// This is a horrible hack because /sync will return the most recent messages for a room
// as soon as you /join it. We do NOT want to process those events in that particular room
// because they may have already been processed (if you toggle the bot in/out of the room).
//
// Work around this by inspecting each room's timeline and seeing if an m.room.member event for us
// exists and is "join" and then discard processing that room entirely if so.
// TODO: We probably want to process messages from after the last join event in the timeline.
for roomID, roomData := range resp.Rooms.Join {
for i := len(roomData.Timeline.Events) - 1; i >= 0; i-- {
e := roomData.Timeline.Events[i]
if e.Type == "m.room.member" && e.StateKey != nil && *e.StateKey == s.UserID {
m := e.Content["membership"]
mship, ok := m.(string)
if !ok {
continue
}
if mship == "join" {
_, ok := resp.Rooms.Join[roomID]
if !ok {
continue
}
delete(resp.Rooms.Join, roomID) // don't re-process messages
delete(resp.Rooms.Invite, roomID) // don't re-process invites
break
}
}
}
}
return true
} | go | func (s *DefaultSyncer) shouldProcessResponse(resp *RespSync, since string) bool {
if since == "" {
return false
}
// This is a horrible hack because /sync will return the most recent messages for a room
// as soon as you /join it. We do NOT want to process those events in that particular room
// because they may have already been processed (if you toggle the bot in/out of the room).
//
// Work around this by inspecting each room's timeline and seeing if an m.room.member event for us
// exists and is "join" and then discard processing that room entirely if so.
// TODO: We probably want to process messages from after the last join event in the timeline.
for roomID, roomData := range resp.Rooms.Join {
for i := len(roomData.Timeline.Events) - 1; i >= 0; i-- {
e := roomData.Timeline.Events[i]
if e.Type == "m.room.member" && e.StateKey != nil && *e.StateKey == s.UserID {
m := e.Content["membership"]
mship, ok := m.(string)
if !ok {
continue
}
if mship == "join" {
_, ok := resp.Rooms.Join[roomID]
if !ok {
continue
}
delete(resp.Rooms.Join, roomID) // don't re-process messages
delete(resp.Rooms.Invite, roomID) // don't re-process invites
break
}
}
}
}
return true
} | [
"func",
"(",
"s",
"*",
"DefaultSyncer",
")",
"shouldProcessResponse",
"(",
"resp",
"*",
"RespSync",
",",
"since",
"string",
")",
"bool",
"{",
"if",
"since",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// This is a horrible hack because /sync will return the most recent messages for a room",
"// as soon as you /join it. We do NOT want to process those events in that particular room",
"// because they may have already been processed (if you toggle the bot in/out of the room).",
"//",
"// Work around this by inspecting each room's timeline and seeing if an m.room.member event for us",
"// exists and is \"join\" and then discard processing that room entirely if so.",
"// TODO: We probably want to process messages from after the last join event in the timeline.",
"for",
"roomID",
",",
"roomData",
":=",
"range",
"resp",
".",
"Rooms",
".",
"Join",
"{",
"for",
"i",
":=",
"len",
"(",
"roomData",
".",
"Timeline",
".",
"Events",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"e",
":=",
"roomData",
".",
"Timeline",
".",
"Events",
"[",
"i",
"]",
"\n",
"if",
"e",
".",
"Type",
"==",
"\"",
"\"",
"&&",
"e",
".",
"StateKey",
"!=",
"nil",
"&&",
"*",
"e",
".",
"StateKey",
"==",
"s",
".",
"UserID",
"{",
"m",
":=",
"e",
".",
"Content",
"[",
"\"",
"\"",
"]",
"\n",
"mship",
",",
"ok",
":=",
"m",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"mship",
"==",
"\"",
"\"",
"{",
"_",
",",
"ok",
":=",
"resp",
".",
"Rooms",
".",
"Join",
"[",
"roomID",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"delete",
"(",
"resp",
".",
"Rooms",
".",
"Join",
",",
"roomID",
")",
"// don't re-process messages",
"\n",
"delete",
"(",
"resp",
".",
"Rooms",
".",
"Invite",
",",
"roomID",
")",
"// don't re-process invites",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // shouldProcessResponse returns true if the response should be processed. May modify the response to remove
// stuff that shouldn't be processed. | [
"shouldProcessResponse",
"returns",
"true",
"if",
"the",
"response",
"should",
"be",
"processed",
".",
"May",
"modify",
"the",
"response",
"to",
"remove",
"stuff",
"that",
"shouldn",
"t",
"be",
"processed",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/sync.go#L101-L134 | train |
matrix-org/gomatrix | store.go | SaveFilterID | func (s *InMemoryStore) SaveFilterID(userID, filterID string) {
s.Filters[userID] = filterID
} | go | func (s *InMemoryStore) SaveFilterID(userID, filterID string) {
s.Filters[userID] = filterID
} | [
"func",
"(",
"s",
"*",
"InMemoryStore",
")",
"SaveFilterID",
"(",
"userID",
",",
"filterID",
"string",
")",
"{",
"s",
".",
"Filters",
"[",
"userID",
"]",
"=",
"filterID",
"\n",
"}"
] | // SaveFilterID to memory. | [
"SaveFilterID",
"to",
"memory",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/store.go#L29-L31 | train |
matrix-org/gomatrix | store.go | SaveNextBatch | func (s *InMemoryStore) SaveNextBatch(userID, nextBatchToken string) {
s.NextBatch[userID] = nextBatchToken
} | go | func (s *InMemoryStore) SaveNextBatch(userID, nextBatchToken string) {
s.NextBatch[userID] = nextBatchToken
} | [
"func",
"(",
"s",
"*",
"InMemoryStore",
")",
"SaveNextBatch",
"(",
"userID",
",",
"nextBatchToken",
"string",
")",
"{",
"s",
".",
"NextBatch",
"[",
"userID",
"]",
"=",
"nextBatchToken",
"\n",
"}"
] | // SaveNextBatch to memory. | [
"SaveNextBatch",
"to",
"memory",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/store.go#L39-L41 | train |
matrix-org/gomatrix | store.go | SaveRoom | func (s *InMemoryStore) SaveRoom(room *Room) {
s.Rooms[room.ID] = room
} | go | func (s *InMemoryStore) SaveRoom(room *Room) {
s.Rooms[room.ID] = room
} | [
"func",
"(",
"s",
"*",
"InMemoryStore",
")",
"SaveRoom",
"(",
"room",
"*",
"Room",
")",
"{",
"s",
".",
"Rooms",
"[",
"room",
".",
"ID",
"]",
"=",
"room",
"\n",
"}"
] | // SaveRoom to memory. | [
"SaveRoom",
"to",
"memory",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/store.go#L49-L51 | train |
matrix-org/gomatrix | store.go | NewInMemoryStore | func NewInMemoryStore() *InMemoryStore {
return &InMemoryStore{
Filters: make(map[string]string),
NextBatch: make(map[string]string),
Rooms: make(map[string]*Room),
}
} | go | func NewInMemoryStore() *InMemoryStore {
return &InMemoryStore{
Filters: make(map[string]string),
NextBatch: make(map[string]string),
Rooms: make(map[string]*Room),
}
} | [
"func",
"NewInMemoryStore",
"(",
")",
"*",
"InMemoryStore",
"{",
"return",
"&",
"InMemoryStore",
"{",
"Filters",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"NextBatch",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"Rooms",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Room",
")",
",",
"}",
"\n",
"}"
] | // NewInMemoryStore constructs a new InMemoryStore. | [
"NewInMemoryStore",
"constructs",
"a",
"new",
"InMemoryStore",
"."
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/store.go#L59-L65 | train |
matrix-org/gomatrix | filter.go | Validate | func (filter *Filter) Validate() error {
if filter.EventFormat != "client" && filter.EventFormat != "federation" {
return errors.New("Bad event_format value. Must be one of [\"client\", \"federation\"]")
}
return nil
} | go | func (filter *Filter) Validate() error {
if filter.EventFormat != "client" && filter.EventFormat != "federation" {
return errors.New("Bad event_format value. Must be one of [\"client\", \"federation\"]")
}
return nil
} | [
"func",
"(",
"filter",
"*",
"Filter",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"filter",
".",
"EventFormat",
"!=",
"\"",
"\"",
"&&",
"filter",
".",
"EventFormat",
"!=",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate checks if the filter contains valid property values | [
"Validate",
"checks",
"if",
"the",
"filter",
"contains",
"valid",
"property",
"values"
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/filter.go#L53-L58 | train |
matrix-org/gomatrix | filter.go | DefaultFilter | func DefaultFilter() Filter {
return Filter{
AccountData: DefaultFilterPart(),
EventFields: nil,
EventFormat: "client",
Presence: DefaultFilterPart(),
Room: RoomFilter{
AccountData: DefaultFilterPart(),
Ephemeral: DefaultFilterPart(),
IncludeLeave: false,
NotRooms: nil,
Rooms: nil,
State: DefaultFilterPart(),
Timeline: DefaultFilterPart(),
},
}
} | go | func DefaultFilter() Filter {
return Filter{
AccountData: DefaultFilterPart(),
EventFields: nil,
EventFormat: "client",
Presence: DefaultFilterPart(),
Room: RoomFilter{
AccountData: DefaultFilterPart(),
Ephemeral: DefaultFilterPart(),
IncludeLeave: false,
NotRooms: nil,
Rooms: nil,
State: DefaultFilterPart(),
Timeline: DefaultFilterPart(),
},
}
} | [
"func",
"DefaultFilter",
"(",
")",
"Filter",
"{",
"return",
"Filter",
"{",
"AccountData",
":",
"DefaultFilterPart",
"(",
")",
",",
"EventFields",
":",
"nil",
",",
"EventFormat",
":",
"\"",
"\"",
",",
"Presence",
":",
"DefaultFilterPart",
"(",
")",
",",
"Room",
":",
"RoomFilter",
"{",
"AccountData",
":",
"DefaultFilterPart",
"(",
")",
",",
"Ephemeral",
":",
"DefaultFilterPart",
"(",
")",
",",
"IncludeLeave",
":",
"false",
",",
"NotRooms",
":",
"nil",
",",
"Rooms",
":",
"nil",
",",
"State",
":",
"DefaultFilterPart",
"(",
")",
",",
"Timeline",
":",
"DefaultFilterPart",
"(",
")",
",",
"}",
",",
"}",
"\n",
"}"
] | // DefaultFilter returns the default filter used by the Matrix server if no filter is provided in the request | [
"DefaultFilter",
"returns",
"the",
"default",
"filter",
"used",
"by",
"the",
"Matrix",
"server",
"if",
"no",
"filter",
"is",
"provided",
"in",
"the",
"request"
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/filter.go#L61-L77 | train |
matrix-org/gomatrix | filter.go | DefaultFilterPart | func DefaultFilterPart() FilterPart {
return FilterPart{
NotRooms: nil,
Rooms: nil,
Limit: 20,
NotSenders: nil,
NotTypes: nil,
Senders: nil,
Types: nil,
}
} | go | func DefaultFilterPart() FilterPart {
return FilterPart{
NotRooms: nil,
Rooms: nil,
Limit: 20,
NotSenders: nil,
NotTypes: nil,
Senders: nil,
Types: nil,
}
} | [
"func",
"DefaultFilterPart",
"(",
")",
"FilterPart",
"{",
"return",
"FilterPart",
"{",
"NotRooms",
":",
"nil",
",",
"Rooms",
":",
"nil",
",",
"Limit",
":",
"20",
",",
"NotSenders",
":",
"nil",
",",
"NotTypes",
":",
"nil",
",",
"Senders",
":",
"nil",
",",
"Types",
":",
"nil",
",",
"}",
"\n",
"}"
] | // DefaultFilterPart returns the default filter part used by the Matrix server if no filter is provided in the request | [
"DefaultFilterPart",
"returns",
"the",
"default",
"filter",
"part",
"used",
"by",
"the",
"Matrix",
"server",
"if",
"no",
"filter",
"is",
"provided",
"in",
"the",
"request"
] | 0c31efc5dc7385fa91705093d77bfc554c2751f9 | https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/filter.go#L80-L90 | train |
go-ozzo/ozzo-validation | error.go | MarshalJSON | func (es Errors) MarshalJSON() ([]byte, error) {
errs := map[string]interface{}{}
for key, err := range es {
if ms, ok := err.(json.Marshaler); ok {
errs[key] = ms
} else {
errs[key] = err.Error()
}
}
return json.Marshal(errs)
} | go | func (es Errors) MarshalJSON() ([]byte, error) {
errs := map[string]interface{}{}
for key, err := range es {
if ms, ok := err.(json.Marshaler); ok {
errs[key] = ms
} else {
errs[key] = err.Error()
}
}
return json.Marshal(errs)
} | [
"func",
"(",
"es",
"Errors",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"errs",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"for",
"key",
",",
"err",
":=",
"range",
"es",
"{",
"if",
"ms",
",",
"ok",
":=",
"err",
".",
"(",
"json",
".",
"Marshaler",
")",
";",
"ok",
"{",
"errs",
"[",
"key",
"]",
"=",
"ms",
"\n",
"}",
"else",
"{",
"errs",
"[",
"key",
"]",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"errs",
")",
"\n",
"}"
] | // MarshalJSON converts the Errors into a valid JSON. | [
"MarshalJSON",
"converts",
"the",
"Errors",
"into",
"a",
"valid",
"JSON",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/error.go#L65-L75 | train |
go-ozzo/ozzo-validation | error.go | Filter | func (es Errors) Filter() error {
for key, value := range es {
if value == nil {
delete(es, key)
}
}
if len(es) == 0 {
return nil
}
return es
} | go | func (es Errors) Filter() error {
for key, value := range es {
if value == nil {
delete(es, key)
}
}
if len(es) == 0 {
return nil
}
return es
} | [
"func",
"(",
"es",
"Errors",
")",
"Filter",
"(",
")",
"error",
"{",
"for",
"key",
",",
"value",
":=",
"range",
"es",
"{",
"if",
"value",
"==",
"nil",
"{",
"delete",
"(",
"es",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"es",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"es",
"\n",
"}"
] | // Filter removes all nils from Errors and returns back the updated Errors as an error.
// If the length of Errors becomes 0, it will return nil. | [
"Filter",
"removes",
"all",
"nils",
"from",
"Errors",
"and",
"returns",
"back",
"the",
"updated",
"Errors",
"as",
"an",
"error",
".",
"If",
"the",
"length",
"of",
"Errors",
"becomes",
"0",
"it",
"will",
"return",
"nil",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/error.go#L79-L89 | train |
go-ozzo/ozzo-validation | string.go | NewStringRule | func NewStringRule(validator stringValidator, message string) *StringRule {
return &StringRule{
validate: validator,
message: message,
}
} | go | func NewStringRule(validator stringValidator, message string) *StringRule {
return &StringRule{
validate: validator,
message: message,
}
} | [
"func",
"NewStringRule",
"(",
"validator",
"stringValidator",
",",
"message",
"string",
")",
"*",
"StringRule",
"{",
"return",
"&",
"StringRule",
"{",
"validate",
":",
"validator",
",",
"message",
":",
"message",
",",
"}",
"\n",
"}"
] | // NewStringRule creates a new validation rule using a function that takes a string value and returns a bool.
// The rule returned will use the function to check if a given string or byte slice is valid or not.
// An empty value is considered to be valid. Please use the Required rule to make sure a value is not empty. | [
"NewStringRule",
"creates",
"a",
"new",
"validation",
"rule",
"using",
"a",
"function",
"that",
"takes",
"a",
"string",
"value",
"and",
"returns",
"a",
"bool",
".",
"The",
"rule",
"returned",
"will",
"use",
"the",
"function",
"to",
"check",
"if",
"a",
"given",
"string",
"or",
"byte",
"slice",
"is",
"valid",
"or",
"not",
".",
"An",
"empty",
"value",
"is",
"considered",
"to",
"be",
"valid",
".",
"Please",
"use",
"the",
"Required",
"rule",
"to",
"make",
"sure",
"a",
"value",
"is",
"not",
"empty",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/string.go#L20-L25 | train |
go-ozzo/ozzo-validation | date.go | Error | func (r *DateRule) Error(message string) *DateRule {
r.message = message
return r
} | go | func (r *DateRule) Error(message string) *DateRule {
r.message = message
return r
} | [
"func",
"(",
"r",
"*",
"DateRule",
")",
"Error",
"(",
"message",
"string",
")",
"*",
"DateRule",
"{",
"r",
".",
"message",
"=",
"message",
"\n",
"return",
"r",
"\n",
"}"
] | // Error sets the error message that is used when the value being validated is not a valid date. | [
"Error",
"sets",
"the",
"error",
"message",
"that",
"is",
"used",
"when",
"the",
"value",
"being",
"validated",
"is",
"not",
"a",
"valid",
"date",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/date.go#L39-L42 | train |
go-ozzo/ozzo-validation | date.go | Min | func (r *DateRule) Min(min time.Time) *DateRule {
r.min = min
return r
} | go | func (r *DateRule) Min(min time.Time) *DateRule {
r.min = min
return r
} | [
"func",
"(",
"r",
"*",
"DateRule",
")",
"Min",
"(",
"min",
"time",
".",
"Time",
")",
"*",
"DateRule",
"{",
"r",
".",
"min",
"=",
"min",
"\n",
"return",
"r",
"\n",
"}"
] | // Min sets the minimum date range. A zero value means skipping the minimum range validation. | [
"Min",
"sets",
"the",
"minimum",
"date",
"range",
".",
"A",
"zero",
"value",
"means",
"skipping",
"the",
"minimum",
"range",
"validation",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/date.go#L51-L54 | train |
go-ozzo/ozzo-validation | date.go | Max | func (r *DateRule) Max(max time.Time) *DateRule {
r.max = max
return r
} | go | func (r *DateRule) Max(max time.Time) *DateRule {
r.max = max
return r
} | [
"func",
"(",
"r",
"*",
"DateRule",
")",
"Max",
"(",
"max",
"time",
".",
"Time",
")",
"*",
"DateRule",
"{",
"r",
".",
"max",
"=",
"max",
"\n",
"return",
"r",
"\n",
"}"
] | // Max sets the maximum date range. A zero value means skipping the maximum range validation. | [
"Max",
"sets",
"the",
"maximum",
"date",
"range",
".",
"A",
"zero",
"value",
"means",
"skipping",
"the",
"maximum",
"range",
"validation",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/date.go#L57-L60 | train |
go-ozzo/ozzo-validation | date.go | Validate | func (r *DateRule) Validate(value interface{}) error {
value, isNil := Indirect(value)
if isNil || IsEmpty(value) {
return nil
}
str, err := EnsureString(value)
if err != nil {
return err
}
date, err := time.Parse(r.layout, str)
if err != nil {
return errors.New(r.message)
}
if !r.min.IsZero() && r.min.After(date) || !r.max.IsZero() && date.After(r.max) {
return errors.New(r.rangeMessage)
}
return nil
} | go | func (r *DateRule) Validate(value interface{}) error {
value, isNil := Indirect(value)
if isNil || IsEmpty(value) {
return nil
}
str, err := EnsureString(value)
if err != nil {
return err
}
date, err := time.Parse(r.layout, str)
if err != nil {
return errors.New(r.message)
}
if !r.min.IsZero() && r.min.After(date) || !r.max.IsZero() && date.After(r.max) {
return errors.New(r.rangeMessage)
}
return nil
} | [
"func",
"(",
"r",
"*",
"DateRule",
")",
"Validate",
"(",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"value",
",",
"isNil",
":=",
"Indirect",
"(",
"value",
")",
"\n",
"if",
"isNil",
"||",
"IsEmpty",
"(",
"value",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"str",
",",
"err",
":=",
"EnsureString",
"(",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"date",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"r",
".",
"layout",
",",
"str",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"r",
".",
"message",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"r",
".",
"min",
".",
"IsZero",
"(",
")",
"&&",
"r",
".",
"min",
".",
"After",
"(",
"date",
")",
"||",
"!",
"r",
".",
"max",
".",
"IsZero",
"(",
")",
"&&",
"date",
".",
"After",
"(",
"r",
".",
"max",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"r",
".",
"rangeMessage",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Validate checks if the given value is a valid date. | [
"Validate",
"checks",
"if",
"the",
"given",
"value",
"is",
"a",
"valid",
"date",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/date.go#L63-L84 | train |
go-ozzo/ozzo-validation | util.go | EnsureString | func EnsureString(value interface{}) (string, error) {
v := reflect.ValueOf(value)
if v.Kind() == reflect.String {
return v.String(), nil
}
if v.Type() == bytesType {
return string(v.Interface().([]byte)), nil
}
return "", errors.New("must be either a string or byte slice")
} | go | func EnsureString(value interface{}) (string, error) {
v := reflect.ValueOf(value)
if v.Kind() == reflect.String {
return v.String(), nil
}
if v.Type() == bytesType {
return string(v.Interface().([]byte)), nil
}
return "", errors.New("must be either a string or byte slice")
} | [
"func",
"EnsureString",
"(",
"value",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
"\n",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"String",
"{",
"return",
"v",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"if",
"v",
".",
"Type",
"(",
")",
"==",
"bytesType",
"{",
"return",
"string",
"(",
"v",
".",
"Interface",
"(",
")",
".",
"(",
"[",
"]",
"byte",
")",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // EnsureString ensures the given value is a string.
// If the value is a byte slice, it will be typecast into a string.
// An error is returned otherwise. | [
"EnsureString",
"ensures",
"the",
"given",
"value",
"is",
"a",
"string",
".",
"If",
"the",
"value",
"is",
"a",
"byte",
"slice",
"it",
"will",
"be",
"typecast",
"into",
"a",
"string",
".",
"An",
"error",
"is",
"returned",
"otherwise",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/util.go#L23-L32 | train |
go-ozzo/ozzo-validation | util.go | StringOrBytes | func StringOrBytes(value interface{}) (isString bool, str string, isBytes bool, bs []byte) {
v := reflect.ValueOf(value)
if v.Kind() == reflect.String {
str = v.String()
isString = true
} else if v.Kind() == reflect.Slice && v.Type() == bytesType {
bs = v.Interface().([]byte)
isBytes = true
}
return
} | go | func StringOrBytes(value interface{}) (isString bool, str string, isBytes bool, bs []byte) {
v := reflect.ValueOf(value)
if v.Kind() == reflect.String {
str = v.String()
isString = true
} else if v.Kind() == reflect.Slice && v.Type() == bytesType {
bs = v.Interface().([]byte)
isBytes = true
}
return
} | [
"func",
"StringOrBytes",
"(",
"value",
"interface",
"{",
"}",
")",
"(",
"isString",
"bool",
",",
"str",
"string",
",",
"isBytes",
"bool",
",",
"bs",
"[",
"]",
"byte",
")",
"{",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
"\n",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"String",
"{",
"str",
"=",
"v",
".",
"String",
"(",
")",
"\n",
"isString",
"=",
"true",
"\n",
"}",
"else",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Slice",
"&&",
"v",
".",
"Type",
"(",
")",
"==",
"bytesType",
"{",
"bs",
"=",
"v",
".",
"Interface",
"(",
")",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"isBytes",
"=",
"true",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // StringOrBytes typecasts a value into a string or byte slice.
// Boolean flags are returned to indicate if the typecasting succeeds or not. | [
"StringOrBytes",
"typecasts",
"a",
"value",
"into",
"a",
"string",
"or",
"byte",
"slice",
".",
"Boolean",
"flags",
"are",
"returned",
"to",
"indicate",
"if",
"the",
"typecasting",
"succeeds",
"or",
"not",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/util.go#L36-L46 | train |
go-ozzo/ozzo-validation | util.go | LengthOfValue | func LengthOfValue(value interface{}) (int, error) {
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.String, reflect.Slice, reflect.Map, reflect.Array:
return v.Len(), nil
}
return 0, fmt.Errorf("cannot get the length of %v", v.Kind())
} | go | func LengthOfValue(value interface{}) (int, error) {
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.String, reflect.Slice, reflect.Map, reflect.Array:
return v.Len(), nil
}
return 0, fmt.Errorf("cannot get the length of %v", v.Kind())
} | [
"func",
"LengthOfValue",
"(",
"value",
"interface",
"{",
"}",
")",
"(",
"int",
",",
"error",
")",
"{",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
"\n",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
",",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
",",
"reflect",
".",
"Array",
":",
"return",
"v",
".",
"Len",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
".",
"Kind",
"(",
")",
")",
"\n",
"}"
] | // LengthOfValue returns the length of a value that is a string, slice, map, or array.
// An error is returned for all other types. | [
"LengthOfValue",
"returns",
"the",
"length",
"of",
"a",
"value",
"that",
"is",
"a",
"string",
"slice",
"map",
"or",
"array",
".",
"An",
"error",
"is",
"returned",
"for",
"all",
"other",
"types",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/util.go#L50-L57 | train |
go-ozzo/ozzo-validation | util.go | ToInt | func ToInt(value interface{}) (int64, error) {
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int(), nil
}
return 0, fmt.Errorf("cannot convert %v to int64", v.Kind())
} | go | func ToInt(value interface{}) (int64, error) {
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int(), nil
}
return 0, fmt.Errorf("cannot convert %v to int64", v.Kind())
} | [
"func",
"ToInt",
"(",
"value",
"interface",
"{",
"}",
")",
"(",
"int64",
",",
"error",
")",
"{",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
"\n",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"return",
"v",
".",
"Int",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
".",
"Kind",
"(",
")",
")",
"\n",
"}"
] | // ToInt converts the given value to an int64.
// An error is returned for all incompatible types. | [
"ToInt",
"converts",
"the",
"given",
"value",
"to",
"an",
"int64",
".",
"An",
"error",
"is",
"returned",
"for",
"all",
"incompatible",
"types",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/util.go#L61-L68 | train |
go-ozzo/ozzo-validation | util.go | ToUint | func ToUint(value interface{}) (uint64, error) {
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint(), nil
}
return 0, fmt.Errorf("cannot convert %v to uint64", v.Kind())
} | go | func ToUint(value interface{}) (uint64, error) {
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint(), nil
}
return 0, fmt.Errorf("cannot convert %v to uint64", v.Kind())
} | [
"func",
"ToUint",
"(",
"value",
"interface",
"{",
"}",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
"\n",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
",",
"reflect",
".",
"Uintptr",
":",
"return",
"v",
".",
"Uint",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
".",
"Kind",
"(",
")",
")",
"\n",
"}"
] | // ToUint converts the given value to an uint64.
// An error is returned for all incompatible types. | [
"ToUint",
"converts",
"the",
"given",
"value",
"to",
"an",
"uint64",
".",
"An",
"error",
"is",
"returned",
"for",
"all",
"incompatible",
"types",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/util.go#L72-L79 | train |
go-ozzo/ozzo-validation | util.go | ToFloat | func ToFloat(value interface{}) (float64, error) {
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.Float32, reflect.Float64:
return v.Float(), nil
}
return 0, fmt.Errorf("cannot convert %v to float64", v.Kind())
} | go | func ToFloat(value interface{}) (float64, error) {
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.Float32, reflect.Float64:
return v.Float(), nil
}
return 0, fmt.Errorf("cannot convert %v to float64", v.Kind())
} | [
"func",
"ToFloat",
"(",
"value",
"interface",
"{",
"}",
")",
"(",
"float64",
",",
"error",
")",
"{",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
"\n",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"return",
"v",
".",
"Float",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
".",
"Kind",
"(",
")",
")",
"\n",
"}"
] | // ToFloat converts the given value to a float64.
// An error is returned for all incompatible types. | [
"ToFloat",
"converts",
"the",
"given",
"value",
"to",
"a",
"float64",
".",
"An",
"error",
"is",
"returned",
"for",
"all",
"incompatible",
"types",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/util.go#L83-L90 | train |
go-ozzo/ozzo-validation | validation.go | validateMap | func validateMap(rv reflect.Value) error {
errs := Errors{}
for _, key := range rv.MapKeys() {
if mv := rv.MapIndex(key).Interface(); mv != nil {
if err := mv.(Validatable).Validate(); err != nil {
errs[fmt.Sprintf("%v", key.Interface())] = err
}
}
}
if len(errs) > 0 {
return errs
}
return nil
} | go | func validateMap(rv reflect.Value) error {
errs := Errors{}
for _, key := range rv.MapKeys() {
if mv := rv.MapIndex(key).Interface(); mv != nil {
if err := mv.(Validatable).Validate(); err != nil {
errs[fmt.Sprintf("%v", key.Interface())] = err
}
}
}
if len(errs) > 0 {
return errs
}
return nil
} | [
"func",
"validateMap",
"(",
"rv",
"reflect",
".",
"Value",
")",
"error",
"{",
"errs",
":=",
"Errors",
"{",
"}",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"rv",
".",
"MapKeys",
"(",
")",
"{",
"if",
"mv",
":=",
"rv",
".",
"MapIndex",
"(",
"key",
")",
".",
"Interface",
"(",
")",
";",
"mv",
"!=",
"nil",
"{",
"if",
"err",
":=",
"mv",
".",
"(",
"Validatable",
")",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"errs",
"[",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"key",
".",
"Interface",
"(",
")",
")",
"]",
"=",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"errs",
")",
">",
"0",
"{",
"return",
"errs",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validateMap validates a map of validatable elements | [
"validateMap",
"validates",
"a",
"map",
"of",
"validatable",
"elements"
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/validation.go#L84-L97 | train |
go-ozzo/ozzo-validation | minmax.go | Min | func Min(min interface{}) *ThresholdRule {
return &ThresholdRule{
threshold: min,
operator: greaterEqualThan,
message: fmt.Sprintf("must be no less than %v", min),
}
} | go | func Min(min interface{}) *ThresholdRule {
return &ThresholdRule{
threshold: min,
operator: greaterEqualThan,
message: fmt.Sprintf("must be no less than %v", min),
}
} | [
"func",
"Min",
"(",
"min",
"interface",
"{",
"}",
")",
"*",
"ThresholdRule",
"{",
"return",
"&",
"ThresholdRule",
"{",
"threshold",
":",
"min",
",",
"operator",
":",
"greaterEqualThan",
",",
"message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"min",
")",
",",
"}",
"\n",
"}"
] | // Min is a validation rule that checks if a value is greater or equal than the specified value.
// By calling Exclusive, the rule will check if the value is strictly greater than the specified value.
// Note that the value being checked and the threshold value must be of the same type.
// Only int, uint, float and time.Time types are supported.
// An empty value is considered valid. Please use the Required rule to make sure a value is not empty. | [
"Min",
"is",
"a",
"validation",
"rule",
"that",
"checks",
"if",
"a",
"value",
"is",
"greater",
"or",
"equal",
"than",
"the",
"specified",
"value",
".",
"By",
"calling",
"Exclusive",
"the",
"rule",
"will",
"check",
"if",
"the",
"value",
"is",
"strictly",
"greater",
"than",
"the",
"specified",
"value",
".",
"Note",
"that",
"the",
"value",
"being",
"checked",
"and",
"the",
"threshold",
"value",
"must",
"be",
"of",
"the",
"same",
"type",
".",
"Only",
"int",
"uint",
"float",
"and",
"time",
".",
"Time",
"types",
"are",
"supported",
".",
"An",
"empty",
"value",
"is",
"considered",
"valid",
".",
"Please",
"use",
"the",
"Required",
"rule",
"to",
"make",
"sure",
"a",
"value",
"is",
"not",
"empty",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/minmax.go#L32-L38 | train |
go-ozzo/ozzo-validation | minmax.go | Max | func Max(max interface{}) *ThresholdRule {
return &ThresholdRule{
threshold: max,
operator: lessEqualThan,
message: fmt.Sprintf("must be no greater than %v", max),
}
} | go | func Max(max interface{}) *ThresholdRule {
return &ThresholdRule{
threshold: max,
operator: lessEqualThan,
message: fmt.Sprintf("must be no greater than %v", max),
}
} | [
"func",
"Max",
"(",
"max",
"interface",
"{",
"}",
")",
"*",
"ThresholdRule",
"{",
"return",
"&",
"ThresholdRule",
"{",
"threshold",
":",
"max",
",",
"operator",
":",
"lessEqualThan",
",",
"message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"max",
")",
",",
"}",
"\n",
"}"
] | // Max is a validation rule that checks if a value is less or equal than the specified value.
// By calling Exclusive, the rule will check if the value is strictly less than the specified value.
// Note that the value being checked and the threshold value must be of the same type.
// Only int, uint, float and time.Time types are supported.
// An empty value is considered valid. Please use the Required rule to make sure a value is not empty. | [
"Max",
"is",
"a",
"validation",
"rule",
"that",
"checks",
"if",
"a",
"value",
"is",
"less",
"or",
"equal",
"than",
"the",
"specified",
"value",
".",
"By",
"calling",
"Exclusive",
"the",
"rule",
"will",
"check",
"if",
"the",
"value",
"is",
"strictly",
"less",
"than",
"the",
"specified",
"value",
".",
"Note",
"that",
"the",
"value",
"being",
"checked",
"and",
"the",
"threshold",
"value",
"must",
"be",
"of",
"the",
"same",
"type",
".",
"Only",
"int",
"uint",
"float",
"and",
"time",
".",
"Time",
"types",
"are",
"supported",
".",
"An",
"empty",
"value",
"is",
"considered",
"valid",
".",
"Please",
"use",
"the",
"Required",
"rule",
"to",
"make",
"sure",
"a",
"value",
"is",
"not",
"empty",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/minmax.go#L45-L51 | train |
go-ozzo/ozzo-validation | minmax.go | Exclusive | func (r *ThresholdRule) Exclusive() *ThresholdRule {
if r.operator == greaterEqualThan {
r.operator = greaterThan
r.message = fmt.Sprintf("must be greater than %v", r.threshold)
} else if r.operator == lessEqualThan {
r.operator = lessThan
r.message = fmt.Sprintf("must be less than %v", r.threshold)
}
return r
} | go | func (r *ThresholdRule) Exclusive() *ThresholdRule {
if r.operator == greaterEqualThan {
r.operator = greaterThan
r.message = fmt.Sprintf("must be greater than %v", r.threshold)
} else if r.operator == lessEqualThan {
r.operator = lessThan
r.message = fmt.Sprintf("must be less than %v", r.threshold)
}
return r
} | [
"func",
"(",
"r",
"*",
"ThresholdRule",
")",
"Exclusive",
"(",
")",
"*",
"ThresholdRule",
"{",
"if",
"r",
".",
"operator",
"==",
"greaterEqualThan",
"{",
"r",
".",
"operator",
"=",
"greaterThan",
"\n",
"r",
".",
"message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"threshold",
")",
"\n",
"}",
"else",
"if",
"r",
".",
"operator",
"==",
"lessEqualThan",
"{",
"r",
".",
"operator",
"=",
"lessThan",
"\n",
"r",
".",
"message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"threshold",
")",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] | // Exclusive sets the comparison to exclude the boundary value. | [
"Exclusive",
"sets",
"the",
"comparison",
"to",
"exclude",
"the",
"boundary",
"value",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/minmax.go#L54-L63 | train |
go-ozzo/ozzo-validation | length.go | Length | func Length(min, max int) *LengthRule {
message := "the value must be empty"
if min == 0 && max > 0 {
message = fmt.Sprintf("the length must be no more than %v", max)
} else if min > 0 && max == 0 {
message = fmt.Sprintf("the length must be no less than %v", min)
} else if min > 0 && max > 0 {
if min == max {
message = fmt.Sprintf("the length must be exactly %v", min)
} else {
message = fmt.Sprintf("the length must be between %v and %v", min, max)
}
}
return &LengthRule{
min: min,
max: max,
message: message,
}
} | go | func Length(min, max int) *LengthRule {
message := "the value must be empty"
if min == 0 && max > 0 {
message = fmt.Sprintf("the length must be no more than %v", max)
} else if min > 0 && max == 0 {
message = fmt.Sprintf("the length must be no less than %v", min)
} else if min > 0 && max > 0 {
if min == max {
message = fmt.Sprintf("the length must be exactly %v", min)
} else {
message = fmt.Sprintf("the length must be between %v and %v", min, max)
}
}
return &LengthRule{
min: min,
max: max,
message: message,
}
} | [
"func",
"Length",
"(",
"min",
",",
"max",
"int",
")",
"*",
"LengthRule",
"{",
"message",
":=",
"\"",
"\"",
"\n",
"if",
"min",
"==",
"0",
"&&",
"max",
">",
"0",
"{",
"message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"max",
")",
"\n",
"}",
"else",
"if",
"min",
">",
"0",
"&&",
"max",
"==",
"0",
"{",
"message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"min",
")",
"\n",
"}",
"else",
"if",
"min",
">",
"0",
"&&",
"max",
">",
"0",
"{",
"if",
"min",
"==",
"max",
"{",
"message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"min",
")",
"\n",
"}",
"else",
"{",
"message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"min",
",",
"max",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"LengthRule",
"{",
"min",
":",
"min",
",",
"max",
":",
"max",
",",
"message",
":",
"message",
",",
"}",
"\n",
"}"
] | // Length returns a validation rule that checks if a value's length is within the specified range.
// If max is 0, it means there is no upper bound for the length.
// This rule should only be used for validating strings, slices, maps, and arrays.
// An empty value is considered valid. Use the Required rule to make sure a value is not empty. | [
"Length",
"returns",
"a",
"validation",
"rule",
"that",
"checks",
"if",
"a",
"value",
"s",
"length",
"is",
"within",
"the",
"specified",
"range",
".",
"If",
"max",
"is",
"0",
"it",
"means",
"there",
"is",
"no",
"upper",
"bound",
"for",
"the",
"length",
".",
"This",
"rule",
"should",
"only",
"be",
"used",
"for",
"validating",
"strings",
"slices",
"maps",
"and",
"arrays",
".",
"An",
"empty",
"value",
"is",
"considered",
"valid",
".",
"Use",
"the",
"Required",
"rule",
"to",
"make",
"sure",
"a",
"value",
"is",
"not",
"empty",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/length.go#L17-L35 | train |
go-ozzo/ozzo-validation | length.go | RuneLength | func RuneLength(min, max int) *LengthRule {
r := Length(min, max)
r.rune = true
return r
} | go | func RuneLength(min, max int) *LengthRule {
r := Length(min, max)
r.rune = true
return r
} | [
"func",
"RuneLength",
"(",
"min",
",",
"max",
"int",
")",
"*",
"LengthRule",
"{",
"r",
":=",
"Length",
"(",
"min",
",",
"max",
")",
"\n",
"r",
".",
"rune",
"=",
"true",
"\n",
"return",
"r",
"\n",
"}"
] | // RuneLength returns a validation rule that checks if a string's rune length is within the specified range.
// If max is 0, it means there is no upper bound for the length.
// This rule should only be used for validating strings, slices, maps, and arrays.
// An empty value is considered valid. Use the Required rule to make sure a value is not empty.
// If the value being validated is not a string, the rule works the same as Length. | [
"RuneLength",
"returns",
"a",
"validation",
"rule",
"that",
"checks",
"if",
"a",
"string",
"s",
"rune",
"length",
"is",
"within",
"the",
"specified",
"range",
".",
"If",
"max",
"is",
"0",
"it",
"means",
"there",
"is",
"no",
"upper",
"bound",
"for",
"the",
"length",
".",
"This",
"rule",
"should",
"only",
"be",
"used",
"for",
"validating",
"strings",
"slices",
"maps",
"and",
"arrays",
".",
"An",
"empty",
"value",
"is",
"considered",
"valid",
".",
"Use",
"the",
"Required",
"rule",
"to",
"make",
"sure",
"a",
"value",
"is",
"not",
"empty",
".",
"If",
"the",
"value",
"being",
"validated",
"is",
"not",
"a",
"string",
"the",
"rule",
"works",
"the",
"same",
"as",
"Length",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/length.go#L42-L46 | train |
go-ozzo/ozzo-validation | struct.go | Field | func Field(fieldPtr interface{}, rules ...Rule) *FieldRules {
return &FieldRules{
fieldPtr: fieldPtr,
rules: rules,
}
} | go | func Field(fieldPtr interface{}, rules ...Rule) *FieldRules {
return &FieldRules{
fieldPtr: fieldPtr,
rules: rules,
}
} | [
"func",
"Field",
"(",
"fieldPtr",
"interface",
"{",
"}",
",",
"rules",
"...",
"Rule",
")",
"*",
"FieldRules",
"{",
"return",
"&",
"FieldRules",
"{",
"fieldPtr",
":",
"fieldPtr",
",",
"rules",
":",
"rules",
",",
"}",
"\n",
"}"
] | // Field specifies a struct field and the corresponding validation rules.
// The struct field must be specified as a pointer to it. | [
"Field",
"specifies",
"a",
"struct",
"field",
"and",
"the",
"corresponding",
"validation",
"rules",
".",
"The",
"struct",
"field",
"must",
"be",
"specified",
"as",
"a",
"pointer",
"to",
"it",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/struct.go#L109-L114 | train |
go-ozzo/ozzo-validation | struct.go | findStructField | func findStructField(structValue reflect.Value, fieldValue reflect.Value) *reflect.StructField {
ptr := fieldValue.Pointer()
for i := structValue.NumField() - 1; i >= 0; i-- {
sf := structValue.Type().Field(i)
if ptr == structValue.Field(i).UnsafeAddr() {
// do additional type comparison because it's possible that the address of
// an embedded struct is the same as the first field of the embedded struct
if sf.Type == fieldValue.Elem().Type() {
return &sf
}
}
if sf.Anonymous {
// delve into anonymous struct to look for the field
fi := structValue.Field(i)
if sf.Type.Kind() == reflect.Ptr {
fi = fi.Elem()
}
if fi.Kind() == reflect.Struct {
if f := findStructField(fi, fieldValue); f != nil {
return f
}
}
}
}
return nil
} | go | func findStructField(structValue reflect.Value, fieldValue reflect.Value) *reflect.StructField {
ptr := fieldValue.Pointer()
for i := structValue.NumField() - 1; i >= 0; i-- {
sf := structValue.Type().Field(i)
if ptr == structValue.Field(i).UnsafeAddr() {
// do additional type comparison because it's possible that the address of
// an embedded struct is the same as the first field of the embedded struct
if sf.Type == fieldValue.Elem().Type() {
return &sf
}
}
if sf.Anonymous {
// delve into anonymous struct to look for the field
fi := structValue.Field(i)
if sf.Type.Kind() == reflect.Ptr {
fi = fi.Elem()
}
if fi.Kind() == reflect.Struct {
if f := findStructField(fi, fieldValue); f != nil {
return f
}
}
}
}
return nil
} | [
"func",
"findStructField",
"(",
"structValue",
"reflect",
".",
"Value",
",",
"fieldValue",
"reflect",
".",
"Value",
")",
"*",
"reflect",
".",
"StructField",
"{",
"ptr",
":=",
"fieldValue",
".",
"Pointer",
"(",
")",
"\n",
"for",
"i",
":=",
"structValue",
".",
"NumField",
"(",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"sf",
":=",
"structValue",
".",
"Type",
"(",
")",
".",
"Field",
"(",
"i",
")",
"\n",
"if",
"ptr",
"==",
"structValue",
".",
"Field",
"(",
"i",
")",
".",
"UnsafeAddr",
"(",
")",
"{",
"// do additional type comparison because it's possible that the address of",
"// an embedded struct is the same as the first field of the embedded struct",
"if",
"sf",
".",
"Type",
"==",
"fieldValue",
".",
"Elem",
"(",
")",
".",
"Type",
"(",
")",
"{",
"return",
"&",
"sf",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"sf",
".",
"Anonymous",
"{",
"// delve into anonymous struct to look for the field",
"fi",
":=",
"structValue",
".",
"Field",
"(",
"i",
")",
"\n",
"if",
"sf",
".",
"Type",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"fi",
"=",
"fi",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"if",
"fi",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Struct",
"{",
"if",
"f",
":=",
"findStructField",
"(",
"fi",
",",
"fieldValue",
")",
";",
"f",
"!=",
"nil",
"{",
"return",
"f",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // findStructField looks for a field in the given struct.
// The field being looked for should be a pointer to the actual struct field.
// If found, the field info will be returned. Otherwise, nil will be returned. | [
"findStructField",
"looks",
"for",
"a",
"field",
"in",
"the",
"given",
"struct",
".",
"The",
"field",
"being",
"looked",
"for",
"should",
"be",
"a",
"pointer",
"to",
"the",
"actual",
"struct",
"field",
".",
"If",
"found",
"the",
"field",
"info",
"will",
"be",
"returned",
".",
"Otherwise",
"nil",
"will",
"be",
"returned",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/struct.go#L119-L144 | train |
go-ozzo/ozzo-validation | struct.go | getErrorFieldName | func getErrorFieldName(f *reflect.StructField) string {
if tag := f.Tag.Get(ErrorTag); tag != "" {
if cps := strings.SplitN(tag, ",", 2); cps[0] != "" {
return cps[0]
}
}
return f.Name
} | go | func getErrorFieldName(f *reflect.StructField) string {
if tag := f.Tag.Get(ErrorTag); tag != "" {
if cps := strings.SplitN(tag, ",", 2); cps[0] != "" {
return cps[0]
}
}
return f.Name
} | [
"func",
"getErrorFieldName",
"(",
"f",
"*",
"reflect",
".",
"StructField",
")",
"string",
"{",
"if",
"tag",
":=",
"f",
".",
"Tag",
".",
"Get",
"(",
"ErrorTag",
")",
";",
"tag",
"!=",
"\"",
"\"",
"{",
"if",
"cps",
":=",
"strings",
".",
"SplitN",
"(",
"tag",
",",
"\"",
"\"",
",",
"2",
")",
";",
"cps",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"return",
"cps",
"[",
"0",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"f",
".",
"Name",
"\n",
"}"
] | // getErrorFieldName returns the name that should be used to represent the validation error of a struct field. | [
"getErrorFieldName",
"returns",
"the",
"name",
"that",
"should",
"be",
"used",
"to",
"represent",
"the",
"validation",
"error",
"of",
"a",
"struct",
"field",
"."
] | 2f76ea62300c36e72bd56c804484cb6db53b69a5 | https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/struct.go#L147-L154 | train |
containers/storage | drivers/btrfs/btrfs.go | Metadata | func (d *Driver) Metadata(id string) (map[string]string, error) {
return nil, nil
} | go | func (d *Driver) Metadata(id string) (map[string]string, error) {
return nil, nil
} | [
"func",
"(",
"d",
"*",
"Driver",
")",
"Metadata",
"(",
"id",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // Metadata returns empty metadata for this driver. | [
"Metadata",
"returns",
"empty",
"metadata",
"for",
"this",
"driver",
"."
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/btrfs/btrfs.go#L153-L155 | train |
containers/storage | drivers/btrfs/btrfs.go | Remove | func (d *Driver) Remove(id string) error {
dir := d.subvolumesDirID(id)
if _, err := os.Stat(dir); err != nil {
return err
}
quotasDir := d.quotasDirID(id)
if _, err := os.Stat(quotasDir); err == nil {
if err := os.Remove(quotasDir); err != nil {
return err
}
} else if !os.IsNotExist(err) {
return err
}
// Call updateQuotaStatus() to invoke status update
d.updateQuotaStatus()
if err := subvolDelete(d.subvolumesDir(), id, d.quotaEnabled); err != nil {
return err
}
if err := system.EnsureRemoveAll(dir); err != nil {
return err
}
if err := d.subvolRescanQuota(); err != nil {
return err
}
return nil
} | go | func (d *Driver) Remove(id string) error {
dir := d.subvolumesDirID(id)
if _, err := os.Stat(dir); err != nil {
return err
}
quotasDir := d.quotasDirID(id)
if _, err := os.Stat(quotasDir); err == nil {
if err := os.Remove(quotasDir); err != nil {
return err
}
} else if !os.IsNotExist(err) {
return err
}
// Call updateQuotaStatus() to invoke status update
d.updateQuotaStatus()
if err := subvolDelete(d.subvolumesDir(), id, d.quotaEnabled); err != nil {
return err
}
if err := system.EnsureRemoveAll(dir); err != nil {
return err
}
if err := d.subvolRescanQuota(); err != nil {
return err
}
return nil
} | [
"func",
"(",
"d",
"*",
"Driver",
")",
"Remove",
"(",
"id",
"string",
")",
"error",
"{",
"dir",
":=",
"d",
".",
"subvolumesDirID",
"(",
"id",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"dir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"quotasDir",
":=",
"d",
".",
"quotasDirID",
"(",
"id",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"quotasDir",
")",
";",
"err",
"==",
"nil",
"{",
"if",
"err",
":=",
"os",
".",
"Remove",
"(",
"quotasDir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Call updateQuotaStatus() to invoke status update",
"d",
".",
"updateQuotaStatus",
"(",
")",
"\n\n",
"if",
"err",
":=",
"subvolDelete",
"(",
"d",
".",
"subvolumesDir",
"(",
")",
",",
"id",
",",
"d",
".",
"quotaEnabled",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"system",
".",
"EnsureRemoveAll",
"(",
"dir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"subvolRescanQuota",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Remove the filesystem with given id. | [
"Remove",
"the",
"filesystem",
"with",
"given",
"id",
"."
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/btrfs/btrfs.go#L612-L639 | train |
containers/storage | drivers/overlay/overlay.go | Metadata | func (d *Driver) Metadata(id string) (map[string]string, error) {
dir := d.dir(id)
if _, err := os.Stat(dir); err != nil {
return nil, err
}
metadata := map[string]string{
"WorkDir": path.Join(dir, "work"),
"MergedDir": path.Join(dir, "merged"),
"UpperDir": path.Join(dir, "diff"),
}
lowerDirs, err := d.getLowerDirs(id)
if err != nil {
return nil, err
}
if len(lowerDirs) > 0 {
metadata["LowerDir"] = strings.Join(lowerDirs, ":")
}
return metadata, nil
} | go | func (d *Driver) Metadata(id string) (map[string]string, error) {
dir := d.dir(id)
if _, err := os.Stat(dir); err != nil {
return nil, err
}
metadata := map[string]string{
"WorkDir": path.Join(dir, "work"),
"MergedDir": path.Join(dir, "merged"),
"UpperDir": path.Join(dir, "diff"),
}
lowerDirs, err := d.getLowerDirs(id)
if err != nil {
return nil, err
}
if len(lowerDirs) > 0 {
metadata["LowerDir"] = strings.Join(lowerDirs, ":")
}
return metadata, nil
} | [
"func",
"(",
"d",
"*",
"Driver",
")",
"Metadata",
"(",
"id",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"dir",
":=",
"d",
".",
"dir",
"(",
"id",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"dir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"metadata",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"path",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
":",
"path",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
":",
"path",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
",",
"}",
"\n\n",
"lowerDirs",
",",
"err",
":=",
"d",
".",
"getLowerDirs",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"lowerDirs",
")",
">",
"0",
"{",
"metadata",
"[",
"\"",
"\"",
"]",
"=",
"strings",
".",
"Join",
"(",
"lowerDirs",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"metadata",
",",
"nil",
"\n",
"}"
] | // Metadata returns meta data about the overlay driver such as
// LowerDir, UpperDir, WorkDir and MergeDir used to store data. | [
"Metadata",
"returns",
"meta",
"data",
"about",
"the",
"overlay",
"driver",
"such",
"as",
"LowerDir",
"UpperDir",
"WorkDir",
"and",
"MergeDir",
"used",
"to",
"store",
"data",
"."
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/overlay/overlay.go#L397-L418 | train |
containers/storage | drivers/overlay/overlay.go | recreateSymlinks | func (d *Driver) recreateSymlinks() error {
// List all the directories under the home directory
dirs, err := ioutil.ReadDir(d.home)
if err != nil {
return fmt.Errorf("error reading driver home directory %q: %v", d.home, err)
}
// This makes the link directory if it doesn't exist
rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
if err != nil {
return err
}
if err := idtools.MkdirAllAs(path.Join(d.home, linkDir), 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
return err
}
for _, dir := range dirs {
// Skip over the linkDir and anything that is not a directory
if dir.Name() == linkDir || !dir.Mode().IsDir() {
continue
}
// Read the "link" file under each layer to get the name of the symlink
data, err := ioutil.ReadFile(path.Join(d.dir(dir.Name()), "link"))
if err != nil {
return fmt.Errorf("error reading name of symlink for %q: %v", dir, err)
}
linkPath := path.Join(d.home, linkDir, strings.Trim(string(data), "\n"))
// Check if the symlink exists, and if it doesn't create it again with the name we
// got from the "link" file
_, err = os.Stat(linkPath)
if err != nil && os.IsNotExist(err) {
if err := os.Symlink(path.Join("..", dir.Name(), "diff"), linkPath); err != nil {
return err
}
} else if err != nil {
return fmt.Errorf("error trying to stat %q: %v", linkPath, err)
}
}
return nil
} | go | func (d *Driver) recreateSymlinks() error {
// List all the directories under the home directory
dirs, err := ioutil.ReadDir(d.home)
if err != nil {
return fmt.Errorf("error reading driver home directory %q: %v", d.home, err)
}
// This makes the link directory if it doesn't exist
rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
if err != nil {
return err
}
if err := idtools.MkdirAllAs(path.Join(d.home, linkDir), 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
return err
}
for _, dir := range dirs {
// Skip over the linkDir and anything that is not a directory
if dir.Name() == linkDir || !dir.Mode().IsDir() {
continue
}
// Read the "link" file under each layer to get the name of the symlink
data, err := ioutil.ReadFile(path.Join(d.dir(dir.Name()), "link"))
if err != nil {
return fmt.Errorf("error reading name of symlink for %q: %v", dir, err)
}
linkPath := path.Join(d.home, linkDir, strings.Trim(string(data), "\n"))
// Check if the symlink exists, and if it doesn't create it again with the name we
// got from the "link" file
_, err = os.Stat(linkPath)
if err != nil && os.IsNotExist(err) {
if err := os.Symlink(path.Join("..", dir.Name(), "diff"), linkPath); err != nil {
return err
}
} else if err != nil {
return fmt.Errorf("error trying to stat %q: %v", linkPath, err)
}
}
return nil
} | [
"func",
"(",
"d",
"*",
"Driver",
")",
"recreateSymlinks",
"(",
")",
"error",
"{",
"// List all the directories under the home directory",
"dirs",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"d",
".",
"home",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"d",
".",
"home",
",",
"err",
")",
"\n",
"}",
"\n",
"// This makes the link directory if it doesn't exist",
"rootUID",
",",
"rootGID",
",",
"err",
":=",
"idtools",
".",
"GetRootUIDGID",
"(",
"d",
".",
"uidMaps",
",",
"d",
".",
"gidMaps",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"idtools",
".",
"MkdirAllAs",
"(",
"path",
".",
"Join",
"(",
"d",
".",
"home",
",",
"linkDir",
")",
",",
"0700",
",",
"rootUID",
",",
"rootGID",
")",
";",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"dir",
":=",
"range",
"dirs",
"{",
"// Skip over the linkDir and anything that is not a directory",
"if",
"dir",
".",
"Name",
"(",
")",
"==",
"linkDir",
"||",
"!",
"dir",
".",
"Mode",
"(",
")",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"// Read the \"link\" file under each layer to get the name of the symlink",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"path",
".",
"Join",
"(",
"d",
".",
"dir",
"(",
"dir",
".",
"Name",
"(",
")",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"dir",
",",
"err",
")",
"\n",
"}",
"\n",
"linkPath",
":=",
"path",
".",
"Join",
"(",
"d",
".",
"home",
",",
"linkDir",
",",
"strings",
".",
"Trim",
"(",
"string",
"(",
"data",
")",
",",
"\"",
"\\n",
"\"",
")",
")",
"\n",
"// Check if the symlink exists, and if it doesn't create it again with the name we",
"// got from the \"link\" file",
"_",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"linkPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"if",
"err",
":=",
"os",
".",
"Symlink",
"(",
"path",
".",
"Join",
"(",
"\"",
"\"",
",",
"dir",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
",",
"linkPath",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"linkPath",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // recreateSymlinks goes through the driver's home directory and checks if the diff directory
// under each layer has a symlink created for it under the linkDir. If the symlink does not
// exist, it creates them | [
"recreateSymlinks",
"goes",
"through",
"the",
"driver",
"s",
"home",
"directory",
"and",
"checks",
"if",
"the",
"diff",
"directory",
"under",
"each",
"layer",
"has",
"a",
"symlink",
"created",
"for",
"it",
"under",
"the",
"linkDir",
".",
"If",
"the",
"symlink",
"does",
"not",
"exist",
"it",
"creates",
"them"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/overlay/overlay.go#L699-L736 | train |
containers/storage | drivers/overlay/overlay.go | UpdateLayerIDMap | func (d *Driver) UpdateLayerIDMap(id string, toContainer, toHost *idtools.IDMappings, mountLabel string) error {
var err error
dir := d.dir(id)
diffDir := filepath.Join(dir, "diff")
rootUID, rootGID := 0, 0
if toHost != nil {
rootUID, rootGID, err = idtools.GetRootUIDGID(toHost.UIDs(), toHost.GIDs())
if err != nil {
return err
}
}
// Mount the new layer and handle ownership changes and possible copy_ups in it.
options := graphdriver.MountOpts{
MountLabel: mountLabel,
Options: strings.Split(d.options.mountOptions, ","),
}
layerFs, err := d.get(id, true, options)
if err != nil {
return err
}
err = graphdriver.ChownPathByMaps(layerFs, toContainer, toHost)
if err != nil {
if err2 := d.Put(id); err2 != nil {
logrus.Errorf("%v; error unmounting %v: %v", err, id, err2)
}
return err
}
if err = d.Put(id); err != nil {
return err
}
// Rotate the diff directories.
i := 0
_, err = os.Stat(nameWithSuffix(diffDir, i))
for err == nil {
i++
_, err = os.Stat(nameWithSuffix(diffDir, i))
}
for i > 0 {
err = os.Rename(nameWithSuffix(diffDir, i-1), nameWithSuffix(diffDir, i))
if err != nil {
return err
}
i--
}
// Re-create the directory that we're going to use as the upper layer.
if err := idtools.MkdirAs(diffDir, 0755, rootUID, rootGID); err != nil {
return err
}
return nil
} | go | func (d *Driver) UpdateLayerIDMap(id string, toContainer, toHost *idtools.IDMappings, mountLabel string) error {
var err error
dir := d.dir(id)
diffDir := filepath.Join(dir, "diff")
rootUID, rootGID := 0, 0
if toHost != nil {
rootUID, rootGID, err = idtools.GetRootUIDGID(toHost.UIDs(), toHost.GIDs())
if err != nil {
return err
}
}
// Mount the new layer and handle ownership changes and possible copy_ups in it.
options := graphdriver.MountOpts{
MountLabel: mountLabel,
Options: strings.Split(d.options.mountOptions, ","),
}
layerFs, err := d.get(id, true, options)
if err != nil {
return err
}
err = graphdriver.ChownPathByMaps(layerFs, toContainer, toHost)
if err != nil {
if err2 := d.Put(id); err2 != nil {
logrus.Errorf("%v; error unmounting %v: %v", err, id, err2)
}
return err
}
if err = d.Put(id); err != nil {
return err
}
// Rotate the diff directories.
i := 0
_, err = os.Stat(nameWithSuffix(diffDir, i))
for err == nil {
i++
_, err = os.Stat(nameWithSuffix(diffDir, i))
}
for i > 0 {
err = os.Rename(nameWithSuffix(diffDir, i-1), nameWithSuffix(diffDir, i))
if err != nil {
return err
}
i--
}
// Re-create the directory that we're going to use as the upper layer.
if err := idtools.MkdirAs(diffDir, 0755, rootUID, rootGID); err != nil {
return err
}
return nil
} | [
"func",
"(",
"d",
"*",
"Driver",
")",
"UpdateLayerIDMap",
"(",
"id",
"string",
",",
"toContainer",
",",
"toHost",
"*",
"idtools",
".",
"IDMappings",
",",
"mountLabel",
"string",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"dir",
":=",
"d",
".",
"dir",
"(",
"id",
")",
"\n",
"diffDir",
":=",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
"\n\n",
"rootUID",
",",
"rootGID",
":=",
"0",
",",
"0",
"\n",
"if",
"toHost",
"!=",
"nil",
"{",
"rootUID",
",",
"rootGID",
",",
"err",
"=",
"idtools",
".",
"GetRootUIDGID",
"(",
"toHost",
".",
"UIDs",
"(",
")",
",",
"toHost",
".",
"GIDs",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Mount the new layer and handle ownership changes and possible copy_ups in it.",
"options",
":=",
"graphdriver",
".",
"MountOpts",
"{",
"MountLabel",
":",
"mountLabel",
",",
"Options",
":",
"strings",
".",
"Split",
"(",
"d",
".",
"options",
".",
"mountOptions",
",",
"\"",
"\"",
")",
",",
"}",
"\n",
"layerFs",
",",
"err",
":=",
"d",
".",
"get",
"(",
"id",
",",
"true",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"graphdriver",
".",
"ChownPathByMaps",
"(",
"layerFs",
",",
"toContainer",
",",
"toHost",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err2",
":=",
"d",
".",
"Put",
"(",
"id",
")",
";",
"err2",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"id",
",",
"err2",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"d",
".",
"Put",
"(",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Rotate the diff directories.",
"i",
":=",
"0",
"\n",
"_",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"nameWithSuffix",
"(",
"diffDir",
",",
"i",
")",
")",
"\n",
"for",
"err",
"==",
"nil",
"{",
"i",
"++",
"\n",
"_",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"nameWithSuffix",
"(",
"diffDir",
",",
"i",
")",
")",
"\n",
"}",
"\n",
"for",
"i",
">",
"0",
"{",
"err",
"=",
"os",
".",
"Rename",
"(",
"nameWithSuffix",
"(",
"diffDir",
",",
"i",
"-",
"1",
")",
",",
"nameWithSuffix",
"(",
"diffDir",
",",
"i",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"i",
"--",
"\n",
"}",
"\n\n",
"// Re-create the directory that we're going to use as the upper layer.",
"if",
"err",
":=",
"idtools",
".",
"MkdirAs",
"(",
"diffDir",
",",
"0755",
",",
"rootUID",
",",
"rootGID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateLayerIDMap updates ID mappings in a from matching the ones specified
// by toContainer to those specified by toHost. | [
"UpdateLayerIDMap",
"updates",
"ID",
"mappings",
"in",
"a",
"from",
"matching",
"the",
"ones",
"specified",
"by",
"toContainer",
"to",
"those",
"specified",
"by",
"toHost",
"."
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/overlay/overlay.go#L1069-L1122 | train |
containers/storage | drivers/aufs/aufs.go | Metadata | func (a *Driver) Metadata(id string) (map[string]string, error) {
return nil, nil
} | go | func (a *Driver) Metadata(id string) (map[string]string, error) {
return nil, nil
} | [
"func",
"(",
"a",
"*",
"Driver",
")",
"Metadata",
"(",
"id",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // Metadata not implemented | [
"Metadata",
"not",
"implemented"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/aufs/aufs.go#L238-L240 | train |
containers/storage | drivers/aufs/aufs.go | CreateFromTemplate | func (a *Driver) CreateFromTemplate(id, template string, templateIDMappings *idtools.IDMappings, parent string, parentIDMappings *idtools.IDMappings, opts *graphdriver.CreateOpts, readWrite bool) error {
return graphdriver.NaiveCreateFromTemplate(a, id, template, templateIDMappings, parent, parentIDMappings, opts, readWrite)
} | go | func (a *Driver) CreateFromTemplate(id, template string, templateIDMappings *idtools.IDMappings, parent string, parentIDMappings *idtools.IDMappings, opts *graphdriver.CreateOpts, readWrite bool) error {
return graphdriver.NaiveCreateFromTemplate(a, id, template, templateIDMappings, parent, parentIDMappings, opts, readWrite)
} | [
"func",
"(",
"a",
"*",
"Driver",
")",
"CreateFromTemplate",
"(",
"id",
",",
"template",
"string",
",",
"templateIDMappings",
"*",
"idtools",
".",
"IDMappings",
",",
"parent",
"string",
",",
"parentIDMappings",
"*",
"idtools",
".",
"IDMappings",
",",
"opts",
"*",
"graphdriver",
".",
"CreateOpts",
",",
"readWrite",
"bool",
")",
"error",
"{",
"return",
"graphdriver",
".",
"NaiveCreateFromTemplate",
"(",
"a",
",",
"id",
",",
"template",
",",
"templateIDMappings",
",",
"parent",
",",
"parentIDMappings",
",",
"opts",
",",
"readWrite",
")",
"\n",
"}"
] | // CreateFromTemplate creates a layer with the same contents and parent as another layer. | [
"CreateFromTemplate",
"creates",
"a",
"layer",
"with",
"the",
"same",
"contents",
"and",
"parent",
"as",
"another",
"layer",
"."
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/aufs/aufs.go#L257-L259 | train |
containers/storage | drivers/aufs/aufs.go | Put | func (a *Driver) Put(id string) error {
a.locker.Lock(id)
defer a.locker.Unlock(id)
a.pathCacheLock.Lock()
m, exists := a.pathCache[id]
if !exists {
m = a.getMountpoint(id)
a.pathCache[id] = m
}
a.pathCacheLock.Unlock()
if count := a.ctr.Decrement(m); count > 0 {
return nil
}
err := a.unmount(m)
if err != nil {
logrus.Debugf("Failed to unmount %s aufs: %v", id, err)
}
return err
} | go | func (a *Driver) Put(id string) error {
a.locker.Lock(id)
defer a.locker.Unlock(id)
a.pathCacheLock.Lock()
m, exists := a.pathCache[id]
if !exists {
m = a.getMountpoint(id)
a.pathCache[id] = m
}
a.pathCacheLock.Unlock()
if count := a.ctr.Decrement(m); count > 0 {
return nil
}
err := a.unmount(m)
if err != nil {
logrus.Debugf("Failed to unmount %s aufs: %v", id, err)
}
return err
} | [
"func",
"(",
"a",
"*",
"Driver",
")",
"Put",
"(",
"id",
"string",
")",
"error",
"{",
"a",
".",
"locker",
".",
"Lock",
"(",
"id",
")",
"\n",
"defer",
"a",
".",
"locker",
".",
"Unlock",
"(",
"id",
")",
"\n",
"a",
".",
"pathCacheLock",
".",
"Lock",
"(",
")",
"\n",
"m",
",",
"exists",
":=",
"a",
".",
"pathCache",
"[",
"id",
"]",
"\n",
"if",
"!",
"exists",
"{",
"m",
"=",
"a",
".",
"getMountpoint",
"(",
"id",
")",
"\n",
"a",
".",
"pathCache",
"[",
"id",
"]",
"=",
"m",
"\n",
"}",
"\n",
"a",
".",
"pathCacheLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"count",
":=",
"a",
".",
"ctr",
".",
"Decrement",
"(",
"m",
")",
";",
"count",
">",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"err",
":=",
"a",
".",
"unmount",
"(",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"id",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Put unmounts and updates list of active mounts. | [
"Put",
"unmounts",
"and",
"updates",
"list",
"of",
"active",
"mounts",
"."
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/aufs/aufs.go#L461-L480 | train |
containers/storage | pkg/chrootarchive/archive.go | NewArchiverWithChown | func NewArchiverWithChown(tarIDMappings *idtools.IDMappings, chownOpts *idtools.IDPair, untarIDMappings *idtools.IDMappings) *archive.Archiver {
archiver := archive.NewArchiverWithChown(tarIDMappings, chownOpts, untarIDMappings)
archiver.Untar = Untar
return archiver
} | go | func NewArchiverWithChown(tarIDMappings *idtools.IDMappings, chownOpts *idtools.IDPair, untarIDMappings *idtools.IDMappings) *archive.Archiver {
archiver := archive.NewArchiverWithChown(tarIDMappings, chownOpts, untarIDMappings)
archiver.Untar = Untar
return archiver
} | [
"func",
"NewArchiverWithChown",
"(",
"tarIDMappings",
"*",
"idtools",
".",
"IDMappings",
",",
"chownOpts",
"*",
"idtools",
".",
"IDPair",
",",
"untarIDMappings",
"*",
"idtools",
".",
"IDMappings",
")",
"*",
"archive",
".",
"Archiver",
"{",
"archiver",
":=",
"archive",
".",
"NewArchiverWithChown",
"(",
"tarIDMappings",
",",
"chownOpts",
",",
"untarIDMappings",
")",
"\n",
"archiver",
".",
"Untar",
"=",
"Untar",
"\n",
"return",
"archiver",
"\n",
"}"
] | // NewArchiverWithChown returns a new Archiver which uses chrootarchive.Untar and the provided ID mapping configuration on both ends | [
"NewArchiverWithChown",
"returns",
"a",
"new",
"Archiver",
"which",
"uses",
"chrootarchive",
".",
"Untar",
"and",
"the",
"provided",
"ID",
"mapping",
"configuration",
"on",
"both",
"ends"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/chrootarchive/archive.go#L26-L30 | train |
containers/storage | pkg/chrootarchive/archive.go | CopyFileWithTarAndChown | func CopyFileWithTarAndChown(chownOpts *idtools.IDPair, hasher io.Writer, uidmap []idtools.IDMap, gidmap []idtools.IDMap) func(src, dest string) error {
untarMappings := idtools.NewIDMappingsFromMaps(uidmap, gidmap)
archiver := NewArchiverWithChown(nil, chownOpts, untarMappings)
if hasher != nil {
originalUntar := archiver.Untar
archiver.Untar = func(tarArchive io.Reader, dest string, options *archive.TarOptions) error {
contentReader, contentWriter, err := os.Pipe()
if err != nil {
return errors.Wrapf(err, "error creating pipe extract data to %q", dest)
}
defer contentReader.Close()
defer contentWriter.Close()
var hashError error
var hashWorker sync.WaitGroup
hashWorker.Add(1)
go func() {
t := tar.NewReader(contentReader)
_, err := t.Next()
if err != nil {
hashError = err
}
if _, err = io.Copy(hasher, t); err != nil && err != io.EOF {
hashError = err
}
hashWorker.Done()
}()
if err = originalUntar(io.TeeReader(tarArchive, contentWriter), dest, options); err != nil {
err = errors.Wrapf(err, "error extracting data to %q while copying", dest)
}
hashWorker.Wait()
if err == nil {
err = errors.Wrapf(hashError, "error calculating digest of data for %q while copying", dest)
}
return err
}
}
return archiver.CopyFileWithTar
} | go | func CopyFileWithTarAndChown(chownOpts *idtools.IDPair, hasher io.Writer, uidmap []idtools.IDMap, gidmap []idtools.IDMap) func(src, dest string) error {
untarMappings := idtools.NewIDMappingsFromMaps(uidmap, gidmap)
archiver := NewArchiverWithChown(nil, chownOpts, untarMappings)
if hasher != nil {
originalUntar := archiver.Untar
archiver.Untar = func(tarArchive io.Reader, dest string, options *archive.TarOptions) error {
contentReader, contentWriter, err := os.Pipe()
if err != nil {
return errors.Wrapf(err, "error creating pipe extract data to %q", dest)
}
defer contentReader.Close()
defer contentWriter.Close()
var hashError error
var hashWorker sync.WaitGroup
hashWorker.Add(1)
go func() {
t := tar.NewReader(contentReader)
_, err := t.Next()
if err != nil {
hashError = err
}
if _, err = io.Copy(hasher, t); err != nil && err != io.EOF {
hashError = err
}
hashWorker.Done()
}()
if err = originalUntar(io.TeeReader(tarArchive, contentWriter), dest, options); err != nil {
err = errors.Wrapf(err, "error extracting data to %q while copying", dest)
}
hashWorker.Wait()
if err == nil {
err = errors.Wrapf(hashError, "error calculating digest of data for %q while copying", dest)
}
return err
}
}
return archiver.CopyFileWithTar
} | [
"func",
"CopyFileWithTarAndChown",
"(",
"chownOpts",
"*",
"idtools",
".",
"IDPair",
",",
"hasher",
"io",
".",
"Writer",
",",
"uidmap",
"[",
"]",
"idtools",
".",
"IDMap",
",",
"gidmap",
"[",
"]",
"idtools",
".",
"IDMap",
")",
"func",
"(",
"src",
",",
"dest",
"string",
")",
"error",
"{",
"untarMappings",
":=",
"idtools",
".",
"NewIDMappingsFromMaps",
"(",
"uidmap",
",",
"gidmap",
")",
"\n",
"archiver",
":=",
"NewArchiverWithChown",
"(",
"nil",
",",
"chownOpts",
",",
"untarMappings",
")",
"\n",
"if",
"hasher",
"!=",
"nil",
"{",
"originalUntar",
":=",
"archiver",
".",
"Untar",
"\n",
"archiver",
".",
"Untar",
"=",
"func",
"(",
"tarArchive",
"io",
".",
"Reader",
",",
"dest",
"string",
",",
"options",
"*",
"archive",
".",
"TarOptions",
")",
"error",
"{",
"contentReader",
",",
"contentWriter",
",",
"err",
":=",
"os",
".",
"Pipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"dest",
")",
"\n",
"}",
"\n",
"defer",
"contentReader",
".",
"Close",
"(",
")",
"\n",
"defer",
"contentWriter",
".",
"Close",
"(",
")",
"\n",
"var",
"hashError",
"error",
"\n",
"var",
"hashWorker",
"sync",
".",
"WaitGroup",
"\n",
"hashWorker",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"t",
":=",
"tar",
".",
"NewReader",
"(",
"contentReader",
")",
"\n",
"_",
",",
"err",
":=",
"t",
".",
"Next",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"hashError",
"=",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"hasher",
",",
"t",
")",
";",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"io",
".",
"EOF",
"{",
"hashError",
"=",
"err",
"\n",
"}",
"\n",
"hashWorker",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"if",
"err",
"=",
"originalUntar",
"(",
"io",
".",
"TeeReader",
"(",
"tarArchive",
",",
"contentWriter",
")",
",",
"dest",
",",
"options",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"dest",
")",
"\n",
"}",
"\n",
"hashWorker",
".",
"Wait",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrapf",
"(",
"hashError",
",",
"\"",
"\"",
",",
"dest",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"archiver",
".",
"CopyFileWithTar",
"\n",
"}"
] | // CopyFileWithTarAndChown returns a function which copies a single file from outside
// of any container into our working container, mapping permissions using the
// container's ID maps, possibly overridden using the passed-in chownOpts | [
"CopyFileWithTarAndChown",
"returns",
"a",
"function",
"which",
"copies",
"a",
"single",
"file",
"from",
"outside",
"of",
"any",
"container",
"into",
"our",
"working",
"container",
"mapping",
"permissions",
"using",
"the",
"container",
"s",
"ID",
"maps",
"possibly",
"overridden",
"using",
"the",
"passed",
"-",
"in",
"chownOpts"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/chrootarchive/archive.go#L86-L123 | train |
containers/storage | pkg/chrootarchive/archive.go | CopyWithTarAndChown | func CopyWithTarAndChown(chownOpts *idtools.IDPair, hasher io.Writer, uidmap []idtools.IDMap, gidmap []idtools.IDMap) func(src, dest string) error {
untarMappings := idtools.NewIDMappingsFromMaps(uidmap, gidmap)
archiver := NewArchiverWithChown(nil, chownOpts, untarMappings)
if hasher != nil {
originalUntar := archiver.Untar
archiver.Untar = func(tarArchive io.Reader, dest string, options *archive.TarOptions) error {
return originalUntar(io.TeeReader(tarArchive, hasher), dest, options)
}
}
return archiver.CopyWithTar
} | go | func CopyWithTarAndChown(chownOpts *idtools.IDPair, hasher io.Writer, uidmap []idtools.IDMap, gidmap []idtools.IDMap) func(src, dest string) error {
untarMappings := idtools.NewIDMappingsFromMaps(uidmap, gidmap)
archiver := NewArchiverWithChown(nil, chownOpts, untarMappings)
if hasher != nil {
originalUntar := archiver.Untar
archiver.Untar = func(tarArchive io.Reader, dest string, options *archive.TarOptions) error {
return originalUntar(io.TeeReader(tarArchive, hasher), dest, options)
}
}
return archiver.CopyWithTar
} | [
"func",
"CopyWithTarAndChown",
"(",
"chownOpts",
"*",
"idtools",
".",
"IDPair",
",",
"hasher",
"io",
".",
"Writer",
",",
"uidmap",
"[",
"]",
"idtools",
".",
"IDMap",
",",
"gidmap",
"[",
"]",
"idtools",
".",
"IDMap",
")",
"func",
"(",
"src",
",",
"dest",
"string",
")",
"error",
"{",
"untarMappings",
":=",
"idtools",
".",
"NewIDMappingsFromMaps",
"(",
"uidmap",
",",
"gidmap",
")",
"\n",
"archiver",
":=",
"NewArchiverWithChown",
"(",
"nil",
",",
"chownOpts",
",",
"untarMappings",
")",
"\n",
"if",
"hasher",
"!=",
"nil",
"{",
"originalUntar",
":=",
"archiver",
".",
"Untar",
"\n",
"archiver",
".",
"Untar",
"=",
"func",
"(",
"tarArchive",
"io",
".",
"Reader",
",",
"dest",
"string",
",",
"options",
"*",
"archive",
".",
"TarOptions",
")",
"error",
"{",
"return",
"originalUntar",
"(",
"io",
".",
"TeeReader",
"(",
"tarArchive",
",",
"hasher",
")",
",",
"dest",
",",
"options",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"archiver",
".",
"CopyWithTar",
"\n",
"}"
] | // CopyWithTarAndChown returns a function which copies a directory tree from outside of
// any container into our working container, mapping permissions using the
// container's ID maps, possibly overridden using the passed-in chownOpts | [
"CopyWithTarAndChown",
"returns",
"a",
"function",
"which",
"copies",
"a",
"directory",
"tree",
"from",
"outside",
"of",
"any",
"container",
"into",
"our",
"working",
"container",
"mapping",
"permissions",
"using",
"the",
"container",
"s",
"ID",
"maps",
"possibly",
"overridden",
"using",
"the",
"passed",
"-",
"in",
"chownOpts"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/chrootarchive/archive.go#L128-L138 | train |
containers/storage | utils.go | ParseIDMapping | func ParseIDMapping(UIDMapSlice, GIDMapSlice []string, subUIDMap, subGIDMap string) (*IDMappingOptions, error) {
options := IDMappingOptions{
HostUIDMapping: true,
HostGIDMapping: true,
}
if subGIDMap == "" && subUIDMap != "" {
subGIDMap = subUIDMap
}
if subUIDMap == "" && subGIDMap != "" {
subUIDMap = subGIDMap
}
if len(GIDMapSlice) == 0 && len(UIDMapSlice) != 0 {
GIDMapSlice = UIDMapSlice
}
if len(UIDMapSlice) == 0 && len(GIDMapSlice) != 0 {
UIDMapSlice = GIDMapSlice
}
if len(UIDMapSlice) == 0 && subUIDMap == "" && os.Getuid() != 0 {
UIDMapSlice = []string{fmt.Sprintf("0:%d:1", os.Getuid())}
}
if len(GIDMapSlice) == 0 && subGIDMap == "" && os.Getuid() != 0 {
GIDMapSlice = []string{fmt.Sprintf("0:%d:1", os.Getgid())}
}
if subUIDMap != "" && subGIDMap != "" {
mappings, err := idtools.NewIDMappings(subUIDMap, subGIDMap)
if err != nil {
return nil, errors.Wrapf(err, "failed to create NewIDMappings for uidmap=%s gidmap=%s", subUIDMap, subGIDMap)
}
options.UIDMap = mappings.UIDs()
options.GIDMap = mappings.GIDs()
}
parsedUIDMap, err := idtools.ParseIDMap(UIDMapSlice, "UID")
if err != nil {
return nil, errors.Wrapf(err, "failed to create ParseUIDMap UID=%s", UIDMapSlice)
}
parsedGIDMap, err := idtools.ParseIDMap(GIDMapSlice, "GID")
if err != nil {
return nil, errors.Wrapf(err, "failed to create ParseGIDMap GID=%s", UIDMapSlice)
}
options.UIDMap = append(options.UIDMap, parsedUIDMap...)
options.GIDMap = append(options.GIDMap, parsedGIDMap...)
if len(options.UIDMap) > 0 {
options.HostUIDMapping = false
}
if len(options.GIDMap) > 0 {
options.HostGIDMapping = false
}
return &options, nil
} | go | func ParseIDMapping(UIDMapSlice, GIDMapSlice []string, subUIDMap, subGIDMap string) (*IDMappingOptions, error) {
options := IDMappingOptions{
HostUIDMapping: true,
HostGIDMapping: true,
}
if subGIDMap == "" && subUIDMap != "" {
subGIDMap = subUIDMap
}
if subUIDMap == "" && subGIDMap != "" {
subUIDMap = subGIDMap
}
if len(GIDMapSlice) == 0 && len(UIDMapSlice) != 0 {
GIDMapSlice = UIDMapSlice
}
if len(UIDMapSlice) == 0 && len(GIDMapSlice) != 0 {
UIDMapSlice = GIDMapSlice
}
if len(UIDMapSlice) == 0 && subUIDMap == "" && os.Getuid() != 0 {
UIDMapSlice = []string{fmt.Sprintf("0:%d:1", os.Getuid())}
}
if len(GIDMapSlice) == 0 && subGIDMap == "" && os.Getuid() != 0 {
GIDMapSlice = []string{fmt.Sprintf("0:%d:1", os.Getgid())}
}
if subUIDMap != "" && subGIDMap != "" {
mappings, err := idtools.NewIDMappings(subUIDMap, subGIDMap)
if err != nil {
return nil, errors.Wrapf(err, "failed to create NewIDMappings for uidmap=%s gidmap=%s", subUIDMap, subGIDMap)
}
options.UIDMap = mappings.UIDs()
options.GIDMap = mappings.GIDs()
}
parsedUIDMap, err := idtools.ParseIDMap(UIDMapSlice, "UID")
if err != nil {
return nil, errors.Wrapf(err, "failed to create ParseUIDMap UID=%s", UIDMapSlice)
}
parsedGIDMap, err := idtools.ParseIDMap(GIDMapSlice, "GID")
if err != nil {
return nil, errors.Wrapf(err, "failed to create ParseGIDMap GID=%s", UIDMapSlice)
}
options.UIDMap = append(options.UIDMap, parsedUIDMap...)
options.GIDMap = append(options.GIDMap, parsedGIDMap...)
if len(options.UIDMap) > 0 {
options.HostUIDMapping = false
}
if len(options.GIDMap) > 0 {
options.HostGIDMapping = false
}
return &options, nil
} | [
"func",
"ParseIDMapping",
"(",
"UIDMapSlice",
",",
"GIDMapSlice",
"[",
"]",
"string",
",",
"subUIDMap",
",",
"subGIDMap",
"string",
")",
"(",
"*",
"IDMappingOptions",
",",
"error",
")",
"{",
"options",
":=",
"IDMappingOptions",
"{",
"HostUIDMapping",
":",
"true",
",",
"HostGIDMapping",
":",
"true",
",",
"}",
"\n",
"if",
"subGIDMap",
"==",
"\"",
"\"",
"&&",
"subUIDMap",
"!=",
"\"",
"\"",
"{",
"subGIDMap",
"=",
"subUIDMap",
"\n",
"}",
"\n",
"if",
"subUIDMap",
"==",
"\"",
"\"",
"&&",
"subGIDMap",
"!=",
"\"",
"\"",
"{",
"subUIDMap",
"=",
"subGIDMap",
"\n",
"}",
"\n",
"if",
"len",
"(",
"GIDMapSlice",
")",
"==",
"0",
"&&",
"len",
"(",
"UIDMapSlice",
")",
"!=",
"0",
"{",
"GIDMapSlice",
"=",
"UIDMapSlice",
"\n",
"}",
"\n",
"if",
"len",
"(",
"UIDMapSlice",
")",
"==",
"0",
"&&",
"len",
"(",
"GIDMapSlice",
")",
"!=",
"0",
"{",
"UIDMapSlice",
"=",
"GIDMapSlice",
"\n",
"}",
"\n",
"if",
"len",
"(",
"UIDMapSlice",
")",
"==",
"0",
"&&",
"subUIDMap",
"==",
"\"",
"\"",
"&&",
"os",
".",
"Getuid",
"(",
")",
"!=",
"0",
"{",
"UIDMapSlice",
"=",
"[",
"]",
"string",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"os",
".",
"Getuid",
"(",
")",
")",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"GIDMapSlice",
")",
"==",
"0",
"&&",
"subGIDMap",
"==",
"\"",
"\"",
"&&",
"os",
".",
"Getuid",
"(",
")",
"!=",
"0",
"{",
"GIDMapSlice",
"=",
"[",
"]",
"string",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"os",
".",
"Getgid",
"(",
")",
")",
"}",
"\n",
"}",
"\n\n",
"if",
"subUIDMap",
"!=",
"\"",
"\"",
"&&",
"subGIDMap",
"!=",
"\"",
"\"",
"{",
"mappings",
",",
"err",
":=",
"idtools",
".",
"NewIDMappings",
"(",
"subUIDMap",
",",
"subGIDMap",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"subUIDMap",
",",
"subGIDMap",
")",
"\n",
"}",
"\n",
"options",
".",
"UIDMap",
"=",
"mappings",
".",
"UIDs",
"(",
")",
"\n",
"options",
".",
"GIDMap",
"=",
"mappings",
".",
"GIDs",
"(",
")",
"\n",
"}",
"\n",
"parsedUIDMap",
",",
"err",
":=",
"idtools",
".",
"ParseIDMap",
"(",
"UIDMapSlice",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"UIDMapSlice",
")",
"\n",
"}",
"\n",
"parsedGIDMap",
",",
"err",
":=",
"idtools",
".",
"ParseIDMap",
"(",
"GIDMapSlice",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"UIDMapSlice",
")",
"\n",
"}",
"\n",
"options",
".",
"UIDMap",
"=",
"append",
"(",
"options",
".",
"UIDMap",
",",
"parsedUIDMap",
"...",
")",
"\n",
"options",
".",
"GIDMap",
"=",
"append",
"(",
"options",
".",
"GIDMap",
",",
"parsedGIDMap",
"...",
")",
"\n",
"if",
"len",
"(",
"options",
".",
"UIDMap",
")",
">",
"0",
"{",
"options",
".",
"HostUIDMapping",
"=",
"false",
"\n",
"}",
"\n",
"if",
"len",
"(",
"options",
".",
"GIDMap",
")",
">",
"0",
"{",
"options",
".",
"HostGIDMapping",
"=",
"false",
"\n",
"}",
"\n",
"return",
"&",
"options",
",",
"nil",
"\n",
"}"
] | // ParseIDMapping takes idmappings and subuid and subgid maps and returns a storage mapping | [
"ParseIDMapping",
"takes",
"idmappings",
"and",
"subuid",
"and",
"subgid",
"maps",
"and",
"returns",
"a",
"storage",
"mapping"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/utils.go#L20-L69 | train |
containers/storage | utils.go | GetRootlessRuntimeDir | func GetRootlessRuntimeDir(rootlessUid int) (string, error) {
runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
if runtimeDir == "" {
tmpDir := fmt.Sprintf("/run/user/%d", rootlessUid)
st, err := system.Stat(tmpDir)
if err == nil && int(st.UID()) == os.Getuid() && st.Mode()&0700 == 0700 && st.Mode()&0066 == 0000 {
return tmpDir, nil
}
}
tmpDir := fmt.Sprintf("%s/%d", os.TempDir(), rootlessUid)
if err := os.MkdirAll(tmpDir, 0700); err != nil {
logrus.Errorf("failed to create %s: %v", tmpDir, err)
} else {
return tmpDir, nil
}
home, err := homeDir()
if err != nil {
return "", errors.Wrapf(err, "neither XDG_RUNTIME_DIR nor HOME was set non-empty")
}
resolvedHome, err := filepath.EvalSymlinks(home)
if err != nil {
return "", errors.Wrapf(err, "cannot resolve %s", home)
}
return filepath.Join(resolvedHome, "rundir"), nil
} | go | func GetRootlessRuntimeDir(rootlessUid int) (string, error) {
runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
if runtimeDir == "" {
tmpDir := fmt.Sprintf("/run/user/%d", rootlessUid)
st, err := system.Stat(tmpDir)
if err == nil && int(st.UID()) == os.Getuid() && st.Mode()&0700 == 0700 && st.Mode()&0066 == 0000 {
return tmpDir, nil
}
}
tmpDir := fmt.Sprintf("%s/%d", os.TempDir(), rootlessUid)
if err := os.MkdirAll(tmpDir, 0700); err != nil {
logrus.Errorf("failed to create %s: %v", tmpDir, err)
} else {
return tmpDir, nil
}
home, err := homeDir()
if err != nil {
return "", errors.Wrapf(err, "neither XDG_RUNTIME_DIR nor HOME was set non-empty")
}
resolvedHome, err := filepath.EvalSymlinks(home)
if err != nil {
return "", errors.Wrapf(err, "cannot resolve %s", home)
}
return filepath.Join(resolvedHome, "rundir"), nil
} | [
"func",
"GetRootlessRuntimeDir",
"(",
"rootlessUid",
"int",
")",
"(",
"string",
",",
"error",
")",
"{",
"runtimeDir",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"runtimeDir",
"==",
"\"",
"\"",
"{",
"tmpDir",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rootlessUid",
")",
"\n",
"st",
",",
"err",
":=",
"system",
".",
"Stat",
"(",
"tmpDir",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"int",
"(",
"st",
".",
"UID",
"(",
")",
")",
"==",
"os",
".",
"Getuid",
"(",
")",
"&&",
"st",
".",
"Mode",
"(",
")",
"&",
"0700",
"==",
"0700",
"&&",
"st",
".",
"Mode",
"(",
")",
"&",
"0066",
"==",
"0000",
"{",
"return",
"tmpDir",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"tmpDir",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"os",
".",
"TempDir",
"(",
")",
",",
"rootlessUid",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"tmpDir",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tmpDir",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"return",
"tmpDir",
",",
"nil",
"\n",
"}",
"\n",
"home",
",",
"err",
":=",
"homeDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"resolvedHome",
",",
"err",
":=",
"filepath",
".",
"EvalSymlinks",
"(",
"home",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"home",
")",
"\n",
"}",
"\n",
"return",
"filepath",
".",
"Join",
"(",
"resolvedHome",
",",
"\"",
"\"",
")",
",",
"nil",
"\n",
"}"
] | // GetRootlessRuntimeDir returns the runtime directory when running as non root | [
"GetRootlessRuntimeDir",
"returns",
"the",
"runtime",
"directory",
"when",
"running",
"as",
"non",
"root"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/utils.go#L72-L96 | train |
containers/storage | utils.go | getRootlessDirInfo | func getRootlessDirInfo(rootlessUid int) (string, string, error) {
rootlessRuntime, err := GetRootlessRuntimeDir(rootlessUid)
if err != nil {
return "", "", err
}
dataDir := os.Getenv("XDG_DATA_HOME")
if dataDir == "" {
home, err := homeDir()
if err != nil {
return "", "", errors.Wrapf(err, "neither XDG_DATA_HOME nor HOME was set non-empty")
}
// runc doesn't like symlinks in the rootfs path, and at least
// on CoreOS /home is a symlink to /var/home, so resolve any symlink.
resolvedHome, err := filepath.EvalSymlinks(home)
if err != nil {
return "", "", errors.Wrapf(err, "cannot resolve %s", home)
}
dataDir = filepath.Join(resolvedHome, ".local", "share")
}
return dataDir, rootlessRuntime, nil
} | go | func getRootlessDirInfo(rootlessUid int) (string, string, error) {
rootlessRuntime, err := GetRootlessRuntimeDir(rootlessUid)
if err != nil {
return "", "", err
}
dataDir := os.Getenv("XDG_DATA_HOME")
if dataDir == "" {
home, err := homeDir()
if err != nil {
return "", "", errors.Wrapf(err, "neither XDG_DATA_HOME nor HOME was set non-empty")
}
// runc doesn't like symlinks in the rootfs path, and at least
// on CoreOS /home is a symlink to /var/home, so resolve any symlink.
resolvedHome, err := filepath.EvalSymlinks(home)
if err != nil {
return "", "", errors.Wrapf(err, "cannot resolve %s", home)
}
dataDir = filepath.Join(resolvedHome, ".local", "share")
}
return dataDir, rootlessRuntime, nil
} | [
"func",
"getRootlessDirInfo",
"(",
"rootlessUid",
"int",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"rootlessRuntime",
",",
"err",
":=",
"GetRootlessRuntimeDir",
"(",
"rootlessUid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"dataDir",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"dataDir",
"==",
"\"",
"\"",
"{",
"home",
",",
"err",
":=",
"homeDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// runc doesn't like symlinks in the rootfs path, and at least",
"// on CoreOS /home is a symlink to /var/home, so resolve any symlink.",
"resolvedHome",
",",
"err",
":=",
"filepath",
".",
"EvalSymlinks",
"(",
"home",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"home",
")",
"\n",
"}",
"\n",
"dataDir",
"=",
"filepath",
".",
"Join",
"(",
"resolvedHome",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"dataDir",
",",
"rootlessRuntime",
",",
"nil",
"\n",
"}"
] | // getRootlessDirInfo returns the parent path of where the storage for containers and
// volumes will be in rootless mode | [
"getRootlessDirInfo",
"returns",
"the",
"parent",
"path",
"of",
"where",
"the",
"storage",
"for",
"containers",
"and",
"volumes",
"will",
"be",
"in",
"rootless",
"mode"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/utils.go#L100-L121 | train |
containers/storage | utils.go | getRootlessStorageOpts | func getRootlessStorageOpts(rootlessUid int) (StoreOptions, error) {
var opts StoreOptions
dataDir, rootlessRuntime, err := getRootlessDirInfo(rootlessUid)
if err != nil {
return opts, err
}
opts.RunRoot = rootlessRuntime
opts.GraphRoot = filepath.Join(dataDir, "containers", "storage")
if path, err := exec.LookPath("fuse-overlayfs"); err == nil {
opts.GraphDriverName = "overlay"
opts.GraphDriverOptions = []string{fmt.Sprintf("overlay.mount_program=%s", path)}
} else {
opts.GraphDriverName = "vfs"
}
return opts, nil
} | go | func getRootlessStorageOpts(rootlessUid int) (StoreOptions, error) {
var opts StoreOptions
dataDir, rootlessRuntime, err := getRootlessDirInfo(rootlessUid)
if err != nil {
return opts, err
}
opts.RunRoot = rootlessRuntime
opts.GraphRoot = filepath.Join(dataDir, "containers", "storage")
if path, err := exec.LookPath("fuse-overlayfs"); err == nil {
opts.GraphDriverName = "overlay"
opts.GraphDriverOptions = []string{fmt.Sprintf("overlay.mount_program=%s", path)}
} else {
opts.GraphDriverName = "vfs"
}
return opts, nil
} | [
"func",
"getRootlessStorageOpts",
"(",
"rootlessUid",
"int",
")",
"(",
"StoreOptions",
",",
"error",
")",
"{",
"var",
"opts",
"StoreOptions",
"\n\n",
"dataDir",
",",
"rootlessRuntime",
",",
"err",
":=",
"getRootlessDirInfo",
"(",
"rootlessUid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"opts",
",",
"err",
"\n",
"}",
"\n",
"opts",
".",
"RunRoot",
"=",
"rootlessRuntime",
"\n",
"opts",
".",
"GraphRoot",
"=",
"filepath",
".",
"Join",
"(",
"dataDir",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"path",
",",
"err",
":=",
"exec",
".",
"LookPath",
"(",
"\"",
"\"",
")",
";",
"err",
"==",
"nil",
"{",
"opts",
".",
"GraphDriverName",
"=",
"\"",
"\"",
"\n",
"opts",
".",
"GraphDriverOptions",
"=",
"[",
"]",
"string",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
")",
"}",
"\n",
"}",
"else",
"{",
"opts",
".",
"GraphDriverName",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"opts",
",",
"nil",
"\n",
"}"
] | // getRootlessStorageOpts returns the storage opts for containers running as non root | [
"getRootlessStorageOpts",
"returns",
"the",
"storage",
"opts",
"for",
"containers",
"running",
"as",
"non",
"root"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/utils.go#L124-L140 | train |
containers/storage | utils.go | DefaultStoreOptions | func DefaultStoreOptions(rootless bool, rootlessUid int) (StoreOptions, error) {
var (
defaultRootlessRunRoot string
defaultRootlessGraphRoot string
err error
)
storageOpts := defaultStoreOptions
if rootless && rootlessUid != 0 {
storageOpts, err = getRootlessStorageOpts(rootlessUid)
if err != nil {
return storageOpts, err
}
}
storageConf, err := DefaultConfigFile(rootless && rootlessUid != 0)
if err != nil {
return storageOpts, err
}
if _, err = os.Stat(storageConf); err == nil {
defaultRootlessRunRoot = storageOpts.RunRoot
defaultRootlessGraphRoot = storageOpts.GraphRoot
storageOpts = StoreOptions{}
ReloadConfigurationFile(storageConf, &storageOpts)
}
if !os.IsNotExist(err) {
return storageOpts, errors.Wrapf(err, "cannot stat %s", storageConf)
}
if rootless && rootlessUid != 0 {
if err == nil {
// If the file did not specify a graphroot or runroot,
// set sane defaults so we don't try and use root-owned
// directories
if storageOpts.RunRoot == "" {
storageOpts.RunRoot = defaultRootlessRunRoot
}
if storageOpts.GraphRoot == "" {
storageOpts.GraphRoot = defaultRootlessGraphRoot
}
} else {
if err := os.MkdirAll(filepath.Dir(storageConf), 0755); err != nil {
return storageOpts, errors.Wrapf(err, "cannot make directory %s", filepath.Dir(storageConf))
}
file, err := os.OpenFile(storageConf, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
if err != nil {
return storageOpts, errors.Wrapf(err, "cannot open %s", storageConf)
}
tomlConfiguration := getTomlStorage(&storageOpts)
defer file.Close()
enc := toml.NewEncoder(file)
if err := enc.Encode(tomlConfiguration); err != nil {
os.Remove(storageConf)
return storageOpts, errors.Wrapf(err, "failed to encode %s", storageConf)
}
}
}
return storageOpts, nil
} | go | func DefaultStoreOptions(rootless bool, rootlessUid int) (StoreOptions, error) {
var (
defaultRootlessRunRoot string
defaultRootlessGraphRoot string
err error
)
storageOpts := defaultStoreOptions
if rootless && rootlessUid != 0 {
storageOpts, err = getRootlessStorageOpts(rootlessUid)
if err != nil {
return storageOpts, err
}
}
storageConf, err := DefaultConfigFile(rootless && rootlessUid != 0)
if err != nil {
return storageOpts, err
}
if _, err = os.Stat(storageConf); err == nil {
defaultRootlessRunRoot = storageOpts.RunRoot
defaultRootlessGraphRoot = storageOpts.GraphRoot
storageOpts = StoreOptions{}
ReloadConfigurationFile(storageConf, &storageOpts)
}
if !os.IsNotExist(err) {
return storageOpts, errors.Wrapf(err, "cannot stat %s", storageConf)
}
if rootless && rootlessUid != 0 {
if err == nil {
// If the file did not specify a graphroot or runroot,
// set sane defaults so we don't try and use root-owned
// directories
if storageOpts.RunRoot == "" {
storageOpts.RunRoot = defaultRootlessRunRoot
}
if storageOpts.GraphRoot == "" {
storageOpts.GraphRoot = defaultRootlessGraphRoot
}
} else {
if err := os.MkdirAll(filepath.Dir(storageConf), 0755); err != nil {
return storageOpts, errors.Wrapf(err, "cannot make directory %s", filepath.Dir(storageConf))
}
file, err := os.OpenFile(storageConf, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
if err != nil {
return storageOpts, errors.Wrapf(err, "cannot open %s", storageConf)
}
tomlConfiguration := getTomlStorage(&storageOpts)
defer file.Close()
enc := toml.NewEncoder(file)
if err := enc.Encode(tomlConfiguration); err != nil {
os.Remove(storageConf)
return storageOpts, errors.Wrapf(err, "failed to encode %s", storageConf)
}
}
}
return storageOpts, nil
} | [
"func",
"DefaultStoreOptions",
"(",
"rootless",
"bool",
",",
"rootlessUid",
"int",
")",
"(",
"StoreOptions",
",",
"error",
")",
"{",
"var",
"(",
"defaultRootlessRunRoot",
"string",
"\n",
"defaultRootlessGraphRoot",
"string",
"\n",
"err",
"error",
"\n",
")",
"\n",
"storageOpts",
":=",
"defaultStoreOptions",
"\n",
"if",
"rootless",
"&&",
"rootlessUid",
"!=",
"0",
"{",
"storageOpts",
",",
"err",
"=",
"getRootlessStorageOpts",
"(",
"rootlessUid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"storageOpts",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"storageConf",
",",
"err",
":=",
"DefaultConfigFile",
"(",
"rootless",
"&&",
"rootlessUid",
"!=",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"storageOpts",
",",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"storageConf",
")",
";",
"err",
"==",
"nil",
"{",
"defaultRootlessRunRoot",
"=",
"storageOpts",
".",
"RunRoot",
"\n",
"defaultRootlessGraphRoot",
"=",
"storageOpts",
".",
"GraphRoot",
"\n",
"storageOpts",
"=",
"StoreOptions",
"{",
"}",
"\n",
"ReloadConfigurationFile",
"(",
"storageConf",
",",
"&",
"storageOpts",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"storageOpts",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"storageConf",
")",
"\n",
"}",
"\n\n",
"if",
"rootless",
"&&",
"rootlessUid",
"!=",
"0",
"{",
"if",
"err",
"==",
"nil",
"{",
"// If the file did not specify a graphroot or runroot,",
"// set sane defaults so we don't try and use root-owned",
"// directories",
"if",
"storageOpts",
".",
"RunRoot",
"==",
"\"",
"\"",
"{",
"storageOpts",
".",
"RunRoot",
"=",
"defaultRootlessRunRoot",
"\n",
"}",
"\n",
"if",
"storageOpts",
".",
"GraphRoot",
"==",
"\"",
"\"",
"{",
"storageOpts",
".",
"GraphRoot",
"=",
"defaultRootlessGraphRoot",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"filepath",
".",
"Dir",
"(",
"storageConf",
")",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"storageOpts",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"filepath",
".",
"Dir",
"(",
"storageConf",
")",
")",
"\n",
"}",
"\n",
"file",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"storageConf",
",",
"os",
".",
"O_RDWR",
"|",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_EXCL",
",",
"0666",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"storageOpts",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"storageConf",
")",
"\n",
"}",
"\n\n",
"tomlConfiguration",
":=",
"getTomlStorage",
"(",
"&",
"storageOpts",
")",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n",
"enc",
":=",
"toml",
".",
"NewEncoder",
"(",
"file",
")",
"\n",
"if",
"err",
":=",
"enc",
".",
"Encode",
"(",
"tomlConfiguration",
")",
";",
"err",
"!=",
"nil",
"{",
"os",
".",
"Remove",
"(",
"storageConf",
")",
"\n\n",
"return",
"storageOpts",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"storageConf",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"storageOpts",
",",
"nil",
"\n",
"}"
] | // DefaultStoreOptions returns the default storage ops for containers | [
"DefaultStoreOptions",
"returns",
"the",
"default",
"storage",
"ops",
"for",
"containers"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/utils.go#L178-L238 | train |
containers/storage | pkg/ostree/ostree.go | ConvertToOSTree | func ConvertToOSTree(repoLocation, root, id string) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
repo, err := otbuiltin.OpenRepo(repoLocation)
if err != nil {
return errors.Wrap(err, "could not open the OSTree repository")
}
skip, whiteouts, err := fixFiles(root, os.Getuid() != 0)
if err != nil {
return errors.Wrap(err, "could not prepare the OSTree directory")
}
if skip {
return nil
}
if _, err := repo.PrepareTransaction(); err != nil {
return errors.Wrap(err, "could not prepare the OSTree transaction")
}
if skip {
return nil
}
commitOpts := otbuiltin.NewCommitOptions()
commitOpts.Timestamp = time.Now()
commitOpts.LinkCheckoutSpeedup = true
commitOpts.Parent = "0000000000000000000000000000000000000000000000000000000000000000"
branch := fmt.Sprintf("containers-storage/%s", id)
for _, w := range whiteouts {
if err := os.Remove(w); err != nil {
return errors.Wrap(err, "could not delete whiteout file")
}
}
if _, err := repo.Commit(root, branch, commitOpts); err != nil {
return errors.Wrap(err, "could not commit the layer")
}
if _, err := repo.CommitTransaction(); err != nil {
return errors.Wrap(err, "could not complete the OSTree transaction")
}
if err := system.EnsureRemoveAll(root); err != nil {
return errors.Wrap(err, "could not delete layer")
}
checkoutOpts := otbuiltin.NewCheckoutOptions()
checkoutOpts.RequireHardlinks = true
checkoutOpts.Whiteouts = false
if err := otbuiltin.Checkout(repoLocation, root, branch, checkoutOpts); err != nil {
return errors.Wrap(err, "could not checkout from OSTree")
}
for _, w := range whiteouts {
if err := unix.Mknod(w, unix.S_IFCHR, 0); err != nil {
return errors.Wrap(err, "could not recreate whiteout file")
}
}
return nil
} | go | func ConvertToOSTree(repoLocation, root, id string) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
repo, err := otbuiltin.OpenRepo(repoLocation)
if err != nil {
return errors.Wrap(err, "could not open the OSTree repository")
}
skip, whiteouts, err := fixFiles(root, os.Getuid() != 0)
if err != nil {
return errors.Wrap(err, "could not prepare the OSTree directory")
}
if skip {
return nil
}
if _, err := repo.PrepareTransaction(); err != nil {
return errors.Wrap(err, "could not prepare the OSTree transaction")
}
if skip {
return nil
}
commitOpts := otbuiltin.NewCommitOptions()
commitOpts.Timestamp = time.Now()
commitOpts.LinkCheckoutSpeedup = true
commitOpts.Parent = "0000000000000000000000000000000000000000000000000000000000000000"
branch := fmt.Sprintf("containers-storage/%s", id)
for _, w := range whiteouts {
if err := os.Remove(w); err != nil {
return errors.Wrap(err, "could not delete whiteout file")
}
}
if _, err := repo.Commit(root, branch, commitOpts); err != nil {
return errors.Wrap(err, "could not commit the layer")
}
if _, err := repo.CommitTransaction(); err != nil {
return errors.Wrap(err, "could not complete the OSTree transaction")
}
if err := system.EnsureRemoveAll(root); err != nil {
return errors.Wrap(err, "could not delete layer")
}
checkoutOpts := otbuiltin.NewCheckoutOptions()
checkoutOpts.RequireHardlinks = true
checkoutOpts.Whiteouts = false
if err := otbuiltin.Checkout(repoLocation, root, branch, checkoutOpts); err != nil {
return errors.Wrap(err, "could not checkout from OSTree")
}
for _, w := range whiteouts {
if err := unix.Mknod(w, unix.S_IFCHR, 0); err != nil {
return errors.Wrap(err, "could not recreate whiteout file")
}
}
return nil
} | [
"func",
"ConvertToOSTree",
"(",
"repoLocation",
",",
"root",
",",
"id",
"string",
")",
"error",
"{",
"runtime",
".",
"LockOSThread",
"(",
")",
"\n",
"defer",
"runtime",
".",
"UnlockOSThread",
"(",
")",
"\n",
"repo",
",",
"err",
":=",
"otbuiltin",
".",
"OpenRepo",
"(",
"repoLocation",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"skip",
",",
"whiteouts",
",",
"err",
":=",
"fixFiles",
"(",
"root",
",",
"os",
".",
"Getuid",
"(",
")",
"!=",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"skip",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"repo",
".",
"PrepareTransaction",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"skip",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"commitOpts",
":=",
"otbuiltin",
".",
"NewCommitOptions",
"(",
")",
"\n",
"commitOpts",
".",
"Timestamp",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"commitOpts",
".",
"LinkCheckoutSpeedup",
"=",
"true",
"\n",
"commitOpts",
".",
"Parent",
"=",
"\"",
"\"",
"\n",
"branch",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n\n",
"for",
"_",
",",
"w",
":=",
"range",
"whiteouts",
"{",
"if",
"err",
":=",
"os",
".",
"Remove",
"(",
"w",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"repo",
".",
"Commit",
"(",
"root",
",",
"branch",
",",
"commitOpts",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"repo",
".",
"CommitTransaction",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"system",
".",
"EnsureRemoveAll",
"(",
"root",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"checkoutOpts",
":=",
"otbuiltin",
".",
"NewCheckoutOptions",
"(",
")",
"\n",
"checkoutOpts",
".",
"RequireHardlinks",
"=",
"true",
"\n",
"checkoutOpts",
".",
"Whiteouts",
"=",
"false",
"\n",
"if",
"err",
":=",
"otbuiltin",
".",
"Checkout",
"(",
"repoLocation",
",",
"root",
",",
"branch",
",",
"checkoutOpts",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"w",
":=",
"range",
"whiteouts",
"{",
"if",
"err",
":=",
"unix",
".",
"Mknod",
"(",
"w",
",",
"unix",
".",
"S_IFCHR",
",",
"0",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Create prepares the filesystem for the OSTREE driver and copies the directory for the given id under the parent. | [
"Create",
"prepares",
"the",
"filesystem",
"for",
"the",
"OSTREE",
"driver",
"and",
"copies",
"the",
"directory",
"for",
"the",
"given",
"id",
"under",
"the",
"parent",
"."
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/ostree/ostree.go#L80-L141 | train |
containers/storage | pkg/archive/copy.go | CopyInfoDestinationPath | func CopyInfoDestinationPath(path string) (info CopyInfo, err error) {
maxSymlinkIter := 10 // filepath.EvalSymlinks uses 255, but 10 already seems like a lot.
path = normalizePath(path)
originalPath := path
stat, err := os.Lstat(path)
if err == nil && stat.Mode()&os.ModeSymlink == 0 {
// The path exists and is not a symlink.
return CopyInfo{
Path: path,
Exists: true,
IsDir: stat.IsDir(),
}, nil
}
// While the path is a symlink.
for n := 0; err == nil && stat.Mode()&os.ModeSymlink != 0; n++ {
if n > maxSymlinkIter {
// Don't follow symlinks more than this arbitrary number of times.
return CopyInfo{}, errors.New("too many symlinks in " + originalPath)
}
// The path is a symbolic link. We need to evaluate it so that the
// destination of the copy operation is the link target and not the
// link itself. This is notably different than CopyInfoSourcePath which
// only evaluates symlinks before the last appearing path separator.
// Also note that it is okay if the last path element is a broken
// symlink as the copy operation should create the target.
var linkTarget string
linkTarget, err = os.Readlink(path)
if err != nil {
return CopyInfo{}, err
}
if !system.IsAbs(linkTarget) {
// Join with the parent directory.
dstParent, _ := SplitPathDirEntry(path)
linkTarget = filepath.Join(dstParent, linkTarget)
}
path = linkTarget
stat, err = os.Lstat(path)
}
if err != nil {
// It's okay if the destination path doesn't exist. We can still
// continue the copy operation if the parent directory exists.
if !os.IsNotExist(err) {
return CopyInfo{}, err
}
// Ensure destination parent dir exists.
dstParent, _ := SplitPathDirEntry(path)
parentDirStat, err := os.Lstat(dstParent)
if err != nil {
return CopyInfo{}, err
}
if !parentDirStat.IsDir() {
return CopyInfo{}, ErrNotDirectory
}
return CopyInfo{Path: path}, nil
}
// The path exists after resolving symlinks.
return CopyInfo{
Path: path,
Exists: true,
IsDir: stat.IsDir(),
}, nil
} | go | func CopyInfoDestinationPath(path string) (info CopyInfo, err error) {
maxSymlinkIter := 10 // filepath.EvalSymlinks uses 255, but 10 already seems like a lot.
path = normalizePath(path)
originalPath := path
stat, err := os.Lstat(path)
if err == nil && stat.Mode()&os.ModeSymlink == 0 {
// The path exists and is not a symlink.
return CopyInfo{
Path: path,
Exists: true,
IsDir: stat.IsDir(),
}, nil
}
// While the path is a symlink.
for n := 0; err == nil && stat.Mode()&os.ModeSymlink != 0; n++ {
if n > maxSymlinkIter {
// Don't follow symlinks more than this arbitrary number of times.
return CopyInfo{}, errors.New("too many symlinks in " + originalPath)
}
// The path is a symbolic link. We need to evaluate it so that the
// destination of the copy operation is the link target and not the
// link itself. This is notably different than CopyInfoSourcePath which
// only evaluates symlinks before the last appearing path separator.
// Also note that it is okay if the last path element is a broken
// symlink as the copy operation should create the target.
var linkTarget string
linkTarget, err = os.Readlink(path)
if err != nil {
return CopyInfo{}, err
}
if !system.IsAbs(linkTarget) {
// Join with the parent directory.
dstParent, _ := SplitPathDirEntry(path)
linkTarget = filepath.Join(dstParent, linkTarget)
}
path = linkTarget
stat, err = os.Lstat(path)
}
if err != nil {
// It's okay if the destination path doesn't exist. We can still
// continue the copy operation if the parent directory exists.
if !os.IsNotExist(err) {
return CopyInfo{}, err
}
// Ensure destination parent dir exists.
dstParent, _ := SplitPathDirEntry(path)
parentDirStat, err := os.Lstat(dstParent)
if err != nil {
return CopyInfo{}, err
}
if !parentDirStat.IsDir() {
return CopyInfo{}, ErrNotDirectory
}
return CopyInfo{Path: path}, nil
}
// The path exists after resolving symlinks.
return CopyInfo{
Path: path,
Exists: true,
IsDir: stat.IsDir(),
}, nil
} | [
"func",
"CopyInfoDestinationPath",
"(",
"path",
"string",
")",
"(",
"info",
"CopyInfo",
",",
"err",
"error",
")",
"{",
"maxSymlinkIter",
":=",
"10",
"// filepath.EvalSymlinks uses 255, but 10 already seems like a lot.",
"\n",
"path",
"=",
"normalizePath",
"(",
"path",
")",
"\n",
"originalPath",
":=",
"path",
"\n\n",
"stat",
",",
"err",
":=",
"os",
".",
"Lstat",
"(",
"path",
")",
"\n\n",
"if",
"err",
"==",
"nil",
"&&",
"stat",
".",
"Mode",
"(",
")",
"&",
"os",
".",
"ModeSymlink",
"==",
"0",
"{",
"// The path exists and is not a symlink.",
"return",
"CopyInfo",
"{",
"Path",
":",
"path",
",",
"Exists",
":",
"true",
",",
"IsDir",
":",
"stat",
".",
"IsDir",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"// While the path is a symlink.",
"for",
"n",
":=",
"0",
";",
"err",
"==",
"nil",
"&&",
"stat",
".",
"Mode",
"(",
")",
"&",
"os",
".",
"ModeSymlink",
"!=",
"0",
";",
"n",
"++",
"{",
"if",
"n",
">",
"maxSymlinkIter",
"{",
"// Don't follow symlinks more than this arbitrary number of times.",
"return",
"CopyInfo",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"originalPath",
")",
"\n",
"}",
"\n\n",
"// The path is a symbolic link. We need to evaluate it so that the",
"// destination of the copy operation is the link target and not the",
"// link itself. This is notably different than CopyInfoSourcePath which",
"// only evaluates symlinks before the last appearing path separator.",
"// Also note that it is okay if the last path element is a broken",
"// symlink as the copy operation should create the target.",
"var",
"linkTarget",
"string",
"\n\n",
"linkTarget",
",",
"err",
"=",
"os",
".",
"Readlink",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"CopyInfo",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"system",
".",
"IsAbs",
"(",
"linkTarget",
")",
"{",
"// Join with the parent directory.",
"dstParent",
",",
"_",
":=",
"SplitPathDirEntry",
"(",
"path",
")",
"\n",
"linkTarget",
"=",
"filepath",
".",
"Join",
"(",
"dstParent",
",",
"linkTarget",
")",
"\n",
"}",
"\n\n",
"path",
"=",
"linkTarget",
"\n",
"stat",
",",
"err",
"=",
"os",
".",
"Lstat",
"(",
"path",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"// It's okay if the destination path doesn't exist. We can still",
"// continue the copy operation if the parent directory exists.",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"CopyInfo",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Ensure destination parent dir exists.",
"dstParent",
",",
"_",
":=",
"SplitPathDirEntry",
"(",
"path",
")",
"\n\n",
"parentDirStat",
",",
"err",
":=",
"os",
".",
"Lstat",
"(",
"dstParent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"CopyInfo",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"parentDirStat",
".",
"IsDir",
"(",
")",
"{",
"return",
"CopyInfo",
"{",
"}",
",",
"ErrNotDirectory",
"\n",
"}",
"\n\n",
"return",
"CopyInfo",
"{",
"Path",
":",
"path",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"// The path exists after resolving symlinks.",
"return",
"CopyInfo",
"{",
"Path",
":",
"path",
",",
"Exists",
":",
"true",
",",
"IsDir",
":",
"stat",
".",
"IsDir",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // CopyInfoDestinationPath stats the given path to create a CopyInfo
// struct representing that resource for the destination of an archive copy
// operation. The given path should be an absolute local path. | [
"CopyInfoDestinationPath",
"stats",
"the",
"given",
"path",
"to",
"create",
"a",
"CopyInfo",
"struct",
"representing",
"that",
"resource",
"for",
"the",
"destination",
"of",
"an",
"archive",
"copy",
"operation",
".",
"The",
"given",
"path",
"should",
"be",
"an",
"absolute",
"local",
"path",
"."
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/archive/copy.go#L165-L238 | train |
containers/storage | pkg/archive/copy.go | CopyResource | func CopyResource(srcPath, dstPath string, followLink bool) error {
var (
srcInfo CopyInfo
err error
)
// Ensure in platform semantics
srcPath = normalizePath(srcPath)
dstPath = normalizePath(dstPath)
// Clean the source and destination paths.
srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath)
dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath)
if srcInfo, err = CopyInfoSourcePath(srcPath, followLink); err != nil {
return err
}
content, err := TarResource(srcInfo)
if err != nil {
return err
}
defer content.Close()
return CopyTo(content, srcInfo, dstPath)
} | go | func CopyResource(srcPath, dstPath string, followLink bool) error {
var (
srcInfo CopyInfo
err error
)
// Ensure in platform semantics
srcPath = normalizePath(srcPath)
dstPath = normalizePath(dstPath)
// Clean the source and destination paths.
srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath)
dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath)
if srcInfo, err = CopyInfoSourcePath(srcPath, followLink); err != nil {
return err
}
content, err := TarResource(srcInfo)
if err != nil {
return err
}
defer content.Close()
return CopyTo(content, srcInfo, dstPath)
} | [
"func",
"CopyResource",
"(",
"srcPath",
",",
"dstPath",
"string",
",",
"followLink",
"bool",
")",
"error",
"{",
"var",
"(",
"srcInfo",
"CopyInfo",
"\n",
"err",
"error",
"\n",
")",
"\n\n",
"// Ensure in platform semantics",
"srcPath",
"=",
"normalizePath",
"(",
"srcPath",
")",
"\n",
"dstPath",
"=",
"normalizePath",
"(",
"dstPath",
")",
"\n\n",
"// Clean the source and destination paths.",
"srcPath",
"=",
"PreserveTrailingDotOrSeparator",
"(",
"filepath",
".",
"Clean",
"(",
"srcPath",
")",
",",
"srcPath",
")",
"\n",
"dstPath",
"=",
"PreserveTrailingDotOrSeparator",
"(",
"filepath",
".",
"Clean",
"(",
"dstPath",
")",
",",
"dstPath",
")",
"\n\n",
"if",
"srcInfo",
",",
"err",
"=",
"CopyInfoSourcePath",
"(",
"srcPath",
",",
"followLink",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"content",
",",
"err",
":=",
"TarResource",
"(",
"srcInfo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"content",
".",
"Close",
"(",
")",
"\n\n",
"return",
"CopyTo",
"(",
"content",
",",
"srcInfo",
",",
"dstPath",
")",
"\n",
"}"
] | // CopyResource performs an archive copy from the given source path to the
// given destination path. The source path MUST exist and the destination
// path's parent directory must exist. | [
"CopyResource",
"performs",
"an",
"archive",
"copy",
"from",
"the",
"given",
"source",
"path",
"to",
"the",
"given",
"destination",
"path",
".",
"The",
"source",
"path",
"MUST",
"exist",
"and",
"the",
"destination",
"path",
"s",
"parent",
"directory",
"must",
"exist",
"."
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/archive/copy.go#L357-L382 | train |
containers/storage | pkg/archive/copy.go | ResolveHostSourcePath | func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseName string, err error) {
if followLink {
resolvedPath, err = filepath.EvalSymlinks(path)
if err != nil {
return
}
resolvedPath, rebaseName = GetRebaseName(path, resolvedPath)
} else {
dirPath, basePath := filepath.Split(path)
// if not follow symbol link, then resolve symbol link of parent dir
var resolvedDirPath string
resolvedDirPath, err = filepath.EvalSymlinks(dirPath)
if err != nil {
return
}
// resolvedDirPath will have been cleaned (no trailing path separators) so
// we can manually join it with the base path element.
resolvedPath = resolvedDirPath + string(filepath.Separator) + basePath
if hasTrailingPathSeparator(path) && filepath.Base(path) != filepath.Base(resolvedPath) {
rebaseName = filepath.Base(path)
}
}
return resolvedPath, rebaseName, nil
} | go | func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseName string, err error) {
if followLink {
resolvedPath, err = filepath.EvalSymlinks(path)
if err != nil {
return
}
resolvedPath, rebaseName = GetRebaseName(path, resolvedPath)
} else {
dirPath, basePath := filepath.Split(path)
// if not follow symbol link, then resolve symbol link of parent dir
var resolvedDirPath string
resolvedDirPath, err = filepath.EvalSymlinks(dirPath)
if err != nil {
return
}
// resolvedDirPath will have been cleaned (no trailing path separators) so
// we can manually join it with the base path element.
resolvedPath = resolvedDirPath + string(filepath.Separator) + basePath
if hasTrailingPathSeparator(path) && filepath.Base(path) != filepath.Base(resolvedPath) {
rebaseName = filepath.Base(path)
}
}
return resolvedPath, rebaseName, nil
} | [
"func",
"ResolveHostSourcePath",
"(",
"path",
"string",
",",
"followLink",
"bool",
")",
"(",
"resolvedPath",
",",
"rebaseName",
"string",
",",
"err",
"error",
")",
"{",
"if",
"followLink",
"{",
"resolvedPath",
",",
"err",
"=",
"filepath",
".",
"EvalSymlinks",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"resolvedPath",
",",
"rebaseName",
"=",
"GetRebaseName",
"(",
"path",
",",
"resolvedPath",
")",
"\n",
"}",
"else",
"{",
"dirPath",
",",
"basePath",
":=",
"filepath",
".",
"Split",
"(",
"path",
")",
"\n\n",
"// if not follow symbol link, then resolve symbol link of parent dir",
"var",
"resolvedDirPath",
"string",
"\n",
"resolvedDirPath",
",",
"err",
"=",
"filepath",
".",
"EvalSymlinks",
"(",
"dirPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// resolvedDirPath will have been cleaned (no trailing path separators) so",
"// we can manually join it with the base path element.",
"resolvedPath",
"=",
"resolvedDirPath",
"+",
"string",
"(",
"filepath",
".",
"Separator",
")",
"+",
"basePath",
"\n",
"if",
"hasTrailingPathSeparator",
"(",
"path",
")",
"&&",
"filepath",
".",
"Base",
"(",
"path",
")",
"!=",
"filepath",
".",
"Base",
"(",
"resolvedPath",
")",
"{",
"rebaseName",
"=",
"filepath",
".",
"Base",
"(",
"path",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"resolvedPath",
",",
"rebaseName",
",",
"nil",
"\n",
"}"
] | // ResolveHostSourcePath decides real path need to be copied with parameters such as
// whether to follow symbol link or not, if followLink is true, resolvedPath will return
// link target of any symbol link file, else it will only resolve symlink of directory
// but return symbol link file itself without resolving. | [
"ResolveHostSourcePath",
"decides",
"real",
"path",
"need",
"to",
"be",
"copied",
"with",
"parameters",
"such",
"as",
"whether",
"to",
"follow",
"symbol",
"link",
"or",
"not",
"if",
"followLink",
"is",
"true",
"resolvedPath",
"will",
"return",
"link",
"target",
"of",
"any",
"symbol",
"link",
"file",
"else",
"it",
"will",
"only",
"resolve",
"symlink",
"of",
"directory",
"but",
"return",
"symbol",
"link",
"file",
"itself",
"without",
"resolving",
"."
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/archive/copy.go#L412-L437 | train |
containers/storage | pkg/archive/copy.go | GetRebaseName | func GetRebaseName(path, resolvedPath string) (string, string) {
// linkTarget will have been cleaned (no trailing path separators and dot) so
// we can manually join it with them
var rebaseName string
if specifiesCurrentDir(path) && !specifiesCurrentDir(resolvedPath) {
resolvedPath += string(filepath.Separator) + "."
}
if hasTrailingPathSeparator(path) && !hasTrailingPathSeparator(resolvedPath) {
resolvedPath += string(filepath.Separator)
}
if filepath.Base(path) != filepath.Base(resolvedPath) {
// In the case where the path had a trailing separator and a symlink
// evaluation has changed the last path component, we will need to
// rebase the name in the archive that is being copied to match the
// originally requested name.
rebaseName = filepath.Base(path)
}
return resolvedPath, rebaseName
} | go | func GetRebaseName(path, resolvedPath string) (string, string) {
// linkTarget will have been cleaned (no trailing path separators and dot) so
// we can manually join it with them
var rebaseName string
if specifiesCurrentDir(path) && !specifiesCurrentDir(resolvedPath) {
resolvedPath += string(filepath.Separator) + "."
}
if hasTrailingPathSeparator(path) && !hasTrailingPathSeparator(resolvedPath) {
resolvedPath += string(filepath.Separator)
}
if filepath.Base(path) != filepath.Base(resolvedPath) {
// In the case where the path had a trailing separator and a symlink
// evaluation has changed the last path component, we will need to
// rebase the name in the archive that is being copied to match the
// originally requested name.
rebaseName = filepath.Base(path)
}
return resolvedPath, rebaseName
} | [
"func",
"GetRebaseName",
"(",
"path",
",",
"resolvedPath",
"string",
")",
"(",
"string",
",",
"string",
")",
"{",
"// linkTarget will have been cleaned (no trailing path separators and dot) so",
"// we can manually join it with them",
"var",
"rebaseName",
"string",
"\n",
"if",
"specifiesCurrentDir",
"(",
"path",
")",
"&&",
"!",
"specifiesCurrentDir",
"(",
"resolvedPath",
")",
"{",
"resolvedPath",
"+=",
"string",
"(",
"filepath",
".",
"Separator",
")",
"+",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"hasTrailingPathSeparator",
"(",
"path",
")",
"&&",
"!",
"hasTrailingPathSeparator",
"(",
"resolvedPath",
")",
"{",
"resolvedPath",
"+=",
"string",
"(",
"filepath",
".",
"Separator",
")",
"\n",
"}",
"\n\n",
"if",
"filepath",
".",
"Base",
"(",
"path",
")",
"!=",
"filepath",
".",
"Base",
"(",
"resolvedPath",
")",
"{",
"// In the case where the path had a trailing separator and a symlink",
"// evaluation has changed the last path component, we will need to",
"// rebase the name in the archive that is being copied to match the",
"// originally requested name.",
"rebaseName",
"=",
"filepath",
".",
"Base",
"(",
"path",
")",
"\n",
"}",
"\n",
"return",
"resolvedPath",
",",
"rebaseName",
"\n",
"}"
] | // GetRebaseName normalizes and compares path and resolvedPath,
// return completed resolved path and rebased file name | [
"GetRebaseName",
"normalizes",
"and",
"compares",
"path",
"and",
"resolvedPath",
"return",
"completed",
"resolved",
"path",
"and",
"rebased",
"file",
"name"
] | 94f0324a5d0c063ffa4adb04361dc2f863b17e05 | https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/archive/copy.go#L441-L461 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.