id
int32
0
167k
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
19,200
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", ...
// 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"...
0c31efc5dc7385fa91705093d77bfc554c2751f9
https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/client.go#L191-L248
19,201
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", "{...
// 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
19,202
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", "{", "...
// 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
19,203
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", "{", ...
// 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
19,204
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",...
// NewDefaultSyncer returns an instantiated DefaultSyncer
[ "NewDefaultSyncer", "returns", "an", "instantiated", "DefaultSyncer" ]
0c31efc5dc7385fa91705093d77bfc554c2751f9
https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/sync.go#L35-L41
19,205
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", ".", "lis...
// 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
19,206
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 wi...
// 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
19,207
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
19,208
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
19,209
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
19,210
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", ")", "...
// NewInMemoryStore constructs a new InMemoryStore.
[ "NewInMemoryStore", "constructs", "a", "new", "InMemoryStore", "." ]
0c31efc5dc7385fa91705093d77bfc554c2751f9
https://github.com/matrix-org/gomatrix/blob/0c31efc5dc7385fa91705093d77bfc554c2751f9/store.go#L59-L65
19,211
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", "(", "\"", "\\\"", "\\\"",...
// 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
19,212
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", "(", ")", ",", "Ro...
// 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
19,213
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", ",...
// 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
19,214
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", ...
// 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
19,215
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...
// 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
19,216
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", "giv...
2f76ea62300c36e72bd56c804484cb6db53b69a5
https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/string.go#L20-L25
19,217
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
19,218
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
19,219
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
19,220
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", "...
// 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
19,221
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",...
// 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
19,222
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...
// 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
19,223
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", ",", ...
// 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
19,224
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", ",", "reflec...
// 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
19,225
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", ",", "ref...
// 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
19,226
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", ",", ...
// 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
19,227
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",...
// 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
19,228
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 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", ...
2f76ea62300c36e72bd56c804484cb6db53b69a5
https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/minmax.go#L32-L38
19,229
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", "(", "\"", "\"", ",", "ma...
// 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", "le...
2f76ea62300c36e72bd56c804484cb6db53b69a5
https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/minmax.go#L45-L51
19,230
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", "...
// 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
19,231
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", ...
// 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", ...
2f76ea62300c36e72bd56c804484cb6db53b69a5
https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/length.go#L17-L35
19,232
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"...
2f76ea62300c36e72bd56c804484cb6db53b69a5
https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/length.go#L42-L46
19,233
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
19,234
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", "....
// 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", ...
2f76ea62300c36e72bd56c804484cb6db53b69a5
https://github.com/go-ozzo/ozzo-validation/blob/2f76ea62300c36e72bd56c804484cb6db53b69a5/struct.go#L119-L144
19,235
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", "("...
// 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
19,236
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
19,237
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", ...
// 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
19,238
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", ...
// 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
19,239
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", "{", "...
// 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", "symlin...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/overlay/overlay.go#L699-L736
19,240
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", ".", "di...
// 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
19,241
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
19,242
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", ...
// 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
19,243
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"...
// 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
19,244
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", ":=", "a...
// 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
19,245
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", ",", "d...
// 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...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/chrootarchive/archive.go#L86-L123
19,246
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"...
// 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"...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/chrootarchive/archive.go#L128-L138
19,247
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", ":", "tru...
// 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
19,248
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...
// 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
19,249
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", "\"", ...
// 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
19,250
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", ...
// 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
19,251
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"...
// 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
19,252
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", ".", "O...
// 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
19,253
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", ...
// 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",...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/archive/copy.go#L165-L238
19,254
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", "(", ...
// 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", ...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/archive/copy.go#L357-L382
19,255
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", ...
// 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", ...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/archive/copy.go#L412-L437
19,256
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"...
// 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
19,257
containers/storage
drivers/driver.go
isDriverNotSupported
func isDriverNotSupported(err error) bool { cause := errors.Cause(err) return cause == ErrNotSupported || cause == ErrPrerequisites || cause == ErrIncompatibleFS }
go
func isDriverNotSupported(err error) bool { cause := errors.Cause(err) return cause == ErrNotSupported || cause == ErrPrerequisites || cause == ErrIncompatibleFS }
[ "func", "isDriverNotSupported", "(", "err", "error", ")", "bool", "{", "cause", ":=", "errors", ".", "Cause", "(", "err", ")", "\n", "return", "cause", "==", "ErrNotSupported", "||", "cause", "==", "ErrPrerequisites", "||", "cause", "==", "ErrIncompatibleFS", ...
// isDriverNotSupported returns true if the error initializing // the graph driver is a non-supported error.
[ "isDriverNotSupported", "returns", "true", "if", "the", "error", "initializing", "the", "graph", "driver", "is", "a", "non", "-", "supported", "error", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/driver.go#L302-L305
19,258
containers/storage
drivers/driver.go
scanPriorDrivers
func scanPriorDrivers(root string) map[string]bool { driversMap := make(map[string]bool) for driver := range drivers { p := filepath.Join(root, driver) if _, err := os.Stat(p); err == nil && driver != "vfs" { driversMap[driver] = true } } return driversMap }
go
func scanPriorDrivers(root string) map[string]bool { driversMap := make(map[string]bool) for driver := range drivers { p := filepath.Join(root, driver) if _, err := os.Stat(p); err == nil && driver != "vfs" { driversMap[driver] = true } } return driversMap }
[ "func", "scanPriorDrivers", "(", "root", "string", ")", "map", "[", "string", "]", "bool", "{", "driversMap", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n\n", "for", "driver", ":=", "range", "drivers", "{", "p", ":=", "filepath", ".",...
// scanPriorDrivers returns an un-ordered scan of directories of prior storage drivers
[ "scanPriorDrivers", "returns", "an", "un", "-", "ordered", "scan", "of", "directories", "of", "prior", "storage", "drivers" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/driver.go#L308-L318
19,259
containers/storage
lockfile_unix.go
openLock
func openLock(path string, ro bool) (int, error) { if ro { return unix.Open(path, os.O_RDONLY, 0) } return unix.Open(path, os.O_RDWR|os.O_CREATE, unix.S_IRUSR|unix.S_IWUSR) }
go
func openLock(path string, ro bool) (int, error) { if ro { return unix.Open(path, os.O_RDONLY, 0) } return unix.Open(path, os.O_RDWR|os.O_CREATE, unix.S_IRUSR|unix.S_IWUSR) }
[ "func", "openLock", "(", "path", "string", ",", "ro", "bool", ")", "(", "int", ",", "error", ")", "{", "if", "ro", "{", "return", "unix", ".", "Open", "(", "path", ",", "os", ".", "O_RDONLY", ",", "0", ")", "\n", "}", "\n", "return", "unix", "....
// openLock opens the file at path and returns the corresponding file // descriptor. Note that the path is opened read-only when ro is set. If ro // is unset, openLock will open the path read-write and create the file if // necessary.
[ "openLock", "opens", "the", "file", "at", "path", "and", "returns", "the", "corresponding", "file", "descriptor", ".", "Note", "that", "the", "path", "is", "opened", "read", "-", "only", "when", "ro", "is", "set", ".", "If", "ro", "is", "unset", "openLoc...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/lockfile_unix.go#L34-L39
19,260
containers/storage
lockfile_unix.go
Unlock
func (l *lockfile) Unlock() { lk := unix.Flock_t{ Type: unix.F_UNLCK, Whence: int16(os.SEEK_SET), Start: 0, Len: 0, Pid: int32(os.Getpid()), } l.stateMutex.Lock() if l.locked == false { // Panic when unlocking an unlocked lock. That's a violation // of the lock semantics and will reveal such. panic("calling Unlock on unlocked lock") } l.counter-- if l.counter < 0 { // Panic when the counter is negative. There is no way we can // recover from a corrupted lock and we need to protect the // storage from corruption. panic(fmt.Sprintf("lock %q has been unlocked too often", l.file)) } if l.counter == 0 { // We should only release the lock when the counter is 0 to // avoid releasing read-locks too early; a given process may // acquire a read lock multiple times. l.locked = false for unix.FcntlFlock(l.fd, unix.F_SETLKW, &lk) != nil { time.Sleep(10 * time.Millisecond) } // Close the file descriptor on the last unlock. unix.Close(int(l.fd)) } if l.locktype == unix.F_RDLCK { l.rwMutex.RUnlock() } else { l.rwMutex.Unlock() } l.stateMutex.Unlock() }
go
func (l *lockfile) Unlock() { lk := unix.Flock_t{ Type: unix.F_UNLCK, Whence: int16(os.SEEK_SET), Start: 0, Len: 0, Pid: int32(os.Getpid()), } l.stateMutex.Lock() if l.locked == false { // Panic when unlocking an unlocked lock. That's a violation // of the lock semantics and will reveal such. panic("calling Unlock on unlocked lock") } l.counter-- if l.counter < 0 { // Panic when the counter is negative. There is no way we can // recover from a corrupted lock and we need to protect the // storage from corruption. panic(fmt.Sprintf("lock %q has been unlocked too often", l.file)) } if l.counter == 0 { // We should only release the lock when the counter is 0 to // avoid releasing read-locks too early; a given process may // acquire a read lock multiple times. l.locked = false for unix.FcntlFlock(l.fd, unix.F_SETLKW, &lk) != nil { time.Sleep(10 * time.Millisecond) } // Close the file descriptor on the last unlock. unix.Close(int(l.fd)) } if l.locktype == unix.F_RDLCK { l.rwMutex.RUnlock() } else { l.rwMutex.Unlock() } l.stateMutex.Unlock() }
[ "func", "(", "l", "*", "lockfile", ")", "Unlock", "(", ")", "{", "lk", ":=", "unix", ".", "Flock_t", "{", "Type", ":", "unix", ".", "F_UNLCK", ",", "Whence", ":", "int16", "(", "os", ".", "SEEK_SET", ")", ",", "Start", ":", "0", ",", "Len", ":"...
// Unlock unlocks the lockfile.
[ "Unlock", "unlocks", "the", "lockfile", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/lockfile_unix.go#L132-L170
19,261
containers/storage
lockfile_unix.go
Locked
func (l *lockfile) Locked() bool { l.stateMutex.Lock() defer l.stateMutex.Unlock() return l.locked && (l.locktype == unix.F_WRLCK) }
go
func (l *lockfile) Locked() bool { l.stateMutex.Lock() defer l.stateMutex.Unlock() return l.locked && (l.locktype == unix.F_WRLCK) }
[ "func", "(", "l", "*", "lockfile", ")", "Locked", "(", ")", "bool", "{", "l", ".", "stateMutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "stateMutex", ".", "Unlock", "(", ")", "\n", "return", "l", ".", "locked", "&&", "(", "l", ".", "lo...
// Locked checks if lockfile is locked for writing by a thread in this process.
[ "Locked", "checks", "if", "lockfile", "is", "locked", "for", "writing", "by", "a", "thread", "in", "this", "process", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/lockfile_unix.go#L173-L177
19,262
containers/storage
lockfile_unix.go
Touch
func (l *lockfile) Touch() error { l.stateMutex.Lock() if !l.locked || (l.locktype != unix.F_WRLCK) { panic("attempted to update last-writer in lockfile without the write lock") } l.stateMutex.Unlock() l.lw = stringid.GenerateRandomID() id := []byte(l.lw) _, err := unix.Seek(int(l.fd), 0, os.SEEK_SET) if err != nil { return err } n, err := unix.Write(int(l.fd), id) if err != nil { return err } if n != len(id) { return unix.ENOSPC } err = unix.Fsync(int(l.fd)) if err != nil { return err } return nil }
go
func (l *lockfile) Touch() error { l.stateMutex.Lock() if !l.locked || (l.locktype != unix.F_WRLCK) { panic("attempted to update last-writer in lockfile without the write lock") } l.stateMutex.Unlock() l.lw = stringid.GenerateRandomID() id := []byte(l.lw) _, err := unix.Seek(int(l.fd), 0, os.SEEK_SET) if err != nil { return err } n, err := unix.Write(int(l.fd), id) if err != nil { return err } if n != len(id) { return unix.ENOSPC } err = unix.Fsync(int(l.fd)) if err != nil { return err } return nil }
[ "func", "(", "l", "*", "lockfile", ")", "Touch", "(", ")", "error", "{", "l", ".", "stateMutex", ".", "Lock", "(", ")", "\n", "if", "!", "l", ".", "locked", "||", "(", "l", ".", "locktype", "!=", "unix", ".", "F_WRLCK", ")", "{", "panic", "(", ...
// Touch updates the lock file with the UID of the user.
[ "Touch", "updates", "the", "lock", "file", "with", "the", "UID", "of", "the", "user", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/lockfile_unix.go#L180-L204
19,263
containers/storage
lockfile_unix.go
Modified
func (l *lockfile) Modified() (bool, error) { id := []byte(l.lw) l.stateMutex.Lock() if !l.locked { panic("attempted to check last-writer in lockfile without locking it first") } l.stateMutex.Unlock() _, err := unix.Seek(int(l.fd), 0, os.SEEK_SET) if err != nil { return true, err } n, err := unix.Read(int(l.fd), id) if err != nil { return true, err } if n != len(id) { return true, nil } lw := l.lw l.lw = string(id) return l.lw != lw, nil }
go
func (l *lockfile) Modified() (bool, error) { id := []byte(l.lw) l.stateMutex.Lock() if !l.locked { panic("attempted to check last-writer in lockfile without locking it first") } l.stateMutex.Unlock() _, err := unix.Seek(int(l.fd), 0, os.SEEK_SET) if err != nil { return true, err } n, err := unix.Read(int(l.fd), id) if err != nil { return true, err } if n != len(id) { return true, nil } lw := l.lw l.lw = string(id) return l.lw != lw, nil }
[ "func", "(", "l", "*", "lockfile", ")", "Modified", "(", ")", "(", "bool", ",", "error", ")", "{", "id", ":=", "[", "]", "byte", "(", "l", ".", "lw", ")", "\n", "l", ".", "stateMutex", ".", "Lock", "(", ")", "\n", "if", "!", "l", ".", "lock...
// Modified indicates if the lockfile has been updated since the last time it // was loaded.
[ "Modified", "indicates", "if", "the", "lockfile", "has", "been", "updated", "since", "the", "last", "time", "it", "was", "loaded", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/lockfile_unix.go#L208-L229
19,264
containers/storage
pkg/idtools/parser.go
ParseIDMap
func ParseIDMap(mapSpec []string, mapSetting string) (idmap []IDMap, err error) { stdErr := fmt.Errorf("error initializing ID mappings: %s setting is malformed", mapSetting) for _, idMapSpec := range mapSpec { idSpec := strings.Fields(strings.Map(nonDigitsToWhitespace, idMapSpec)) if len(idSpec)%3 != 0 { return nil, stdErr } for i := range idSpec { if i%3 != 0 { continue } cid, hid, size, err := parseTriple(idSpec[i : i+3]) if err != nil { return nil, stdErr } // Avoid possible integer overflow on 32bit builds if bits.UintSize == 32 && (cid > math.MaxInt32 || hid > math.MaxInt32 || size > math.MaxInt32) { return nil, stdErr } mapping := IDMap{ ContainerID: int(cid), HostID: int(hid), Size: int(size), } idmap = append(idmap, mapping) } } return idmap, nil }
go
func ParseIDMap(mapSpec []string, mapSetting string) (idmap []IDMap, err error) { stdErr := fmt.Errorf("error initializing ID mappings: %s setting is malformed", mapSetting) for _, idMapSpec := range mapSpec { idSpec := strings.Fields(strings.Map(nonDigitsToWhitespace, idMapSpec)) if len(idSpec)%3 != 0 { return nil, stdErr } for i := range idSpec { if i%3 != 0 { continue } cid, hid, size, err := parseTriple(idSpec[i : i+3]) if err != nil { return nil, stdErr } // Avoid possible integer overflow on 32bit builds if bits.UintSize == 32 && (cid > math.MaxInt32 || hid > math.MaxInt32 || size > math.MaxInt32) { return nil, stdErr } mapping := IDMap{ ContainerID: int(cid), HostID: int(hid), Size: int(size), } idmap = append(idmap, mapping) } } return idmap, nil }
[ "func", "ParseIDMap", "(", "mapSpec", "[", "]", "string", ",", "mapSetting", "string", ")", "(", "idmap", "[", "]", "IDMap", ",", "err", "error", ")", "{", "stdErr", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mapSetting", ")", "\n", "for", ...
// ParseIDMap parses idmap triples from string.
[ "ParseIDMap", "parses", "idmap", "triples", "from", "string", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/idtools/parser.go#L35-L63
19,265
containers/storage
pkg/system/meminfo_solaris.go
getTotalMem
func getTotalMem() int64 { pagesize := C.sysconf(C._SC_PAGESIZE) npages := C.sysconf(C._SC_PHYS_PAGES) return int64(pagesize * npages) }
go
func getTotalMem() int64 { pagesize := C.sysconf(C._SC_PAGESIZE) npages := C.sysconf(C._SC_PHYS_PAGES) return int64(pagesize * npages) }
[ "func", "getTotalMem", "(", ")", "int64", "{", "pagesize", ":=", "C", ".", "sysconf", "(", "C", ".", "_SC_PAGESIZE", ")", "\n", "npages", ":=", "C", ".", "sysconf", "(", "C", ".", "_SC_PHYS_PAGES", ")", "\n", "return", "int64", "(", "pagesize", "*", ...
// Get the system memory info using sysconf same as prtconf
[ "Get", "the", "system", "memory", "info", "using", "sysconf", "same", "as", "prtconf" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/system/meminfo_solaris.go#L70-L74
19,266
containers/storage
pkg/pools/pools.go
newBufioReaderPoolWithSize
func newBufioReaderPoolWithSize(size int) *BufioReaderPool { pool := &sync.Pool{ New: func() interface{} { return bufio.NewReaderSize(nil, size) }, } return &BufioReaderPool{pool: pool} }
go
func newBufioReaderPoolWithSize(size int) *BufioReaderPool { pool := &sync.Pool{ New: func() interface{} { return bufio.NewReaderSize(nil, size) }, } return &BufioReaderPool{pool: pool} }
[ "func", "newBufioReaderPoolWithSize", "(", "size", "int", ")", "*", "BufioReaderPool", "{", "pool", ":=", "&", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "bufio", ".", "NewReaderSize", "(", "nil", ",", ...
// newBufioReaderPoolWithSize is unexported because new pools should be // added here to be shared where required.
[ "newBufioReaderPoolWithSize", "is", "unexported", "because", "new", "pools", "should", "be", "added", "here", "to", "be", "shared", "where", "required", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/pools/pools.go#L41-L46
19,267
containers/storage
pkg/pools/pools.go
Copy
func Copy(dst io.Writer, src io.Reader) (written int64, err error) { buf := BufioReader32KPool.Get(src) written, err = io.Copy(dst, buf) BufioReader32KPool.Put(buf) return }
go
func Copy(dst io.Writer, src io.Reader) (written int64, err error) { buf := BufioReader32KPool.Get(src) written, err = io.Copy(dst, buf) BufioReader32KPool.Put(buf) return }
[ "func", "Copy", "(", "dst", "io", ".", "Writer", ",", "src", "io", ".", "Reader", ")", "(", "written", "int64", ",", "err", "error", ")", "{", "buf", ":=", "BufioReader32KPool", ".", "Get", "(", "src", ")", "\n", "written", ",", "err", "=", "io", ...
// Copy is a convenience wrapper which uses a buffer to avoid allocation in io.Copy.
[ "Copy", "is", "a", "convenience", "wrapper", "which", "uses", "a", "buffer", "to", "avoid", "allocation", "in", "io", ".", "Copy", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/pools/pools.go#L62-L67
19,268
containers/storage
drivers/quota/projectquota.go
setProjectID
func setProjectID(targetPath string, projectID uint32) error { dir, err := openDir(targetPath) if err != nil { return err } defer closeDir(dir) var fsx C.struct_fsxattr _, _, errno := unix.Syscall(unix.SYS_IOCTL, getDirFd(dir), C.FS_IOC_FSGETXATTR, uintptr(unsafe.Pointer(&fsx))) if errno != 0 { return fmt.Errorf("Failed to get projid for %s: %v", targetPath, errno.Error()) } fsx.fsx_projid = C.__u32(projectID) fsx.fsx_xflags |= C.FS_XFLAG_PROJINHERIT _, _, errno = unix.Syscall(unix.SYS_IOCTL, getDirFd(dir), C.FS_IOC_FSSETXATTR, uintptr(unsafe.Pointer(&fsx))) if errno != 0 { return fmt.Errorf("Failed to set projid for %s: %v", targetPath, errno.Error()) } return nil }
go
func setProjectID(targetPath string, projectID uint32) error { dir, err := openDir(targetPath) if err != nil { return err } defer closeDir(dir) var fsx C.struct_fsxattr _, _, errno := unix.Syscall(unix.SYS_IOCTL, getDirFd(dir), C.FS_IOC_FSGETXATTR, uintptr(unsafe.Pointer(&fsx))) if errno != 0 { return fmt.Errorf("Failed to get projid for %s: %v", targetPath, errno.Error()) } fsx.fsx_projid = C.__u32(projectID) fsx.fsx_xflags |= C.FS_XFLAG_PROJINHERIT _, _, errno = unix.Syscall(unix.SYS_IOCTL, getDirFd(dir), C.FS_IOC_FSSETXATTR, uintptr(unsafe.Pointer(&fsx))) if errno != 0 { return fmt.Errorf("Failed to set projid for %s: %v", targetPath, errno.Error()) } return nil }
[ "func", "setProjectID", "(", "targetPath", "string", ",", "projectID", "uint32", ")", "error", "{", "dir", ",", "err", ":=", "openDir", "(", "targetPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "closeDir", ...
// setProjectID - set the project id of path on xfs
[ "setProjectID", "-", "set", "the", "project", "id", "of", "path", "on", "xfs" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/quota/projectquota.go#L244-L266
19,269
containers/storage
drivers/quota/projectquota.go
findNextProjectID
func (q *Control) findNextProjectID(home string) error { files, err := ioutil.ReadDir(home) if err != nil { return fmt.Errorf("read directory failed : %s", home) } for _, file := range files { if !file.IsDir() { continue } path := filepath.Join(home, file.Name()) projid, err := getProjectID(path) if err != nil { return err } if projid > 0 { q.quotas[path] = projid } if q.nextProjectID <= projid { q.nextProjectID = projid + 1 } } return nil }
go
func (q *Control) findNextProjectID(home string) error { files, err := ioutil.ReadDir(home) if err != nil { return fmt.Errorf("read directory failed : %s", home) } for _, file := range files { if !file.IsDir() { continue } path := filepath.Join(home, file.Name()) projid, err := getProjectID(path) if err != nil { return err } if projid > 0 { q.quotas[path] = projid } if q.nextProjectID <= projid { q.nextProjectID = projid + 1 } } return nil }
[ "func", "(", "q", "*", "Control", ")", "findNextProjectID", "(", "home", "string", ")", "error", "{", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "home", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "...
// findNextProjectID - find the next project id to be used for containers // by scanning driver home directory to find used project ids
[ "findNextProjectID", "-", "find", "the", "next", "project", "id", "to", "be", "used", "for", "containers", "by", "scanning", "driver", "home", "directory", "to", "find", "used", "project", "ids" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/quota/projectquota.go#L270-L293
19,270
containers/storage
drivers/template.go
NaiveCreateFromTemplate
func NaiveCreateFromTemplate(d TemplateDriver, id, template string, templateIDMappings *idtools.IDMappings, parent string, parentIDMappings *idtools.IDMappings, opts *CreateOpts, readWrite bool) error { var err error if readWrite { err = d.CreateReadWrite(id, parent, opts) } else { err = d.Create(id, parent, opts) } if err != nil { return err } diff, err := d.Diff(template, templateIDMappings, parent, parentIDMappings, opts.MountLabel) if err != nil { if err2 := d.Remove(id); err2 != nil { logrus.Errorf("error removing layer %q: %v", id, err2) } return err } if _, err = d.ApplyDiff(id, templateIDMappings, parent, opts.MountLabel, diff); err != nil { if err2 := d.Remove(id); err2 != nil { logrus.Errorf("error removing layer %q: %v", id, err2) } return err } return nil }
go
func NaiveCreateFromTemplate(d TemplateDriver, id, template string, templateIDMappings *idtools.IDMappings, parent string, parentIDMappings *idtools.IDMappings, opts *CreateOpts, readWrite bool) error { var err error if readWrite { err = d.CreateReadWrite(id, parent, opts) } else { err = d.Create(id, parent, opts) } if err != nil { return err } diff, err := d.Diff(template, templateIDMappings, parent, parentIDMappings, opts.MountLabel) if err != nil { if err2 := d.Remove(id); err2 != nil { logrus.Errorf("error removing layer %q: %v", id, err2) } return err } if _, err = d.ApplyDiff(id, templateIDMappings, parent, opts.MountLabel, diff); err != nil { if err2 := d.Remove(id); err2 != nil { logrus.Errorf("error removing layer %q: %v", id, err2) } return err } return nil }
[ "func", "NaiveCreateFromTemplate", "(", "d", "TemplateDriver", ",", "id", ",", "template", "string", ",", "templateIDMappings", "*", "idtools", ".", "IDMappings", ",", "parent", "string", ",", "parentIDMappings", "*", "idtools", ".", "IDMappings", ",", "opts", "...
// CreateFromTemplate creates a layer with the same contents and parent as // another layer. Internally, it may even depend on that other layer // continuing to exist, as if it were actually a child of the child layer.
[ "CreateFromTemplate", "creates", "a", "layer", "with", "the", "same", "contents", "and", "parent", "as", "another", "layer", ".", "Internally", "it", "may", "even", "depend", "on", "that", "other", "layer", "continuing", "to", "exist", "as", "if", "it", "wer...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/template.go#L21-L45
19,271
containers/storage
pkg/stringutils/stringutils.go
GenerateRandomASCIIString
func GenerateRandomASCIIString(n int) string { chars := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:` " res := make([]byte, n) for i := 0; i < n; i++ { res[i] = chars[rand.Intn(len(chars))] } return string(res) }
go
func GenerateRandomASCIIString(n int) string { chars := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:` " res := make([]byte, n) for i := 0; i < n; i++ { res[i] = chars[rand.Intn(len(chars))] } return string(res) }
[ "func", "GenerateRandomASCIIString", "(", "n", "int", ")", "string", "{", "chars", ":=", "\"", "\"", "+", "\"", "\"", "+", "\"", "\\\\", "\\\"", "\"", "\n", "res", ":=", "make", "(", "[", "]", "byte", ",", "n", ")", "\n", "for", "i", ":=", "0", ...
// GenerateRandomASCIIString generates an ASCII random string with length n.
[ "GenerateRandomASCIIString", "generates", "an", "ASCII", "random", "string", "with", "length", "n", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/stringutils/stringutils.go#L22-L31
19,272
containers/storage
pkg/stringutils/stringutils.go
Truncate
func Truncate(s string, maxlen int) string { r := []rune(s) if len(r) <= maxlen { return s } return string(r[:maxlen]) }
go
func Truncate(s string, maxlen int) string { r := []rune(s) if len(r) <= maxlen { return s } return string(r[:maxlen]) }
[ "func", "Truncate", "(", "s", "string", ",", "maxlen", "int", ")", "string", "{", "r", ":=", "[", "]", "rune", "(", "s", ")", "\n", "if", "len", "(", "r", ")", "<=", "maxlen", "{", "return", "s", "\n", "}", "\n", "return", "string", "(", "r", ...
// Truncate truncates a string to maxlen.
[ "Truncate", "truncates", "a", "string", "to", "maxlen", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/stringutils/stringutils.go#L47-L53
19,273
containers/storage
pkg/stringutils/stringutils.go
InSlice
func InSlice(slice []string, s string) bool { for _, ss := range slice { if strings.ToLower(s) == strings.ToLower(ss) { return true } } return false }
go
func InSlice(slice []string, s string) bool { for _, ss := range slice { if strings.ToLower(s) == strings.ToLower(ss) { return true } } return false }
[ "func", "InSlice", "(", "slice", "[", "]", "string", ",", "s", "string", ")", "bool", "{", "for", "_", ",", "ss", ":=", "range", "slice", "{", "if", "strings", ".", "ToLower", "(", "s", ")", "==", "strings", ".", "ToLower", "(", "ss", ")", "{", ...
// InSlice tests whether a string is contained in a slice of strings or not. // Comparison is case insensitive
[ "InSlice", "tests", "whether", "a", "string", "is", "contained", "in", "a", "slice", "of", "strings", "or", "not", ".", "Comparison", "is", "case", "insensitive" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/stringutils/stringutils.go#L57-L64
19,274
containers/storage
pkg/stringutils/stringutils.go
ShellQuoteArguments
func ShellQuoteArguments(args []string) string { var buf bytes.Buffer for i, arg := range args { if i != 0 { buf.WriteByte(' ') } quote(arg, &buf) } return buf.String() }
go
func ShellQuoteArguments(args []string) string { var buf bytes.Buffer for i, arg := range args { if i != 0 { buf.WriteByte(' ') } quote(arg, &buf) } return buf.String() }
[ "func", "ShellQuoteArguments", "(", "args", "[", "]", "string", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "i", ",", "arg", ":=", "range", "args", "{", "if", "i", "!=", "0", "{", "buf", ".", "WriteByte", "(", "' '", ")",...
// ShellQuoteArguments takes a list of strings and escapes them so they will be // handled right when passed as arguments to a program via a shell
[ "ShellQuoteArguments", "takes", "a", "list", "of", "strings", "and", "escapes", "them", "so", "they", "will", "be", "handled", "right", "when", "passed", "as", "arguments", "to", "a", "program", "via", "a", "shell" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/stringutils/stringutils.go#L90-L99
19,275
containers/storage
pkg/system/exitcode.go
ProcessExitCode
func ProcessExitCode(err error) (exitCode int) { if err != nil { var exiterr error if exitCode, exiterr = GetExitCode(err); exiterr != nil { // TODO: Fix this so we check the error's text. // we've failed to retrieve exit code, so we set it to 127 exitCode = 127 } } return }
go
func ProcessExitCode(err error) (exitCode int) { if err != nil { var exiterr error if exitCode, exiterr = GetExitCode(err); exiterr != nil { // TODO: Fix this so we check the error's text. // we've failed to retrieve exit code, so we set it to 127 exitCode = 127 } } return }
[ "func", "ProcessExitCode", "(", "err", "error", ")", "(", "exitCode", "int", ")", "{", "if", "err", "!=", "nil", "{", "var", "exiterr", "error", "\n", "if", "exitCode", ",", "exiterr", "=", "GetExitCode", "(", "err", ")", ";", "exiterr", "!=", "nil", ...
// ProcessExitCode process the specified error and returns the exit status code // if the error was of type exec.ExitError, returns nothing otherwise.
[ "ProcessExitCode", "process", "the", "specified", "error", "and", "returns", "the", "exit", "status", "code", "if", "the", "error", "was", "of", "type", "exec", ".", "ExitError", "returns", "nothing", "otherwise", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/system/exitcode.go#L23-L33
19,276
containers/storage
drivers/vfs/driver.go
Create
func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error { return d.create(id, parent, opts, true) }
go
func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error { return d.create(id, parent, opts, true) }
[ "func", "(", "d", "*", "Driver", ")", "Create", "(", "id", ",", "parent", "string", ",", "opts", "*", "graphdriver", ".", "CreateOpts", ")", "error", "{", "return", "d", ".", "create", "(", "id", ",", "parent", ",", "opts", ",", "true", ")", "\n", ...
// Create prepares the filesystem for the VFS driver and copies the directory for the given id under the parent.
[ "Create", "prepares", "the", "filesystem", "for", "the", "VFS", "driver", "and", "copies", "the", "directory", "for", "the", "given", "id", "under", "the", "parent", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/vfs/driver.go#L117-L119
19,277
containers/storage
drivers/vfs/driver.go
AdditionalImageStores
func (d *Driver) AdditionalImageStores() []string { if len(d.homes) > 1 { return d.homes[1:] } return nil }
go
func (d *Driver) AdditionalImageStores() []string { if len(d.homes) > 1 { return d.homes[1:] } return nil }
[ "func", "(", "d", "*", "Driver", ")", "AdditionalImageStores", "(", ")", "[", "]", "string", "{", "if", "len", "(", "d", ".", "homes", ")", ">", "1", "{", "return", "d", ".", "homes", "[", "1", ":", "]", "\n", "}", "\n", "return", "nil", "\n", ...
// AdditionalImageStores returns additional image stores supported by the driver
[ "AdditionalImageStores", "returns", "additional", "image", "stores", "supported", "by", "the", "driver" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/vfs/driver.go#L221-L226
19,278
containers/storage
images.go
recomputeDigests
func (image *Image) recomputeDigests() error { validDigests := make([]digest.Digest, 0, len(image.BigDataDigests)+1) digests := make(map[digest.Digest]struct{}) if image.Digest != "" { if err := image.Digest.Validate(); err != nil { return errors.Wrapf(err, "error validating image digest %q", string(image.Digest)) } digests[image.Digest] = struct{}{} validDigests = append(validDigests, image.Digest) } for name, digest := range image.BigDataDigests { if !bigDataNameIsManifest(name) { continue } if digest.Validate() != nil { return errors.Wrapf(digest.Validate(), "error validating digest %q for big data item %q", string(digest), name) } // Deduplicate the digest values. if _, known := digests[digest]; !known { digests[digest] = struct{}{} validDigests = append(validDigests, digest) } } if image.Digest == "" && len(validDigests) > 0 { image.Digest = validDigests[0] } image.Digests = validDigests return nil }
go
func (image *Image) recomputeDigests() error { validDigests := make([]digest.Digest, 0, len(image.BigDataDigests)+1) digests := make(map[digest.Digest]struct{}) if image.Digest != "" { if err := image.Digest.Validate(); err != nil { return errors.Wrapf(err, "error validating image digest %q", string(image.Digest)) } digests[image.Digest] = struct{}{} validDigests = append(validDigests, image.Digest) } for name, digest := range image.BigDataDigests { if !bigDataNameIsManifest(name) { continue } if digest.Validate() != nil { return errors.Wrapf(digest.Validate(), "error validating digest %q for big data item %q", string(digest), name) } // Deduplicate the digest values. if _, known := digests[digest]; !known { digests[digest] = struct{}{} validDigests = append(validDigests, digest) } } if image.Digest == "" && len(validDigests) > 0 { image.Digest = validDigests[0] } image.Digests = validDigests return nil }
[ "func", "(", "image", "*", "Image", ")", "recomputeDigests", "(", ")", "error", "{", "validDigests", ":=", "make", "(", "[", "]", "digest", ".", "Digest", ",", "0", ",", "len", "(", "image", ".", "BigDataDigests", ")", "+", "1", ")", "\n", "digests",...
// recomputeDigests takes a fixed digest and a name-to-digest map and builds a // list of the unique values that would identify the image.
[ "recomputeDigests", "takes", "a", "fixed", "digest", "and", "a", "name", "-", "to", "-", "digest", "map", "and", "builds", "a", "list", "of", "the", "unique", "values", "that", "would", "identify", "the", "image", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/images.go#L207-L235
19,279
containers/storage
drivers/windows/windows.go
InitFilter
func InitFilter(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) { logrus.Debugf("WindowsGraphDriver InitFilter at %s", home) for _, option := range options { if strings.HasPrefix(option, "windows.mountopt=") { return nil, fmt.Errorf("windows driver does not support mount options") } else { return nil, fmt.Errorf("option %s not supported", option) } } fsType, err := getFileSystemType(string(home[0])) if err != nil { return nil, err } if strings.ToLower(fsType) == "refs" { return nil, fmt.Errorf("%s is on an ReFS volume - ReFS volumes are not supported", home) } if err := idtools.MkdirAllAs(home, 0700, 0, 0); err != nil { return nil, fmt.Errorf("windowsfilter failed to create '%s': %v", home, err) } d := &Driver{ info: hcsshim.DriverInfo{ HomeDir: home, Flavour: filterDriver, }, cache: make(map[string]string), ctr: graphdriver.NewRefCounter(&checker{}), } return d, nil }
go
func InitFilter(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) { logrus.Debugf("WindowsGraphDriver InitFilter at %s", home) for _, option := range options { if strings.HasPrefix(option, "windows.mountopt=") { return nil, fmt.Errorf("windows driver does not support mount options") } else { return nil, fmt.Errorf("option %s not supported", option) } } fsType, err := getFileSystemType(string(home[0])) if err != nil { return nil, err } if strings.ToLower(fsType) == "refs" { return nil, fmt.Errorf("%s is on an ReFS volume - ReFS volumes are not supported", home) } if err := idtools.MkdirAllAs(home, 0700, 0, 0); err != nil { return nil, fmt.Errorf("windowsfilter failed to create '%s': %v", home, err) } d := &Driver{ info: hcsshim.DriverInfo{ HomeDir: home, Flavour: filterDriver, }, cache: make(map[string]string), ctr: graphdriver.NewRefCounter(&checker{}), } return d, nil }
[ "func", "InitFilter", "(", "home", "string", ",", "options", "[", "]", "string", ",", "uidMaps", ",", "gidMaps", "[", "]", "idtools", ".", "IDMap", ")", "(", "graphdriver", ".", "Driver", ",", "error", ")", "{", "logrus", ".", "Debugf", "(", "\"", "\...
// InitFilter returns a new Windows storage filter driver.
[ "InitFilter", "returns", "a", "new", "Windows", "storage", "filter", "driver", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/windows/windows.go#L86-L118
19,280
containers/storage
drivers/windows/windows.go
Put
func (d *Driver) Put(id string) error { panicIfUsedByLcow() logrus.Debugf("WindowsGraphDriver Put() id %s", id) rID, err := d.resolveID(id) if err != nil { return err } if count := d.ctr.Decrement(rID); count > 0 { return nil } d.cacheMu.Lock() _, exists := d.cache[rID] delete(d.cache, rID) d.cacheMu.Unlock() // If the cache was not populated, then the layer was left unprepared and deactivated if !exists { return nil } if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { return err } return hcsshim.DeactivateLayer(d.info, rID) }
go
func (d *Driver) Put(id string) error { panicIfUsedByLcow() logrus.Debugf("WindowsGraphDriver Put() id %s", id) rID, err := d.resolveID(id) if err != nil { return err } if count := d.ctr.Decrement(rID); count > 0 { return nil } d.cacheMu.Lock() _, exists := d.cache[rID] delete(d.cache, rID) d.cacheMu.Unlock() // If the cache was not populated, then the layer was left unprepared and deactivated if !exists { return nil } if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { return err } return hcsshim.DeactivateLayer(d.info, rID) }
[ "func", "(", "d", "*", "Driver", ")", "Put", "(", "id", "string", ")", "error", "{", "panicIfUsedByLcow", "(", ")", "\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "id", ")", "\n\n", "rID", ",", "err", ":=", "d", ".", "resolveID", "(", "id",...
// Put adds a new layer to the driver.
[ "Put", "adds", "a", "new", "layer", "to", "the", "driver", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/windows/windows.go#L432-L457
19,281
containers/storage
drivers/windows/windows.go
Diff
func (d *Driver) Diff(id string, idMappings *idtools.IDMappings, parent string, parentMappings *idtools.IDMappings, mountLabel string) (_ io.ReadCloser, err error) { panicIfUsedByLcow() rID, err := d.resolveID(id) if err != nil { return } layerChain, err := d.getLayerChain(rID) if err != nil { return } // this is assuming that the layer is unmounted if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { return nil, err } prepare := func() { if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil { logrus.Warnf("Failed to Deactivate %s: %s", rID, err) } } arch, err := d.exportLayer(rID, layerChain) if err != nil { prepare() return } return ioutils.NewReadCloserWrapper(arch, func() error { err := arch.Close() prepare() return err }), nil }
go
func (d *Driver) Diff(id string, idMappings *idtools.IDMappings, parent string, parentMappings *idtools.IDMappings, mountLabel string) (_ io.ReadCloser, err error) { panicIfUsedByLcow() rID, err := d.resolveID(id) if err != nil { return } layerChain, err := d.getLayerChain(rID) if err != nil { return } // this is assuming that the layer is unmounted if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { return nil, err } prepare := func() { if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil { logrus.Warnf("Failed to Deactivate %s: %s", rID, err) } } arch, err := d.exportLayer(rID, layerChain) if err != nil { prepare() return } return ioutils.NewReadCloserWrapper(arch, func() error { err := arch.Close() prepare() return err }), nil }
[ "func", "(", "d", "*", "Driver", ")", "Diff", "(", "id", "string", ",", "idMappings", "*", "idtools", ".", "IDMappings", ",", "parent", "string", ",", "parentMappings", "*", "idtools", ".", "IDMappings", ",", "mountLabel", "string", ")", "(", "_", "io", ...
// Diff produces an archive of the changes between the specified // layer and its parent layer which may be "". // The layer should be mounted when calling this function
[ "Diff", "produces", "an", "archive", "of", "the", "changes", "between", "the", "specified", "layer", "and", "its", "parent", "layer", "which", "may", "be", ".", "The", "layer", "should", "be", "mounted", "when", "calling", "this", "function" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/windows/windows.go#L491-L523
19,282
containers/storage
drivers/windows/windows.go
ApplyDiff
func (d *Driver) ApplyDiff(id string, idMappings *idtools.IDMappings, parent, mountLabel string, diff io.Reader) (int64, error) { panicIfUsedByLcow() var layerChain []string if parent != "" { rPId, err := d.resolveID(parent) if err != nil { return 0, err } parentChain, err := d.getLayerChain(rPId) if err != nil { return 0, err } parentPath, err := hcsshim.GetLayerMountPath(d.info, rPId) if err != nil { return 0, err } layerChain = append(layerChain, parentPath) layerChain = append(layerChain, parentChain...) } size, err := d.importLayer(id, diff, layerChain) if err != nil { return 0, err } if err = d.setLayerChain(id, layerChain); err != nil { return 0, err } return size, nil }
go
func (d *Driver) ApplyDiff(id string, idMappings *idtools.IDMappings, parent, mountLabel string, diff io.Reader) (int64, error) { panicIfUsedByLcow() var layerChain []string if parent != "" { rPId, err := d.resolveID(parent) if err != nil { return 0, err } parentChain, err := d.getLayerChain(rPId) if err != nil { return 0, err } parentPath, err := hcsshim.GetLayerMountPath(d.info, rPId) if err != nil { return 0, err } layerChain = append(layerChain, parentPath) layerChain = append(layerChain, parentChain...) } size, err := d.importLayer(id, diff, layerChain) if err != nil { return 0, err } if err = d.setLayerChain(id, layerChain); err != nil { return 0, err } return size, nil }
[ "func", "(", "d", "*", "Driver", ")", "ApplyDiff", "(", "id", "string", ",", "idMappings", "*", "idtools", ".", "IDMappings", ",", "parent", ",", "mountLabel", "string", ",", "diff", "io", ".", "Reader", ")", "(", "int64", ",", "error", ")", "{", "pa...
// ApplyDiff extracts the changeset from the given diff into the // layer with the specified id and parent, returning the size of the // new layer in bytes. // The layer should not be mounted when calling this function
[ "ApplyDiff", "extracts", "the", "changeset", "from", "the", "given", "diff", "into", "the", "layer", "with", "the", "specified", "id", "and", "parent", "returning", "the", "size", "of", "the", "new", "layer", "in", "bytes", ".", "The", "layer", "should", "...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/windows/windows.go#L584-L614
19,283
containers/storage
drivers/windows/windows.go
Metadata
func (d *Driver) Metadata(id string) (map[string]string, error) { panicIfUsedByLcow() m := make(map[string]string) m["dir"] = d.dir(id) return m, nil }
go
func (d *Driver) Metadata(id string) (map[string]string, error) { panicIfUsedByLcow() m := make(map[string]string) m["dir"] = d.dir(id) return m, nil }
[ "func", "(", "d", "*", "Driver", ")", "Metadata", "(", "id", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "panicIfUsedByLcow", "(", ")", "\n", "m", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "...
// Metadata returns custom driver information.
[ "Metadata", "returns", "custom", "driver", "information", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/windows/windows.go#L641-L646
19,284
containers/storage
drivers/windows/windows.go
UpdateLayerIDMap
func (d *Driver) UpdateLayerIDMap(id string, toContainer, toHost *idtools.IDMappings, mountLabel string) error { return fmt.Errorf("windows doesn't support changing ID mappings") }
go
func (d *Driver) UpdateLayerIDMap(id string, toContainer, toHost *idtools.IDMappings, mountLabel string) error { return fmt.Errorf("windows doesn't support changing ID mappings") }
[ "func", "(", "d", "*", "Driver", ")", "UpdateLayerIDMap", "(", "id", "string", ",", "toContainer", ",", "toHost", "*", "idtools", ".", "IDMappings", ",", "mountLabel", "string", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "...
// UpdateLayerIDMap changes ownerships in the layer's filesystem tree from // matching those in toContainer to matching those in toHost.
[ "UpdateLayerIDMap", "changes", "ownerships", "in", "the", "layer", "s", "filesystem", "tree", "from", "matching", "those", "in", "toContainer", "to", "matching", "those", "in", "toHost", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/windows/windows.go#L961-L963
19,285
containers/storage
drivers/devmapper/deviceset.go
cleanupDeletedDevices
func (devices *DeviceSet) cleanupDeletedDevices() error { devices.Lock() // If there are no deleted devices, there is nothing to do. if devices.nrDeletedDevices == 0 { devices.Unlock() return nil } var deletedDevices []*devInfo for _, info := range devices.Devices { if !info.Deleted { continue } logrus.Debugf("devmapper: Found deleted device %s.", info.Hash) deletedDevices = append(deletedDevices, info) } // Delete the deleted devices. DeleteDevice() first takes the info lock // and then devices.Lock(). So drop it to avoid deadlock. devices.Unlock() for _, info := range deletedDevices { // This will again try deferred deletion. if err := devices.DeleteDevice(info.Hash, false); err != nil { logrus.Warnf("devmapper: Deletion of device %s, device_id=%v failed:%v", info.Hash, info.DeviceID, err) } } return nil }
go
func (devices *DeviceSet) cleanupDeletedDevices() error { devices.Lock() // If there are no deleted devices, there is nothing to do. if devices.nrDeletedDevices == 0 { devices.Unlock() return nil } var deletedDevices []*devInfo for _, info := range devices.Devices { if !info.Deleted { continue } logrus.Debugf("devmapper: Found deleted device %s.", info.Hash) deletedDevices = append(deletedDevices, info) } // Delete the deleted devices. DeleteDevice() first takes the info lock // and then devices.Lock(). So drop it to avoid deadlock. devices.Unlock() for _, info := range deletedDevices { // This will again try deferred deletion. if err := devices.DeleteDevice(info.Hash, false); err != nil { logrus.Warnf("devmapper: Deletion of device %s, device_id=%v failed:%v", info.Hash, info.DeviceID, err) } } return nil }
[ "func", "(", "devices", "*", "DeviceSet", ")", "cleanupDeletedDevices", "(", ")", "error", "{", "devices", ".", "Lock", "(", ")", "\n\n", "// If there are no deleted devices, there is nothing to do.", "if", "devices", ".", "nrDeletedDevices", "==", "0", "{", "device...
// Cleanup deleted devices. It assumes that all the devices have been // loaded in the hash table.
[ "Cleanup", "deleted", "devices", ".", "It", "assumes", "that", "all", "the", "devices", "have", "been", "loaded", "in", "the", "hash", "table", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/devmapper/deviceset.go#L658-L689
19,286
containers/storage
drivers/devmapper/deviceset.go
thinPoolExists
func (devices *DeviceSet) thinPoolExists(thinPoolDevice string) (bool, error) { logrus.Debugf("devmapper: Checking for existence of the pool %s", thinPoolDevice) info, err := devicemapper.GetInfo(thinPoolDevice) if err != nil { return false, fmt.Errorf("devmapper: GetInfo() on device %s failed: %v", thinPoolDevice, err) } // Device does not exist. if info.Exists == 0 { return false, nil } _, _, deviceType, _, err := devicemapper.GetStatus(thinPoolDevice) if err != nil { return false, fmt.Errorf("devmapper: GetStatus() on device %s failed: %v", thinPoolDevice, err) } if deviceType != "thin-pool" { return false, fmt.Errorf("devmapper: Device %s is not a thin pool", thinPoolDevice) } return true, nil }
go
func (devices *DeviceSet) thinPoolExists(thinPoolDevice string) (bool, error) { logrus.Debugf("devmapper: Checking for existence of the pool %s", thinPoolDevice) info, err := devicemapper.GetInfo(thinPoolDevice) if err != nil { return false, fmt.Errorf("devmapper: GetInfo() on device %s failed: %v", thinPoolDevice, err) } // Device does not exist. if info.Exists == 0 { return false, nil } _, _, deviceType, _, err := devicemapper.GetStatus(thinPoolDevice) if err != nil { return false, fmt.Errorf("devmapper: GetStatus() on device %s failed: %v", thinPoolDevice, err) } if deviceType != "thin-pool" { return false, fmt.Errorf("devmapper: Device %s is not a thin pool", thinPoolDevice) } return true, nil }
[ "func", "(", "devices", "*", "DeviceSet", ")", "thinPoolExists", "(", "thinPoolDevice", "string", ")", "(", "bool", ",", "error", ")", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "thinPoolDevice", ")", "\n\n", "info", ",", "err", ":=", "devicemap...
// Returns if thin pool device exists or not. If device exists, also makes // sure it is a thin pool device and not some other type of device.
[ "Returns", "if", "thin", "pool", "device", "exists", "or", "not", ".", "If", "device", "exists", "also", "makes", "sure", "it", "is", "a", "thin", "pool", "device", "and", "not", "some", "other", "type", "of", "device", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/devmapper/deviceset.go#L1094-L1117
19,287
containers/storage
drivers/devmapper/deviceset.go
getDeviceMajorMinor
func getDeviceMajorMinor(file *os.File) (uint64, uint64, error) { var stat unix.Stat_t err := unix.Stat(file.Name(), &stat) if err != nil { return 0, 0, err } dev := stat.Rdev majorNum := major(dev) minorNum := minor(dev) logrus.Debugf("devmapper: Major:Minor for device: %s is:%v:%v", file.Name(), majorNum, minorNum) return majorNum, minorNum, nil }
go
func getDeviceMajorMinor(file *os.File) (uint64, uint64, error) { var stat unix.Stat_t err := unix.Stat(file.Name(), &stat) if err != nil { return 0, 0, err } dev := stat.Rdev majorNum := major(dev) minorNum := minor(dev) logrus.Debugf("devmapper: Major:Minor for device: %s is:%v:%v", file.Name(), majorNum, minorNum) return majorNum, minorNum, nil }
[ "func", "getDeviceMajorMinor", "(", "file", "*", "os", ".", "File", ")", "(", "uint64", ",", "uint64", ",", "error", ")", "{", "var", "stat", "unix", ".", "Stat_t", "\n", "err", ":=", "unix", ".", "Stat", "(", "file", ".", "Name", "(", ")", ",", ...
// Determine the major and minor number of loopback device
[ "Determine", "the", "major", "and", "minor", "number", "of", "loopback", "device" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/devmapper/deviceset.go#L1534-L1547
19,288
containers/storage
drivers/devmapper/deviceset.go
issueDiscard
func (devices *DeviceSet) issueDiscard(info *devInfo) error { logrus.Debugf("devmapper: issueDiscard START(device: %s).", info.Hash) defer logrus.Debugf("devmapper: issueDiscard END(device: %s).", info.Hash) // This is a workaround for the kernel not discarding block so // on the thin pool when we remove a thinp device, so we do it // manually. // Even if device is deferred deleted, activate it and issue // discards. if err := devices.activateDeviceIfNeeded(info, true); err != nil { return err } devinfo, err := devicemapper.GetInfo(info.Name()) if err != nil { return err } if devinfo.OpenCount != 0 { logrus.Debugf("devmapper: Device: %s is in use. OpenCount=%d. Not issuing discards.", info.Hash, devinfo.OpenCount) return nil } if err := devicemapper.BlockDeviceDiscard(info.DevName()); err != nil { logrus.Debugf("devmapper: Error discarding block on device: %s (ignoring)", err) } return nil }
go
func (devices *DeviceSet) issueDiscard(info *devInfo) error { logrus.Debugf("devmapper: issueDiscard START(device: %s).", info.Hash) defer logrus.Debugf("devmapper: issueDiscard END(device: %s).", info.Hash) // This is a workaround for the kernel not discarding block so // on the thin pool when we remove a thinp device, so we do it // manually. // Even if device is deferred deleted, activate it and issue // discards. if err := devices.activateDeviceIfNeeded(info, true); err != nil { return err } devinfo, err := devicemapper.GetInfo(info.Name()) if err != nil { return err } if devinfo.OpenCount != 0 { logrus.Debugf("devmapper: Device: %s is in use. OpenCount=%d. Not issuing discards.", info.Hash, devinfo.OpenCount) return nil } if err := devicemapper.BlockDeviceDiscard(info.DevName()); err != nil { logrus.Debugf("devmapper: Error discarding block on device: %s (ignoring)", err) } return nil }
[ "func", "(", "devices", "*", "DeviceSet", ")", "issueDiscard", "(", "info", "*", "devInfo", ")", "error", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "info", ".", "Hash", ")", "\n", "defer", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "i...
// Issue discard only if device open count is zero.
[ "Issue", "discard", "only", "if", "device", "open", "count", "is", "zero", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/devmapper/deviceset.go#L2044-L2070
19,289
containers/storage
store.go
GetDigestLock
func (s *store) GetDigestLock(d digest.Digest) (Locker, error) { return GetLockfile(filepath.Join(s.digestLockRoot, d.String())) }
go
func (s *store) GetDigestLock(d digest.Digest) (Locker, error) { return GetLockfile(filepath.Join(s.digestLockRoot, d.String())) }
[ "func", "(", "s", "*", "store", ")", "GetDigestLock", "(", "d", "digest", ".", "Digest", ")", "(", "Locker", ",", "error", ")", "{", "return", "GetLockfile", "(", "filepath", ".", "Join", "(", "s", ".", "digestLockRoot", ",", "d", ".", "String", "(",...
// GetDigestLock returns a digest-specific Locker.
[ "GetDigestLock", "returns", "a", "digest", "-", "specific", "Locker", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/store.go#L715-L717
19,290
containers/storage
store.go
LayerStore
func (s *store) LayerStore() (LayerStore, error) { s.graphLock.Lock() defer s.graphLock.Unlock() if s.graphLock.TouchedSince(s.lastLoaded) { s.graphDriver = nil s.layerStore = nil s.lastLoaded = time.Now() } if s.layerStore != nil { return s.layerStore, nil } driver, err := s.getGraphDriver() if err != nil { return nil, err } driverPrefix := s.graphDriverName + "-" rlpath := filepath.Join(s.runRoot, driverPrefix+"layers") if err := os.MkdirAll(rlpath, 0700); err != nil { return nil, err } glpath := filepath.Join(s.graphRoot, driverPrefix+"layers") if err := os.MkdirAll(glpath, 0700); err != nil { return nil, err } rls, err := newLayerStore(rlpath, glpath, driver, s.uidMap, s.gidMap) if err != nil { return nil, err } s.layerStore = rls return s.layerStore, nil }
go
func (s *store) LayerStore() (LayerStore, error) { s.graphLock.Lock() defer s.graphLock.Unlock() if s.graphLock.TouchedSince(s.lastLoaded) { s.graphDriver = nil s.layerStore = nil s.lastLoaded = time.Now() } if s.layerStore != nil { return s.layerStore, nil } driver, err := s.getGraphDriver() if err != nil { return nil, err } driverPrefix := s.graphDriverName + "-" rlpath := filepath.Join(s.runRoot, driverPrefix+"layers") if err := os.MkdirAll(rlpath, 0700); err != nil { return nil, err } glpath := filepath.Join(s.graphRoot, driverPrefix+"layers") if err := os.MkdirAll(glpath, 0700); err != nil { return nil, err } rls, err := newLayerStore(rlpath, glpath, driver, s.uidMap, s.gidMap) if err != nil { return nil, err } s.layerStore = rls return s.layerStore, nil }
[ "func", "(", "s", "*", "store", ")", "LayerStore", "(", ")", "(", "LayerStore", ",", "error", ")", "{", "s", ".", "graphLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "graphLock", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "graphLock"...
// LayerStore obtains and returns a handle to the writeable layer store object // used by the Store. Accessing this store directly will bypass locking and // synchronization, so it is not a part of the exported Store interface.
[ "LayerStore", "obtains", "and", "returns", "a", "handle", "to", "the", "writeable", "layer", "store", "object", "used", "by", "the", "Store", ".", "Accessing", "this", "store", "directly", "will", "bypass", "locking", "and", "synchronization", "so", "it", "is"...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/store.go#L752-L782
19,291
containers/storage
store.go
ImageStore
func (s *store) ImageStore() (ImageStore, error) { if s.imageStore != nil { return s.imageStore, nil } return nil, ErrLoadError }
go
func (s *store) ImageStore() (ImageStore, error) { if s.imageStore != nil { return s.imageStore, nil } return nil, ErrLoadError }
[ "func", "(", "s", "*", "store", ")", "ImageStore", "(", ")", "(", "ImageStore", ",", "error", ")", "{", "if", "s", ".", "imageStore", "!=", "nil", "{", "return", "s", ".", "imageStore", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "ErrLoadErr...
// ImageStore obtains and returns a handle to the writable image store object // used by the Store. Accessing this store directly will bypass locking and // synchronization, so it is not a part of the exported Store interface.
[ "ImageStore", "obtains", "and", "returns", "a", "handle", "to", "the", "writable", "image", "store", "object", "used", "by", "the", "Store", ".", "Accessing", "this", "store", "directly", "will", "bypass", "locking", "and", "synchronization", "so", "it", "is",...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/store.go#L816-L821
19,292
containers/storage
store.go
ContainerStore
func (s *store) ContainerStore() (ContainerStore, error) { if s.containerStore != nil { return s.containerStore, nil } return nil, ErrLoadError }
go
func (s *store) ContainerStore() (ContainerStore, error) { if s.containerStore != nil { return s.containerStore, nil } return nil, ErrLoadError }
[ "func", "(", "s", "*", "store", ")", "ContainerStore", "(", ")", "(", "ContainerStore", ",", "error", ")", "{", "if", "s", ".", "containerStore", "!=", "nil", "{", "return", "s", ".", "containerStore", ",", "nil", "\n", "}", "\n", "return", "nil", ",...
// ContainerStore obtains and returns a handle to the container store object // used by the Store. Accessing this store directly will bypass locking and // synchronization, so it is not a part of the exported Store interface.
[ "ContainerStore", "obtains", "and", "returns", "a", "handle", "to", "the", "container", "store", "object", "used", "by", "the", "Store", ".", "Accessing", "this", "store", "directly", "will", "bypass", "locking", "and", "synchronization", "so", "it", "is", "no...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/store.go#L849-L854
19,293
containers/storage
store.go
makeBigDataBaseName
func makeBigDataBaseName(key string) string { reader := strings.NewReader(key) for reader.Len() > 0 { ch, size, err := reader.ReadRune() if err != nil || size != 1 { break } if ch != '.' && !(ch >= '0' && ch <= '9') && !(ch >= 'a' && ch <= 'z') { break } } if reader.Len() > 0 { return "=" + base64.StdEncoding.EncodeToString([]byte(key)) } return key }
go
func makeBigDataBaseName(key string) string { reader := strings.NewReader(key) for reader.Len() > 0 { ch, size, err := reader.ReadRune() if err != nil || size != 1 { break } if ch != '.' && !(ch >= '0' && ch <= '9') && !(ch >= 'a' && ch <= 'z') { break } } if reader.Len() > 0 { return "=" + base64.StdEncoding.EncodeToString([]byte(key)) } return key }
[ "func", "makeBigDataBaseName", "(", "key", "string", ")", "string", "{", "reader", ":=", "strings", ".", "NewReader", "(", "key", ")", "\n", "for", "reader", ".", "Len", "(", ")", ">", "0", "{", "ch", ",", "size", ",", "err", ":=", "reader", ".", "...
// Convert a BigData key name into an acceptable file name.
[ "Convert", "a", "BigData", "key", "name", "into", "an", "acceptable", "file", "name", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/store.go#L3167-L3182
19,294
containers/storage
store.go
DefaultConfigFile
func DefaultConfigFile(rootless bool) (string, error) { if rootless { home, err := homeDir() if err != nil { return "", errors.Wrapf(err, "cannot determine users homedir") } return filepath.Join(home, ".config/containers/storage.conf"), nil } return defaultConfigFile, nil }
go
func DefaultConfigFile(rootless bool) (string, error) { if rootless { home, err := homeDir() if err != nil { return "", errors.Wrapf(err, "cannot determine users homedir") } return filepath.Join(home, ".config/containers/storage.conf"), nil } return defaultConfigFile, nil }
[ "func", "DefaultConfigFile", "(", "rootless", "bool", ")", "(", "string", ",", "error", ")", "{", "if", "rootless", "{", "home", ",", "err", ":=", "homeDir", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "...
// DefaultConfigFile returns the path to the storage config file used
[ "DefaultConfigFile", "returns", "the", "path", "to", "the", "storage", "config", "file", "used" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/store.go#L3243-L3252
19,295
containers/storage
pkg/archive/changes_linux.go
walkchunk
func walkchunk(path string, fi os.FileInfo, dir string, root *FileInfo) error { if fi == nil { return nil } parent := root.LookUp(filepath.Dir(path)) if parent == nil { return fmt.Errorf("walkchunk: Unexpectedly no parent for %s", path) } info := &FileInfo{ name: filepath.Base(path), children: make(map[string]*FileInfo), parent: parent, idMappings: root.idMappings, } cpath := filepath.Join(dir, path) stat, err := system.FromStatT(fi.Sys().(*syscall.Stat_t)) if err != nil { return err } info.stat = stat info.capability, _ = system.Lgetxattr(cpath, "security.capability") // lgetxattr(2): fs access parent.children[info.name] = info return nil }
go
func walkchunk(path string, fi os.FileInfo, dir string, root *FileInfo) error { if fi == nil { return nil } parent := root.LookUp(filepath.Dir(path)) if parent == nil { return fmt.Errorf("walkchunk: Unexpectedly no parent for %s", path) } info := &FileInfo{ name: filepath.Base(path), children: make(map[string]*FileInfo), parent: parent, idMappings: root.idMappings, } cpath := filepath.Join(dir, path) stat, err := system.FromStatT(fi.Sys().(*syscall.Stat_t)) if err != nil { return err } info.stat = stat info.capability, _ = system.Lgetxattr(cpath, "security.capability") // lgetxattr(2): fs access parent.children[info.name] = info return nil }
[ "func", "walkchunk", "(", "path", "string", ",", "fi", "os", ".", "FileInfo", ",", "dir", "string", ",", "root", "*", "FileInfo", ")", "error", "{", "if", "fi", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "parent", ":=", "root", ".", "LookU...
// Given a FileInfo, its path info, and a reference to the root of the tree // being constructed, register this file with the tree.
[ "Given", "a", "FileInfo", "its", "path", "info", "and", "a", "reference", "to", "the", "root", "of", "the", "tree", "being", "constructed", "register", "this", "file", "with", "the", "tree", "." ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/archive/changes_linux.go#L66-L89
19,296
containers/storage
pkg/archive/diff.go
ApplyLayer
func ApplyLayer(dest string, layer io.Reader) (int64, error) { return applyLayerHandler(dest, layer, &TarOptions{}, true) }
go
func ApplyLayer(dest string, layer io.Reader) (int64, error) { return applyLayerHandler(dest, layer, &TarOptions{}, true) }
[ "func", "ApplyLayer", "(", "dest", "string", ",", "layer", "io", ".", "Reader", ")", "(", "int64", ",", "error", ")", "{", "return", "applyLayerHandler", "(", "dest", ",", "layer", ",", "&", "TarOptions", "{", "}", ",", "true", ")", "\n", "}" ]
// ApplyLayer parses a diff in the standard layer format from `layer`, // and applies it to the directory `dest`. The stream `layer` can be // compressed or uncompressed. // Returns the size in bytes of the contents of the layer.
[ "ApplyLayer", "parses", "a", "diff", "in", "the", "standard", "layer", "format", "from", "layer", "and", "applies", "it", "to", "the", "directory", "dest", ".", "The", "stream", "layer", "can", "be", "compressed", "or", "uncompressed", ".", "Returns", "the",...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/archive/diff.go#L226-L228
19,297
containers/storage
pkg/archive/diff.go
applyLayerHandler
func applyLayerHandler(dest string, layer io.Reader, options *TarOptions, decompress bool) (int64, error) { dest = filepath.Clean(dest) // We need to be able to set any perms oldmask, err := system.Umask(0) if err != nil { return 0, err } defer system.Umask(oldmask) // ignore err, ErrNotSupportedPlatform if decompress { layer, err = DecompressStream(layer) if err != nil { return 0, err } } return UnpackLayer(dest, layer, options) }
go
func applyLayerHandler(dest string, layer io.Reader, options *TarOptions, decompress bool) (int64, error) { dest = filepath.Clean(dest) // We need to be able to set any perms oldmask, err := system.Umask(0) if err != nil { return 0, err } defer system.Umask(oldmask) // ignore err, ErrNotSupportedPlatform if decompress { layer, err = DecompressStream(layer) if err != nil { return 0, err } } return UnpackLayer(dest, layer, options) }
[ "func", "applyLayerHandler", "(", "dest", "string", ",", "layer", "io", ".", "Reader", ",", "options", "*", "TarOptions", ",", "decompress", "bool", ")", "(", "int64", ",", "error", ")", "{", "dest", "=", "filepath", ".", "Clean", "(", "dest", ")", "\n...
// do the bulk load of ApplyLayer, but allow for not calling DecompressStream
[ "do", "the", "bulk", "load", "of", "ApplyLayer", "but", "allow", "for", "not", "calling", "DecompressStream" ]
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/pkg/archive/diff.go#L239-L256
19,298
containers/storage
drivers/chown.go
ChownPathByMaps
func ChownPathByMaps(path string, toContainer, toHost *idtools.IDMappings) error { if toContainer == nil { toContainer = &idtools.IDMappings{} } if toHost == nil { toHost = &idtools.IDMappings{} } config, err := json.Marshal([4][]idtools.IDMap{toContainer.UIDs(), toContainer.GIDs(), toHost.UIDs(), toHost.GIDs()}) if err != nil { return err } cmd := reexec.Command(chownByMapsCmd, path) cmd.Stdin = bytes.NewReader(config) output, err := cmd.CombinedOutput() if len(output) > 0 && err != nil { return fmt.Errorf("%v: %s", err, string(output)) } if err != nil { return err } if len(output) > 0 { return fmt.Errorf("%s", string(output)) } return nil }
go
func ChownPathByMaps(path string, toContainer, toHost *idtools.IDMappings) error { if toContainer == nil { toContainer = &idtools.IDMappings{} } if toHost == nil { toHost = &idtools.IDMappings{} } config, err := json.Marshal([4][]idtools.IDMap{toContainer.UIDs(), toContainer.GIDs(), toHost.UIDs(), toHost.GIDs()}) if err != nil { return err } cmd := reexec.Command(chownByMapsCmd, path) cmd.Stdin = bytes.NewReader(config) output, err := cmd.CombinedOutput() if len(output) > 0 && err != nil { return fmt.Errorf("%v: %s", err, string(output)) } if err != nil { return err } if len(output) > 0 { return fmt.Errorf("%s", string(output)) } return nil }
[ "func", "ChownPathByMaps", "(", "path", "string", ",", "toContainer", ",", "toHost", "*", "idtools", ".", "IDMappings", ")", "error", "{", "if", "toContainer", "==", "nil", "{", "toContainer", "=", "&", "idtools", ".", "IDMappings", "{", "}", "\n", "}", ...
// ChownPathByMaps walks the filesystem tree, changing the ownership // information using the toContainer and toHost mappings, using them to replace // on-disk owner UIDs and GIDs which are "host" values in the first map with // UIDs and GIDs for "host" values from the second map which correspond to the // same "container" IDs.
[ "ChownPathByMaps", "walks", "the", "filesystem", "tree", "changing", "the", "ownership", "information", "using", "the", "toContainer", "and", "toHost", "mappings", "using", "them", "to", "replace", "on", "-", "disk", "owner", "UIDs", "and", "GIDs", "which", "are...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/chown.go#L72-L98
19,299
containers/storage
drivers/chown.go
UpdateLayerIDMap
func (n *naiveLayerIDMapUpdater) UpdateLayerIDMap(id string, toContainer, toHost *idtools.IDMappings, mountLabel string) error { driver := n.ProtoDriver options := MountOpts{ MountLabel: mountLabel, } layerFs, err := driver.Get(id, options) if err != nil { return err } defer func() { driver.Put(id) }() return ChownPathByMaps(layerFs, toContainer, toHost) }
go
func (n *naiveLayerIDMapUpdater) UpdateLayerIDMap(id string, toContainer, toHost *idtools.IDMappings, mountLabel string) error { driver := n.ProtoDriver options := MountOpts{ MountLabel: mountLabel, } layerFs, err := driver.Get(id, options) if err != nil { return err } defer func() { driver.Put(id) }() return ChownPathByMaps(layerFs, toContainer, toHost) }
[ "func", "(", "n", "*", "naiveLayerIDMapUpdater", ")", "UpdateLayerIDMap", "(", "id", "string", ",", "toContainer", ",", "toHost", "*", "idtools", ".", "IDMappings", ",", "mountLabel", "string", ")", "error", "{", "driver", ":=", "n", ".", "ProtoDriver", "\n"...
// UpdateLayerIDMap walks the layer's filesystem tree, changing the ownership // information using the toContainer and toHost mappings, using them to replace // on-disk owner UIDs and GIDs which are "host" values in the first map with // UIDs and GIDs for "host" values from the second map which correspond to the // same "container" IDs.
[ "UpdateLayerIDMap", "walks", "the", "layer", "s", "filesystem", "tree", "changing", "the", "ownership", "information", "using", "the", "toContainer", "and", "toHost", "mappings", "using", "them", "to", "replace", "on", "-", "disk", "owner", "UIDs", "and", "GIDs"...
94f0324a5d0c063ffa4adb04361dc2f863b17e05
https://github.com/containers/storage/blob/94f0324a5d0c063ffa4adb04361dc2f863b17e05/drivers/chown.go#L115-L129