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
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
3,000
apcera/util
hashutil/sha256util.go
IsSha256Valid
func IsSha256Valid(s string) bool { if len(s) != 64 { return false } b, err := hex.DecodeString(s) if err != nil { return false } if len(b) != 32 { return false } return true }
go
func IsSha256Valid(s string) bool { if len(s) != 64 { return false } b, err := hex.DecodeString(s) if err != nil { return false } if len(b) != 32 { return false } return true }
[ "func", "IsSha256Valid", "(", "s", "string", ")", "bool", "{", "if", "len", "(", "s", ")", "!=", "64", "{", "return", "false", "\n", "}", "\n", "b", ",", "err", ":=", "hex", ".", "DecodeString", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "b", ")", "!=", "32", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Simple function that allows verification that a string is in fact a valid // SHA256 formated string.
[ "Simple", "function", "that", "allows", "verification", "that", "a", "string", "is", "in", "fact", "a", "valid", "SHA256", "formated", "string", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/sha256util.go#L13-L25
3,001
apcera/util
hashutil/sha256util.go
NewSha256
func NewSha256(r io.Reader) *Sha256Reader { s := new(Sha256Reader) s.hashReader = newHashReader(sha256.New(), r) return s }
go
func NewSha256(r io.Reader) *Sha256Reader { s := new(Sha256Reader) s.hashReader = newHashReader(sha256.New(), r) return s }
[ "func", "NewSha256", "(", "r", "io", ".", "Reader", ")", "*", "Sha256Reader", "{", "s", ":=", "new", "(", "Sha256Reader", ")", "\n", "s", ".", "hashReader", "=", "newHashReader", "(", "sha256", ".", "New", "(", ")", ",", "r", ")", "\n", "return", "s", "\n", "}" ]
// Returns a new Sha256Reader.
[ "Returns", "a", "new", "Sha256Reader", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/sha256util.go#L34-L38
3,002
apcera/util
hashutil/sha256util.go
Sha256
func (s *Sha256Reader) Sha256() string { return hex.EncodeToString(s.hash.Sum(nil)) }
go
func (s *Sha256Reader) Sha256() string { return hex.EncodeToString(s.hash.Sum(nil)) }
[ "func", "(", "s", "*", "Sha256Reader", ")", "Sha256", "(", ")", "string", "{", "return", "hex", ".", "EncodeToString", "(", "s", ".", "hash", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// Returns the SHA256 for all data that has been passed through this Reader // already. This should ideally be called after the Reader is Closed, but // otherwise its safe to call any time.
[ "Returns", "the", "SHA256", "for", "all", "data", "that", "has", "been", "passed", "through", "this", "Reader", "already", ".", "This", "should", "ideally", "be", "called", "after", "the", "Reader", "is", "Closed", "but", "otherwise", "its", "safe", "to", "call", "any", "time", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/sha256util.go#L43-L45
3,003
apcera/util
wsconn/websocket_connection.go
NewWebsocketConnection
func NewWebsocketConnection(ws Conn) net.Conn { wsconn := &WebsocketConnection{ ws: ws, readTimeout: 60 * time.Second, writeTimeout: 10 * time.Second, pingInterval: 10 * time.Second, closedChan: make(chan bool), textChan: make(chan []byte, 100), } wsconn.startPingInterval() return wsconn }
go
func NewWebsocketConnection(ws Conn) net.Conn { wsconn := &WebsocketConnection{ ws: ws, readTimeout: 60 * time.Second, writeTimeout: 10 * time.Second, pingInterval: 10 * time.Second, closedChan: make(chan bool), textChan: make(chan []byte, 100), } wsconn.startPingInterval() return wsconn }
[ "func", "NewWebsocketConnection", "(", "ws", "Conn", ")", "net", ".", "Conn", "{", "wsconn", ":=", "&", "WebsocketConnection", "{", "ws", ":", "ws", ",", "readTimeout", ":", "60", "*", "time", ".", "Second", ",", "writeTimeout", ":", "10", "*", "time", ".", "Second", ",", "pingInterval", ":", "10", "*", "time", ".", "Second", ",", "closedChan", ":", "make", "(", "chan", "bool", ")", ",", "textChan", ":", "make", "(", "chan", "[", "]", "byte", ",", "100", ")", ",", "}", "\n", "wsconn", ".", "startPingInterval", "(", ")", "\n", "return", "wsconn", "\n", "}" ]
// Returns a websocket connection wrapper to the net.Conn interface.
[ "Returns", "a", "websocket", "connection", "wrapper", "to", "the", "net", ".", "Conn", "interface", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/wsconn/websocket_connection.go#L32-L43
3,004
apcera/util
wsconn/websocket_connection.go
startPingInterval
func (conn *WebsocketConnection) startPingInterval() { go func() { for { select { case <-conn.closedChan: return case <-time.After(conn.pingInterval): func() { conn.writeMutex.Lock() defer conn.writeMutex.Unlock() conn.ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(conn.writeTimeout)) }() } } }() }
go
func (conn *WebsocketConnection) startPingInterval() { go func() { for { select { case <-conn.closedChan: return case <-time.After(conn.pingInterval): func() { conn.writeMutex.Lock() defer conn.writeMutex.Unlock() conn.ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(conn.writeTimeout)) }() } } }() }
[ "func", "(", "conn", "*", "WebsocketConnection", ")", "startPingInterval", "(", ")", "{", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "conn", ".", "closedChan", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "conn", ".", "pingInterval", ")", ":", "func", "(", ")", "{", "conn", ".", "writeMutex", ".", "Lock", "(", ")", "\n", "defer", "conn", ".", "writeMutex", ".", "Unlock", "(", ")", "\n", "conn", ".", "ws", ".", "WriteControl", "(", "websocket", ".", "PingMessage", ",", "[", "]", "byte", "{", "}", ",", "time", ".", "Now", "(", ")", ".", "Add", "(", "conn", ".", "writeTimeout", ")", ")", "\n", "}", "(", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// Begins a goroutine to send a periodic ping to the other end
[ "Begins", "a", "goroutine", "to", "send", "a", "periodic", "ping", "to", "the", "other", "end" ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/wsconn/websocket_connection.go#L59-L74
3,005
apcera/util
wsconn/websocket_connection.go
waitForReader
func (conn *WebsocketConnection) waitForReader() error { // no existing readers, wait for one for { opCode, reader, err := conn.ws.NextReader() if err != nil { return err } switch opCode { case websocket.BinaryMessage: // binary packet conn.reader = reader return nil case websocket.TextMessage: // plain text package b, err := ioutil.ReadAll(reader) if err == nil { conn.textChan <- b } case websocket.PingMessage: // receeived a ping, so send a pong go func() { conn.writeMutex.Lock() defer conn.writeMutex.Unlock() conn.ws.WriteControl(websocket.PongMessage, []byte{}, time.Now().Add(conn.writeTimeout)) }() case websocket.PongMessage: // received a pong, update read deadline conn.ws.SetReadDeadline(time.Now().Add(conn.readTimeout)) case websocket.CloseMessage: // received close, so return EOF return io.EOF } } }
go
func (conn *WebsocketConnection) waitForReader() error { // no existing readers, wait for one for { opCode, reader, err := conn.ws.NextReader() if err != nil { return err } switch opCode { case websocket.BinaryMessage: // binary packet conn.reader = reader return nil case websocket.TextMessage: // plain text package b, err := ioutil.ReadAll(reader) if err == nil { conn.textChan <- b } case websocket.PingMessage: // receeived a ping, so send a pong go func() { conn.writeMutex.Lock() defer conn.writeMutex.Unlock() conn.ws.WriteControl(websocket.PongMessage, []byte{}, time.Now().Add(conn.writeTimeout)) }() case websocket.PongMessage: // received a pong, update read deadline conn.ws.SetReadDeadline(time.Now().Add(conn.readTimeout)) case websocket.CloseMessage: // received close, so return EOF return io.EOF } } }
[ "func", "(", "conn", "*", "WebsocketConnection", ")", "waitForReader", "(", ")", "error", "{", "// no existing readers, wait for one", "for", "{", "opCode", ",", "reader", ",", "err", ":=", "conn", ".", "ws", ".", "NextReader", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "switch", "opCode", "{", "case", "websocket", ".", "BinaryMessage", ":", "// binary packet", "conn", ".", "reader", "=", "reader", "\n", "return", "nil", "\n\n", "case", "websocket", ".", "TextMessage", ":", "// plain text package", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "reader", ")", "\n", "if", "err", "==", "nil", "{", "conn", ".", "textChan", "<-", "b", "\n", "}", "\n\n", "case", "websocket", ".", "PingMessage", ":", "// receeived a ping, so send a pong", "go", "func", "(", ")", "{", "conn", ".", "writeMutex", ".", "Lock", "(", ")", "\n", "defer", "conn", ".", "writeMutex", ".", "Unlock", "(", ")", "\n", "conn", ".", "ws", ".", "WriteControl", "(", "websocket", ".", "PongMessage", ",", "[", "]", "byte", "{", "}", ",", "time", ".", "Now", "(", ")", ".", "Add", "(", "conn", ".", "writeTimeout", ")", ")", "\n", "}", "(", ")", "\n\n", "case", "websocket", ".", "PongMessage", ":", "// received a pong, update read deadline", "conn", ".", "ws", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "conn", ".", "readTimeout", ")", ")", "\n\n", "case", "websocket", ".", "CloseMessage", ":", "// received close, so return EOF", "return", "io", ".", "EOF", "\n", "}", "\n", "}", "\n", "}" ]
// This method loops until a binary opcode comes in and returns its reader. // While looping it will receive and process other opcodes, such as pings.
[ "This", "method", "loops", "until", "a", "binary", "opcode", "comes", "in", "and", "returns", "its", "reader", ".", "While", "looping", "it", "will", "receive", "and", "process", "other", "opcodes", "such", "as", "pings", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/wsconn/websocket_connection.go#L78-L116
3,006
apcera/util
wsconn/websocket_connection.go
Read
func (conn *WebsocketConnection) Read(b []byte) (n int, err error) { if conn.reader == nil { err = conn.waitForReader() if err != nil { return } } rn, rerr := conn.reader.Read(b) switch rerr { case io.EOF: conn.reader = nil default: n, err = rn, rerr } return }
go
func (conn *WebsocketConnection) Read(b []byte) (n int, err error) { if conn.reader == nil { err = conn.waitForReader() if err != nil { return } } rn, rerr := conn.reader.Read(b) switch rerr { case io.EOF: conn.reader = nil default: n, err = rn, rerr } return }
[ "func", "(", "conn", "*", "WebsocketConnection", ")", "Read", "(", "b", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "conn", ".", "reader", "==", "nil", "{", "err", "=", "conn", ".", "waitForReader", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "rn", ",", "rerr", ":=", "conn", ".", "reader", ".", "Read", "(", "b", ")", "\n", "switch", "rerr", "{", "case", "io", ".", "EOF", ":", "conn", ".", "reader", "=", "nil", "\n", "default", ":", "n", ",", "err", "=", "rn", ",", "rerr", "\n", "}", "\n", "return", "\n", "}" ]
// Reads slice of bytes off of the websocket connection.
[ "Reads", "slice", "of", "bytes", "off", "of", "the", "websocket", "connection", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/wsconn/websocket_connection.go#L125-L141
3,007
apcera/util
wsconn/websocket_connection.go
Write
func (conn *WebsocketConnection) Write(b []byte) (n int, err error) { conn.writeMutex.Lock() defer conn.writeMutex.Unlock() // allocate a writer var writer io.WriteCloser writer, err = conn.ws.NextWriter(websocket.BinaryMessage) if err != nil { return } // write n, err = writer.Write(b) if err != nil { return } // close it err = writer.Close() return }
go
func (conn *WebsocketConnection) Write(b []byte) (n int, err error) { conn.writeMutex.Lock() defer conn.writeMutex.Unlock() // allocate a writer var writer io.WriteCloser writer, err = conn.ws.NextWriter(websocket.BinaryMessage) if err != nil { return } // write n, err = writer.Write(b) if err != nil { return } // close it err = writer.Close() return }
[ "func", "(", "conn", "*", "WebsocketConnection", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "conn", ".", "writeMutex", ".", "Lock", "(", ")", "\n", "defer", "conn", ".", "writeMutex", ".", "Unlock", "(", ")", "\n\n", "// allocate a writer", "var", "writer", "io", ".", "WriteCloser", "\n", "writer", ",", "err", "=", "conn", ".", "ws", ".", "NextWriter", "(", "websocket", ".", "BinaryMessage", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// write", "n", ",", "err", "=", "writer", ".", "Write", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// close it", "err", "=", "writer", ".", "Close", "(", ")", "\n", "return", "\n", "}" ]
// Writes the given bytes as a binary opcode segment onto the websocket.
[ "Writes", "the", "given", "bytes", "as", "a", "binary", "opcode", "segment", "onto", "the", "websocket", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/wsconn/websocket_connection.go#L144-L164
3,008
apcera/util
wsconn/websocket_connection.go
Close
func (conn *WebsocketConnection) Close() error { defer close(conn.closedChan) defer close(conn.textChan) return conn.ws.Close() }
go
func (conn *WebsocketConnection) Close() error { defer close(conn.closedChan) defer close(conn.textChan) return conn.ws.Close() }
[ "func", "(", "conn", "*", "WebsocketConnection", ")", "Close", "(", ")", "error", "{", "defer", "close", "(", "conn", ".", "closedChan", ")", "\n", "defer", "close", "(", "conn", ".", "textChan", ")", "\n", "return", "conn", ".", "ws", ".", "Close", "(", ")", "\n", "}" ]
// Closes the connection and exits from the ping loop.
[ "Closes", "the", "connection", "and", "exits", "from", "the", "ping", "loop", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/wsconn/websocket_connection.go#L167-L171
3,009
apcera/util
wsconn/websocket_connection.go
SetDeadline
func (conn *WebsocketConnection) SetDeadline(t time.Time) error { if err := conn.ws.SetReadDeadline(t); err != nil { return err } return conn.ws.SetWriteDeadline(t) }
go
func (conn *WebsocketConnection) SetDeadline(t time.Time) error { if err := conn.ws.SetReadDeadline(t); err != nil { return err } return conn.ws.SetWriteDeadline(t) }
[ "func", "(", "conn", "*", "WebsocketConnection", ")", "SetDeadline", "(", "t", "time", ".", "Time", ")", "error", "{", "if", "err", ":=", "conn", ".", "ws", ".", "SetReadDeadline", "(", "t", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "conn", ".", "ws", ".", "SetWriteDeadline", "(", "t", ")", "\n", "}" ]
// SetDeadline the read and write deadlines associated with the connection.
[ "SetDeadline", "the", "read", "and", "write", "deadlines", "associated", "with", "the", "connection", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/wsconn/websocket_connection.go#L184-L189
3,010
apcera/util
wsconn/websocket_connection.go
SetReadDeadline
func (conn *WebsocketConnection) SetReadDeadline(t time.Time) error { return conn.ws.SetReadDeadline(t) }
go
func (conn *WebsocketConnection) SetReadDeadline(t time.Time) error { return conn.ws.SetReadDeadline(t) }
[ "func", "(", "conn", "*", "WebsocketConnection", ")", "SetReadDeadline", "(", "t", "time", ".", "Time", ")", "error", "{", "return", "conn", ".", "ws", ".", "SetReadDeadline", "(", "t", ")", "\n", "}" ]
// SetReadDeadline sets the read deadline associated with the connection.
[ "SetReadDeadline", "sets", "the", "read", "deadline", "associated", "with", "the", "connection", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/wsconn/websocket_connection.go#L192-L194
3,011
apcera/util
wsconn/websocket_connection.go
SetWriteDeadline
func (conn *WebsocketConnection) SetWriteDeadline(t time.Time) error { return conn.ws.SetWriteDeadline(t) }
go
func (conn *WebsocketConnection) SetWriteDeadline(t time.Time) error { return conn.ws.SetWriteDeadline(t) }
[ "func", "(", "conn", "*", "WebsocketConnection", ")", "SetWriteDeadline", "(", "t", "time", ".", "Time", ")", "error", "{", "return", "conn", ".", "ws", ".", "SetWriteDeadline", "(", "t", ")", "\n", "}" ]
// SetWriteDeadline sets the write deadline assocated with the connection.
[ "SetWriteDeadline", "sets", "the", "write", "deadline", "assocated", "with", "the", "connection", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/wsconn/websocket_connection.go#L197-L199
3,012
apcera/util
s3util/packaging_util.go
Zipper
func Zipper(zipPath string) (*bytes.Buffer, error) { f, err := os.Open(zipPath) if err != nil { return nil, err } defer f.Close() buffer := bytes.NewBuffer(nil) w := zip.NewWriter(buffer) fh := zip.FileHeader{} fh.Name = filepath.Base(zipPath) fh.SetMode(0755) // Add some files to the archive. var files = []struct { Name string FileHandle *os.File Header *zip.FileHeader }{ {fh.Name, f, &fh}, } // Loop through all files listed above // Can be created using file.Name or a custom file.Header for flexibility. // To set permissions you need to use the file.Header construct. for _, file := range files { var zf io.Writer if file.Header == nil { zf, err = w.Create(file.Name) } else { zf, err = w.CreateHeader(file.Header) } if err != nil { return nil, err } if _, err := io.Copy(zf, f); err != nil { return nil, err } } if err := w.Close(); err != nil { return nil, err } return buffer, nil }
go
func Zipper(zipPath string) (*bytes.Buffer, error) { f, err := os.Open(zipPath) if err != nil { return nil, err } defer f.Close() buffer := bytes.NewBuffer(nil) w := zip.NewWriter(buffer) fh := zip.FileHeader{} fh.Name = filepath.Base(zipPath) fh.SetMode(0755) // Add some files to the archive. var files = []struct { Name string FileHandle *os.File Header *zip.FileHeader }{ {fh.Name, f, &fh}, } // Loop through all files listed above // Can be created using file.Name or a custom file.Header for flexibility. // To set permissions you need to use the file.Header construct. for _, file := range files { var zf io.Writer if file.Header == nil { zf, err = w.Create(file.Name) } else { zf, err = w.CreateHeader(file.Header) } if err != nil { return nil, err } if _, err := io.Copy(zf, f); err != nil { return nil, err } } if err := w.Close(); err != nil { return nil, err } return buffer, nil }
[ "func", "Zipper", "(", "zipPath", "string", ")", "(", "*", "bytes", ".", "Buffer", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "zipPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "buffer", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "w", ":=", "zip", ".", "NewWriter", "(", "buffer", ")", "\n", "fh", ":=", "zip", ".", "FileHeader", "{", "}", "\n", "fh", ".", "Name", "=", "filepath", ".", "Base", "(", "zipPath", ")", "\n", "fh", ".", "SetMode", "(", "0755", ")", "\n\n", "// Add some files to the archive.", "var", "files", "=", "[", "]", "struct", "{", "Name", "string", "\n", "FileHandle", "*", "os", ".", "File", "\n", "Header", "*", "zip", ".", "FileHeader", "\n", "}", "{", "{", "fh", ".", "Name", ",", "f", ",", "&", "fh", "}", ",", "}", "\n\n", "// Loop through all files listed above", "// Can be created using file.Name or a custom file.Header for flexibility.", "// To set permissions you need to use the file.Header construct.", "for", "_", ",", "file", ":=", "range", "files", "{", "var", "zf", "io", ".", "Writer", "\n", "if", "file", ".", "Header", "==", "nil", "{", "zf", ",", "err", "=", "w", ".", "Create", "(", "file", ".", "Name", ")", "\n", "}", "else", "{", "zf", ",", "err", "=", "w", ".", "CreateHeader", "(", "file", ".", "Header", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "zf", ",", "f", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "w", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buffer", ",", "nil", "\n", "}" ]
// Zipper zips file contents at a path. Helper to prepare zipped data for upload // to S3.
[ "Zipper", "zips", "file", "contents", "at", "a", "path", ".", "Helper", "to", "prepare", "zipped", "data", "for", "upload", "to", "S3", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/s3util/packaging_util.go#L17-L62
3,013
apcera/util
s3util/packaging_util.go
Gzipper
func Gzipper(gzipPath string) (*bytes.Buffer, error) { f, err := os.Open(gzipPath) if err != nil { return nil, err } defer f.Close() // Gzip the binary data and toss it in a buffer. buffer := bytes.NewBuffer(nil) gzipData := gzip.NewWriter(buffer) gzipData.Header.Name = filepath.Base(gzipPath) gzipData.Header.ModTime = time.Now() if _, err := io.Copy(gzipData, f); err != nil { return nil, err } if err := gzipData.Close(); err != nil { return nil, err } return buffer, nil }
go
func Gzipper(gzipPath string) (*bytes.Buffer, error) { f, err := os.Open(gzipPath) if err != nil { return nil, err } defer f.Close() // Gzip the binary data and toss it in a buffer. buffer := bytes.NewBuffer(nil) gzipData := gzip.NewWriter(buffer) gzipData.Header.Name = filepath.Base(gzipPath) gzipData.Header.ModTime = time.Now() if _, err := io.Copy(gzipData, f); err != nil { return nil, err } if err := gzipData.Close(); err != nil { return nil, err } return buffer, nil }
[ "func", "Gzipper", "(", "gzipPath", "string", ")", "(", "*", "bytes", ".", "Buffer", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "gzipPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "// Gzip the binary data and toss it in a buffer.", "buffer", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "gzipData", ":=", "gzip", ".", "NewWriter", "(", "buffer", ")", "\n", "gzipData", ".", "Header", ".", "Name", "=", "filepath", ".", "Base", "(", "gzipPath", ")", "\n", "gzipData", ".", "Header", ".", "ModTime", "=", "time", ".", "Now", "(", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "gzipData", ",", "f", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "gzipData", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buffer", ",", "nil", "\n", "}" ]
// Gzipper gzips the file at the path. Helper to prepare gzipped data for upload // to S3.
[ "Gzipper", "gzips", "the", "file", "at", "the", "path", ".", "Helper", "to", "prepare", "gzipped", "data", "for", "upload", "to", "S3", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/s3util/packaging_util.go#L66-L85
3,014
apcera/util
tarhelper/tar.go
NewTar
func NewTar(w io.Writer, targetDir string) *Tar { return &Tar{ target: targetDir, dest: w, hardLinks: make(map[uint64]string), IncludePermissions: true, IncludeOwners: false, OwnerMappingFunc: defaultMappingFunc, GroupMappingFunc: defaultMappingFunc, } }
go
func NewTar(w io.Writer, targetDir string) *Tar { return &Tar{ target: targetDir, dest: w, hardLinks: make(map[uint64]string), IncludePermissions: true, IncludeOwners: false, OwnerMappingFunc: defaultMappingFunc, GroupMappingFunc: defaultMappingFunc, } }
[ "func", "NewTar", "(", "w", "io", ".", "Writer", ",", "targetDir", "string", ")", "*", "Tar", "{", "return", "&", "Tar", "{", "target", ":", "targetDir", ",", "dest", ":", "w", ",", "hardLinks", ":", "make", "(", "map", "[", "uint64", "]", "string", ")", ",", "IncludePermissions", ":", "true", ",", "IncludeOwners", ":", "false", ",", "OwnerMappingFunc", ":", "defaultMappingFunc", ",", "GroupMappingFunc", ":", "defaultMappingFunc", ",", "}", "\n", "}" ]
// NewTar returns a Tar ready to write the contents of targetDir to w.
[ "NewTar", "returns", "a", "Tar", "ready", "to", "write", "the", "contents", "of", "targetDir", "to", "w", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/tarhelper/tar.go#L158-L168
3,015
apcera/util
tarhelper/tar.go
IncludeRegexp
func (t *Tar) IncludeRegexp(re *regexp.Regexp, dirOnly bool) { t.ignorePaths = append(t.ignorePaths, ignoreInfo{regexp: re, exclude: false, dirOnly: dirOnly}) }
go
func (t *Tar) IncludeRegexp(re *regexp.Regexp, dirOnly bool) { t.ignorePaths = append(t.ignorePaths, ignoreInfo{regexp: re, exclude: false, dirOnly: dirOnly}) }
[ "func", "(", "t", "*", "Tar", ")", "IncludeRegexp", "(", "re", "*", "regexp", ".", "Regexp", ",", "dirOnly", "bool", ")", "{", "t", ".", "ignorePaths", "=", "append", "(", "t", ".", "ignorePaths", ",", "ignoreInfo", "{", "regexp", ":", "re", ",", "exclude", ":", "false", ",", "dirOnly", ":", "dirOnly", "}", ")", "\n", "}" ]
// IncludeRegexp adds a Regexp into the list to consider when selectiong files // to exclude. Files or directories matching the regexp will _not_ be excluded, // even if they matched a previous Regexp. Files are only considered a match if // they match the Regexp and isDir is false.
[ "IncludeRegexp", "adds", "a", "Regexp", "into", "the", "list", "to", "consider", "when", "selectiong", "files", "to", "exclude", ".", "Files", "or", "directories", "matching", "the", "regexp", "will", "_not_", "be", "excluded", "even", "if", "they", "matched", "a", "previous", "Regexp", ".", "Files", "are", "only", "considered", "a", "match", "if", "they", "match", "the", "Regexp", "and", "isDir", "is", "false", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/tarhelper/tar.go#L264-L266
3,016
apcera/util
tarhelper/tar.go
ExcludeRegexp
func (t *Tar) ExcludeRegexp(re *regexp.Regexp, dirOnly bool) { t.ignorePaths = append(t.ignorePaths, ignoreInfo{regexp: re, exclude: true, dirOnly: dirOnly}) }
go
func (t *Tar) ExcludeRegexp(re *regexp.Regexp, dirOnly bool) { t.ignorePaths = append(t.ignorePaths, ignoreInfo{regexp: re, exclude: true, dirOnly: dirOnly}) }
[ "func", "(", "t", "*", "Tar", ")", "ExcludeRegexp", "(", "re", "*", "regexp", ".", "Regexp", ",", "dirOnly", "bool", ")", "{", "t", ".", "ignorePaths", "=", "append", "(", "t", ".", "ignorePaths", ",", "ignoreInfo", "{", "regexp", ":", "re", ",", "exclude", ":", "true", ",", "dirOnly", ":", "dirOnly", "}", ")", "\n", "}" ]
// ExcludeRegexp adds a Regexp into the list to consider when selectiong files // to exclude. Files or directories matching the regexp will be excluded, even // if they matched a previous Regexp from IncludeRegexp. Files are only // considered a match if they match the Regexp and isDir is false.
[ "ExcludeRegexp", "adds", "a", "Regexp", "into", "the", "list", "to", "consider", "when", "selectiong", "files", "to", "exclude", ".", "Files", "or", "directories", "matching", "the", "regexp", "will", "be", "excluded", "even", "if", "they", "matched", "a", "previous", "Regexp", "from", "IncludeRegexp", ".", "Files", "are", "only", "considered", "a", "match", "if", "they", "match", "the", "Regexp", "and", "isDir", "is", "false", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/tarhelper/tar.go#L272-L274
3,017
apcera/util
tarhelper/tar.go
shouldBeExcluded
func (t *Tar) shouldBeExcluded(name string, isDir bool) bool { name = filepath.ToSlash(filepath.Clean(name)) var exclude bool for _, re := range t.ignorePaths { if re.regexp.MatchString(name) || re.regexp.MatchString(filepath.Base(name)) { if !re.dirOnly || (re.dirOnly && isDir) { exclude = re.exclude } } } return exclude }
go
func (t *Tar) shouldBeExcluded(name string, isDir bool) bool { name = filepath.ToSlash(filepath.Clean(name)) var exclude bool for _, re := range t.ignorePaths { if re.regexp.MatchString(name) || re.regexp.MatchString(filepath.Base(name)) { if !re.dirOnly || (re.dirOnly && isDir) { exclude = re.exclude } } } return exclude }
[ "func", "(", "t", "*", "Tar", ")", "shouldBeExcluded", "(", "name", "string", ",", "isDir", "bool", ")", "bool", "{", "name", "=", "filepath", ".", "ToSlash", "(", "filepath", ".", "Clean", "(", "name", ")", ")", "\n", "var", "exclude", "bool", "\n", "for", "_", ",", "re", ":=", "range", "t", ".", "ignorePaths", "{", "if", "re", ".", "regexp", ".", "MatchString", "(", "name", ")", "||", "re", ".", "regexp", ".", "MatchString", "(", "filepath", ".", "Base", "(", "name", ")", ")", "{", "if", "!", "re", ".", "dirOnly", "||", "(", "re", ".", "dirOnly", "&&", "isDir", ")", "{", "exclude", "=", "re", ".", "exclude", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "exclude", "\n", "}" ]
// shouldBeExcluded determines if supplied name is contained in the slice of // files to exclude. ignorePaths are considered in order so that files excluded // by one criteria can be reincluded by a later one.
[ "shouldBeExcluded", "determines", "if", "supplied", "name", "is", "contained", "in", "the", "slice", "of", "files", "to", "exclude", ".", "ignorePaths", "are", "considered", "in", "order", "so", "that", "files", "excluded", "by", "one", "criteria", "can", "be", "reincluded", "by", "a", "later", "one", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/tarhelper/tar.go#L558-L570
3,018
apcera/util
tarhelper/tar.go
excludeRootPath
func (t *Tar) excludeRootPath(headerName string) bool { if t.ExcludeRootPath && headerName == "./" { return true } return false }
go
func (t *Tar) excludeRootPath(headerName string) bool { if t.ExcludeRootPath && headerName == "./" { return true } return false }
[ "func", "(", "t", "*", "Tar", ")", "excludeRootPath", "(", "headerName", "string", ")", "bool", "{", "if", "t", ".", "ExcludeRootPath", "&&", "headerName", "==", "\"", "\"", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// excludeRootPath determines if the path is the root path and should be // excluded.
[ "excludeRootPath", "determines", "if", "the", "path", "is", "the", "root", "path", "and", "should", "be", "excluded", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/tarhelper/tar.go#L574-L580
3,019
apcera/util
tarhelper/untar.go
checkName
func checkName(name string) error { if len(name) == 0 { return fmt.Errorf("No name given for tar element.") } comp := strings.Split(name, string(os.PathSeparator)) if len(comp) > 0 && comp[0] == "" { return fmt.Errorf("No absolute paths allowed.") } for i, c := range comp { switch { case c == "" && i != len(comp)-1: // don't allow an empty name, unless it is the last element... handles // cases where we may have "./" come in as the name return fmt.Errorf("Empty name in file path.") case c == "..": return fmt.Errorf("Double dots not allowed in path.") } } return nil }
go
func checkName(name string) error { if len(name) == 0 { return fmt.Errorf("No name given for tar element.") } comp := strings.Split(name, string(os.PathSeparator)) if len(comp) > 0 && comp[0] == "" { return fmt.Errorf("No absolute paths allowed.") } for i, c := range comp { switch { case c == "" && i != len(comp)-1: // don't allow an empty name, unless it is the last element... handles // cases where we may have "./" come in as the name return fmt.Errorf("Empty name in file path.") case c == "..": return fmt.Errorf("Double dots not allowed in path.") } } return nil }
[ "func", "checkName", "(", "name", "string", ")", "error", "{", "if", "len", "(", "name", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "comp", ":=", "strings", ".", "Split", "(", "name", ",", "string", "(", "os", ".", "PathSeparator", ")", ")", "\n", "if", "len", "(", "comp", ")", ">", "0", "&&", "comp", "[", "0", "]", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ",", "c", ":=", "range", "comp", "{", "switch", "{", "case", "c", "==", "\"", "\"", "&&", "i", "!=", "len", "(", "comp", ")", "-", "1", ":", "// don't allow an empty name, unless it is the last element... handles", "// cases where we may have \"./\" come in as the name", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "c", "==", "\"", "\"", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Checks the security of the given name. Anything that looks // fishy will be rejected.
[ "Checks", "the", "security", "of", "the", "given", "name", ".", "Anything", "that", "looks", "fishy", "will", "be", "rejected", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/tarhelper/untar.go#L227-L246
3,020
apcera/util
tarhelper/untar.go
checkLinkName
func checkLinkName(dest, src, targetBase string) error { if len(dest) == 0 { return fmt.Errorf("No name given for tar element.") } return nil }
go
func checkLinkName(dest, src, targetBase string) error { if len(dest) == 0 { return fmt.Errorf("No name given for tar element.") } return nil }
[ "func", "checkLinkName", "(", "dest", ",", "src", ",", "targetBase", "string", ")", "error", "{", "if", "len", "(", "dest", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Checks the security of the given link name. Anything that looks fishy // will be rejected.
[ "Checks", "the", "security", "of", "the", "given", "link", "name", ".", "Anything", "that", "looks", "fishy", "will", "be", "rejected", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/tarhelper/untar.go#L250-L255
3,021
apcera/util
tarhelper/untar.go
checkEntryAgainstWhitelist
func (u *Untar) checkEntryAgainstWhitelist(header *tar.Header) bool { if len(u.PathWhitelist) == 0 { return true } name := "/" + filepath.Clean(header.Name) for _, p := range u.PathWhitelist { // Whitelist: "/foo" File: "/foo" if p == name { return true } if strings.HasSuffix(p, "/") { // Whitelist: "/usr/bin/" Dir: "/usr/bin" if p == name+"/" && header.Typeflag == tar.TypeDir { return true } // Whitelist: "/usr/bin/" File: "/usr/bin/bash" if strings.HasPrefix(name, p) { return true } } } return false }
go
func (u *Untar) checkEntryAgainstWhitelist(header *tar.Header) bool { if len(u.PathWhitelist) == 0 { return true } name := "/" + filepath.Clean(header.Name) for _, p := range u.PathWhitelist { // Whitelist: "/foo" File: "/foo" if p == name { return true } if strings.HasSuffix(p, "/") { // Whitelist: "/usr/bin/" Dir: "/usr/bin" if p == name+"/" && header.Typeflag == tar.TypeDir { return true } // Whitelist: "/usr/bin/" File: "/usr/bin/bash" if strings.HasPrefix(name, p) { return true } } } return false }
[ "func", "(", "u", "*", "Untar", ")", "checkEntryAgainstWhitelist", "(", "header", "*", "tar", ".", "Header", ")", "bool", "{", "if", "len", "(", "u", ".", "PathWhitelist", ")", "==", "0", "{", "return", "true", "\n", "}", "\n\n", "name", ":=", "\"", "\"", "+", "filepath", ".", "Clean", "(", "header", ".", "Name", ")", "\n\n", "for", "_", ",", "p", ":=", "range", "u", ".", "PathWhitelist", "{", "// Whitelist: \"/foo\" File: \"/foo\"", "if", "p", "==", "name", "{", "return", "true", "\n", "}", "\n\n", "if", "strings", ".", "HasSuffix", "(", "p", ",", "\"", "\"", ")", "{", "// Whitelist: \"/usr/bin/\" Dir: \"/usr/bin\"", "if", "p", "==", "name", "+", "\"", "\"", "&&", "header", ".", "Typeflag", "==", "tar", ".", "TypeDir", "{", "return", "true", "\n", "}", "\n\n", "// Whitelist: \"/usr/bin/\" File: \"/usr/bin/bash\"", "if", "strings", ".", "HasPrefix", "(", "name", ",", "p", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// checkEntryAgainstWhitelist will check if the specified file should be allowed // to be extracted against the current PathWhitelist. If no PathWhitelist is // allowed, then it will allow all files.
[ "checkEntryAgainstWhitelist", "will", "check", "if", "the", "specified", "file", "should", "be", "allowed", "to", "be", "extracted", "against", "the", "current", "PathWhitelist", ".", "If", "no", "PathWhitelist", "is", "allowed", "then", "it", "will", "allow", "all", "files", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/tarhelper/untar.go#L650-L677
3,022
apcera/util
hashutil/sha512util.go
NewSha512
func NewSha512(r io.Reader) *Sha512Reader { s := new(Sha512Reader) s.hashReader = newHashReader(sha512.New(), r) return s }
go
func NewSha512(r io.Reader) *Sha512Reader { s := new(Sha512Reader) s.hashReader = newHashReader(sha512.New(), r) return s }
[ "func", "NewSha512", "(", "r", "io", ".", "Reader", ")", "*", "Sha512Reader", "{", "s", ":=", "new", "(", "Sha512Reader", ")", "\n", "s", ".", "hashReader", "=", "newHashReader", "(", "sha512", ".", "New", "(", ")", ",", "r", ")", "\n", "return", "s", "\n", "}" ]
// Returns a new Sha512Reader.
[ "Returns", "a", "new", "Sha512Reader", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/sha512util.go#L34-L38
3,023
apcera/util
hashutil/sha512util.go
Sha512
func (s *Sha512Reader) Sha512() string { return hex.EncodeToString(s.hash.Sum(nil)) }
go
func (s *Sha512Reader) Sha512() string { return hex.EncodeToString(s.hash.Sum(nil)) }
[ "func", "(", "s", "*", "Sha512Reader", ")", "Sha512", "(", ")", "string", "{", "return", "hex", ".", "EncodeToString", "(", "s", ".", "hash", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// Returns the SHA512 for all data that has been passed through this Reader // already. This should ideally be called after the Reader is Closed, but // otherwise its safe to call any time.
[ "Returns", "the", "SHA512", "for", "all", "data", "that", "has", "been", "passed", "through", "this", "Reader", "already", ".", "This", "should", "ideally", "be", "called", "after", "the", "Reader", "is", "Closed", "but", "otherwise", "its", "safe", "to", "call", "any", "time", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/sha512util.go#L43-L45
3,024
apcera/util
hashutil/md5util.go
NewMd5
func NewMd5(r io.Reader) *Md5Reader { m := &Md5Reader{} m.hashReader = newHashReader(md5.New(), r) return m }
go
func NewMd5(r io.Reader) *Md5Reader { m := &Md5Reader{} m.hashReader = newHashReader(md5.New(), r) return m }
[ "func", "NewMd5", "(", "r", "io", ".", "Reader", ")", "*", "Md5Reader", "{", "m", ":=", "&", "Md5Reader", "{", "}", "\n", "m", ".", "hashReader", "=", "newHashReader", "(", "md5", ".", "New", "(", ")", ",", "r", ")", "\n", "return", "m", "\n", "}" ]
// Returns a new Md5Reader.
[ "Returns", "a", "new", "Md5Reader", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/md5util.go#L34-L38
3,025
apcera/util
hashutil/md5util.go
Md5
func (m *Md5Reader) Md5() string { return hex.EncodeToString(m.hash.Sum(nil)) }
go
func (m *Md5Reader) Md5() string { return hex.EncodeToString(m.hash.Sum(nil)) }
[ "func", "(", "m", "*", "Md5Reader", ")", "Md5", "(", ")", "string", "{", "return", "hex", ".", "EncodeToString", "(", "m", ".", "hash", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// Returns the MD5 for all data that has been passed through this Reader // already. This should ideally be called after the Reader is Closed, but // otherwise its safe to call any time.
[ "Returns", "the", "MD5", "for", "all", "data", "that", "has", "been", "passed", "through", "this", "Reader", "already", ".", "This", "should", "ideally", "be", "called", "after", "the", "Reader", "is", "Closed", "but", "otherwise", "its", "safe", "to", "call", "any", "time", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/md5util.go#L43-L45
3,026
apcera/util
tempfile/tempfile.go
New
func New(r io.Reader) (ReadSeekCloser, error) { tf, err := ioutil.TempFile(os.TempDir(), "temporary-file") if err != nil { return nil, err } f := &unlinkOnCloseFile{tf} successful := false defer func() { if !successful { f.Close() } }() if _, err := io.Copy(f, r); err != nil { return nil, err } if _, err := f.Seek(0, 0); err != nil { return nil, err } successful = true return f, nil }
go
func New(r io.Reader) (ReadSeekCloser, error) { tf, err := ioutil.TempFile(os.TempDir(), "temporary-file") if err != nil { return nil, err } f := &unlinkOnCloseFile{tf} successful := false defer func() { if !successful { f.Close() } }() if _, err := io.Copy(f, r); err != nil { return nil, err } if _, err := f.Seek(0, 0); err != nil { return nil, err } successful = true return f, nil }
[ "func", "New", "(", "r", "io", ".", "Reader", ")", "(", "ReadSeekCloser", ",", "error", ")", "{", "tf", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "os", ".", "TempDir", "(", ")", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "f", ":=", "&", "unlinkOnCloseFile", "{", "tf", "}", "\n", "successful", ":=", "false", "\n", "defer", "func", "(", ")", "{", "if", "!", "successful", "{", "f", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "f", ",", "r", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "f", ".", "Seek", "(", "0", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "successful", "=", "true", "\n", "return", "f", ",", "nil", "\n", "}" ]
// New will take in a io.Reader and write its content to a new temporary // file. The temporary file will be automatically removed when it closed.
[ "New", "will", "take", "in", "a", "io", ".", "Reader", "and", "write", "its", "content", "to", "a", "new", "temporary", "file", ".", "The", "temporary", "file", "will", "be", "automatically", "removed", "when", "it", "closed", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/tempfile/tempfile.go#L32-L54
3,027
apcera/util
spawn/spawn.go
loadConfig
func loadConfig(configFile string) ([][]string, error) { f, err := os.Open(configFile) if err != nil { return nil, err } defer f.Close() var config [][]string if err := json.NewDecoder(f).Decode(&config); err != nil { return nil, err } return config, nil }
go
func loadConfig(configFile string) ([][]string, error) { f, err := os.Open(configFile) if err != nil { return nil, err } defer f.Close() var config [][]string if err := json.NewDecoder(f).Decode(&config); err != nil { return nil, err } return config, nil }
[ "func", "loadConfig", "(", "configFile", "string", ")", "(", "[", "]", "[", "]", "string", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "configFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "var", "config", "[", "]", "[", "]", "string", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "f", ")", ".", "Decode", "(", "&", "config", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "config", ",", "nil", "\n", "}" ]
// loadConfig handles loading specified configuration file and returning it.
[ "loadConfig", "handles", "loading", "specified", "configuration", "file", "and", "returning", "it", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/spawn/spawn.go#L130-L142
3,028
apcera/util
events/stream.go
StreamEvents
func (e *EventClient) StreamEvents(w io.Writer, streamFQN string, timeout time.Duration) error { timeoutTicker := time.NewTimer(timeout).C handleEventStream := func(args []interface{}, kwargs map[string]interface{}) { event := args[0].(map[string]interface{}) output := fmt.Sprintf("FQN: %q, Source: %s, Time: %b, Type: %d, Payload: %v", event["resource"], event["event_source"], event["time"], int(event["type"].(float64)), event["payload"]) fmt.Fprintln(w, output) timeoutTicker = time.NewTimer(timeout).C } if err := e.Subscribe(streamFQN, handleEventStream); err != nil { return err } // By default, nginx terminates inactive connections after 60 seconds. So, // we pong. keepAlive := time.NewTicker(30 * time.Second) defer keepAlive.Stop() for { select { // Streams till the connection is closed by the API Server case <-e.ReceiveDone: return nil // If the connection has remained inactive beyond input.Timeout, unsubscribe case <-timeoutTicker: return nil // NGINX terminates inactive connections post 60 seconds. // Sending a WAMP Hello{} message (harmless) as a packet ping to NGINX case <-keepAlive.C: e.Send(&turnpike.Hello{}) } } }
go
func (e *EventClient) StreamEvents(w io.Writer, streamFQN string, timeout time.Duration) error { timeoutTicker := time.NewTimer(timeout).C handleEventStream := func(args []interface{}, kwargs map[string]interface{}) { event := args[0].(map[string]interface{}) output := fmt.Sprintf("FQN: %q, Source: %s, Time: %b, Type: %d, Payload: %v", event["resource"], event["event_source"], event["time"], int(event["type"].(float64)), event["payload"]) fmt.Fprintln(w, output) timeoutTicker = time.NewTimer(timeout).C } if err := e.Subscribe(streamFQN, handleEventStream); err != nil { return err } // By default, nginx terminates inactive connections after 60 seconds. So, // we pong. keepAlive := time.NewTicker(30 * time.Second) defer keepAlive.Stop() for { select { // Streams till the connection is closed by the API Server case <-e.ReceiveDone: return nil // If the connection has remained inactive beyond input.Timeout, unsubscribe case <-timeoutTicker: return nil // NGINX terminates inactive connections post 60 seconds. // Sending a WAMP Hello{} message (harmless) as a packet ping to NGINX case <-keepAlive.C: e.Send(&turnpike.Hello{}) } } }
[ "func", "(", "e", "*", "EventClient", ")", "StreamEvents", "(", "w", "io", ".", "Writer", ",", "streamFQN", "string", ",", "timeout", "time", ".", "Duration", ")", "error", "{", "timeoutTicker", ":=", "time", ".", "NewTimer", "(", "timeout", ")", ".", "C", "\n\n", "handleEventStream", ":=", "func", "(", "args", "[", "]", "interface", "{", "}", ",", "kwargs", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "event", ":=", "args", "[", "0", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n\n", "output", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "event", "[", "\"", "\"", "]", ",", "event", "[", "\"", "\"", "]", ",", "event", "[", "\"", "\"", "]", ",", "int", "(", "event", "[", "\"", "\"", "]", ".", "(", "float64", ")", ")", ",", "event", "[", "\"", "\"", "]", ")", "\n", "fmt", ".", "Fprintln", "(", "w", ",", "output", ")", "\n", "timeoutTicker", "=", "time", ".", "NewTimer", "(", "timeout", ")", ".", "C", "\n", "}", "\n\n", "if", "err", ":=", "e", ".", "Subscribe", "(", "streamFQN", ",", "handleEventStream", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// By default, nginx terminates inactive connections after 60 seconds. So,", "// we pong.", "keepAlive", ":=", "time", ".", "NewTicker", "(", "30", "*", "time", ".", "Second", ")", "\n", "defer", "keepAlive", ".", "Stop", "(", ")", "\n", "for", "{", "select", "{", "// Streams till the connection is closed by the API Server", "case", "<-", "e", ".", "ReceiveDone", ":", "return", "nil", "\n", "// If the connection has remained inactive beyond input.Timeout, unsubscribe", "case", "<-", "timeoutTicker", ":", "return", "nil", "\n", "// NGINX terminates inactive connections post 60 seconds.", "// Sending a WAMP Hello{} message (harmless) as a packet ping to NGINX", "case", "<-", "keepAlive", ".", "C", ":", "e", ".", "Send", "(", "&", "turnpike", ".", "Hello", "{", "}", ")", "\n", "}", "\n", "}", "\n", "}" ]
// StreamEvents streams events from a given resource FQN to a specific writer. // It blocks until the stream is disconnected, and will continue writing to // the given writer. It will time if it has not received an event within the // given timeout.
[ "StreamEvents", "streams", "events", "from", "a", "given", "resource", "FQN", "to", "a", "specific", "writer", ".", "It", "blocks", "until", "the", "stream", "is", "disconnected", "and", "will", "continue", "writing", "to", "the", "given", "writer", ".", "It", "will", "time", "if", "it", "has", "not", "received", "an", "event", "within", "the", "given", "timeout", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/events/stream.go#L17-L50
3,029
apcera/util
taskrenderer/renderer.go
RenderEvents
func (r *Renderer) RenderEvents(eventCh <-chan *TaskEvent) { for event := range eventCh { r.RenderEvent(event) } }
go
func (r *Renderer) RenderEvents(eventCh <-chan *TaskEvent) { for event := range eventCh { r.RenderEvent(event) } }
[ "func", "(", "r", "*", "Renderer", ")", "RenderEvents", "(", "eventCh", "<-", "chan", "*", "TaskEvent", ")", "{", "for", "event", ":=", "range", "eventCh", "{", "r", ".", "RenderEvent", "(", "event", ")", "\n", "}", "\n", "}" ]
// RenderEvents reads every event sent on the given channel and renders it. // The channel can be closed by the caller at any time to stop rendering.
[ "RenderEvents", "reads", "every", "event", "sent", "on", "the", "given", "channel", "and", "renders", "it", ".", "The", "channel", "can", "be", "closed", "by", "the", "caller", "at", "any", "time", "to", "stop", "rendering", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/taskrenderer/renderer.go#L31-L35
3,030
apcera/util
taskrenderer/renderer.go
RenderEvent
func (r *Renderer) RenderEvent(event *TaskEvent) string { switch event.Type { case "eos": return "" } s := "" if r.options.showTime { s += fmt.Sprintf("(%s) ", time.Unix(0, event.Time).Format(time.UnixDate)) } if event.Thread != "" { s += fmt.Sprintf("[%s] -- ", event.Thread) } s += fmt.Sprintf("%s", event.Stage) if event.Subtask.Name != "" { s += " -- " if event.Subtask.Total != 0 { s += fmt.Sprintf("(%d/%d): ", event.Subtask.Index, event.Subtask.Total) } s += fmt.Sprintf("%s", event.Subtask.Name) if event.Subtask.Progress.Total != 0 { s += fmt.Sprintf(" ... %d%%", (event.Subtask.Progress.Current/event.Subtask.Progress.Total)*100, ) } } return s }
go
func (r *Renderer) RenderEvent(event *TaskEvent) string { switch event.Type { case "eos": return "" } s := "" if r.options.showTime { s += fmt.Sprintf("(%s) ", time.Unix(0, event.Time).Format(time.UnixDate)) } if event.Thread != "" { s += fmt.Sprintf("[%s] -- ", event.Thread) } s += fmt.Sprintf("%s", event.Stage) if event.Subtask.Name != "" { s += " -- " if event.Subtask.Total != 0 { s += fmt.Sprintf("(%d/%d): ", event.Subtask.Index, event.Subtask.Total) } s += fmt.Sprintf("%s", event.Subtask.Name) if event.Subtask.Progress.Total != 0 { s += fmt.Sprintf(" ... %d%%", (event.Subtask.Progress.Current/event.Subtask.Progress.Total)*100, ) } } return s }
[ "func", "(", "r", "*", "Renderer", ")", "RenderEvent", "(", "event", "*", "TaskEvent", ")", "string", "{", "switch", "event", ".", "Type", "{", "case", "\"", "\"", ":", "return", "\"", "\"", "\n", "}", "\n\n", "s", ":=", "\"", "\"", "\n\n", "if", "r", ".", "options", ".", "showTime", "{", "s", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "time", ".", "Unix", "(", "0", ",", "event", ".", "Time", ")", ".", "Format", "(", "time", ".", "UnixDate", ")", ")", "\n", "}", "\n\n", "if", "event", ".", "Thread", "!=", "\"", "\"", "{", "s", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "event", ".", "Thread", ")", "\n", "}", "\n\n", "s", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "event", ".", "Stage", ")", "\n\n", "if", "event", ".", "Subtask", ".", "Name", "!=", "\"", "\"", "{", "s", "+=", "\"", "\"", "\n", "if", "event", ".", "Subtask", ".", "Total", "!=", "0", "{", "s", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "event", ".", "Subtask", ".", "Index", ",", "event", ".", "Subtask", ".", "Total", ")", "\n", "}", "\n\n", "s", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "event", ".", "Subtask", ".", "Name", ")", "\n\n", "if", "event", ".", "Subtask", ".", "Progress", ".", "Total", "!=", "0", "{", "s", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "(", "event", ".", "Subtask", ".", "Progress", ".", "Current", "/", "event", ".", "Subtask", ".", "Progress", ".", "Total", ")", "*", "100", ",", ")", "\n", "}", "\n", "}", "\n\n", "return", "s", "\n", "}" ]
// renderEvent varies output depending on the information provided // by the current taskEvent.
[ "renderEvent", "varies", "output", "depending", "on", "the", "information", "provided", "by", "the", "current", "taskEvent", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/taskrenderer/renderer.go#L39-L73
3,031
apcera/util
iprange/iprange.go
Contains
func (ipr *IPRange) Contains(ip net.IP) bool { // if ip is less than start, return false if bytes.Compare([]byte(ip), []byte(ipr.Start)) < 0 { return false } // return true if ip is less than or equal to end return bytes.Compare([]byte(ip), []byte(ipr.End)) <= 0 }
go
func (ipr *IPRange) Contains(ip net.IP) bool { // if ip is less than start, return false if bytes.Compare([]byte(ip), []byte(ipr.Start)) < 0 { return false } // return true if ip is less than or equal to end return bytes.Compare([]byte(ip), []byte(ipr.End)) <= 0 }
[ "func", "(", "ipr", "*", "IPRange", ")", "Contains", "(", "ip", "net", ".", "IP", ")", "bool", "{", "// if ip is less than start, return false", "if", "bytes", ".", "Compare", "(", "[", "]", "byte", "(", "ip", ")", ",", "[", "]", "byte", "(", "ipr", ".", "Start", ")", ")", "<", "0", "{", "return", "false", "\n", "}", "\n", "// return true if ip is less than or equal to end", "return", "bytes", ".", "Compare", "(", "[", "]", "byte", "(", "ip", ")", ",", "[", "]", "byte", "(", "ipr", ".", "End", ")", ")", "<=", "0", "\n", "}" ]
// Contains returns whether or not the given IP address is within the specified // IPRange.
[ "Contains", "returns", "whether", "or", "not", "the", "given", "IP", "address", "is", "within", "the", "specified", "IPRange", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/iprange.go#L82-L89
3,032
apcera/util
iprange/iprange.go
Overlaps
func (ipr *IPRange) Overlaps(o *IPRange) bool { // if the start of o is less than our start, we need to make sure the end of o // is less than our start if bytes.Compare([]byte(o.Start), []byte(ipr.Start)) < 0 { return bytes.Compare([]byte(o.End), []byte(ipr.Start)) >= 0 } // if the start of o is greater than our end, then no overlap if bytes.Compare([]byte(o.Start), []byte(ipr.End)) > 0 { return false } // otherwise, their start is within our range, and thus there is overlap return true }
go
func (ipr *IPRange) Overlaps(o *IPRange) bool { // if the start of o is less than our start, we need to make sure the end of o // is less than our start if bytes.Compare([]byte(o.Start), []byte(ipr.Start)) < 0 { return bytes.Compare([]byte(o.End), []byte(ipr.Start)) >= 0 } // if the start of o is greater than our end, then no overlap if bytes.Compare([]byte(o.Start), []byte(ipr.End)) > 0 { return false } // otherwise, their start is within our range, and thus there is overlap return true }
[ "func", "(", "ipr", "*", "IPRange", ")", "Overlaps", "(", "o", "*", "IPRange", ")", "bool", "{", "// if the start of o is less than our start, we need to make sure the end of o", "// is less than our start", "if", "bytes", ".", "Compare", "(", "[", "]", "byte", "(", "o", ".", "Start", ")", ",", "[", "]", "byte", "(", "ipr", ".", "Start", ")", ")", "<", "0", "{", "return", "bytes", ".", "Compare", "(", "[", "]", "byte", "(", "o", ".", "End", ")", ",", "[", "]", "byte", "(", "ipr", ".", "Start", ")", ")", ">=", "0", "\n", "}", "\n", "// if the start of o is greater than our end, then no overlap", "if", "bytes", ".", "Compare", "(", "[", "]", "byte", "(", "o", ".", "Start", ")", ",", "[", "]", "byte", "(", "ipr", ".", "End", ")", ")", ">", "0", "{", "return", "false", "\n", "}", "\n", "// otherwise, their start is within our range, and thus there is overlap", "return", "true", "\n", "}" ]
// Overlaps checks whether another IPRange instance has an overlap in IPs with // the current range. If will return true if there is any cross section between // the two ranges.
[ "Overlaps", "checks", "whether", "another", "IPRange", "instance", "has", "an", "overlap", "in", "IPs", "with", "the", "current", "range", ".", "If", "will", "return", "true", "if", "there", "is", "any", "cross", "section", "between", "the", "two", "ranges", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/iprange.go#L94-L106
3,033
apcera/util
iprange/iprange.go
spliceIP
func spliceIP(baseIP, partialIP string) string { baseParts := strings.Split(baseIP, ".") partialParts := strings.Split(partialIP, ".") finalParts := append(baseParts[:(len(baseParts)-len(partialParts))], partialParts...) return strings.Join(finalParts, ".") }
go
func spliceIP(baseIP, partialIP string) string { baseParts := strings.Split(baseIP, ".") partialParts := strings.Split(partialIP, ".") finalParts := append(baseParts[:(len(baseParts)-len(partialParts))], partialParts...) return strings.Join(finalParts, ".") }
[ "func", "spliceIP", "(", "baseIP", ",", "partialIP", "string", ")", "string", "{", "baseParts", ":=", "strings", ".", "Split", "(", "baseIP", ",", "\"", "\"", ")", "\n", "partialParts", ":=", "strings", ".", "Split", "(", "partialIP", ",", "\"", "\"", ")", "\n", "finalParts", ":=", "append", "(", "baseParts", "[", ":", "(", "len", "(", "baseParts", ")", "-", "len", "(", "partialParts", ")", ")", "]", ",", "partialParts", "...", ")", "\n", "return", "strings", ".", "Join", "(", "finalParts", ",", "\"", "\"", ")", "\n", "}" ]
// FIXME this only handles IPv4 at the moment
[ "FIXME", "this", "only", "handles", "IPv4", "at", "the", "moment" ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/iprange.go#L109-L114
3,034
apcera/util
uuid/uuid.go
Less
func (u UUIDSlice) Less(i, j int) bool { return u[i] < u[j] }
go
func (u UUIDSlice) Less(i, j int) bool { return u[i] < u[j] }
[ "func", "(", "u", "UUIDSlice", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "u", "[", "i", "]", "<", "u", "[", "j", "]", "\n", "}" ]
// Compares two the other UUID and returns true if this object is "less than" // the other object.
[ "Compares", "two", "the", "other", "UUID", "and", "returns", "true", "if", "this", "object", "is", "less", "than", "the", "other", "object", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L44-L46
3,035
apcera/util
uuid/uuid.go
Swap
func (u UUIDSlice) Swap(i, j int) { u[i], u[j] = u[j], u[i] }
go
func (u UUIDSlice) Swap(i, j int) { u[i], u[j] = u[j], u[i] }
[ "func", "(", "u", "UUIDSlice", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "u", "[", "i", "]", ",", "u", "[", "j", "]", "=", "u", "[", "j", "]", ",", "u", "[", "i", "]", "\n", "}" ]
// Swaps the elements at index i and j in the given Slice.
[ "Swaps", "the", "elements", "at", "index", "i", "and", "j", "in", "the", "given", "Slice", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L49-L51
3,036
apcera/util
uuid/uuid.go
setNodeName
func setNodeName() { // Implementation specific optimization. Pre populate the counter with // a random seed to reduce the risk of collision. clockCorrect = uint16(math_rand.Int31() & 0xffff) // Get a mac address from an interface on this machine. interfaces, _ := net.Interfaces() if interfaces != nil { for _, i := range interfaces { if len(i.HardwareAddr) == UUIDHardwareByteLen { nodeName = i.HardwareAddr return } } } // Randomly generated node names should always have the LSB of the first // byte set to 1 as per the IEEE. nodeName = make([]byte, UUIDHardwareByteLen) io.ReadFull(crypto_rand.Reader, nodeName) nodeName[0] = nodeName[0] | 0x01 }
go
func setNodeName() { // Implementation specific optimization. Pre populate the counter with // a random seed to reduce the risk of collision. clockCorrect = uint16(math_rand.Int31() & 0xffff) // Get a mac address from an interface on this machine. interfaces, _ := net.Interfaces() if interfaces != nil { for _, i := range interfaces { if len(i.HardwareAddr) == UUIDHardwareByteLen { nodeName = i.HardwareAddr return } } } // Randomly generated node names should always have the LSB of the first // byte set to 1 as per the IEEE. nodeName = make([]byte, UUIDHardwareByteLen) io.ReadFull(crypto_rand.Reader, nodeName) nodeName[0] = nodeName[0] | 0x01 }
[ "func", "setNodeName", "(", ")", "{", "// Implementation specific optimization. Pre populate the counter with", "// a random seed to reduce the risk of collision.", "clockCorrect", "=", "uint16", "(", "math_rand", ".", "Int31", "(", ")", "&", "0xffff", ")", "\n\n", "// Get a mac address from an interface on this machine.", "interfaces", ",", "_", ":=", "net", ".", "Interfaces", "(", ")", "\n", "if", "interfaces", "!=", "nil", "{", "for", "_", ",", "i", ":=", "range", "interfaces", "{", "if", "len", "(", "i", ".", "HardwareAddr", ")", "==", "UUIDHardwareByteLen", "{", "nodeName", "=", "i", ".", "HardwareAddr", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Randomly generated node names should always have the LSB of the first", "// byte set to 1 as per the IEEE.", "nodeName", "=", "make", "(", "[", "]", "byte", ",", "UUIDHardwareByteLen", ")", "\n", "io", ".", "ReadFull", "(", "crypto_rand", ".", "Reader", ",", "nodeName", ")", "\n", "nodeName", "[", "0", "]", "=", "nodeName", "[", "0", "]", "|", "0x01", "\n", "}" ]
// Sets the "node name" value that will be used for the life of this process. // // This is currently not completely safe as it will fall back to using random // data if no mac address can be found, and if two machines fall into that // state it is possible for them to generate colliding UUIDs.
[ "Sets", "the", "node", "name", "value", "that", "will", "be", "used", "for", "the", "life", "of", "this", "process", ".", "This", "is", "currently", "not", "completely", "safe", "as", "it", "will", "fall", "back", "to", "using", "random", "data", "if", "no", "mac", "address", "can", "be", "found", "and", "if", "two", "machines", "fall", "into", "that", "state", "it", "is", "possible", "for", "them", "to", "generate", "colliding", "UUIDs", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L72-L93
3,037
apcera/util
uuid/uuid.go
Variant1
func Variant1() (u UUID) { // Format is as follows // Time stamp (60 bits): aaabbbbcccccccc // clock id (16 bits): dddd // node id (48 bits): eeeeeeeeeeee // Output is: cccccccc-bbbb-1aaa-dddd-Eeeeeeeeeeee // where 1 is mandated, and E must have its MSB set. setupOnce.Do(setNodeName) // UUID uses time as nano seconds since the west adopted the // Gregorian calendar, divided by 100. We manage this by adding // a precomputed offset since Unix() uses time since Jan 1, 1970. ts := (time.Now().UnixNano() / 100) + Variant1EpochOffset // Clock correct gets incremented every time we generate two UUIDs in the // same 100 nano second period. Should be rare. if ts == lastTime { clockCorrect += 1 } else { lastTime = ts } u = make([]byte, UUIDByteLen) u[0] = byte((ts >> (3 * 8)) & 0xff) u[1] = byte((ts >> (2 * 8)) & 0xff) u[2] = byte((ts >> (1 * 8)) & 0xff) u[3] = byte(ts & 0xff) u[4] = byte((ts >> (5 * 8)) & 0xff) u[5] = byte((ts >> (4 * 8)) & 0xff) u[6] = byte((ts>>(7*8))&0x0f + 0x10) u[7] = byte((ts >> (6 * 8)) & 0xff) u[8] = byte((clockCorrect>>1)&0x1f) | 0x80 u[9] = byte(clockCorrect & 0xff) u[10] = byte(nodeName[0]) u[11] = byte(nodeName[1]) u[12] = byte(nodeName[2]) u[13] = byte(nodeName[3]) u[14] = byte(nodeName[4]) u[15] = byte(nodeName[5]) return u }
go
func Variant1() (u UUID) { // Format is as follows // Time stamp (60 bits): aaabbbbcccccccc // clock id (16 bits): dddd // node id (48 bits): eeeeeeeeeeee // Output is: cccccccc-bbbb-1aaa-dddd-Eeeeeeeeeeee // where 1 is mandated, and E must have its MSB set. setupOnce.Do(setNodeName) // UUID uses time as nano seconds since the west adopted the // Gregorian calendar, divided by 100. We manage this by adding // a precomputed offset since Unix() uses time since Jan 1, 1970. ts := (time.Now().UnixNano() / 100) + Variant1EpochOffset // Clock correct gets incremented every time we generate two UUIDs in the // same 100 nano second period. Should be rare. if ts == lastTime { clockCorrect += 1 } else { lastTime = ts } u = make([]byte, UUIDByteLen) u[0] = byte((ts >> (3 * 8)) & 0xff) u[1] = byte((ts >> (2 * 8)) & 0xff) u[2] = byte((ts >> (1 * 8)) & 0xff) u[3] = byte(ts & 0xff) u[4] = byte((ts >> (5 * 8)) & 0xff) u[5] = byte((ts >> (4 * 8)) & 0xff) u[6] = byte((ts>>(7*8))&0x0f + 0x10) u[7] = byte((ts >> (6 * 8)) & 0xff) u[8] = byte((clockCorrect>>1)&0x1f) | 0x80 u[9] = byte(clockCorrect & 0xff) u[10] = byte(nodeName[0]) u[11] = byte(nodeName[1]) u[12] = byte(nodeName[2]) u[13] = byte(nodeName[3]) u[14] = byte(nodeName[4]) u[15] = byte(nodeName[5]) return u }
[ "func", "Variant1", "(", ")", "(", "u", "UUID", ")", "{", "// Format is as follows", "// Time stamp (60 bits): aaabbbbcccccccc", "// clock id (16 bits): dddd", "// node id (48 bits): eeeeeeeeeeee", "// Output is: cccccccc-bbbb-1aaa-dddd-Eeeeeeeeeeee", "// where 1 is mandated, and E must have its MSB set.", "setupOnce", ".", "Do", "(", "setNodeName", ")", "\n\n", "// UUID uses time as nano seconds since the west adopted the", "// Gregorian calendar, divided by 100. We manage this by adding", "// a precomputed offset since Unix() uses time since Jan 1, 1970.", "ts", ":=", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "/", "100", ")", "+", "Variant1EpochOffset", "\n\n", "// Clock correct gets incremented every time we generate two UUIDs in the", "// same 100 nano second period. Should be rare.", "if", "ts", "==", "lastTime", "{", "clockCorrect", "+=", "1", "\n", "}", "else", "{", "lastTime", "=", "ts", "\n", "}", "\n\n", "u", "=", "make", "(", "[", "]", "byte", ",", "UUIDByteLen", ")", "\n", "u", "[", "0", "]", "=", "byte", "(", "(", "ts", ">>", "(", "3", "*", "8", ")", ")", "&", "0xff", ")", "\n", "u", "[", "1", "]", "=", "byte", "(", "(", "ts", ">>", "(", "2", "*", "8", ")", ")", "&", "0xff", ")", "\n", "u", "[", "2", "]", "=", "byte", "(", "(", "ts", ">>", "(", "1", "*", "8", ")", ")", "&", "0xff", ")", "\n", "u", "[", "3", "]", "=", "byte", "(", "ts", "&", "0xff", ")", "\n", "u", "[", "4", "]", "=", "byte", "(", "(", "ts", ">>", "(", "5", "*", "8", ")", ")", "&", "0xff", ")", "\n", "u", "[", "5", "]", "=", "byte", "(", "(", "ts", ">>", "(", "4", "*", "8", ")", ")", "&", "0xff", ")", "\n", "u", "[", "6", "]", "=", "byte", "(", "(", "ts", ">>", "(", "7", "*", "8", ")", ")", "&", "0x0f", "+", "0x10", ")", "\n", "u", "[", "7", "]", "=", "byte", "(", "(", "ts", ">>", "(", "6", "*", "8", ")", ")", "&", "0xff", ")", "\n", "u", "[", "8", "]", "=", "byte", "(", "(", "clockCorrect", ">>", "1", ")", "&", "0x1f", ")", "|", "0x80", "\n", "u", "[", "9", "]", "=", "byte", "(", "clockCorrect", "&", "0xff", ")", "\n", "u", "[", "10", "]", "=", "byte", "(", "nodeName", "[", "0", "]", ")", "\n", "u", "[", "11", "]", "=", "byte", "(", "nodeName", "[", "1", "]", ")", "\n", "u", "[", "12", "]", "=", "byte", "(", "nodeName", "[", "2", "]", ")", "\n", "u", "[", "13", "]", "=", "byte", "(", "nodeName", "[", "3", "]", ")", "\n", "u", "[", "14", "]", "=", "byte", "(", "nodeName", "[", "4", "]", ")", "\n", "u", "[", "15", "]", "=", "byte", "(", "nodeName", "[", "5", "]", ")", "\n\n", "return", "u", "\n", "}" ]
// Generates a "Variant 1" style UUID. This uses the machines MAC address, and // the time since 15 October 1582 in nanoseconds, divided by 100. // // This form of UUID is useful when you do not care if you leak MAC info, can // be sure that MAC addresses are not duplicated on your network, and can // be sure that no more than 9,999 UUIDs will be generated every 100ns.
[ "Generates", "a", "Variant", "1", "style", "UUID", ".", "This", "uses", "the", "machines", "MAC", "address", "and", "the", "time", "since", "15", "October", "1582", "in", "nanoseconds", "divided", "by", "100", ".", "This", "form", "of", "UUID", "is", "useful", "when", "you", "do", "not", "care", "if", "you", "leak", "MAC", "info", "can", "be", "sure", "that", "MAC", "addresses", "are", "not", "duplicated", "on", "your", "network", "and", "can", "be", "sure", "that", "no", "more", "than", "9", "999", "UUIDs", "will", "be", "generated", "every", "100ns", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L101-L143
3,038
apcera/util
uuid/uuid.go
Variant3
func Variant3(namespace UUID, name string) (u UUID) { h := md5.New() h.Write([]byte(namespace)) h.Write([]byte(name)) u = h.Sum(nil)[0:16] u[6] = (u[6] & 0x0f) | 0x30 u[8] = (u[8] & 0x1f) | 0x80 return u }
go
func Variant3(namespace UUID, name string) (u UUID) { h := md5.New() h.Write([]byte(namespace)) h.Write([]byte(name)) u = h.Sum(nil)[0:16] u[6] = (u[6] & 0x0f) | 0x30 u[8] = (u[8] & 0x1f) | 0x80 return u }
[ "func", "Variant3", "(", "namespace", "UUID", ",", "name", "string", ")", "(", "u", "UUID", ")", "{", "h", ":=", "md5", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "[", "]", "byte", "(", "namespace", ")", ")", "\n", "h", ".", "Write", "(", "[", "]", "byte", "(", "name", ")", ")", "\n", "u", "=", "h", ".", "Sum", "(", "nil", ")", "[", "0", ":", "16", "]", "\n", "u", "[", "6", "]", "=", "(", "u", "[", "6", "]", "&", "0x0f", ")", "|", "0x30", "\n", "u", "[", "8", "]", "=", "(", "u", "[", "8", "]", "&", "0x1f", ")", "|", "0x80", "\n", "return", "u", "\n", "}" ]
// Generate a "Variant 3" style UUID. These UUIDs are not time based, instead // using a namespace and a string to generate a hashed number. Variant 3 // is MD5 based and should only be used for legacy reasons. Use Variant 5 for // all new projects.
[ "Generate", "a", "Variant", "3", "style", "UUID", ".", "These", "UUIDs", "are", "not", "time", "based", "instead", "using", "a", "namespace", "and", "a", "string", "to", "generate", "a", "hashed", "number", ".", "Variant", "3", "is", "MD5", "based", "and", "should", "only", "be", "used", "for", "legacy", "reasons", ".", "Use", "Variant", "5", "for", "all", "new", "projects", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L173-L181
3,039
apcera/util
uuid/uuid.go
Variant4
func Variant4() (u UUID) { // Output is: rrrrrrrr-rrrr-4rrr-Rrrr-rrrrrrrrrrrr // where 4 is mandated, and R must be one of 8, 9, A or B. u = make([]byte, UUIDByteLen) io.ReadFull(crypto_rand.Reader, u) u[6] = (u[6] & 0x0f) + 0x40 u[8] = (u[8] & 0x1f) + 0x80 return u }
go
func Variant4() (u UUID) { // Output is: rrrrrrrr-rrrr-4rrr-Rrrr-rrrrrrrrrrrr // where 4 is mandated, and R must be one of 8, 9, A or B. u = make([]byte, UUIDByteLen) io.ReadFull(crypto_rand.Reader, u) u[6] = (u[6] & 0x0f) + 0x40 u[8] = (u[8] & 0x1f) + 0x80 return u }
[ "func", "Variant4", "(", ")", "(", "u", "UUID", ")", "{", "// Output is: rrrrrrrr-rrrr-4rrr-Rrrr-rrrrrrrrrrrr", "// where 4 is mandated, and R must be one of 8, 9, A or B.", "u", "=", "make", "(", "[", "]", "byte", ",", "UUIDByteLen", ")", "\n", "io", ".", "ReadFull", "(", "crypto_rand", ".", "Reader", ",", "u", ")", "\n", "u", "[", "6", "]", "=", "(", "u", "[", "6", "]", "&", "0x0f", ")", "+", "0x40", "\n", "u", "[", "8", "]", "=", "(", "u", "[", "8", "]", "&", "0x1f", ")", "+", "0x80", "\n\n", "return", "u", "\n", "}" ]
// Generates a "Variant 4" style UUID. These are nothing more than random // data with the proper reserved bits set. // // A random UUID has not assurance that it is in fact unique. These are only // usable if you can survive duplication, or have a central source to // verify uniqueness.
[ "Generates", "a", "Variant", "4", "style", "UUID", ".", "These", "are", "nothing", "more", "than", "random", "data", "with", "the", "proper", "reserved", "bits", "set", ".", "A", "random", "UUID", "has", "not", "assurance", "that", "it", "is", "in", "fact", "unique", ".", "These", "are", "only", "usable", "if", "you", "can", "survive", "duplication", "or", "have", "a", "central", "source", "to", "verify", "uniqueness", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L189-L198
3,040
apcera/util
uuid/uuid.go
Variant5
func Variant5(namespace UUID, name string) (u UUID) { h := sha1.New() h.Write([]byte(namespace)) h.Write([]byte(name)) u = h.Sum(nil)[0:16] u[6] = (u[6] & 0x0f) | 0x50 u[8] = (u[8] & 0x3f) | 0x80 return u }
go
func Variant5(namespace UUID, name string) (u UUID) { h := sha1.New() h.Write([]byte(namespace)) h.Write([]byte(name)) u = h.Sum(nil)[0:16] u[6] = (u[6] & 0x0f) | 0x50 u[8] = (u[8] & 0x3f) | 0x80 return u }
[ "func", "Variant5", "(", "namespace", "UUID", ",", "name", "string", ")", "(", "u", "UUID", ")", "{", "h", ":=", "sha1", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "[", "]", "byte", "(", "namespace", ")", ")", "\n", "h", ".", "Write", "(", "[", "]", "byte", "(", "name", ")", ")", "\n", "u", "=", "h", ".", "Sum", "(", "nil", ")", "[", "0", ":", "16", "]", "\n", "u", "[", "6", "]", "=", "(", "u", "[", "6", "]", "&", "0x0f", ")", "|", "0x50", "\n", "u", "[", "8", "]", "=", "(", "u", "[", "8", "]", "&", "0x3f", ")", "|", "0x80", "\n", "return", "u", "\n", "}" ]
// Generate a "Variant 5" style UUID. These are functionally the same as // Variant 3, using sha1 rather than md5. Variant 5 UUIDs are recommended for // all new designs where Variant 3 would have normally been used. It takes a // given UUID as a name space and a string identifier, given the same name // space and string this will produce the same UUID.
[ "Generate", "a", "Variant", "5", "style", "UUID", ".", "These", "are", "functionally", "the", "same", "as", "Variant", "3", "using", "sha1", "rather", "than", "md5", ".", "Variant", "5", "UUIDs", "are", "recommended", "for", "all", "new", "designs", "where", "Variant", "3", "would", "have", "normally", "been", "used", ".", "It", "takes", "a", "given", "UUID", "as", "a", "name", "space", "and", "a", "string", "identifier", "given", "the", "same", "name", "space", "and", "string", "this", "will", "produce", "the", "same", "UUID", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L205-L213
3,041
apcera/util
uuid/uuid.go
Compare
func (u UUID) Compare(o UUID) int { return bytes.Compare(u, o) }
go
func (u UUID) Compare(o UUID) int { return bytes.Compare(u, o) }
[ "func", "(", "u", "UUID", ")", "Compare", "(", "o", "UUID", ")", "int", "{", "return", "bytes", ".", "Compare", "(", "u", ",", "o", ")", "\n", "}" ]
// Compares two UUID objects.
[ "Compares", "two", "UUID", "objects", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L222-L224
3,042
apcera/util
uuid/uuid.go
Equal
func (u UUID) Equal(o UUID) bool { return bytes.Equal(u, o) }
go
func (u UUID) Equal(o UUID) bool { return bytes.Equal(u, o) }
[ "func", "(", "u", "UUID", ")", "Equal", "(", "o", "UUID", ")", "bool", "{", "return", "bytes", ".", "Equal", "(", "u", ",", "o", ")", "\n", "}" ]
// Checks to see if two UUID objects are equal.
[ "Checks", "to", "see", "if", "two", "UUID", "objects", "are", "equal", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L227-L229
3,043
apcera/util
uuid/uuid.go
MarshalJSON
func (u UUID) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("\"%s\"", u.String())), nil }
go
func (u UUID) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("\"%s\"", u.String())), nil }
[ "func", "(", "u", "UUID", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "u", ".", "String", "(", ")", ")", ")", ",", "nil", "\n", "}" ]
// Returns the string representation, quoted, as bytes, for JSON encoding
[ "Returns", "the", "string", "representation", "quoted", "as", "bytes", "for", "JSON", "encoding" ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L282-L284
3,044
apcera/util
uuid/uuid.go
FromString
func FromString(s string) (u UUID, e error) { if len(s) != UUIDStringLen { return nil, &BadUUIDStringError{"length is not 36 bytes: " + s} } // Make enough space for the storage. u = make([]byte, UUIDByteLen) s_byte := []byte(s) var i int var err error i, err = hex.Decode(u[0:4], s_byte[0:8]) if err != nil || i != 4 { return nil, &BadUUIDStringError{"Invalid first component: " + s} } if s_byte[8] != '-' { return nil, &BadUUIDStringError{"Position 8 is not a dash: " + s} } i, err = hex.Decode(u[4:6], s_byte[9:13]) if err != nil || i != 2 { return nil, &BadUUIDStringError{"Invalid second component: " + s} } if s_byte[13] != '-' { return nil, &BadUUIDStringError{"Position 13 is not a dash: " + s} } i, err = hex.Decode(u[6:8], s_byte[14:18]) if err != nil || i != 2 { return nil, &BadUUIDStringError{"Invalid third component: " + s} } if s_byte[18] != '-' { return nil, &BadUUIDStringError{"Position 18 is not a dash: " + s} } i, err = hex.Decode(u[8:10], s_byte[19:23]) if err != nil || i != 2 { return nil, &BadUUIDStringError{"Invalid fourth component: " + s} } if s_byte[23] != '-' { return nil, &BadUUIDStringError{"Position 23 is not a dash: " + s} } i, err = hex.Decode(u[10:16], s_byte[24:36]) if err != nil || i != 6 { return nil, &BadUUIDStringError{"Invalid fifth component: " + s} } if u[8]&0xc0 != 0x80 { return nil, &BadUUIDStringError{"Reserved bits used: " + s} } return u, nil }
go
func FromString(s string) (u UUID, e error) { if len(s) != UUIDStringLen { return nil, &BadUUIDStringError{"length is not 36 bytes: " + s} } // Make enough space for the storage. u = make([]byte, UUIDByteLen) s_byte := []byte(s) var i int var err error i, err = hex.Decode(u[0:4], s_byte[0:8]) if err != nil || i != 4 { return nil, &BadUUIDStringError{"Invalid first component: " + s} } if s_byte[8] != '-' { return nil, &BadUUIDStringError{"Position 8 is not a dash: " + s} } i, err = hex.Decode(u[4:6], s_byte[9:13]) if err != nil || i != 2 { return nil, &BadUUIDStringError{"Invalid second component: " + s} } if s_byte[13] != '-' { return nil, &BadUUIDStringError{"Position 13 is not a dash: " + s} } i, err = hex.Decode(u[6:8], s_byte[14:18]) if err != nil || i != 2 { return nil, &BadUUIDStringError{"Invalid third component: " + s} } if s_byte[18] != '-' { return nil, &BadUUIDStringError{"Position 18 is not a dash: " + s} } i, err = hex.Decode(u[8:10], s_byte[19:23]) if err != nil || i != 2 { return nil, &BadUUIDStringError{"Invalid fourth component: " + s} } if s_byte[23] != '-' { return nil, &BadUUIDStringError{"Position 23 is not a dash: " + s} } i, err = hex.Decode(u[10:16], s_byte[24:36]) if err != nil || i != 6 { return nil, &BadUUIDStringError{"Invalid fifth component: " + s} } if u[8]&0xc0 != 0x80 { return nil, &BadUUIDStringError{"Reserved bits used: " + s} } return u, nil }
[ "func", "FromString", "(", "s", "string", ")", "(", "u", "UUID", ",", "e", "error", ")", "{", "if", "len", "(", "s", ")", "!=", "UUIDStringLen", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "// Make enough space for the storage.", "u", "=", "make", "(", "[", "]", "byte", ",", "UUIDByteLen", ")", "\n", "s_byte", ":=", "[", "]", "byte", "(", "s", ")", "\n\n", "var", "i", "int", "\n", "var", "err", "error", "\n\n", "i", ",", "err", "=", "hex", ".", "Decode", "(", "u", "[", "0", ":", "4", "]", ",", "s_byte", "[", "0", ":", "8", "]", ")", "\n", "if", "err", "!=", "nil", "||", "i", "!=", "4", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "if", "s_byte", "[", "8", "]", "!=", "'-'", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "i", ",", "err", "=", "hex", ".", "Decode", "(", "u", "[", "4", ":", "6", "]", ",", "s_byte", "[", "9", ":", "13", "]", ")", "\n", "if", "err", "!=", "nil", "||", "i", "!=", "2", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "if", "s_byte", "[", "13", "]", "!=", "'-'", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "i", ",", "err", "=", "hex", ".", "Decode", "(", "u", "[", "6", ":", "8", "]", ",", "s_byte", "[", "14", ":", "18", "]", ")", "\n", "if", "err", "!=", "nil", "||", "i", "!=", "2", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "if", "s_byte", "[", "18", "]", "!=", "'-'", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "i", ",", "err", "=", "hex", ".", "Decode", "(", "u", "[", "8", ":", "10", "]", ",", "s_byte", "[", "19", ":", "23", "]", ")", "\n", "if", "err", "!=", "nil", "||", "i", "!=", "2", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "if", "s_byte", "[", "23", "]", "!=", "'-'", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "i", ",", "err", "=", "hex", ".", "Decode", "(", "u", "[", "10", ":", "16", "]", ",", "s_byte", "[", "24", ":", "36", "]", ")", "\n", "if", "err", "!=", "nil", "||", "i", "!=", "6", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "if", "u", "[", "8", "]", "&", "0xc0", "!=", "0x80", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "+", "s", "}", "\n", "}", "\n\n", "return", "u", ",", "nil", "\n", "}" ]
// Converts a string representation of a UUID into a UUID object.
[ "Converts", "a", "string", "representation", "of", "a", "UUID", "into", "a", "UUID", "object", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L301-L359
3,045
apcera/util
uuid/uuid.go
FromBytes
func FromBytes(raw []byte) (u UUID, e error) { if len(raw) != UUIDByteLen { return nil, &NotAUUIDError{ fmt.Sprintf( "Length of memory object should be %d, is %d", UUIDByteLen, len(raw)), len(raw)} } if raw[8]&0xc0 != 0x80 { return nil, &BadUUIDStringError{"Reserved bits used"} } return UUID(raw), nil }
go
func FromBytes(raw []byte) (u UUID, e error) { if len(raw) != UUIDByteLen { return nil, &NotAUUIDError{ fmt.Sprintf( "Length of memory object should be %d, is %d", UUIDByteLen, len(raw)), len(raw)} } if raw[8]&0xc0 != 0x80 { return nil, &BadUUIDStringError{"Reserved bits used"} } return UUID(raw), nil }
[ "func", "FromBytes", "(", "raw", "[", "]", "byte", ")", "(", "u", "UUID", ",", "e", "error", ")", "{", "if", "len", "(", "raw", ")", "!=", "UUIDByteLen", "{", "return", "nil", ",", "&", "NotAUUIDError", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "UUIDByteLen", ",", "len", "(", "raw", ")", ")", ",", "len", "(", "raw", ")", "}", "\n", "}", "\n", "if", "raw", "[", "8", "]", "&", "0xc0", "!=", "0x80", "{", "return", "nil", ",", "&", "BadUUIDStringError", "{", "\"", "\"", "}", "\n", "}", "\n", "return", "UUID", "(", "raw", ")", ",", "nil", "\n", "}" ]
// Constructs a UUID from a raw bytes object
[ "Constructs", "a", "UUID", "from", "a", "raw", "bytes", "object" ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/uuid/uuid.go#L372-L383
3,046
apcera/util
events/wamp_client.go
NewWAMPSessionClient
func NewWAMPSessionClient(wampServerURL, authToken, realm string) (*EventClient, error) { u, err := url.Parse(wampServerURL) if err != nil { return nil, err } if u.Scheme == "https" { u.Scheme = "wss" } else { u.Scheme = "ws" } targetURL := u.String() if authToken != "" { authorization, err := url.Parse(authToken) if err != nil { return nil, err } if authorization.String() != "" { query := "authorization=" + authorization.String() targetURL += "?" + query } } wampClient, err := turnpike.NewWebsocketClient(turnpike.JSON, targetURL, nil) if err != nil { return nil, err } _, err = wampClient.JoinRealm(realm, nil) if err != nil { return nil, err } // ReceiveDone is notified when the client's connection to the router is lost. wampClient.ReceiveDone = make(chan bool) return &EventClient{wampClient}, nil }
go
func NewWAMPSessionClient(wampServerURL, authToken, realm string) (*EventClient, error) { u, err := url.Parse(wampServerURL) if err != nil { return nil, err } if u.Scheme == "https" { u.Scheme = "wss" } else { u.Scheme = "ws" } targetURL := u.String() if authToken != "" { authorization, err := url.Parse(authToken) if err != nil { return nil, err } if authorization.String() != "" { query := "authorization=" + authorization.String() targetURL += "?" + query } } wampClient, err := turnpike.NewWebsocketClient(turnpike.JSON, targetURL, nil) if err != nil { return nil, err } _, err = wampClient.JoinRealm(realm, nil) if err != nil { return nil, err } // ReceiveDone is notified when the client's connection to the router is lost. wampClient.ReceiveDone = make(chan bool) return &EventClient{wampClient}, nil }
[ "func", "NewWAMPSessionClient", "(", "wampServerURL", ",", "authToken", ",", "realm", "string", ")", "(", "*", "EventClient", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "wampServerURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "u", ".", "Scheme", "==", "\"", "\"", "{", "u", ".", "Scheme", "=", "\"", "\"", "\n", "}", "else", "{", "u", ".", "Scheme", "=", "\"", "\"", "\n", "}", "\n\n", "targetURL", ":=", "u", ".", "String", "(", ")", "\n", "if", "authToken", "!=", "\"", "\"", "{", "authorization", ",", "err", ":=", "url", ".", "Parse", "(", "authToken", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "authorization", ".", "String", "(", ")", "!=", "\"", "\"", "{", "query", ":=", "\"", "\"", "+", "authorization", ".", "String", "(", ")", "\n", "targetURL", "+=", "\"", "\"", "+", "query", "\n", "}", "\n", "}", "\n\n", "wampClient", ",", "err", ":=", "turnpike", ".", "NewWebsocketClient", "(", "turnpike", ".", "JSON", ",", "targetURL", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "wampClient", ".", "JoinRealm", "(", "realm", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// ReceiveDone is notified when the client's connection to the router is lost.", "wampClient", ".", "ReceiveDone", "=", "make", "(", "chan", "bool", ")", "\n\n", "return", "&", "EventClient", "{", "wampClient", "}", ",", "nil", "\n", "}" ]
// NewWAMPSessionClient returns a client handle associated with a session. It // accepts an optional authorization token to supply as a query parameter on the // initial request.
[ "NewWAMPSessionClient", "returns", "a", "client", "handle", "associated", "with", "a", "session", ".", "It", "accepts", "an", "optional", "authorization", "token", "to", "supply", "as", "a", "query", "parameter", "on", "the", "initial", "request", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/events/wamp_client.go#L19-L57
3,047
apcera/util
hashutil/hashutil.go
newHashReader
func newHashReader(h hash.Hash, r io.Reader) *hashReader { m := &hashReader{ source: r, hash: h, } return m }
go
func newHashReader(h hash.Hash, r io.Reader) *hashReader { m := &hashReader{ source: r, hash: h, } return m }
[ "func", "newHashReader", "(", "h", "hash", ".", "Hash", ",", "r", "io", ".", "Reader", ")", "*", "hashReader", "{", "m", ":=", "&", "hashReader", "{", "source", ":", "r", ",", "hash", ":", "h", ",", "}", "\n", "return", "m", "\n", "}" ]
// Returns a new hashReader.
[ "Returns", "a", "new", "hashReader", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/hashutil.go#L24-L30
3,048
apcera/util
hashutil/hashutil.go
Read
func (m *hashReader) Read(p []byte) (n int, err error) { n, err = m.source.Read(p) if n > 0 { // hash.Hash assures us that this can never return an error. m.hash.Write(p[0:n]) m.length += int64(n) } return }
go
func (m *hashReader) Read(p []byte) (n int, err error) { n, err = m.source.Read(p) if n > 0 { // hash.Hash assures us that this can never return an error. m.hash.Write(p[0:n]) m.length += int64(n) } return }
[ "func", "(", "m", "*", "hashReader", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "n", ",", "err", "=", "m", ".", "source", ".", "Read", "(", "p", ")", "\n", "if", "n", ">", "0", "{", "// hash.Hash assures us that this can never return an error.", "m", ".", "hash", ".", "Write", "(", "p", "[", "0", ":", "n", "]", ")", "\n", "m", ".", "length", "+=", "int64", "(", "n", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Reads from the source, and returns the values upstream after adding the data // to the hash.
[ "Reads", "from", "the", "source", "and", "returns", "the", "values", "upstream", "after", "adding", "the", "data", "to", "the", "hash", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/hashutil.go#L34-L42
3,049
apcera/util
hashutil/hashutil.go
Close
func (m *hashReader) Close() error { if m.source == nil { return nil } if r, ok := m.source.(io.Closer); ok { return r.Close() } return nil }
go
func (m *hashReader) Close() error { if m.source == nil { return nil } if r, ok := m.source.(io.Closer); ok { return r.Close() } return nil }
[ "func", "(", "m", "*", "hashReader", ")", "Close", "(", ")", "error", "{", "if", "m", ".", "source", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "r", ",", "ok", ":=", "m", ".", "source", ".", "(", "io", ".", "Closer", ")", ";", "ok", "{", "return", "r", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Closes the source, if it implements io.Closer.
[ "Closes", "the", "source", "if", "it", "implements", "io", ".", "Closer", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/hashutil.go#L45-L53
3,050
apcera/util
envmap/envmap.go
Keys
func (e *EnvMap) Keys() []string { var keys []string for k, _ := range e.Map() { keys = append(keys, k) } return keys }
go
func (e *EnvMap) Keys() []string { var keys []string for k, _ := range e.Map() { keys = append(keys, k) } return keys }
[ "func", "(", "e", "*", "EnvMap", ")", "Keys", "(", ")", "[", "]", "string", "{", "var", "keys", "[", "]", "string", "\n", "for", "k", ",", "_", ":=", "range", "e", ".", "Map", "(", ")", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n\n", "return", "keys", "\n", "}" ]
// Keys returns an array of the keys of the environment map.
[ "Keys", "returns", "an", "array", "of", "the", "keys", "of", "the", "environment", "map", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/envmap/envmap.go#L126-L133
3,051
apcera/util
deepmerge/merge.go
uglyDeepCopy
func uglyDeepCopy(v interface{}) (interface{}, error) { // marshal ugly := &uglyWrapper{Field: v} b, err := json.Marshal(ugly) if err != nil { return nil, err } // demarshal var ugly2 *uglyWrapper err = json.Unmarshal(b, &ugly2) if err != nil { return nil, err } return ugly2.Field, nil }
go
func uglyDeepCopy(v interface{}) (interface{}, error) { // marshal ugly := &uglyWrapper{Field: v} b, err := json.Marshal(ugly) if err != nil { return nil, err } // demarshal var ugly2 *uglyWrapper err = json.Unmarshal(b, &ugly2) if err != nil { return nil, err } return ugly2.Field, nil }
[ "func", "uglyDeepCopy", "(", "v", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// marshal", "ugly", ":=", "&", "uglyWrapper", "{", "Field", ":", "v", "}", "\n", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "ugly", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// demarshal", "var", "ugly2", "*", "uglyWrapper", "\n", "err", "=", "json", ".", "Unmarshal", "(", "b", ",", "&", "ugly2", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "ugly2", ".", "Field", ",", "nil", "\n", "}" ]
// uglyDeepCopy is a truly ugly and hacky way to ensure a deep copy is done on // an object, but it is what is necessary to ensure that the source object is // fully cloned so that it can be assigned to the destination and ensure futher // changes within the destination do not use a shared pointer and alter the // source. This method of wrapping it in JSON has side effects around integer // handling in Go and limits object types, such has maps with only string // keys. However, Go has no true deep copy functionality built in or currently // available via third party packages that work or are up to date.
[ "uglyDeepCopy", "is", "a", "truly", "ugly", "and", "hacky", "way", "to", "ensure", "a", "deep", "copy", "is", "done", "on", "an", "object", "but", "it", "is", "what", "is", "necessary", "to", "ensure", "that", "the", "source", "object", "is", "fully", "cloned", "so", "that", "it", "can", "be", "assigned", "to", "the", "destination", "and", "ensure", "futher", "changes", "within", "the", "destination", "do", "not", "use", "a", "shared", "pointer", "and", "alter", "the", "source", ".", "This", "method", "of", "wrapping", "it", "in", "JSON", "has", "side", "effects", "around", "integer", "handling", "in", "Go", "and", "limits", "object", "types", "such", "has", "maps", "with", "only", "string", "keys", ".", "However", "Go", "has", "no", "true", "deep", "copy", "functionality", "built", "in", "or", "currently", "available", "via", "third", "party", "packages", "that", "work", "or", "are", "up", "to", "date", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/deepmerge/merge.go#L83-L99
3,052
apcera/util
docker/v1/registry.go
GetImage
func GetImage(name, registryURL string) (*Image, int, error) { if name == "" { return nil, -1, errors.New("image name is empty") } var ru *url.URL var err error if len(registryURL) != 0 { ru, err = url.Parse(registryURL) } else { ru, err = url.Parse(DockerHubRegistryURL) registryURL = DockerHubRegistryURL } if err != nil { return nil, -1, err } // In order to get layers from Docker CDN we need to hit 'images' endpoint // and request the token. Client should also accept and store cookies, as // they are needed to fetch the layer data later. imagesURL := fmt.Sprintf("%s/v1/repositories/%s/images", registryURL, name) req, err := http.NewRequest("GET", imagesURL, nil) if err != nil { return nil, -1, err } // FIXME: Send 'Connection: close' header on HTTP requests // as reusing the connection is still prone to EOF/Connection reset errors // in certain network environments... // See: ENGT-9670 // https://stackoverflow.com/questions/17714494/golang-http-request-results-in-eof-errors req.Close = true req.Header.Set("X-Docker-Token", "true") client := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, } client.Jar, err = cookiejar.New(nil) // Docker repo API sets and uses cookies for CDN. if err != nil { return nil, -1, err } res, err := client.Do(req) if err != nil { return nil, -1, err } defer res.Body.Close() switch res.StatusCode { case http.StatusOK: // Fall through. case http.StatusNotFound: return nil, res.StatusCode, fmt.Errorf("image %q not found", name) default: return nil, res.StatusCode, fmt.Errorf("HTTP %d ", res.StatusCode) } token := res.Header.Get("X-Docker-Token") endpoints := strings.Split(res.Header.Get("X-Docker-Endpoints"), ",") if len(endpoints) == 0 { return nil, res.StatusCode, errors.New("Docker index response didn't contain any endpoints") } for i := range endpoints { endpoints[i] = strings.Trim(endpoints[i], " ") } img := &Image{ Name: name, client: client, endpoints: endpoints, token: token, scheme: ru.Scheme, } img.tags, err = img.fetchTags() if err != nil { return nil, res.StatusCode, err } return img, res.StatusCode, nil }
go
func GetImage(name, registryURL string) (*Image, int, error) { if name == "" { return nil, -1, errors.New("image name is empty") } var ru *url.URL var err error if len(registryURL) != 0 { ru, err = url.Parse(registryURL) } else { ru, err = url.Parse(DockerHubRegistryURL) registryURL = DockerHubRegistryURL } if err != nil { return nil, -1, err } // In order to get layers from Docker CDN we need to hit 'images' endpoint // and request the token. Client should also accept and store cookies, as // they are needed to fetch the layer data later. imagesURL := fmt.Sprintf("%s/v1/repositories/%s/images", registryURL, name) req, err := http.NewRequest("GET", imagesURL, nil) if err != nil { return nil, -1, err } // FIXME: Send 'Connection: close' header on HTTP requests // as reusing the connection is still prone to EOF/Connection reset errors // in certain network environments... // See: ENGT-9670 // https://stackoverflow.com/questions/17714494/golang-http-request-results-in-eof-errors req.Close = true req.Header.Set("X-Docker-Token", "true") client := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, } client.Jar, err = cookiejar.New(nil) // Docker repo API sets and uses cookies for CDN. if err != nil { return nil, -1, err } res, err := client.Do(req) if err != nil { return nil, -1, err } defer res.Body.Close() switch res.StatusCode { case http.StatusOK: // Fall through. case http.StatusNotFound: return nil, res.StatusCode, fmt.Errorf("image %q not found", name) default: return nil, res.StatusCode, fmt.Errorf("HTTP %d ", res.StatusCode) } token := res.Header.Get("X-Docker-Token") endpoints := strings.Split(res.Header.Get("X-Docker-Endpoints"), ",") if len(endpoints) == 0 { return nil, res.StatusCode, errors.New("Docker index response didn't contain any endpoints") } for i := range endpoints { endpoints[i] = strings.Trim(endpoints[i], " ") } img := &Image{ Name: name, client: client, endpoints: endpoints, token: token, scheme: ru.Scheme, } img.tags, err = img.fetchTags() if err != nil { return nil, res.StatusCode, err } return img, res.StatusCode, nil }
[ "func", "GetImage", "(", "name", ",", "registryURL", "string", ")", "(", "*", "Image", ",", "int", ",", "error", ")", "{", "if", "name", "==", "\"", "\"", "{", "return", "nil", ",", "-", "1", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "ru", "*", "url", ".", "URL", "\n", "var", "err", "error", "\n", "if", "len", "(", "registryURL", ")", "!=", "0", "{", "ru", ",", "err", "=", "url", ".", "Parse", "(", "registryURL", ")", "\n", "}", "else", "{", "ru", ",", "err", "=", "url", ".", "Parse", "(", "DockerHubRegistryURL", ")", "\n", "registryURL", "=", "DockerHubRegistryURL", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "err", "\n", "}", "\n\n", "// In order to get layers from Docker CDN we need to hit 'images' endpoint", "// and request the token. Client should also accept and store cookies, as", "// they are needed to fetch the layer data later.", "imagesURL", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "registryURL", ",", "name", ")", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "imagesURL", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "err", "\n", "}", "\n\n", "// FIXME: Send 'Connection: close' header on HTTP requests", "// as reusing the connection is still prone to EOF/Connection reset errors", "// in certain network environments...", "// See: ENGT-9670", "// https://stackoverflow.com/questions/17714494/golang-http-request-results-in-eof-errors", "req", ".", "Close", "=", "true", "\n\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "client", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "}", ",", "}", "\n", "client", ".", "Jar", ",", "err", "=", "cookiejar", ".", "New", "(", "nil", ")", "// Docker repo API sets and uses cookies for CDN.", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "err", "\n", "}", "\n\n", "res", ",", "err", ":=", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "err", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "switch", "res", ".", "StatusCode", "{", "case", "http", ".", "StatusOK", ":", "// Fall through.", "case", "http", ".", "StatusNotFound", ":", "return", "nil", ",", "res", ".", "StatusCode", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "default", ":", "return", "nil", ",", "res", ".", "StatusCode", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "StatusCode", ")", "\n", "}", "\n\n", "token", ":=", "res", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "endpoints", ":=", "strings", ".", "Split", "(", "res", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n\n", "if", "len", "(", "endpoints", ")", "==", "0", "{", "return", "nil", ",", "res", ".", "StatusCode", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ":=", "range", "endpoints", "{", "endpoints", "[", "i", "]", "=", "strings", ".", "Trim", "(", "endpoints", "[", "i", "]", ",", "\"", "\"", ")", "\n", "}", "\n\n", "img", ":=", "&", "Image", "{", "Name", ":", "name", ",", "client", ":", "client", ",", "endpoints", ":", "endpoints", ",", "token", ":", "token", ",", "scheme", ":", "ru", ".", "Scheme", ",", "}", "\n\n", "img", ".", "tags", ",", "err", "=", "img", ".", "fetchTags", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "res", ".", "StatusCode", ",", "err", "\n", "}", "\n\n", "return", "img", ",", "res", ".", "StatusCode", ",", "nil", "\n", "}" ]
// GetImage fetches Docker repository information from the specified Docker // registry. If the registry is an empty string it defaults to the DockerHub. // The integer return value is the status code of the HTTP response.
[ "GetImage", "fetches", "Docker", "repository", "information", "from", "the", "specified", "Docker", "registry", ".", "If", "the", "registry", "is", "an", "empty", "string", "it", "defaults", "to", "the", "DockerHub", ".", "The", "integer", "return", "value", "is", "the", "status", "code", "of", "the", "HTTP", "response", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L41-L125
3,053
apcera/util
docker/v1/registry.go
Tags
func (i *Image) Tags() []string { result := make([]string, 0) for tag, _ := range i.tags { result = append(result, tag) } return result }
go
func (i *Image) Tags() []string { result := make([]string, 0) for tag, _ := range i.tags { result = append(result, tag) } return result }
[ "func", "(", "i", "*", "Image", ")", "Tags", "(", ")", "[", "]", "string", "{", "result", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n\n", "for", "tag", ",", "_", ":=", "range", "i", ".", "tags", "{", "result", "=", "append", "(", "result", ",", "tag", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Tags returns a list of tags available for image
[ "Tags", "returns", "a", "list", "of", "tags", "available", "for", "image" ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L128-L136
3,054
apcera/util
docker/v1/registry.go
TagLayerID
func (i *Image) TagLayerID(tagName string) (string, error) { layerID, ok := i.tags[tagName] if !ok { return "", fmt.Errorf("can't find tag '%s' for image '%s'", tagName, i.Name) } return layerID, nil }
go
func (i *Image) TagLayerID(tagName string) (string, error) { layerID, ok := i.tags[tagName] if !ok { return "", fmt.Errorf("can't find tag '%s' for image '%s'", tagName, i.Name) } return layerID, nil }
[ "func", "(", "i", "*", "Image", ")", "TagLayerID", "(", "tagName", "string", ")", "(", "string", ",", "error", ")", "{", "layerID", ",", "ok", ":=", "i", ".", "tags", "[", "tagName", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tagName", ",", "i", ".", "Name", ")", "\n", "}", "\n\n", "return", "layerID", ",", "nil", "\n", "}" ]
// TagLayerID returns a layer ID for a given tag.
[ "TagLayerID", "returns", "a", "layer", "ID", "for", "a", "given", "tag", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L139-L146
3,055
apcera/util
docker/v1/registry.go
Metadata
func (i *Image) Metadata(tagName string, v interface{}) error { layerID, ok := i.tags[tagName] if !ok { return fmt.Errorf("can't find tag '%s' for image '%s'", tagName, i.Name) } err := i.parseResponse(fmt.Sprintf("v1/images/%s/json", layerID), &v) if err != nil { return err } return nil }
go
func (i *Image) Metadata(tagName string, v interface{}) error { layerID, ok := i.tags[tagName] if !ok { return fmt.Errorf("can't find tag '%s' for image '%s'", tagName, i.Name) } err := i.parseResponse(fmt.Sprintf("v1/images/%s/json", layerID), &v) if err != nil { return err } return nil }
[ "func", "(", "i", "*", "Image", ")", "Metadata", "(", "tagName", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "layerID", ",", "ok", ":=", "i", ".", "tags", "[", "tagName", "]", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tagName", ",", "i", ".", "Name", ")", "\n", "}", "\n\n", "err", ":=", "i", ".", "parseResponse", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "layerID", ")", ",", "&", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Metadata unmarshals a Docker image metadata into provided 'v' interface.
[ "Metadata", "unmarshals", "a", "Docker", "image", "metadata", "into", "provided", "v", "interface", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L149-L160
3,056
apcera/util
docker/v1/registry.go
History
func (i *Image) History(tagName string) ([]string, error) { layerID, ok := i.tags[tagName] if !ok { return nil, fmt.Errorf("can't find tag '%s' for image '%s'", tagName, i.Name) } var history []string err := i.parseResponse(fmt.Sprintf("v1/images/%s/ancestry", layerID), &history) if err != nil { return nil, err } return history, nil }
go
func (i *Image) History(tagName string) ([]string, error) { layerID, ok := i.tags[tagName] if !ok { return nil, fmt.Errorf("can't find tag '%s' for image '%s'", tagName, i.Name) } var history []string err := i.parseResponse(fmt.Sprintf("v1/images/%s/ancestry", layerID), &history) if err != nil { return nil, err } return history, nil }
[ "func", "(", "i", "*", "Image", ")", "History", "(", "tagName", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "layerID", ",", "ok", ":=", "i", ".", "tags", "[", "tagName", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tagName", ",", "i", ".", "Name", ")", "\n", "}", "\n\n", "var", "history", "[", "]", "string", "\n", "err", ":=", "i", ".", "parseResponse", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "layerID", ")", ",", "&", "history", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "history", ",", "nil", "\n", "}" ]
// History returns an ordered list of layers that make up Docker. The order is reverse, it goes from // the latest layer to the base layer. Client can iterate these layers and download them using LayerReader.
[ "History", "returns", "an", "ordered", "list", "of", "layers", "that", "make", "up", "Docker", ".", "The", "order", "is", "reverse", "it", "goes", "from", "the", "latest", "layer", "to", "the", "base", "layer", ".", "Client", "can", "iterate", "these", "layers", "and", "download", "them", "using", "LayerReader", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L164-L176
3,057
apcera/util
docker/v1/registry.go
LayerReader
func (i *Image) LayerReader(id string) (io.ReadCloser, error) { resp, err := i.getResponse(fmt.Sprintf("v1/images/%s/layer", id)) if err != nil { return nil, err } return resp.Body, nil }
go
func (i *Image) LayerReader(id string) (io.ReadCloser, error) { resp, err := i.getResponse(fmt.Sprintf("v1/images/%s/layer", id)) if err != nil { return nil, err } return resp.Body, nil }
[ "func", "(", "i", "*", "Image", ")", "LayerReader", "(", "id", "string", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "resp", ",", "err", ":=", "i", ".", "getResponse", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "resp", ".", "Body", ",", "nil", "\n", "}" ]
// LayerReader returns io.ReadCloser that can be used to read Docker layer data.
[ "LayerReader", "returns", "io", ".", "ReadCloser", "that", "can", "be", "used", "to", "read", "Docker", "layer", "data", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L179-L185
3,058
apcera/util
docker/v1/registry.go
LayerURLs
func (i *Image) LayerURLs(id string) []string { var urls []string for _, ep := range i.endpoints { urls = append(urls, fmt.Sprintf("%s://%s/v1/images/%s/layer", i.scheme, ep, id)) } return urls }
go
func (i *Image) LayerURLs(id string) []string { var urls []string for _, ep := range i.endpoints { urls = append(urls, fmt.Sprintf("%s://%s/v1/images/%s/layer", i.scheme, ep, id)) } return urls }
[ "func", "(", "i", "*", "Image", ")", "LayerURLs", "(", "id", "string", ")", "[", "]", "string", "{", "var", "urls", "[", "]", "string", "\n", "for", "_", ",", "ep", ":=", "range", "i", ".", "endpoints", "{", "urls", "=", "append", "(", "urls", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ".", "scheme", ",", "ep", ",", "id", ")", ")", "\n", "}", "\n", "return", "urls", "\n", "}" ]
// LayerURLs returns several URLs for a specific layer.
[ "LayerURLs", "returns", "several", "URLs", "for", "a", "specific", "layer", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L188-L194
3,059
apcera/util
docker/v1/registry.go
AuthorizationHeader
func (i *Image) AuthorizationHeader() string { if i.token == "" { return "" } return fmt.Sprintf("Token %s", i.token) }
go
func (i *Image) AuthorizationHeader() string { if i.token == "" { return "" } return fmt.Sprintf("Token %s", i.token) }
[ "func", "(", "i", "*", "Image", ")", "AuthorizationHeader", "(", ")", "string", "{", "if", "i", ".", "token", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ".", "token", ")", "\n", "}" ]
// AuthorizationHeader exposes the authorization header created for the image // for external layer downloads.
[ "AuthorizationHeader", "exposes", "the", "authorization", "header", "created", "for", "the", "image", "for", "external", "layer", "downloads", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L198-L203
3,060
apcera/util
docker/v1/registry.go
fetchTags
func (i *Image) fetchTags() (map[string]string, error) { // There is a weird quirk about Docker API: if tags are requested from index.docker.io, // it returns a list of short layer IDs, so it's impossible to use them to download actual layers. // However, when we hit the endpoint returned by image index API response, it has an expected format. var tags map[string]string err := i.parseResponse(fmt.Sprintf("v1/repositories/%s/tags", i.Name), &tags) if err != nil { return nil, err } return tags, nil }
go
func (i *Image) fetchTags() (map[string]string, error) { // There is a weird quirk about Docker API: if tags are requested from index.docker.io, // it returns a list of short layer IDs, so it's impossible to use them to download actual layers. // However, when we hit the endpoint returned by image index API response, it has an expected format. var tags map[string]string err := i.parseResponse(fmt.Sprintf("v1/repositories/%s/tags", i.Name), &tags) if err != nil { return nil, err } return tags, nil }
[ "func", "(", "i", "*", "Image", ")", "fetchTags", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "// There is a weird quirk about Docker API: if tags are requested from index.docker.io,", "// it returns a list of short layer IDs, so it's impossible to use them to download actual layers.", "// However, when we hit the endpoint returned by image index API response, it has an expected format.", "var", "tags", "map", "[", "string", "]", "string", "\n", "err", ":=", "i", ".", "parseResponse", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ".", "Name", ")", ",", "&", "tags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "tags", ",", "nil", "\n", "}" ]
// fetchTags fetches tags for the image and caches them in the Image struct, // so that other methods can look them up efficiently.
[ "fetchTags", "fetches", "tags", "for", "the", "image", "and", "caches", "them", "in", "the", "Image", "struct", "so", "that", "other", "methods", "can", "look", "them", "up", "efficiently", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L207-L217
3,061
apcera/util
docker/v1/registry.go
getResponse
func (i *Image) getResponse(path string) (*http.Response, error) { errors := make(map[string]error) for _, ep := range i.endpoints { resp, err := i.getResponseFromURL(fmt.Sprintf("%s://%s/%s", i.scheme, ep, path)) if err != nil { errors[ep] = err continue } return resp, nil } return nil, combineEndpointErrors(errors) }
go
func (i *Image) getResponse(path string) (*http.Response, error) { errors := make(map[string]error) for _, ep := range i.endpoints { resp, err := i.getResponseFromURL(fmt.Sprintf("%s://%s/%s", i.scheme, ep, path)) if err != nil { errors[ep] = err continue } return resp, nil } return nil, combineEndpointErrors(errors) }
[ "func", "(", "i", "*", "Image", ")", "getResponse", "(", "path", "string", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "errors", ":=", "make", "(", "map", "[", "string", "]", "error", ")", "\n\n", "for", "_", ",", "ep", ":=", "range", "i", ".", "endpoints", "{", "resp", ",", "err", ":=", "i", ".", "getResponseFromURL", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ".", "scheme", ",", "ep", ",", "path", ")", ")", "\n", "if", "err", "!=", "nil", "{", "errors", "[", "ep", "]", "=", "err", "\n", "continue", "\n", "}", "\n\n", "return", "resp", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "combineEndpointErrors", "(", "errors", ")", "\n", "}" ]
// getAPIResponse takes a path and tries to get Docker API response from each // available Docker API endpoint. It returns raw HTTP response.
[ "getAPIResponse", "takes", "a", "path", "and", "tries", "to", "get", "Docker", "API", "response", "from", "each", "available", "Docker", "API", "endpoint", ".", "It", "returns", "raw", "HTTP", "response", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L221-L235
3,062
apcera/util
docker/v1/registry.go
parseResponse
func (i *Image) parseResponse(path string, result interface{}) error { errors := make(map[string]error) for _, ep := range i.endpoints { err := i.parseResponseFromURL(fmt.Sprintf("%s://%s/%s", i.scheme, ep, path), result) if err != nil { errors[ep] = err continue } return nil } return combineEndpointErrors(errors) }
go
func (i *Image) parseResponse(path string, result interface{}) error { errors := make(map[string]error) for _, ep := range i.endpoints { err := i.parseResponseFromURL(fmt.Sprintf("%s://%s/%s", i.scheme, ep, path), result) if err != nil { errors[ep] = err continue } return nil } return combineEndpointErrors(errors) }
[ "func", "(", "i", "*", "Image", ")", "parseResponse", "(", "path", "string", ",", "result", "interface", "{", "}", ")", "error", "{", "errors", ":=", "make", "(", "map", "[", "string", "]", "error", ")", "\n\n", "for", "_", ",", "ep", ":=", "range", "i", ".", "endpoints", "{", "err", ":=", "i", ".", "parseResponseFromURL", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ".", "scheme", ",", "ep", ",", "path", ")", ",", "result", ")", "\n", "if", "err", "!=", "nil", "{", "errors", "[", "ep", "]", "=", "err", "\n", "continue", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n\n", "return", "combineEndpointErrors", "(", "errors", ")", "\n", "}" ]
// parseJSONResponse takes a path and tries to get Docker API response from each // available Docker API endpoint. It tries to parse response as JSON and saves // the parsed version in the provided 'result' variable.
[ "parseJSONResponse", "takes", "a", "path", "and", "tries", "to", "get", "Docker", "API", "response", "from", "each", "available", "Docker", "API", "endpoint", ".", "It", "tries", "to", "parse", "response", "as", "JSON", "and", "saves", "the", "parsed", "version", "in", "the", "provided", "result", "variable", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L240-L254
3,063
apcera/util
docker/v1/registry.go
getResponseFromURL
func (i *Image) getResponseFromURL(u string) (*http.Response, error) { req, err := http.NewRequest("GET", u, nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Token "+i.token) res, err := i.client.Do(req) if err != nil { return nil, err } if res.StatusCode != http.StatusOK { defer res.Body.Close() type errorMsg struct { Error string `json:"error"` } var errMsg errorMsg if err := json.NewDecoder(res.Body).Decode(&errMsg); err == nil { return nil, fmt.Errorf("%s: HTTP %d - %s", u, res.StatusCode, errMsg.Error) } return nil, fmt.Errorf("%s: HTTP %d", u, res.StatusCode) } return res, nil }
go
func (i *Image) getResponseFromURL(u string) (*http.Response, error) { req, err := http.NewRequest("GET", u, nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Token "+i.token) res, err := i.client.Do(req) if err != nil { return nil, err } if res.StatusCode != http.StatusOK { defer res.Body.Close() type errorMsg struct { Error string `json:"error"` } var errMsg errorMsg if err := json.NewDecoder(res.Body).Decode(&errMsg); err == nil { return nil, fmt.Errorf("%s: HTTP %d - %s", u, res.StatusCode, errMsg.Error) } return nil, fmt.Errorf("%s: HTTP %d", u, res.StatusCode) } return res, nil }
[ "func", "(", "i", "*", "Image", ")", "getResponseFromURL", "(", "u", "string", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "u", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", "+", "i", ".", "token", ")", "\n\n", "res", ",", "err", ":=", "i", ".", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "res", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "type", "errorMsg", "struct", "{", "Error", "string", "`json:\"error\"`", "\n", "}", "\n\n", "var", "errMsg", "errorMsg", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "res", ".", "Body", ")", ".", "Decode", "(", "&", "errMsg", ")", ";", "err", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "u", ",", "res", ".", "StatusCode", ",", "errMsg", ".", "Error", ")", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "u", ",", "res", ".", "StatusCode", ")", "\n", "}", "\n\n", "return", "res", ",", "nil", "\n", "}" ]
// getAPIResponseFromURL returns raw Docker API response at URL 'u'.
[ "getAPIResponseFromURL", "returns", "raw", "Docker", "API", "response", "at", "URL", "u", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L257-L284
3,064
apcera/util
docker/v1/registry.go
parseResponseFromURL
func (i *Image) parseResponseFromURL(u string, result interface{}) error { resp, err := i.getResponseFromURL(u) if err != nil { return err } defer resp.Body.Close() dec := json.NewDecoder(resp.Body) if err := dec.Decode(&result); err != nil { return err } return nil }
go
func (i *Image) parseResponseFromURL(u string, result interface{}) error { resp, err := i.getResponseFromURL(u) if err != nil { return err } defer resp.Body.Close() dec := json.NewDecoder(resp.Body) if err := dec.Decode(&result); err != nil { return err } return nil }
[ "func", "(", "i", "*", "Image", ")", "parseResponseFromURL", "(", "u", "string", ",", "result", "interface", "{", "}", ")", "error", "{", "resp", ",", "err", ":=", "i", ".", "getResponseFromURL", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "dec", ":=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "result", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// parseResponseFromURL returns parsed JSON of a Docker API response at URL 'u'.
[ "parseResponseFromURL", "returns", "parsed", "JSON", "of", "a", "Docker", "API", "response", "at", "URL", "u", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L287-L301
3,065
apcera/util
docker/v1/registry.go
Cookie
func (i *Image) Cookie(u string) (string, error) { if i.client.Jar == nil { return "", nil } baseURL, err := url.Parse(u) if err != nil { return "", fmt.Errorf("Invalid URL: %s", err) } cookies := i.client.Jar.Cookies(baseURL) if len(cookies) == 0 { return "", nil } return cookies[0].String(), nil }
go
func (i *Image) Cookie(u string) (string, error) { if i.client.Jar == nil { return "", nil } baseURL, err := url.Parse(u) if err != nil { return "", fmt.Errorf("Invalid URL: %s", err) } cookies := i.client.Jar.Cookies(baseURL) if len(cookies) == 0 { return "", nil } return cookies[0].String(), nil }
[ "func", "(", "i", "*", "Image", ")", "Cookie", "(", "u", "string", ")", "(", "string", ",", "error", ")", "{", "if", "i", ".", "client", ".", "Jar", "==", "nil", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n\n", "baseURL", ",", "err", ":=", "url", ".", "Parse", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "cookies", ":=", "i", ".", "client", ".", "Jar", ".", "Cookies", "(", "baseURL", ")", "\n", "if", "len", "(", "cookies", ")", "==", "0", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n\n", "return", "cookies", "[", "0", "]", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// Cookie returns the string representation of the first // cookie stored in stored client's cookie jar.
[ "Cookie", "returns", "the", "string", "representation", "of", "the", "first", "cookie", "stored", "in", "stored", "client", "s", "cookie", "jar", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L305-L321
3,066
apcera/util
docker/v1/registry.go
combineEndpointErrors
func combineEndpointErrors(allErrors map[string]error) error { var parts []string for ep, err := range allErrors { parts = append(parts, fmt.Sprintf("%s: %s", ep, err)) } return errors.New(strings.Join(parts, ", ")) }
go
func combineEndpointErrors(allErrors map[string]error) error { var parts []string for ep, err := range allErrors { parts = append(parts, fmt.Sprintf("%s: %s", ep, err)) } return errors.New(strings.Join(parts, ", ")) }
[ "func", "combineEndpointErrors", "(", "allErrors", "map", "[", "string", "]", "error", ")", "error", "{", "var", "parts", "[", "]", "string", "\n", "for", "ep", ",", "err", ":=", "range", "allErrors", "{", "parts", "=", "append", "(", "parts", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ep", ",", "err", ")", ")", "\n", "}", "\n", "return", "errors", ".", "New", "(", "strings", ".", "Join", "(", "parts", ",", "\"", "\"", ")", ")", "\n", "}" ]
// combineEndpointErrors takes a mapping of Docker API endpoints to errors encountered // while talking to them and returns a single error that contains all endpoint URLs // along with error for each URL.
[ "combineEndpointErrors", "takes", "a", "mapping", "of", "Docker", "API", "endpoints", "to", "errors", "encountered", "while", "talking", "to", "them", "and", "returns", "a", "single", "error", "that", "contains", "all", "endpoint", "URLs", "along", "with", "error", "for", "each", "URL", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/v1/registry.go#L326-L332
3,067
apcera/util
docker/registry_url.go
ParseFullDockerRegistryURL
func ParseFullDockerRegistryURL(s string) (*DockerRegistryURL, error) { s = handleSchemelessQuayRegistries(s) registryURL := &DockerRegistryURL{ Scheme: "https", } u, err := url.Parse(s) if err != nil { return nil, err } if u.Scheme == "" || u.Host == "" { return registryURL, fmt.Errorf("Registry URL must provide a scheme and host: %q", s) } registryURL.Scheme = u.Scheme registryURL.Userinfo = u.User host, port, err := splitHostPort(u.Host) if err != nil { return nil, err } registryURL.Host = host registryURL.Port = port // Parse everything after <scheme>://<host>:<port> err = registryURL.parsePath(u.Path) if err != nil { return nil, err } return registryURL, nil }
go
func ParseFullDockerRegistryURL(s string) (*DockerRegistryURL, error) { s = handleSchemelessQuayRegistries(s) registryURL := &DockerRegistryURL{ Scheme: "https", } u, err := url.Parse(s) if err != nil { return nil, err } if u.Scheme == "" || u.Host == "" { return registryURL, fmt.Errorf("Registry URL must provide a scheme and host: %q", s) } registryURL.Scheme = u.Scheme registryURL.Userinfo = u.User host, port, err := splitHostPort(u.Host) if err != nil { return nil, err } registryURL.Host = host registryURL.Port = port // Parse everything after <scheme>://<host>:<port> err = registryURL.parsePath(u.Path) if err != nil { return nil, err } return registryURL, nil }
[ "func", "ParseFullDockerRegistryURL", "(", "s", "string", ")", "(", "*", "DockerRegistryURL", ",", "error", ")", "{", "s", "=", "handleSchemelessQuayRegistries", "(", "s", ")", "\n\n", "registryURL", ":=", "&", "DockerRegistryURL", "{", "Scheme", ":", "\"", "\"", ",", "}", "\n\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "u", ".", "Scheme", "==", "\"", "\"", "||", "u", ".", "Host", "==", "\"", "\"", "{", "return", "registryURL", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n\n", "registryURL", ".", "Scheme", "=", "u", ".", "Scheme", "\n", "registryURL", ".", "Userinfo", "=", "u", ".", "User", "\n\n", "host", ",", "port", ",", "err", ":=", "splitHostPort", "(", "u", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "registryURL", ".", "Host", "=", "host", "\n", "registryURL", ".", "Port", "=", "port", "\n\n", "// Parse everything after <scheme>://<host>:<port>", "err", "=", "registryURL", ".", "parsePath", "(", "u", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "registryURL", ",", "nil", "\n", "}" ]
// ParseFullDockerRegistryURL validates an input string URL to make sure // that it conforms to the Docker V1 registry URL schema.
[ "ParseFullDockerRegistryURL", "validates", "an", "input", "string", "URL", "to", "make", "sure", "that", "it", "conforms", "to", "the", "Docker", "V1", "registry", "URL", "schema", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/registry_url.go#L91-L123
3,068
apcera/util
docker/registry_url.go
splitHostPort
func splitHostPort(hostport string) (string, string, error) { if strings.Contains(hostport, ":") { return net.SplitHostPort(hostport) } else { return hostport, "", nil } }
go
func splitHostPort(hostport string) (string, string, error) { if strings.Contains(hostport, ":") { return net.SplitHostPort(hostport) } else { return hostport, "", nil } }
[ "func", "splitHostPort", "(", "hostport", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "if", "strings", ".", "Contains", "(", "hostport", ",", "\"", "\"", ")", "{", "return", "net", ".", "SplitHostPort", "(", "hostport", ")", "\n", "}", "else", "{", "return", "hostport", ",", "\"", "\"", ",", "nil", "\n", "}", "\n", "}" ]
// splitHostPort wraps net.SplitHostPort, and can be called on a host // whether or not it contains a port segment.
[ "splitHostPort", "wraps", "net", ".", "SplitHostPort", "and", "can", "be", "called", "on", "a", "host", "whether", "or", "not", "it", "contains", "a", "port", "segment", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/registry_url.go#L138-L144
3,069
apcera/util
docker/registry_url.go
cleanPath
func cleanPath(s string) (string, error) { s = strings.Trim(s, "/") if strings.HasPrefix(s, ":") { return "", fmt.Errorf("Path cannot be made up of just a tag: %q", s) } return s, nil }
go
func cleanPath(s string) (string, error) { s = strings.Trim(s, "/") if strings.HasPrefix(s, ":") { return "", fmt.Errorf("Path cannot be made up of just a tag: %q", s) } return s, nil }
[ "func", "cleanPath", "(", "s", "string", ")", "(", "string", ",", "error", ")", "{", "s", "=", "strings", ".", "Trim", "(", "s", ",", "\"", "\"", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "s", ",", "\"", "\"", ")", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "return", "s", ",", "nil", "\n", "}" ]
// cleanPath removes leading and trailing forward slashes // and makes sure that the path does not only contain a tag.
[ "cleanPath", "removes", "leading", "and", "trailing", "forward", "slashes", "and", "makes", "sure", "that", "the", "path", "does", "not", "only", "contain", "a", "tag", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/registry_url.go#L171-L177
3,070
apcera/util
docker/registry_url.go
parseTag
func parseTag(s string) (prefix, tag string, err error) { splitString := strings.Split(s, ":") if len(splitString) == 1 { prefix = splitString[0] } else if len(splitString) == 2 { prefix, tag = splitString[0], splitString[1] } else { // Unlikely edge case but it doesn't hurt to test for it. return "", "", fmt.Errorf("Path should not contain more than one colon: %q", s) } if strings.HasSuffix(prefix, "/") { return "", "", fmt.Errorf(`Image name must not have a trailing "/": %s`, prefix) } return prefix, tag, nil }
go
func parseTag(s string) (prefix, tag string, err error) { splitString := strings.Split(s, ":") if len(splitString) == 1 { prefix = splitString[0] } else if len(splitString) == 2 { prefix, tag = splitString[0], splitString[1] } else { // Unlikely edge case but it doesn't hurt to test for it. return "", "", fmt.Errorf("Path should not contain more than one colon: %q", s) } if strings.HasSuffix(prefix, "/") { return "", "", fmt.Errorf(`Image name must not have a trailing "/": %s`, prefix) } return prefix, tag, nil }
[ "func", "parseTag", "(", "s", "string", ")", "(", "prefix", ",", "tag", "string", ",", "err", "error", ")", "{", "splitString", ":=", "strings", ".", "Split", "(", "s", ",", "\"", "\"", ")", "\n", "if", "len", "(", "splitString", ")", "==", "1", "{", "prefix", "=", "splitString", "[", "0", "]", "\n", "}", "else", "if", "len", "(", "splitString", ")", "==", "2", "{", "prefix", ",", "tag", "=", "splitString", "[", "0", "]", ",", "splitString", "[", "1", "]", "\n", "}", "else", "{", "// Unlikely edge case but it doesn't hurt to test for it.", "return", "\"", "\"", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n\n", "if", "strings", ".", "HasSuffix", "(", "prefix", ",", "\"", "\"", ")", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "`Image name must not have a trailing \"/\": %s`", ",", "prefix", ")", "\n", "}", "\n\n", "return", "prefix", ",", "tag", ",", "nil", "\n", "}" ]
// parseTag splits the Repository tag from the prefix.
[ "parseTag", "splits", "the", "Repository", "tag", "from", "the", "prefix", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/registry_url.go#L180-L196
3,071
apcera/util
docker/registry_url.go
baseURL
func (u *DockerRegistryURL) baseURL(includeCredentials bool) string { if u.Scheme == "" || u.Host == "" { return "" } var result string if u.Userinfo != nil && includeCredentials { result = fmt.Sprintf("%s://%s@%s", u.Scheme, u.Userinfo, u.Host) } else { result = fmt.Sprintf("%s://%s", u.Scheme, u.Host) } if u.Port != "" { result = fmt.Sprintf("%s:%s", result, u.Port) } return result }
go
func (u *DockerRegistryURL) baseURL(includeCredentials bool) string { if u.Scheme == "" || u.Host == "" { return "" } var result string if u.Userinfo != nil && includeCredentials { result = fmt.Sprintf("%s://%s@%s", u.Scheme, u.Userinfo, u.Host) } else { result = fmt.Sprintf("%s://%s", u.Scheme, u.Host) } if u.Port != "" { result = fmt.Sprintf("%s:%s", result, u.Port) } return result }
[ "func", "(", "u", "*", "DockerRegistryURL", ")", "baseURL", "(", "includeCredentials", "bool", ")", "string", "{", "if", "u", ".", "Scheme", "==", "\"", "\"", "||", "u", ".", "Host", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n\n", "var", "result", "string", "\n", "if", "u", ".", "Userinfo", "!=", "nil", "&&", "includeCredentials", "{", "result", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "u", ".", "Scheme", ",", "u", ".", "Userinfo", ",", "u", ".", "Host", ")", "\n", "}", "else", "{", "result", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "u", ".", "Scheme", ",", "u", ".", "Host", ")", "\n", "}", "\n\n", "if", "u", ".", "Port", "!=", "\"", "\"", "{", "result", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "result", ",", "u", ".", "Port", ")", "\n", "}", "\n", "return", "result", "\n\n", "}" ]
// baseURL is wrapped by BaseURL and BaseURLNoCredentials. // The boolean flag indicates whether credentials are included in the return string.
[ "baseURL", "is", "wrapped", "by", "BaseURL", "and", "BaseURLNoCredentials", ".", "The", "boolean", "flag", "indicates", "whether", "credentials", "are", "included", "in", "the", "return", "string", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/registry_url.go#L200-L217
3,072
apcera/util
docker/registry_url.go
HostPort
func (u *DockerRegistryURL) HostPort() string { if u.Port == "" { return u.Host } return net.JoinHostPort(u.Host, u.Port) }
go
func (u *DockerRegistryURL) HostPort() string { if u.Port == "" { return u.Host } return net.JoinHostPort(u.Host, u.Port) }
[ "func", "(", "u", "*", "DockerRegistryURL", ")", "HostPort", "(", ")", "string", "{", "if", "u", ".", "Port", "==", "\"", "\"", "{", "return", "u", ".", "Host", "\n", "}", "\n", "return", "net", ".", "JoinHostPort", "(", "u", ".", "Host", ",", "u", ".", "Port", ")", "\n\n", "}" ]
// HostPort returns the HostPort of the registry URL. If there is no port, then // it returns just the host.
[ "HostPort", "returns", "the", "HostPort", "of", "the", "registry", "URL", ".", "If", "there", "is", "no", "port", "then", "it", "returns", "just", "the", "host", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/registry_url.go#L221-L227
3,073
apcera/util
docker/registry_url.go
AddLibraryNamespace
func (u *DockerRegistryURL) AddLibraryNamespace() { // If the image name does not contain '/', it is intended to be an official // image; so we add the `library` namespace to the URL. if !strings.Contains(u.ImageName, "/") { u.ImageName = fmt.Sprintf("library/%s", u.ImageName) } }
go
func (u *DockerRegistryURL) AddLibraryNamespace() { // If the image name does not contain '/', it is intended to be an official // image; so we add the `library` namespace to the URL. if !strings.Contains(u.ImageName, "/") { u.ImageName = fmt.Sprintf("library/%s", u.ImageName) } }
[ "func", "(", "u", "*", "DockerRegistryURL", ")", "AddLibraryNamespace", "(", ")", "{", "// If the image name does not contain '/', it is intended to be an official", "// image; so we add the `library` namespace to the URL.", "if", "!", "strings", ".", "Contains", "(", "u", ".", "ImageName", ",", "\"", "\"", ")", "{", "u", ".", "ImageName", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "u", ".", "ImageName", ")", "\n", "}", "\n", "}" ]
// AddLibraryNamespace explicitly appends the `library` namespace used for // official images.
[ "AddLibraryNamespace", "explicitly", "appends", "the", "library", "namespace", "used", "for", "official", "images", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/registry_url.go#L231-L237
3,074
apcera/util
docker/registry_url.go
baseString
func (u *DockerRegistryURL) baseString(includeCredentials bool) string { var base string if includeCredentials { base = u.BaseURL() } else { base = u.BaseURLNoCredentials() } s := u.Path() if s == "" { return base } else { return fmt.Sprintf("%s/%s", base, s) } }
go
func (u *DockerRegistryURL) baseString(includeCredentials bool) string { var base string if includeCredentials { base = u.BaseURL() } else { base = u.BaseURLNoCredentials() } s := u.Path() if s == "" { return base } else { return fmt.Sprintf("%s/%s", base, s) } }
[ "func", "(", "u", "*", "DockerRegistryURL", ")", "baseString", "(", "includeCredentials", "bool", ")", "string", "{", "var", "base", "string", "\n", "if", "includeCredentials", "{", "base", "=", "u", ".", "BaseURL", "(", ")", "\n", "}", "else", "{", "base", "=", "u", ".", "BaseURLNoCredentials", "(", ")", "\n", "}", "\n\n", "s", ":=", "u", ".", "Path", "(", ")", "\n", "if", "s", "==", "\"", "\"", "{", "return", "base", "\n", "}", "else", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "base", ",", "s", ")", "\n", "}", "\n", "}" ]
// baseString is wrapped by String and StringNoCredentials. // It exposes a flag to indicate whether to include credentials in the BaseURL.
[ "baseString", "is", "wrapped", "by", "String", "and", "StringNoCredentials", ".", "It", "exposes", "a", "flag", "to", "indicate", "whether", "to", "include", "credentials", "in", "the", "BaseURL", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/registry_url.go#L261-L275
3,075
apcera/util
docker/registry_url.go
MarshalJSON
func (u *DockerRegistryURL) MarshalJSON() ([]byte, error) { // Using the alias type allows it to have all the same fields as the // DockerRegistryURL but avoids a loop when marshalling since it will not // have the same MarshalJSON method. type Alias DockerRegistryURL ui := "" if u != nil && u.Userinfo != nil { ui = u.Userinfo.String() } return json.Marshal(&struct { Userinfo string `json:",omitempty"` *Alias }{ Userinfo: ui, Alias: (*Alias)(u), }) }
go
func (u *DockerRegistryURL) MarshalJSON() ([]byte, error) { // Using the alias type allows it to have all the same fields as the // DockerRegistryURL but avoids a loop when marshalling since it will not // have the same MarshalJSON method. type Alias DockerRegistryURL ui := "" if u != nil && u.Userinfo != nil { ui = u.Userinfo.String() } return json.Marshal(&struct { Userinfo string `json:",omitempty"` *Alias }{ Userinfo: ui, Alias: (*Alias)(u), }) }
[ "func", "(", "u", "*", "DockerRegistryURL", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Using the alias type allows it to have all the same fields as the", "// DockerRegistryURL but avoids a loop when marshalling since it will not", "// have the same MarshalJSON method.", "type", "Alias", "DockerRegistryURL", "\n", "ui", ":=", "\"", "\"", "\n", "if", "u", "!=", "nil", "&&", "u", ".", "Userinfo", "!=", "nil", "{", "ui", "=", "u", ".", "Userinfo", ".", "String", "(", ")", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "&", "struct", "{", "Userinfo", "string", "`json:\",omitempty\"`", "\n", "*", "Alias", "\n", "}", "{", "Userinfo", ":", "ui", ",", "Alias", ":", "(", "*", "Alias", ")", "(", "u", ")", ",", "}", ")", "\n", "}" ]
// MarshalJSON implements marshalling which will maintain the url.Userinfo // details which are normally lost due to lack of exported fields.
[ "MarshalJSON", "implements", "marshalling", "which", "will", "maintain", "the", "url", ".", "Userinfo", "details", "which", "are", "normally", "lost", "due", "to", "lack", "of", "exported", "fields", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/registry_url.go#L294-L310
3,076
apcera/util
docker/registry_url.go
UnmarshalJSON
func (u *DockerRegistryURL) UnmarshalJSON(data []byte) error { // Using the alias type allows it to have all the same fields as the // DockerRegistryURL but avoids a loop when marshalling since it will not // have the same UnmarshalJSON method. type Alias DockerRegistryURL aux := &struct { Userinfo string `json:",omitempty"` *Alias }{ Alias: (*Alias)(u), } if err := json.Unmarshal(data, &aux); err != nil { return err } if aux.Userinfo == "" { return nil } ui, err := url.Parse("http://" + aux.Userinfo + "@foo.com") if err != nil { return fmt.Errorf("error parsing userinfo: %s", err) } u.Userinfo = ui.User return nil }
go
func (u *DockerRegistryURL) UnmarshalJSON(data []byte) error { // Using the alias type allows it to have all the same fields as the // DockerRegistryURL but avoids a loop when marshalling since it will not // have the same UnmarshalJSON method. type Alias DockerRegistryURL aux := &struct { Userinfo string `json:",omitempty"` *Alias }{ Alias: (*Alias)(u), } if err := json.Unmarshal(data, &aux); err != nil { return err } if aux.Userinfo == "" { return nil } ui, err := url.Parse("http://" + aux.Userinfo + "@foo.com") if err != nil { return fmt.Errorf("error parsing userinfo: %s", err) } u.Userinfo = ui.User return nil }
[ "func", "(", "u", "*", "DockerRegistryURL", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "// Using the alias type allows it to have all the same fields as the", "// DockerRegistryURL but avoids a loop when marshalling since it will not", "// have the same UnmarshalJSON method.", "type", "Alias", "DockerRegistryURL", "\n", "aux", ":=", "&", "struct", "{", "Userinfo", "string", "`json:\",omitempty\"`", "\n", "*", "Alias", "\n", "}", "{", "Alias", ":", "(", "*", "Alias", ")", "(", "u", ")", ",", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "aux", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "aux", ".", "Userinfo", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "ui", ",", "err", ":=", "url", ".", "Parse", "(", "\"", "\"", "+", "aux", ".", "Userinfo", "+", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "u", ".", "Userinfo", "=", "ui", ".", "User", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON implements unmarshalling which will maintain the url.Userinfo // details which are normally lost due to lack of exported fields.
[ "UnmarshalJSON", "implements", "unmarshalling", "which", "will", "maintain", "the", "url", ".", "Userinfo", "details", "which", "are", "normally", "lost", "due", "to", "lack", "of", "exported", "fields", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/docker/registry_url.go#L314-L337
3,077
Jumpscale/go-raml
raml/parser.go
ParseFile
func ParseFile(filePath string, root Root) error { workDir, fileName := filepath.Split(filePath) _, err := ParseReadFile(workDir, fileName, root) return err }
go
func ParseFile(filePath string, root Root) error { workDir, fileName := filepath.Split(filePath) _, err := ParseReadFile(workDir, fileName, root) return err }
[ "func", "ParseFile", "(", "filePath", "string", ",", "root", "Root", ")", "error", "{", "workDir", ",", "fileName", ":=", "filepath", ".", "Split", "(", "filePath", ")", "\n", "_", ",", "err", ":=", "ParseReadFile", "(", "workDir", ",", "fileName", ",", "root", ")", "\n", "return", "err", "\n", "}" ]
// ParseFile parses an RAML file. // Returns a raml.APIDefinition value or an error if // something went wrong.
[ "ParseFile", "parses", "an", "RAML", "file", ".", "Returns", "a", "raml", ".", "APIDefinition", "value", "or", "an", "error", "if", "something", "went", "wrong", "." ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/parser.go#L67-L71
3,078
Jumpscale/go-raml
raml/parser.go
ParseReadFile
func ParseReadFile(workDir, fileName string, root Root) ([]byte, error) { if strings.HasSuffix(fmt.Sprint(reflect.TypeOf(root)), "APIDefinition") { // when we parse for APIDefinition, we reset ramlFileDir ramlFileDir = workDir } // Read original file contents into a byte array mainFileBytes, err := readFileOrURL(workDir, fileName) if err != nil { return []byte{}, err } // Get the contents of the main file mainFileBuffer := bytes.NewBuffer(mainFileBytes) // Verify the YAML version var ramlVersion string firstLine, err := mainFileBuffer.ReadString('\n') if err != nil { return []byte{}, fmt.Errorf("Problem reading RAML file (Error: %s)", err.Error()) } // We read some data... if len(firstLine) >= 10 { ramlVersion = firstLine[:10] } if ramlVersion != "#%RAML 1.0" { return []byte{}, errors.New("Input file is not a RAML 1.0 file. Make " + "sure the file starts with #%RAML 1.0") } // Pre-process the original file, following !include directive preprocessedContentsBytes, err := preProcess(mainFileBuffer, workDir) if err != nil { return []byte{}, fmt.Errorf("Error preprocessing RAML file (Error: %s)", err.Error()) } if log.GetLevel() == log.DebugLevel { pretty.Println(string(preprocessedContentsBytes)) } // Unmarshal into an APIDefinition value // Go! err = yaml.Unmarshal(preprocessedContentsBytes, root) // Any errors? if err != nil { // Create a RAML error value ramlError := new(Error) // Copy the YAML errors into it.. if yamlErrors, ok := err.(*yaml.TypeError); ok { populateRAMLError(ramlError, yamlErrors) } else { // Or just any other error, though this shouldn't happen. ramlError.Errors = append(ramlError.Errors, err.Error()) } return []byte{}, ramlError } if err := root.PostProcess(workDir, fileName); err != nil { return preprocessedContentsBytes, err } // Good. return preprocessedContentsBytes, nil }
go
func ParseReadFile(workDir, fileName string, root Root) ([]byte, error) { if strings.HasSuffix(fmt.Sprint(reflect.TypeOf(root)), "APIDefinition") { // when we parse for APIDefinition, we reset ramlFileDir ramlFileDir = workDir } // Read original file contents into a byte array mainFileBytes, err := readFileOrURL(workDir, fileName) if err != nil { return []byte{}, err } // Get the contents of the main file mainFileBuffer := bytes.NewBuffer(mainFileBytes) // Verify the YAML version var ramlVersion string firstLine, err := mainFileBuffer.ReadString('\n') if err != nil { return []byte{}, fmt.Errorf("Problem reading RAML file (Error: %s)", err.Error()) } // We read some data... if len(firstLine) >= 10 { ramlVersion = firstLine[:10] } if ramlVersion != "#%RAML 1.0" { return []byte{}, errors.New("Input file is not a RAML 1.0 file. Make " + "sure the file starts with #%RAML 1.0") } // Pre-process the original file, following !include directive preprocessedContentsBytes, err := preProcess(mainFileBuffer, workDir) if err != nil { return []byte{}, fmt.Errorf("Error preprocessing RAML file (Error: %s)", err.Error()) } if log.GetLevel() == log.DebugLevel { pretty.Println(string(preprocessedContentsBytes)) } // Unmarshal into an APIDefinition value // Go! err = yaml.Unmarshal(preprocessedContentsBytes, root) // Any errors? if err != nil { // Create a RAML error value ramlError := new(Error) // Copy the YAML errors into it.. if yamlErrors, ok := err.(*yaml.TypeError); ok { populateRAMLError(ramlError, yamlErrors) } else { // Or just any other error, though this shouldn't happen. ramlError.Errors = append(ramlError.Errors, err.Error()) } return []byte{}, ramlError } if err := root.PostProcess(workDir, fileName); err != nil { return preprocessedContentsBytes, err } // Good. return preprocessedContentsBytes, nil }
[ "func", "ParseReadFile", "(", "workDir", ",", "fileName", "string", ",", "root", "Root", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "strings", ".", "HasSuffix", "(", "fmt", ".", "Sprint", "(", "reflect", ".", "TypeOf", "(", "root", ")", ")", ",", "\"", "\"", ")", "{", "// when we parse for APIDefinition, we reset ramlFileDir", "ramlFileDir", "=", "workDir", "\n", "}", "\n\n", "// Read original file contents into a byte array", "mainFileBytes", ",", "err", ":=", "readFileOrURL", "(", "workDir", ",", "fileName", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "byte", "{", "}", ",", "err", "\n", "}", "\n\n", "// Get the contents of the main file", "mainFileBuffer", ":=", "bytes", ".", "NewBuffer", "(", "mainFileBytes", ")", "\n\n", "// Verify the YAML version", "var", "ramlVersion", "string", "\n", "firstLine", ",", "err", ":=", "mainFileBuffer", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "byte", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "// We read some data...", "if", "len", "(", "firstLine", ")", ">=", "10", "{", "ramlVersion", "=", "firstLine", "[", ":", "10", "]", "\n", "}", "\n", "if", "ramlVersion", "!=", "\"", "\"", "{", "return", "[", "]", "byte", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// Pre-process the original file, following !include directive", "preprocessedContentsBytes", ",", "err", ":=", "preProcess", "(", "mainFileBuffer", ",", "workDir", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "byte", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "if", "log", ".", "GetLevel", "(", ")", "==", "log", ".", "DebugLevel", "{", "pretty", ".", "Println", "(", "string", "(", "preprocessedContentsBytes", ")", ")", "\n", "}", "\n\n", "// Unmarshal into an APIDefinition value", "// Go!", "err", "=", "yaml", ".", "Unmarshal", "(", "preprocessedContentsBytes", ",", "root", ")", "\n\n", "// Any errors?", "if", "err", "!=", "nil", "{", "// Create a RAML error value", "ramlError", ":=", "new", "(", "Error", ")", "\n\n", "// Copy the YAML errors into it..", "if", "yamlErrors", ",", "ok", ":=", "err", ".", "(", "*", "yaml", ".", "TypeError", ")", ";", "ok", "{", "populateRAMLError", "(", "ramlError", ",", "yamlErrors", ")", "\n", "}", "else", "{", "// Or just any other error, though this shouldn't happen.", "ramlError", ".", "Errors", "=", "append", "(", "ramlError", ".", "Errors", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "[", "]", "byte", "{", "}", ",", "ramlError", "\n", "}", "\n\n", "if", "err", ":=", "root", ".", "PostProcess", "(", "workDir", ",", "fileName", ")", ";", "err", "!=", "nil", "{", "return", "preprocessedContentsBytes", ",", "err", "\n", "}", "\n\n", "// Good.", "return", "preprocessedContentsBytes", ",", "nil", "\n", "}" ]
// ParseReadFile parse an .raml file. // It returns API definition and the concatenated .raml file.
[ "ParseReadFile", "parse", "an", ".", "raml", "file", ".", "It", "returns", "API", "definition", "and", "the", "concatenated", ".", "raml", "file", "." ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/parser.go#L75-L147
3,079
Jumpscale/go-raml
raml/parser.go
readFileContents
func readFileContents(workingDirectory string, fileName string) ([]byte, error) { filePath := filepath.Join(workingDirectory, fileName) if fileName == "" { return nil, fmt.Errorf("File name cannot be nil: %s", filePath) } // Read the file fileContentsArray, err := ioutil.ReadFile(filePath) if err != nil { return nil, fmt.Errorf("Could not read file %s (Error: %s)", filePath, err.Error()) } return fileContentsArray, nil }
go
func readFileContents(workingDirectory string, fileName string) ([]byte, error) { filePath := filepath.Join(workingDirectory, fileName) if fileName == "" { return nil, fmt.Errorf("File name cannot be nil: %s", filePath) } // Read the file fileContentsArray, err := ioutil.ReadFile(filePath) if err != nil { return nil, fmt.Errorf("Could not read file %s (Error: %s)", filePath, err.Error()) } return fileContentsArray, nil }
[ "func", "readFileContents", "(", "workingDirectory", "string", ",", "fileName", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "filePath", ":=", "filepath", ".", "Join", "(", "workingDirectory", ",", "fileName", ")", "\n\n", "if", "fileName", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filePath", ")", "\n", "}", "\n\n", "// Read the file", "fileContentsArray", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filePath", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "fileContentsArray", ",", "nil", "\n", "}" ]
// Reads the contents of a file, returns a bytes buffer
[ "Reads", "the", "contents", "of", "a", "file", "returns", "a", "bytes", "buffer" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/parser.go#L168-L185
3,080
Jumpscale/go-raml
raml/parser.go
isURL
func isURL(path string) bool { if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") { if _, err := url.Parse(path); err == nil { return true } } return false }
go
func isURL(path string) bool { if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") { if _, err := url.Parse(path); err == nil { return true } } return false }
[ "func", "isURL", "(", "path", "string", ")", "bool", "{", "if", "strings", ".", "HasPrefix", "(", "path", ",", "\"", "\"", ")", "||", "strings", ".", "HasPrefix", "(", "path", ",", "\"", "\"", ")", "{", "if", "_", ",", "err", ":=", "url", ".", "Parse", "(", "path", ")", ";", "err", "==", "nil", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// returns true if the path is an HTTP URL
[ "returns", "true", "if", "the", "path", "is", "an", "HTTP", "URL" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/parser.go#L188-L195
3,081
Jumpscale/go-raml
raml/parser.go
preProcess
func preProcess(originalContents io.Reader, workingDirectory string) ([]byte, error) { // NOTE: Since YAML doesn't support !include directives, and since go-yaml // does NOT play nice with !include tags, this has to be done like this. // I am considering modifying go-yaml to add custom handlers for specific // tags, to add support for !include, but for now - this method is // GoodEnough(TM) and since it will only happen once, I am not prematurely // optimizing it. var preprocessedContents bytes.Buffer // Go over each line, looking for !include tags scanner := bufio.NewScanner(originalContents) var line string // Scan the file until we reach EOF or error out for scanner.Scan() { line = scanner.Text() // Did we find an !include directive to handle? if idx := strings.Index(line, "!include"); idx != -1 { included := line[idx+includeStringLen:] preprocessedContents.Write([]byte(line[:idx])) // Get the included file contents includedContents, err := readFileOrURL(workingDirectory, included) if err != nil { return nil, fmt.Errorf("Error including file %s:\n %s", included, err.Error()) } // we only parse utf8 content if !utf8.Valid(includedContents) { includedContents = []byte("") } // add newline to included content prepender := []byte("\n") // if it is in response body, we prepend "|" to make it as string trimmedLine := strings.TrimSpace(line) if strings.HasPrefix(trimmedLine, "type ") || strings.HasPrefix(trimmedLine, "type:") { // in body prepender = []byte("|\n") } includedContents = append(prepender, includedContents...) // TODO: Check that you only insert .yaml, .raml, .txt and .md files // In case of .raml or .yaml, remove the comments // In case of other files, Base64 them first. // TODO: Better, step by step checks .. though prolly it'll panic // Write text files in the same indentation as the first line internalScanner := bufio.NewScanner(bytes.NewBuffer(includedContents)) // Indent by this much firstLine := true indentationString := "" // Go over each line, write it for internalScanner.Scan() { internalLine := internalScanner.Text() preprocessedContents.WriteString(indentationString) if firstLine { indentationString = strings.Repeat(" ", idx) firstLine = false } preprocessedContents.WriteString(internalLine) preprocessedContents.WriteByte('\n') } } else { // No, just a simple line.. write it preprocessedContents.WriteString(line) preprocessedContents.WriteByte('\n') } } // Any errors encountered? if err := scanner.Err(); err != nil { return nil, fmt.Errorf("Error reading YAML file: %s", err.Error()) } // Return the preprocessed contents return preprocessedContents.Bytes(), nil }
go
func preProcess(originalContents io.Reader, workingDirectory string) ([]byte, error) { // NOTE: Since YAML doesn't support !include directives, and since go-yaml // does NOT play nice with !include tags, this has to be done like this. // I am considering modifying go-yaml to add custom handlers for specific // tags, to add support for !include, but for now - this method is // GoodEnough(TM) and since it will only happen once, I am not prematurely // optimizing it. var preprocessedContents bytes.Buffer // Go over each line, looking for !include tags scanner := bufio.NewScanner(originalContents) var line string // Scan the file until we reach EOF or error out for scanner.Scan() { line = scanner.Text() // Did we find an !include directive to handle? if idx := strings.Index(line, "!include"); idx != -1 { included := line[idx+includeStringLen:] preprocessedContents.Write([]byte(line[:idx])) // Get the included file contents includedContents, err := readFileOrURL(workingDirectory, included) if err != nil { return nil, fmt.Errorf("Error including file %s:\n %s", included, err.Error()) } // we only parse utf8 content if !utf8.Valid(includedContents) { includedContents = []byte("") } // add newline to included content prepender := []byte("\n") // if it is in response body, we prepend "|" to make it as string trimmedLine := strings.TrimSpace(line) if strings.HasPrefix(trimmedLine, "type ") || strings.HasPrefix(trimmedLine, "type:") { // in body prepender = []byte("|\n") } includedContents = append(prepender, includedContents...) // TODO: Check that you only insert .yaml, .raml, .txt and .md files // In case of .raml or .yaml, remove the comments // In case of other files, Base64 them first. // TODO: Better, step by step checks .. though prolly it'll panic // Write text files in the same indentation as the first line internalScanner := bufio.NewScanner(bytes.NewBuffer(includedContents)) // Indent by this much firstLine := true indentationString := "" // Go over each line, write it for internalScanner.Scan() { internalLine := internalScanner.Text() preprocessedContents.WriteString(indentationString) if firstLine { indentationString = strings.Repeat(" ", idx) firstLine = false } preprocessedContents.WriteString(internalLine) preprocessedContents.WriteByte('\n') } } else { // No, just a simple line.. write it preprocessedContents.WriteString(line) preprocessedContents.WriteByte('\n') } } // Any errors encountered? if err := scanner.Err(); err != nil { return nil, fmt.Errorf("Error reading YAML file: %s", err.Error()) } // Return the preprocessed contents return preprocessedContents.Bytes(), nil }
[ "func", "preProcess", "(", "originalContents", "io", ".", "Reader", ",", "workingDirectory", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// NOTE: Since YAML doesn't support !include directives, and since go-yaml", "// does NOT play nice with !include tags, this has to be done like this.", "// I am considering modifying go-yaml to add custom handlers for specific", "// tags, to add support for !include, but for now - this method is", "// GoodEnough(TM) and since it will only happen once, I am not prematurely", "// optimizing it.", "var", "preprocessedContents", "bytes", ".", "Buffer", "\n\n", "// Go over each line, looking for !include tags", "scanner", ":=", "bufio", ".", "NewScanner", "(", "originalContents", ")", "\n", "var", "line", "string", "\n\n", "// Scan the file until we reach EOF or error out", "for", "scanner", ".", "Scan", "(", ")", "{", "line", "=", "scanner", ".", "Text", "(", ")", "\n\n", "// Did we find an !include directive to handle?", "if", "idx", ":=", "strings", ".", "Index", "(", "line", ",", "\"", "\"", ")", ";", "idx", "!=", "-", "1", "{", "included", ":=", "line", "[", "idx", "+", "includeStringLen", ":", "]", "\n\n", "preprocessedContents", ".", "Write", "(", "[", "]", "byte", "(", "line", "[", ":", "idx", "]", ")", ")", "\n\n", "// Get the included file contents", "includedContents", ",", "err", ":=", "readFileOrURL", "(", "workingDirectory", ",", "included", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "included", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "// we only parse utf8 content", "if", "!", "utf8", ".", "Valid", "(", "includedContents", ")", "{", "includedContents", "=", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// add newline to included content", "prepender", ":=", "[", "]", "byte", "(", "\"", "\\n", "\"", ")", "\n\n", "// if it is in response body, we prepend \"|\" to make it as string", "trimmedLine", ":=", "strings", ".", "TrimSpace", "(", "line", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "trimmedLine", ",", "\"", "\"", ")", "||", "strings", ".", "HasPrefix", "(", "trimmedLine", ",", "\"", "\"", ")", "{", "// in body", "prepender", "=", "[", "]", "byte", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "includedContents", "=", "append", "(", "prepender", ",", "includedContents", "...", ")", "\n\n", "// TODO: Check that you only insert .yaml, .raml, .txt and .md files", "// In case of .raml or .yaml, remove the comments", "// In case of other files, Base64 them first.", "// TODO: Better, step by step checks .. though prolly it'll panic", "// Write text files in the same indentation as the first line", "internalScanner", ":=", "bufio", ".", "NewScanner", "(", "bytes", ".", "NewBuffer", "(", "includedContents", ")", ")", "\n\n", "// Indent by this much", "firstLine", ":=", "true", "\n", "indentationString", ":=", "\"", "\"", "\n\n", "// Go over each line, write it", "for", "internalScanner", ".", "Scan", "(", ")", "{", "internalLine", ":=", "internalScanner", ".", "Text", "(", ")", "\n\n", "preprocessedContents", ".", "WriteString", "(", "indentationString", ")", "\n", "if", "firstLine", "{", "indentationString", "=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "idx", ")", "\n", "firstLine", "=", "false", "\n", "}", "\n\n", "preprocessedContents", ".", "WriteString", "(", "internalLine", ")", "\n", "preprocessedContents", ".", "WriteByte", "(", "'\\n'", ")", "\n", "}", "\n\n", "}", "else", "{", "// No, just a simple line.. write it", "preprocessedContents", ".", "WriteString", "(", "line", ")", "\n", "preprocessedContents", ".", "WriteByte", "(", "'\\n'", ")", "\n", "}", "\n", "}", "\n\n", "// Any errors encountered?", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "// Return the preprocessed contents", "return", "preprocessedContents", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// preProcess acts as a preprocessor for a RAML document in YAML format, // including files referenced via !include. It returns a pre-processed document.
[ "preProcess", "acts", "as", "a", "preprocessor", "for", "a", "RAML", "document", "in", "YAML", "format", "including", "files", "referenced", "via", "!include", ".", "It", "returns", "a", "pre", "-", "processed", "document", "." ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/parser.go#L199-L291
3,082
Jumpscale/go-raml
raml/utils.go
appendStrNotExist
func appendStrNotExist(str string, arr []string) []string { // check if a `str` exist in `arr` isStrInArr := func(str string, arr []string) bool { for _, s := range arr { if str == s { return true } } return false } if !isStrInArr(str, arr) { arr = append(arr, str) } return arr }
go
func appendStrNotExist(str string, arr []string) []string { // check if a `str` exist in `arr` isStrInArr := func(str string, arr []string) bool { for _, s := range arr { if str == s { return true } } return false } if !isStrInArr(str, arr) { arr = append(arr, str) } return arr }
[ "func", "appendStrNotExist", "(", "str", "string", ",", "arr", "[", "]", "string", ")", "[", "]", "string", "{", "// check if a `str` exist in `arr`", "isStrInArr", ":=", "func", "(", "str", "string", ",", "arr", "[", "]", "string", ")", "bool", "{", "for", "_", ",", "s", ":=", "range", "arr", "{", "if", "str", "==", "s", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", "\n\n", "if", "!", "isStrInArr", "(", "str", ",", "arr", ")", "{", "arr", "=", "append", "(", "arr", ",", "str", ")", "\n", "}", "\n", "return", "arr", "\n", "}" ]
// append `str` to `arr` if `str` not exist in `arr`
[ "append", "str", "to", "arr", "if", "str", "not", "exist", "in", "arr" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/utils.go#L4-L19
3,083
Jumpscale/go-raml
codegen/tarantool/resources.go
Handler
func (m *method) Handler() string { var name string if len(m.DisplayName) > 0 { name = commons.DisplayNameToFuncName(m.DisplayName) } else { name = commons.NormalizeIdentifier(commons.NormalizeURI(m.Endpoint)) + m.Verb() } return casee.ToSnakeCase(name + "Handler") }
go
func (m *method) Handler() string { var name string if len(m.DisplayName) > 0 { name = commons.DisplayNameToFuncName(m.DisplayName) } else { name = commons.NormalizeIdentifier(commons.NormalizeURI(m.Endpoint)) + m.Verb() } return casee.ToSnakeCase(name + "Handler") }
[ "func", "(", "m", "*", "method", ")", "Handler", "(", ")", "string", "{", "var", "name", "string", "\n", "if", "len", "(", "m", ".", "DisplayName", ")", ">", "0", "{", "name", "=", "commons", ".", "DisplayNameToFuncName", "(", "m", ".", "DisplayName", ")", "\n", "}", "else", "{", "name", "=", "commons", ".", "NormalizeIdentifier", "(", "commons", ".", "NormalizeURI", "(", "m", ".", "Endpoint", ")", ")", "+", "m", ".", "Verb", "(", ")", "\n", "}", "\n", "return", "casee", ".", "ToSnakeCase", "(", "name", "+", "\"", "\"", ")", "\n", "}" ]
// Handler returns the name of the function that handles requests for this method
[ "Handler", "returns", "the", "name", "of", "the", "function", "that", "handles", "requests", "for", "this", "method" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/codegen/tarantool/resources.go#L33-L41
3,084
Jumpscale/go-raml
codegen/golang/struct.go
newStructDef
func newStructDef(apiDef *raml.APIDefinition, name, packageName, description string, properties map[string]interface{}) structDef { // generate struct's fields from type properties fields := make(map[string]fieldDef) for k, v := range properties { prop := raml.ToProperty(k, v) fields[prop.Name] = newFieldDef(apiDef, name, prop, packageName) } return structDef{ Name: strings.Title(commons.NormalizeIdentifier(name)), PackageName: packageName, Fields: fields, Description: commons.ParseDescription(description), } }
go
func newStructDef(apiDef *raml.APIDefinition, name, packageName, description string, properties map[string]interface{}) structDef { // generate struct's fields from type properties fields := make(map[string]fieldDef) for k, v := range properties { prop := raml.ToProperty(k, v) fields[prop.Name] = newFieldDef(apiDef, name, prop, packageName) } return structDef{ Name: strings.Title(commons.NormalizeIdentifier(name)), PackageName: packageName, Fields: fields, Description: commons.ParseDescription(description), } }
[ "func", "newStructDef", "(", "apiDef", "*", "raml", ".", "APIDefinition", ",", "name", ",", "packageName", ",", "description", "string", ",", "properties", "map", "[", "string", "]", "interface", "{", "}", ")", "structDef", "{", "// generate struct's fields from type properties", "fields", ":=", "make", "(", "map", "[", "string", "]", "fieldDef", ")", "\n", "for", "k", ",", "v", ":=", "range", "properties", "{", "prop", ":=", "raml", ".", "ToProperty", "(", "k", ",", "v", ")", "\n", "fields", "[", "prop", ".", "Name", "]", "=", "newFieldDef", "(", "apiDef", ",", "name", ",", "prop", ",", "packageName", ")", "\n", "}", "\n", "return", "structDef", "{", "Name", ":", "strings", ".", "Title", "(", "commons", ".", "NormalizeIdentifier", "(", "name", ")", ")", ",", "PackageName", ":", "packageName", ",", "Fields", ":", "fields", ",", "Description", ":", "commons", ".", "ParseDescription", "(", "description", ")", ",", "}", "\n", "}" ]
// create new struct definition
[ "create", "new", "struct", "definition" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/codegen/golang/struct.go#L37-L50
3,085
Jumpscale/go-raml
codegen/golang/struct.go
newStructDefFromType
func newStructDefFromType(apiDef *raml.APIDefinition, t raml.Type, sName, packageName string) structDef { sd := newStructDef(apiDef, sName, packageName, t.Description, t.Properties) sd.T = t // handle advanced type on raml1.0 sd.handleAdvancedType(apiDef) return sd }
go
func newStructDefFromType(apiDef *raml.APIDefinition, t raml.Type, sName, packageName string) structDef { sd := newStructDef(apiDef, sName, packageName, t.Description, t.Properties) sd.T = t // handle advanced type on raml1.0 sd.handleAdvancedType(apiDef) return sd }
[ "func", "newStructDefFromType", "(", "apiDef", "*", "raml", ".", "APIDefinition", ",", "t", "raml", ".", "Type", ",", "sName", ",", "packageName", "string", ")", "structDef", "{", "sd", ":=", "newStructDef", "(", "apiDef", ",", "sName", ",", "packageName", ",", "t", ".", "Description", ",", "t", ".", "Properties", ")", "\n", "sd", ".", "T", "=", "t", "\n\n", "// handle advanced type on raml1.0", "sd", ".", "handleAdvancedType", "(", "apiDef", ")", "\n\n", "return", "sd", "\n", "}" ]
// create struct definition from RAML Type node
[ "create", "struct", "definition", "from", "RAML", "Type", "node" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/codegen/golang/struct.go#L53-L61
3,086
Jumpscale/go-raml
codegen/golang/struct.go
generate
func (sd structDef) generate(dir string) error { // generate enums for _, f := range sd.Fields { if f.Enum != nil { if err := f.Enum.generate(dir); err != nil { return err } } } if sd.Enum != nil { return sd.Enum.generate(dir) } fileName := filepath.Join(dir, sd.Name+".go") return commons.GenerateFile(sd, structTemplateLocation, "struct_template", fileName, true) }
go
func (sd structDef) generate(dir string) error { // generate enums for _, f := range sd.Fields { if f.Enum != nil { if err := f.Enum.generate(dir); err != nil { return err } } } if sd.Enum != nil { return sd.Enum.generate(dir) } fileName := filepath.Join(dir, sd.Name+".go") return commons.GenerateFile(sd, structTemplateLocation, "struct_template", fileName, true) }
[ "func", "(", "sd", "structDef", ")", "generate", "(", "dir", "string", ")", "error", "{", "// generate enums", "for", "_", ",", "f", ":=", "range", "sd", ".", "Fields", "{", "if", "f", ".", "Enum", "!=", "nil", "{", "if", "err", ":=", "f", ".", "Enum", ".", "generate", "(", "dir", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "sd", ".", "Enum", "!=", "nil", "{", "return", "sd", ".", "Enum", ".", "generate", "(", "dir", ")", "\n", "}", "\n", "fileName", ":=", "filepath", ".", "Join", "(", "dir", ",", "sd", ".", "Name", "+", "\"", "\"", ")", "\n", "return", "commons", ".", "GenerateFile", "(", "sd", ",", "structTemplateLocation", ",", "\"", "\"", ",", "fileName", ",", "true", ")", "\n", "}" ]
// generate Go struct
[ "generate", "Go", "struct" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/codegen/golang/struct.go#L64-L78
3,087
Jumpscale/go-raml
codegen/golang/struct.go
Imports
func (sd structDef) Imports() []string { ip := map[string]struct{}{} if sd.needFmt() { ip[`"fmt"`] = struct{}{} } if sd.OneLineDef == "" { ip[`"gopkg.in/validator.v2"`] = struct{}{} } // libraries for _, fd := range sd.Fields { if fd.fieldType == "json.RawMessage" { ip[`"encoding/json"`] = struct{}{} } else if lib := libImportPath(globRootImportPath, fd.fieldType, globLibRootURLs); lib != "" { ip[lib] = struct{}{} } } return commons.MapToSortedStrings(ip) }
go
func (sd structDef) Imports() []string { ip := map[string]struct{}{} if sd.needFmt() { ip[`"fmt"`] = struct{}{} } if sd.OneLineDef == "" { ip[`"gopkg.in/validator.v2"`] = struct{}{} } // libraries for _, fd := range sd.Fields { if fd.fieldType == "json.RawMessage" { ip[`"encoding/json"`] = struct{}{} } else if lib := libImportPath(globRootImportPath, fd.fieldType, globLibRootURLs); lib != "" { ip[lib] = struct{}{} } } return commons.MapToSortedStrings(ip) }
[ "func", "(", "sd", "structDef", ")", "Imports", "(", ")", "[", "]", "string", "{", "ip", ":=", "map", "[", "string", "]", "struct", "{", "}", "{", "}", "\n\n", "if", "sd", ".", "needFmt", "(", ")", "{", "ip", "[", "`\"fmt\"`", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "if", "sd", ".", "OneLineDef", "==", "\"", "\"", "{", "ip", "[", "`\"gopkg.in/validator.v2\"`", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "// libraries", "for", "_", ",", "fd", ":=", "range", "sd", ".", "Fields", "{", "if", "fd", ".", "fieldType", "==", "\"", "\"", "{", "ip", "[", "`\"encoding/json\"`", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "else", "if", "lib", ":=", "libImportPath", "(", "globRootImportPath", ",", "fd", ".", "fieldType", ",", "globLibRootURLs", ")", ";", "lib", "!=", "\"", "\"", "{", "ip", "[", "lib", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "return", "commons", ".", "MapToSortedStrings", "(", "ip", ")", "\n", "}" ]
// Imports returns all packages that // need to be imported by this struct
[ "Imports", "returns", "all", "packages", "that", "need", "to", "be", "imported", "by", "this", "struct" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/codegen/golang/struct.go#L122-L141
3,088
Jumpscale/go-raml
codegen/golang/struct.go
generateInputValidator
func generateInputValidator(packageName, dir string) error { var ctx = struct { PackageName string }{ PackageName: packageName, } fileName := filepath.Join(dir, inputValidatorFileResult) return commons.GenerateFile(ctx, inputValidatorTemplateLocation, "struct_input_validator_template", fileName, true) }
go
func generateInputValidator(packageName, dir string) error { var ctx = struct { PackageName string }{ PackageName: packageName, } fileName := filepath.Join(dir, inputValidatorFileResult) return commons.GenerateFile(ctx, inputValidatorTemplateLocation, "struct_input_validator_template", fileName, true) }
[ "func", "generateInputValidator", "(", "packageName", ",", "dir", "string", ")", "error", "{", "var", "ctx", "=", "struct", "{", "PackageName", "string", "\n", "}", "{", "PackageName", ":", "packageName", ",", "}", "\n", "fileName", ":=", "filepath", ".", "Join", "(", "dir", ",", "inputValidatorFileResult", ")", "\n", "return", "commons", ".", "GenerateFile", "(", "ctx", ",", "inputValidatorTemplateLocation", ",", "\"", "\"", ",", "fileName", ",", "true", ")", "\n", "}" ]
// generate input validator helper file
[ "generate", "input", "validator", "helper", "file" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/codegen/golang/struct.go#L254-L262
3,089
Jumpscale/go-raml
codegen/golang/struct.go
needFmt
func (sd structDef) needFmt() bool { // array type min items and max items if sd.T.MinItems > 0 || sd.T.MaxItems > 0 { return true } // unique items for _, f := range sd.Fields { if f.UniqueItems { return true } } return false }
go
func (sd structDef) needFmt() bool { // array type min items and max items if sd.T.MinItems > 0 || sd.T.MaxItems > 0 { return true } // unique items for _, f := range sd.Fields { if f.UniqueItems { return true } } return false }
[ "func", "(", "sd", "structDef", ")", "needFmt", "(", ")", "bool", "{", "// array type min items and max items", "if", "sd", ".", "T", ".", "MinItems", ">", "0", "||", "sd", ".", "T", ".", "MaxItems", ">", "0", "{", "return", "true", "\n", "}", "\n\n", "// unique items", "for", "_", ",", "f", ":=", "range", "sd", ".", "Fields", "{", "if", "f", ".", "UniqueItems", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// true if this struct need to import 'fmt' package // It is required by validation code, // because validation error will need `fmt` to build error message
[ "true", "if", "this", "struct", "need", "to", "import", "fmt", "package", "It", "is", "required", "by", "validation", "code", "because", "validation", "error", "will", "need", "fmt", "to", "build", "error", "message" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/codegen/golang/struct.go#L267-L280
3,090
Jumpscale/go-raml
codegen/server.go
Generate
func (s *Server) Generate() error { apiDef := new(raml.APIDefinition) // parse the raml file dir, fileName := filepath.Split(s.RAMLFile) ramlBytes, err := raml.ParseReadFile(dir, fileName, apiDef) if err != nil { return err } var generator generator.Server switch s.Lang { case langGo: generator = golang.NewServer(apiDef, s.PackageName, s.APIDocsDir, s.RootImportPath, s.WithMain, s.Dir, s.LibRootURLs) case langPython: generator = python.NewServer(s.Kind, apiDef, s.APIDocsDir, s.Dir, s.WithMain, s.LibRootURLs) case langNim: generator = nim.NewServer(apiDef, s.APIDocsDir, s.Dir) case langTarantool: generator = tarantool.NewServer(apiDef, s.APIDocsDir, s.Dir) default: return errInvalidLang } err = generator.Generate() if err != nil { return err } if s.APIDocsDir == "" { return nil } if s.Lang == langNim { s.APIDocsDir = "public/" + s.APIDocsDir } log.Infof("Generating API Docs to %v", s.APIDocsDir) return apidocs.Generate(apiDef, s.RAMLFile, ramlBytes, filepath.Join(s.Dir, s.APIDocsDir), s.LibRootURLs) }
go
func (s *Server) Generate() error { apiDef := new(raml.APIDefinition) // parse the raml file dir, fileName := filepath.Split(s.RAMLFile) ramlBytes, err := raml.ParseReadFile(dir, fileName, apiDef) if err != nil { return err } var generator generator.Server switch s.Lang { case langGo: generator = golang.NewServer(apiDef, s.PackageName, s.APIDocsDir, s.RootImportPath, s.WithMain, s.Dir, s.LibRootURLs) case langPython: generator = python.NewServer(s.Kind, apiDef, s.APIDocsDir, s.Dir, s.WithMain, s.LibRootURLs) case langNim: generator = nim.NewServer(apiDef, s.APIDocsDir, s.Dir) case langTarantool: generator = tarantool.NewServer(apiDef, s.APIDocsDir, s.Dir) default: return errInvalidLang } err = generator.Generate() if err != nil { return err } if s.APIDocsDir == "" { return nil } if s.Lang == langNim { s.APIDocsDir = "public/" + s.APIDocsDir } log.Infof("Generating API Docs to %v", s.APIDocsDir) return apidocs.Generate(apiDef, s.RAMLFile, ramlBytes, filepath.Join(s.Dir, s.APIDocsDir), s.LibRootURLs) }
[ "func", "(", "s", "*", "Server", ")", "Generate", "(", ")", "error", "{", "apiDef", ":=", "new", "(", "raml", ".", "APIDefinition", ")", "\n", "// parse the raml file", "dir", ",", "fileName", ":=", "filepath", ".", "Split", "(", "s", ".", "RAMLFile", ")", "\n", "ramlBytes", ",", "err", ":=", "raml", ".", "ParseReadFile", "(", "dir", ",", "fileName", ",", "apiDef", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "generator", "generator", ".", "Server", "\n\n", "switch", "s", ".", "Lang", "{", "case", "langGo", ":", "generator", "=", "golang", ".", "NewServer", "(", "apiDef", ",", "s", ".", "PackageName", ",", "s", ".", "APIDocsDir", ",", "s", ".", "RootImportPath", ",", "s", ".", "WithMain", ",", "s", ".", "Dir", ",", "s", ".", "LibRootURLs", ")", "\n", "case", "langPython", ":", "generator", "=", "python", ".", "NewServer", "(", "s", ".", "Kind", ",", "apiDef", ",", "s", ".", "APIDocsDir", ",", "s", ".", "Dir", ",", "s", ".", "WithMain", ",", "s", ".", "LibRootURLs", ")", "\n", "case", "langNim", ":", "generator", "=", "nim", ".", "NewServer", "(", "apiDef", ",", "s", ".", "APIDocsDir", ",", "s", ".", "Dir", ")", "\n", "case", "langTarantool", ":", "generator", "=", "tarantool", ".", "NewServer", "(", "apiDef", ",", "s", ".", "APIDocsDir", ",", "s", ".", "Dir", ")", "\n", "default", ":", "return", "errInvalidLang", "\n", "}", "\n", "err", "=", "generator", ".", "Generate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "s", ".", "APIDocsDir", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "if", "s", ".", "Lang", "==", "langNim", "{", "s", ".", "APIDocsDir", "=", "\"", "\"", "+", "s", ".", "APIDocsDir", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "s", ".", "APIDocsDir", ")", "\n\n", "return", "apidocs", ".", "Generate", "(", "apiDef", ",", "s", ".", "RAMLFile", ",", "ramlBytes", ",", "filepath", ".", "Join", "(", "s", ".", "Dir", ",", "s", ".", "APIDocsDir", ")", ",", "s", ".", "LibRootURLs", ")", "\n", "}" ]
// Generate generates API server files
[ "Generate", "generates", "API", "server", "files" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/codegen/server.go#L37-L77
3,091
Jumpscale/go-raml
raml/method.go
postProcess
func (m *Method) postProcess(r *Resource, name string, traitsMap map[string]Trait, apiDef *APIDefinition) { m.Name = name m.inheritFromTraits(r, append(r.Is, m.Is...), traitsMap, apiDef) r.Methods = append(r.Methods, m) // post process the responses resps := make(map[HTTPCode]Response) for code, resp := range m.Responses { resp.postProcess() resps[code] = resp } m.Responses = resps // post process request body m.Bodies.postProcess() }
go
func (m *Method) postProcess(r *Resource, name string, traitsMap map[string]Trait, apiDef *APIDefinition) { m.Name = name m.inheritFromTraits(r, append(r.Is, m.Is...), traitsMap, apiDef) r.Methods = append(r.Methods, m) // post process the responses resps := make(map[HTTPCode]Response) for code, resp := range m.Responses { resp.postProcess() resps[code] = resp } m.Responses = resps // post process request body m.Bodies.postProcess() }
[ "func", "(", "m", "*", "Method", ")", "postProcess", "(", "r", "*", "Resource", ",", "name", "string", ",", "traitsMap", "map", "[", "string", "]", "Trait", ",", "apiDef", "*", "APIDefinition", ")", "{", "m", ".", "Name", "=", "name", "\n", "m", ".", "inheritFromTraits", "(", "r", ",", "append", "(", "r", ".", "Is", ",", "m", ".", "Is", "...", ")", ",", "traitsMap", ",", "apiDef", ")", "\n", "r", ".", "Methods", "=", "append", "(", "r", ".", "Methods", ",", "m", ")", "\n\n", "// post process the responses", "resps", ":=", "make", "(", "map", "[", "HTTPCode", "]", "Response", ")", "\n", "for", "code", ",", "resp", ":=", "range", "m", ".", "Responses", "{", "resp", ".", "postProcess", "(", ")", "\n", "resps", "[", "code", "]", "=", "resp", "\n", "}", "\n", "m", ".", "Responses", "=", "resps", "\n\n", "// post process request body", "m", ".", "Bodies", ".", "postProcess", "(", ")", "\n", "}" ]
// doing post processing that can't be done by YAML parser
[ "doing", "post", "processing", "that", "can", "t", "be", "done", "by", "YAML", "parser" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/method.go#L68-L83
3,092
Jumpscale/go-raml
raml/method.go
inheritFromATrait
func (m *Method) inheritFromATrait(r *Resource, t *Trait, dicts map[string]interface{}, apiDef *APIDefinition) error { dicts = initTraitDicts(r, m, dicts) m.Description = substituteParams(m.Description, t.Description, dicts) m.Bodies.inherit(t.Bodies, dicts, m.resourceTypeName, apiDef) m.inheritHeaders(t.Headers, dicts) m.inheritResponses(t.Responses, dicts, apiDef) m.inheritQueryParams(t.QueryParameters, dicts) m.inheritProtocols(t.Protocols) // optional bodies // optional headers // optional responses // optional query parameters return nil }
go
func (m *Method) inheritFromATrait(r *Resource, t *Trait, dicts map[string]interface{}, apiDef *APIDefinition) error { dicts = initTraitDicts(r, m, dicts) m.Description = substituteParams(m.Description, t.Description, dicts) m.Bodies.inherit(t.Bodies, dicts, m.resourceTypeName, apiDef) m.inheritHeaders(t.Headers, dicts) m.inheritResponses(t.Responses, dicts, apiDef) m.inheritQueryParams(t.QueryParameters, dicts) m.inheritProtocols(t.Protocols) // optional bodies // optional headers // optional responses // optional query parameters return nil }
[ "func", "(", "m", "*", "Method", ")", "inheritFromATrait", "(", "r", "*", "Resource", ",", "t", "*", "Trait", ",", "dicts", "map", "[", "string", "]", "interface", "{", "}", ",", "apiDef", "*", "APIDefinition", ")", "error", "{", "dicts", "=", "initTraitDicts", "(", "r", ",", "m", ",", "dicts", ")", "\n\n", "m", ".", "Description", "=", "substituteParams", "(", "m", ".", "Description", ",", "t", ".", "Description", ",", "dicts", ")", "\n\n", "m", ".", "Bodies", ".", "inherit", "(", "t", ".", "Bodies", ",", "dicts", ",", "m", ".", "resourceTypeName", ",", "apiDef", ")", "\n\n", "m", ".", "inheritHeaders", "(", "t", ".", "Headers", ",", "dicts", ")", "\n\n", "m", ".", "inheritResponses", "(", "t", ".", "Responses", ",", "dicts", ",", "apiDef", ")", "\n\n", "m", ".", "inheritQueryParams", "(", "t", ".", "QueryParameters", ",", "dicts", ")", "\n\n", "m", ".", "inheritProtocols", "(", "t", ".", "Protocols", ")", "\n\n", "// optional bodies", "// optional headers", "// optional responses", "// optional query parameters", "return", "nil", "\n", "}" ]
// inherit from a trait // dicts is map of trait parameters values
[ "inherit", "from", "a", "trait", "dicts", "is", "map", "of", "trait", "parameters", "values" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/method.go#L138-L159
3,093
Jumpscale/go-raml
raml/method.go
inheritHeaders
func (m *Method) inheritHeaders(parents map[HTTPHeader]Header, dicts map[string]interface{}) { m.Headers = inheritHeaders(m.Headers, parents, dicts) }
go
func (m *Method) inheritHeaders(parents map[HTTPHeader]Header, dicts map[string]interface{}) { m.Headers = inheritHeaders(m.Headers, parents, dicts) }
[ "func", "(", "m", "*", "Method", ")", "inheritHeaders", "(", "parents", "map", "[", "HTTPHeader", "]", "Header", ",", "dicts", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "m", ".", "Headers", "=", "inheritHeaders", "(", "m", ".", "Headers", ",", "parents", ",", "dicts", ")", "\n", "}" ]
// inheritHeaders inherit method's headers from parent headers. // parent headers could be from resource type or a trait
[ "inheritHeaders", "inherit", "method", "s", "headers", "from", "parent", "headers", ".", "parent", "headers", "could", "be", "from", "resource", "type", "or", "a", "trait" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/method.go#L163-L165
3,094
Jumpscale/go-raml
raml/method.go
inheritHeaders
func inheritHeaders(childs, parents map[HTTPHeader]Header, dicts map[string]interface{}) map[HTTPHeader]Header { if len(childs) == 0 { childs = map[HTTPHeader]Header{} } for name, parent := range parents { h, ok := childs[name] if !ok { if optionalTraitProperty(string(name)) { // don't inherit optional property if not exist continue } h = Header{} } parent.Name = string(name) np := NamedParameter(h) np.inherit(NamedParameter(parent), dicts) childs[name] = Header(np) } return childs }
go
func inheritHeaders(childs, parents map[HTTPHeader]Header, dicts map[string]interface{}) map[HTTPHeader]Header { if len(childs) == 0 { childs = map[HTTPHeader]Header{} } for name, parent := range parents { h, ok := childs[name] if !ok { if optionalTraitProperty(string(name)) { // don't inherit optional property if not exist continue } h = Header{} } parent.Name = string(name) np := NamedParameter(h) np.inherit(NamedParameter(parent), dicts) childs[name] = Header(np) } return childs }
[ "func", "inheritHeaders", "(", "childs", ",", "parents", "map", "[", "HTTPHeader", "]", "Header", ",", "dicts", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "HTTPHeader", "]", "Header", "{", "if", "len", "(", "childs", ")", "==", "0", "{", "childs", "=", "map", "[", "HTTPHeader", "]", "Header", "{", "}", "\n", "}", "\n\n", "for", "name", ",", "parent", ":=", "range", "parents", "{", "h", ",", "ok", ":=", "childs", "[", "name", "]", "\n", "if", "!", "ok", "{", "if", "optionalTraitProperty", "(", "string", "(", "name", ")", ")", "{", "// don't inherit optional property if not exist", "continue", "\n", "}", "\n", "h", "=", "Header", "{", "}", "\n", "}", "\n", "parent", ".", "Name", "=", "string", "(", "name", ")", "\n", "np", ":=", "NamedParameter", "(", "h", ")", "\n", "np", ".", "inherit", "(", "NamedParameter", "(", "parent", ")", ",", "dicts", ")", "\n", "childs", "[", "name", "]", "=", "Header", "(", "np", ")", "\n", "}", "\n", "return", "childs", "\n", "}" ]
// inheritHeaders inherits headers from parents to childs
[ "inheritHeaders", "inherits", "headers", "from", "parents", "to", "childs" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/method.go#L168-L187
3,095
Jumpscale/go-raml
raml/method.go
inheritQueryParams
func (m *Method) inheritQueryParams(parents map[string]NamedParameter, dicts map[string]interface{}) { if len(m.QueryParameters) == 0 { m.QueryParameters = map[string]NamedParameter{} } for name, parent := range parents { qp, ok := m.QueryParameters[name] if !ok { if optionalTraitProperty(string(name)) { // don't inherit optional property if not exist continue } qp = NamedParameter{Name: name} } parent.Name = name // parent name is not initialized by the parser qp.inherit(parent, dicts) m.QueryParameters[qp.Name] = qp } }
go
func (m *Method) inheritQueryParams(parents map[string]NamedParameter, dicts map[string]interface{}) { if len(m.QueryParameters) == 0 { m.QueryParameters = map[string]NamedParameter{} } for name, parent := range parents { qp, ok := m.QueryParameters[name] if !ok { if optionalTraitProperty(string(name)) { // don't inherit optional property if not exist continue } qp = NamedParameter{Name: name} } parent.Name = name // parent name is not initialized by the parser qp.inherit(parent, dicts) m.QueryParameters[qp.Name] = qp } }
[ "func", "(", "m", "*", "Method", ")", "inheritQueryParams", "(", "parents", "map", "[", "string", "]", "NamedParameter", ",", "dicts", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "if", "len", "(", "m", ".", "QueryParameters", ")", "==", "0", "{", "m", ".", "QueryParameters", "=", "map", "[", "string", "]", "NamedParameter", "{", "}", "\n", "}", "\n", "for", "name", ",", "parent", ":=", "range", "parents", "{", "qp", ",", "ok", ":=", "m", ".", "QueryParameters", "[", "name", "]", "\n", "if", "!", "ok", "{", "if", "optionalTraitProperty", "(", "string", "(", "name", ")", ")", "{", "// don't inherit optional property if not exist", "continue", "\n", "}", "\n", "qp", "=", "NamedParameter", "{", "Name", ":", "name", "}", "\n", "}", "\n", "parent", ".", "Name", "=", "name", "// parent name is not initialized by the parser", "\n", "qp", ".", "inherit", "(", "parent", ",", "dicts", ")", "\n", "m", ".", "QueryParameters", "[", "qp", ".", "Name", "]", "=", "qp", "\n", "}", "\n\n", "}" ]
// inheritQueryParams inherit method's query params from parent query params. // parent query params could be from resource type or a trait
[ "inheritQueryParams", "inherit", "method", "s", "query", "params", "from", "parent", "query", "params", ".", "parent", "query", "params", "could", "be", "from", "resource", "type", "or", "a", "trait" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/method.go#L191-L208
3,096
Jumpscale/go-raml
raml/method.go
inheritProtocols
func (m *Method) inheritProtocols(parent []string) { for _, p := range parent { m.Protocols = appendStrNotExist(p, m.Protocols) } }
go
func (m *Method) inheritProtocols(parent []string) { for _, p := range parent { m.Protocols = appendStrNotExist(p, m.Protocols) } }
[ "func", "(", "m", "*", "Method", ")", "inheritProtocols", "(", "parent", "[", "]", "string", ")", "{", "for", "_", ",", "p", ":=", "range", "parent", "{", "m", ".", "Protocols", "=", "appendStrNotExist", "(", "p", ",", "m", ".", "Protocols", ")", "\n", "}", "\n", "}" ]
// inheritProtocols inherit method's protocols from parent protocols // parent protocols could be from resource type or a trait
[ "inheritProtocols", "inherit", "method", "s", "protocols", "from", "parent", "protocols", "parent", "protocols", "could", "be", "from", "resource", "type", "or", "a", "trait" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/method.go#L212-L216
3,097
Jumpscale/go-raml
raml/method.go
inheritResponses
func (m *Method) inheritResponses(parent map[HTTPCode]Response, dicts map[string]interface{}, apiDef *APIDefinition) { if len(m.Responses) == 0 { // allocate if needed m.Responses = map[HTTPCode]Response{} } for code, rParent := range parent { resp, ok := m.Responses[code] if !ok { if optionalTraitProperty(fmt.Sprintf("%v", code)) { // don't inherit optional property if not exist continue } resp = Response{HTTPCode: code} } resp.inherit(rParent, dicts, m.resourceTypeName, apiDef) m.Responses[code] = resp } }
go
func (m *Method) inheritResponses(parent map[HTTPCode]Response, dicts map[string]interface{}, apiDef *APIDefinition) { if len(m.Responses) == 0 { // allocate if needed m.Responses = map[HTTPCode]Response{} } for code, rParent := range parent { resp, ok := m.Responses[code] if !ok { if optionalTraitProperty(fmt.Sprintf("%v", code)) { // don't inherit optional property if not exist continue } resp = Response{HTTPCode: code} } resp.inherit(rParent, dicts, m.resourceTypeName, apiDef) m.Responses[code] = resp } }
[ "func", "(", "m", "*", "Method", ")", "inheritResponses", "(", "parent", "map", "[", "HTTPCode", "]", "Response", ",", "dicts", "map", "[", "string", "]", "interface", "{", "}", ",", "apiDef", "*", "APIDefinition", ")", "{", "if", "len", "(", "m", ".", "Responses", ")", "==", "0", "{", "// allocate if needed", "m", ".", "Responses", "=", "map", "[", "HTTPCode", "]", "Response", "{", "}", "\n", "}", "\n", "for", "code", ",", "rParent", ":=", "range", "parent", "{", "resp", ",", "ok", ":=", "m", ".", "Responses", "[", "code", "]", "\n", "if", "!", "ok", "{", "if", "optionalTraitProperty", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "code", ")", ")", "{", "// don't inherit optional property if not exist", "continue", "\n", "}", "\n", "resp", "=", "Response", "{", "HTTPCode", ":", "code", "}", "\n", "}", "\n", "resp", ".", "inherit", "(", "rParent", ",", "dicts", ",", "m", ".", "resourceTypeName", ",", "apiDef", ")", "\n", "m", ".", "Responses", "[", "code", "]", "=", "resp", "\n", "}", "\n\n", "}" ]
// inheritResponses inherit method's responses from parent responses // parent responses could be from resource type or a trait
[ "inheritResponses", "inherit", "method", "s", "responses", "from", "parent", "responses", "parent", "responses", "could", "be", "from", "resource", "type", "or", "a", "trait" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/method.go#L220-L237
3,098
Jumpscale/go-raml
raml/method.go
inherit
func (resp *Response) inherit(parent Response, dicts map[string]interface{}, rtName string, apiDef *APIDefinition) { resp.Description = substituteParams(resp.Description, parent.Description, dicts) resp.Bodies.inherit(parent.Bodies, dicts, rtName, apiDef) resp.Headers = inheritHeaders(resp.Headers, parent.Headers, dicts) }
go
func (resp *Response) inherit(parent Response, dicts map[string]interface{}, rtName string, apiDef *APIDefinition) { resp.Description = substituteParams(resp.Description, parent.Description, dicts) resp.Bodies.inherit(parent.Bodies, dicts, rtName, apiDef) resp.Headers = inheritHeaders(resp.Headers, parent.Headers, dicts) }
[ "func", "(", "resp", "*", "Response", ")", "inherit", "(", "parent", "Response", ",", "dicts", "map", "[", "string", "]", "interface", "{", "}", ",", "rtName", "string", ",", "apiDef", "*", "APIDefinition", ")", "{", "resp", ".", "Description", "=", "substituteParams", "(", "resp", ".", "Description", ",", "parent", ".", "Description", ",", "dicts", ")", "\n", "resp", ".", "Bodies", ".", "inherit", "(", "parent", ".", "Bodies", ",", "dicts", ",", "rtName", ",", "apiDef", ")", "\n", "resp", ".", "Headers", "=", "inheritHeaders", "(", "resp", ".", "Headers", ",", "parent", ".", "Headers", ",", "dicts", ")", "\n", "}" ]
// inherit from parent response
[ "inherit", "from", "parent", "response" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/method.go#L270-L275
3,099
Jumpscale/go-raml
raml/method.go
inherit
func (b *Bodies) inherit(parent Bodies, dicts map[string]interface{}, rtName string, apiDef *APIDefinition) { b.Schema = substituteParams(b.Schema, parent.Schema, dicts) b.Description = substituteParams(b.Description, parent.Description, dicts) b.Example = substituteParams(b.Example, parent.Example, dicts) b.Type = mergeTypeName(substituteParams(b.Type, parent.Type, dicts), rtName, apiDef) // request body if parent.ApplicationJSON != nil { if b.ApplicationJSON == nil { // allocate if needed b.ApplicationJSON = &BodiesProperty{Properties: map[string]interface{}{}} } else if b.ApplicationJSON.Properties == nil { b.ApplicationJSON.Properties = map[string]interface{}{} } b.ApplicationJSON.Type = substituteParams(b.ApplicationJSON.TypeString(), parent.ApplicationJSON.TypeString(), dicts) // check if type name is in library if typeStr, ok := b.ApplicationJSON.Type.(string); ok { b.ApplicationJSON.Type = mergeTypeName(typeStr, rtName, apiDef) } for k, p := range parent.ApplicationJSON.Properties { if _, ok := b.ApplicationJSON.Properties[k]; !ok { // handle optional properties as described in // https://github.com/raml-org/raml-spec/blob/raml-10/versions/raml-10/raml-10.md#optional-properties switch { case strings.HasSuffix(k, `\?`): // if ended with `\?` we make it optional property k = k[:len(k)-2] + "?" case strings.HasSuffix(k, "?"): // if only ended with `?`, we can ignore it continue } k = substituteParams(k, k, dicts) prop := toProperty(k, p) inheritedType := substituteParams(prop.TypeString(), prop.TypeString(), dicts) b.ApplicationJSON.Properties[k] = mergeTypeName(inheritedType, rtName, apiDef) } } } // TODO : formimeytype }
go
func (b *Bodies) inherit(parent Bodies, dicts map[string]interface{}, rtName string, apiDef *APIDefinition) { b.Schema = substituteParams(b.Schema, parent.Schema, dicts) b.Description = substituteParams(b.Description, parent.Description, dicts) b.Example = substituteParams(b.Example, parent.Example, dicts) b.Type = mergeTypeName(substituteParams(b.Type, parent.Type, dicts), rtName, apiDef) // request body if parent.ApplicationJSON != nil { if b.ApplicationJSON == nil { // allocate if needed b.ApplicationJSON = &BodiesProperty{Properties: map[string]interface{}{}} } else if b.ApplicationJSON.Properties == nil { b.ApplicationJSON.Properties = map[string]interface{}{} } b.ApplicationJSON.Type = substituteParams(b.ApplicationJSON.TypeString(), parent.ApplicationJSON.TypeString(), dicts) // check if type name is in library if typeStr, ok := b.ApplicationJSON.Type.(string); ok { b.ApplicationJSON.Type = mergeTypeName(typeStr, rtName, apiDef) } for k, p := range parent.ApplicationJSON.Properties { if _, ok := b.ApplicationJSON.Properties[k]; !ok { // handle optional properties as described in // https://github.com/raml-org/raml-spec/blob/raml-10/versions/raml-10/raml-10.md#optional-properties switch { case strings.HasSuffix(k, `\?`): // if ended with `\?` we make it optional property k = k[:len(k)-2] + "?" case strings.HasSuffix(k, "?"): // if only ended with `?`, we can ignore it continue } k = substituteParams(k, k, dicts) prop := toProperty(k, p) inheritedType := substituteParams(prop.TypeString(), prop.TypeString(), dicts) b.ApplicationJSON.Properties[k] = mergeTypeName(inheritedType, rtName, apiDef) } } } // TODO : formimeytype }
[ "func", "(", "b", "*", "Bodies", ")", "inherit", "(", "parent", "Bodies", ",", "dicts", "map", "[", "string", "]", "interface", "{", "}", ",", "rtName", "string", ",", "apiDef", "*", "APIDefinition", ")", "{", "b", ".", "Schema", "=", "substituteParams", "(", "b", ".", "Schema", ",", "parent", ".", "Schema", ",", "dicts", ")", "\n", "b", ".", "Description", "=", "substituteParams", "(", "b", ".", "Description", ",", "parent", ".", "Description", ",", "dicts", ")", "\n", "b", ".", "Example", "=", "substituteParams", "(", "b", ".", "Example", ",", "parent", ".", "Example", ",", "dicts", ")", "\n\n", "b", ".", "Type", "=", "mergeTypeName", "(", "substituteParams", "(", "b", ".", "Type", ",", "parent", ".", "Type", ",", "dicts", ")", ",", "rtName", ",", "apiDef", ")", "\n\n", "// request body", "if", "parent", ".", "ApplicationJSON", "!=", "nil", "{", "if", "b", ".", "ApplicationJSON", "==", "nil", "{", "// allocate if needed", "b", ".", "ApplicationJSON", "=", "&", "BodiesProperty", "{", "Properties", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "}", "\n", "}", "else", "if", "b", ".", "ApplicationJSON", ".", "Properties", "==", "nil", "{", "b", ".", "ApplicationJSON", ".", "Properties", "=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "}", "\n\n", "b", ".", "ApplicationJSON", ".", "Type", "=", "substituteParams", "(", "b", ".", "ApplicationJSON", ".", "TypeString", "(", ")", ",", "parent", ".", "ApplicationJSON", ".", "TypeString", "(", ")", ",", "dicts", ")", "\n", "// check if type name is in library", "if", "typeStr", ",", "ok", ":=", "b", ".", "ApplicationJSON", ".", "Type", ".", "(", "string", ")", ";", "ok", "{", "b", ".", "ApplicationJSON", ".", "Type", "=", "mergeTypeName", "(", "typeStr", ",", "rtName", ",", "apiDef", ")", "\n", "}", "\n\n", "for", "k", ",", "p", ":=", "range", "parent", ".", "ApplicationJSON", ".", "Properties", "{", "if", "_", ",", "ok", ":=", "b", ".", "ApplicationJSON", ".", "Properties", "[", "k", "]", ";", "!", "ok", "{", "// handle optional properties as described in", "// https://github.com/raml-org/raml-spec/blob/raml-10/versions/raml-10/raml-10.md#optional-properties", "switch", "{", "case", "strings", ".", "HasSuffix", "(", "k", ",", "`\\?`", ")", ":", "// if ended with `\\?` we make it optional property", "k", "=", "k", "[", ":", "len", "(", "k", ")", "-", "2", "]", "+", "\"", "\"", "\n", "case", "strings", ".", "HasSuffix", "(", "k", ",", "\"", "\"", ")", ":", "// if only ended with `?`, we can ignore it", "continue", "\n", "}", "\n", "k", "=", "substituteParams", "(", "k", ",", "k", ",", "dicts", ")", "\n", "prop", ":=", "toProperty", "(", "k", ",", "p", ")", "\n", "inheritedType", ":=", "substituteParams", "(", "prop", ".", "TypeString", "(", ")", ",", "prop", ".", "TypeString", "(", ")", ",", "dicts", ")", "\n", "b", ".", "ApplicationJSON", ".", "Properties", "[", "k", "]", "=", "mergeTypeName", "(", "inheritedType", ",", "rtName", ",", "apiDef", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// TODO : formimeytype", "}" ]
// inherit inherits bodies properties from a parent bodies // parent object could be from trait or response type
[ "inherit", "inherits", "bodies", "properties", "from", "a", "parent", "bodies", "parent", "object", "could", "be", "from", "trait", "or", "response", "type" ]
f151e1e143c47282b294fe70c5e56f113988ed10
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/raml/method.go#L363-L404