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
partition
stringclasses
1 value
revel/revel
i18n.go
loadMessageFile
func loadMessageFile(path string, info os.FileInfo, osError error) error { if osError != nil { return osError } if info.IsDir() { return nil } if matched, _ := regexp.MatchString(messageFilePattern, info.Name()); matched { messageConfig, err := parseMessagesFile(path) if err != nil { return err } locale := parseLocaleFromFileName(info.Name()) // If we have already parsed a message file for this locale, merge both if _, exists := messages[locale]; exists { messages[locale].Merge(messageConfig) i18nLog.Debugf("Successfully merged messages for locale '%s'", locale) } else { messages[locale] = messageConfig } i18nLog.Debug("Successfully loaded messages from file", "file", info.Name()) } else { i18nLog.Warn("Ignoring file because it did not have a valid extension", "file", info.Name()) } return nil }
go
func loadMessageFile(path string, info os.FileInfo, osError error) error { if osError != nil { return osError } if info.IsDir() { return nil } if matched, _ := regexp.MatchString(messageFilePattern, info.Name()); matched { messageConfig, err := parseMessagesFile(path) if err != nil { return err } locale := parseLocaleFromFileName(info.Name()) // If we have already parsed a message file for this locale, merge both if _, exists := messages[locale]; exists { messages[locale].Merge(messageConfig) i18nLog.Debugf("Successfully merged messages for locale '%s'", locale) } else { messages[locale] = messageConfig } i18nLog.Debug("Successfully loaded messages from file", "file", info.Name()) } else { i18nLog.Warn("Ignoring file because it did not have a valid extension", "file", info.Name()) } return nil }
[ "func", "loadMessageFile", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "osError", "error", ")", "error", "{", "if", "osError", "!=", "nil", "{", "return", "osError", "\n", "}", "\n", "if", "info", ".", "IsDir", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "if", "matched", ",", "_", ":=", "regexp", ".", "MatchString", "(", "messageFilePattern", ",", "info", ".", "Name", "(", ")", ")", ";", "matched", "{", "messageConfig", ",", "err", ":=", "parseMessagesFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "locale", ":=", "parseLocaleFromFileName", "(", "info", ".", "Name", "(", ")", ")", "\n\n", "// If we have already parsed a message file for this locale, merge both", "if", "_", ",", "exists", ":=", "messages", "[", "locale", "]", ";", "exists", "{", "messages", "[", "locale", "]", ".", "Merge", "(", "messageConfig", ")", "\n", "i18nLog", ".", "Debugf", "(", "\"", "\"", ",", "locale", ")", "\n", "}", "else", "{", "messages", "[", "locale", "]", "=", "messageConfig", "\n", "}", "\n\n", "i18nLog", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "info", ".", "Name", "(", ")", ")", "\n", "}", "else", "{", "i18nLog", ".", "Warn", "(", "\"", "\"", ",", "\"", "\"", ",", "info", ".", "Name", "(", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Load a single message file
[ "Load", "a", "single", "message", "file" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/i18n.go#L142-L171
train
revel/revel
i18n.go
hasAcceptLanguageHeader
func hasAcceptLanguageHeader(request *Request) (bool, string) { if request.AcceptLanguages != nil && len(request.AcceptLanguages) > 0 { return true, request.AcceptLanguages[0].Language } return false, "" }
go
func hasAcceptLanguageHeader(request *Request) (bool, string) { if request.AcceptLanguages != nil && len(request.AcceptLanguages) > 0 { return true, request.AcceptLanguages[0].Language } return false, "" }
[ "func", "hasAcceptLanguageHeader", "(", "request", "*", "Request", ")", "(", "bool", ",", "string", ")", "{", "if", "request", ".", "AcceptLanguages", "!=", "nil", "&&", "len", "(", "request", ".", "AcceptLanguages", ")", ">", "0", "{", "return", "true", ",", "request", ".", "AcceptLanguages", "[", "0", "]", ".", "Language", "\n", "}", "\n\n", "return", "false", ",", "\"", "\"", "\n", "}" ]
// Determine whether the given request has valid Accept-Language value. // // Assumes that the accept languages stored in the request are sorted according to quality, with top // quality first in the slice.
[ "Determine", "whether", "the", "given", "request", "has", "valid", "Accept", "-", "Language", "value", ".", "Assumes", "that", "the", "accept", "languages", "stored", "in", "the", "request", "are", "sorted", "according", "to", "quality", "with", "top", "quality", "first", "in", "the", "slice", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/i18n.go#L225-L231
train
revel/revel
i18n.go
hasLocaleCookie
func hasLocaleCookie(request *Request) (bool, string) { if request != nil { name := Config.StringDefault(localeCookieConfigKey, CookiePrefix+"_LANG") cookie, err := request.Cookie(name) if err == nil { return true, cookie.GetValue() } i18nLog.Debug("Unable to read locale cookie ", "name", name, "error", err) } return false, "" }
go
func hasLocaleCookie(request *Request) (bool, string) { if request != nil { name := Config.StringDefault(localeCookieConfigKey, CookiePrefix+"_LANG") cookie, err := request.Cookie(name) if err == nil { return true, cookie.GetValue() } i18nLog.Debug("Unable to read locale cookie ", "name", name, "error", err) } return false, "" }
[ "func", "hasLocaleCookie", "(", "request", "*", "Request", ")", "(", "bool", ",", "string", ")", "{", "if", "request", "!=", "nil", "{", "name", ":=", "Config", ".", "StringDefault", "(", "localeCookieConfigKey", ",", "CookiePrefix", "+", "\"", "\"", ")", "\n", "cookie", ",", "err", ":=", "request", ".", "Cookie", "(", "name", ")", "\n", "if", "err", "==", "nil", "{", "return", "true", ",", "cookie", ".", "GetValue", "(", ")", "\n", "}", "\n", "i18nLog", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "name", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "false", ",", "\"", "\"", "\n", "}" ]
// Determine whether the given request has a valid language cookie value.
[ "Determine", "whether", "the", "given", "request", "has", "a", "valid", "language", "cookie", "value", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/i18n.go#L234-L245
train
revel/revel
logger/terminal_format.go
JsonFormatEx
func JsonFormatEx(pretty, lineSeparated bool) LogFormat { jsonMarshal := json.Marshal if pretty { jsonMarshal = func(v interface{}) ([]byte, error) { return json.MarshalIndent(v, "", " ") } } return FormatFunc(func(r *Record) []byte { props := make(map[string]interface{}) props["t"] = r.Time props["lvl"] = levelString[r.Level] props["msg"] = r.Message for k, v := range r.Context { props[k] = formatJsonValue(v) } b, err := jsonMarshal(props) if err != nil { b, _ = jsonMarshal(map[string]string{ errorKey: err.Error(), }) return b } if lineSeparated { b = append(b, '\n') } return b }) }
go
func JsonFormatEx(pretty, lineSeparated bool) LogFormat { jsonMarshal := json.Marshal if pretty { jsonMarshal = func(v interface{}) ([]byte, error) { return json.MarshalIndent(v, "", " ") } } return FormatFunc(func(r *Record) []byte { props := make(map[string]interface{}) props["t"] = r.Time props["lvl"] = levelString[r.Level] props["msg"] = r.Message for k, v := range r.Context { props[k] = formatJsonValue(v) } b, err := jsonMarshal(props) if err != nil { b, _ = jsonMarshal(map[string]string{ errorKey: err.Error(), }) return b } if lineSeparated { b = append(b, '\n') } return b }) }
[ "func", "JsonFormatEx", "(", "pretty", ",", "lineSeparated", "bool", ")", "LogFormat", "{", "jsonMarshal", ":=", "json", ".", "Marshal", "\n", "if", "pretty", "{", "jsonMarshal", "=", "func", "(", "v", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "MarshalIndent", "(", "v", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "FormatFunc", "(", "func", "(", "r", "*", "Record", ")", "[", "]", "byte", "{", "props", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n\n", "props", "[", "\"", "\"", "]", "=", "r", ".", "Time", "\n", "props", "[", "\"", "\"", "]", "=", "levelString", "[", "r", ".", "Level", "]", "\n", "props", "[", "\"", "\"", "]", "=", "r", ".", "Message", "\n", "for", "k", ",", "v", ":=", "range", "r", ".", "Context", "{", "props", "[", "k", "]", "=", "formatJsonValue", "(", "v", ")", "\n", "}", "\n\n", "b", ",", "err", ":=", "jsonMarshal", "(", "props", ")", "\n", "if", "err", "!=", "nil", "{", "b", ",", "_", "=", "jsonMarshal", "(", "map", "[", "string", "]", "string", "{", "errorKey", ":", "err", ".", "Error", "(", ")", ",", "}", ")", "\n", "return", "b", "\n", "}", "\n\n", "if", "lineSeparated", "{", "b", "=", "append", "(", "b", ",", "'\\n'", ")", "\n", "}", "\n\n", "return", "b", "\n", "}", ")", "\n", "}" ]
// JsonFormatEx formats log records as JSON objects. If pretty is true, // records will be pretty-printed. If lineSeparated is true, records // will be logged with a new line between each record.
[ "JsonFormatEx", "formats", "log", "records", "as", "JSON", "objects", ".", "If", "pretty", "is", "true", "records", "will", "be", "pretty", "-", "printed", ".", "If", "lineSeparated", "is", "true", "records", "will", "be", "logged", "with", "a", "new", "line", "between", "each", "record", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/terminal_format.go#L203-L235
train
revel/revel
session_engine.go
initSessionEngine
func initSessionEngine() { // Check for session engine to use and assign it sename := Config.StringDefault("session.engine", "revel-cookie") if se, found := sessionEngineMap[sename]; found { CurrentSessionEngine = se() } else { sessionLog.Warn("Session engine '%s' not found, using default session engine revel-cookie", sename) CurrentSessionEngine = sessionEngineMap["revel-cookie"]() } }
go
func initSessionEngine() { // Check for session engine to use and assign it sename := Config.StringDefault("session.engine", "revel-cookie") if se, found := sessionEngineMap[sename]; found { CurrentSessionEngine = se() } else { sessionLog.Warn("Session engine '%s' not found, using default session engine revel-cookie", sename) CurrentSessionEngine = sessionEngineMap["revel-cookie"]() } }
[ "func", "initSessionEngine", "(", ")", "{", "// Check for session engine to use and assign it", "sename", ":=", "Config", ".", "StringDefault", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "se", ",", "found", ":=", "sessionEngineMap", "[", "sename", "]", ";", "found", "{", "CurrentSessionEngine", "=", "se", "(", ")", "\n", "}", "else", "{", "sessionLog", ".", "Warn", "(", "\"", "\"", ",", "sename", ")", "\n", "CurrentSessionEngine", "=", "sessionEngineMap", "[", "\"", "\"", "]", "(", ")", "\n", "}", "\n", "}" ]
// Called when application is starting up
[ "Called", "when", "application", "is", "starting", "up" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/session_engine.go#L26-L35
train
revel/revel
errors.go
NewErrorFromPanic
func NewErrorFromPanic(err interface{}) *Error { // Parse the filename and line from the originating line of app code. // /Users/robfig/code/gocode/src/revel/examples/booking/app/controllers/hotels.go:191 (0x44735) stack := string(debug.Stack()) frame, basePath := findRelevantStackFrame(stack) if frame == -1 { return nil } stack = stack[frame:] stackElement := stack[:strings.Index(stack, "\n")] colonIndex := strings.LastIndex(stackElement, ":") filename := stackElement[:colonIndex] var line int fmt.Sscan(stackElement[colonIndex+1:], &line) // Show an error page. description := "Unspecified error" if err != nil { description = fmt.Sprint(err) } lines, readErr := ReadLines(filename) if readErr != nil { utilLog.Error("Unable to read file", "file", filename, "error", readErr) } return &Error{ Title: "Runtime Panic", Path: filename[len(basePath):], Line: line, Description: description, SourceLines: lines, Stack: stack, } }
go
func NewErrorFromPanic(err interface{}) *Error { // Parse the filename and line from the originating line of app code. // /Users/robfig/code/gocode/src/revel/examples/booking/app/controllers/hotels.go:191 (0x44735) stack := string(debug.Stack()) frame, basePath := findRelevantStackFrame(stack) if frame == -1 { return nil } stack = stack[frame:] stackElement := stack[:strings.Index(stack, "\n")] colonIndex := strings.LastIndex(stackElement, ":") filename := stackElement[:colonIndex] var line int fmt.Sscan(stackElement[colonIndex+1:], &line) // Show an error page. description := "Unspecified error" if err != nil { description = fmt.Sprint(err) } lines, readErr := ReadLines(filename) if readErr != nil { utilLog.Error("Unable to read file", "file", filename, "error", readErr) } return &Error{ Title: "Runtime Panic", Path: filename[len(basePath):], Line: line, Description: description, SourceLines: lines, Stack: stack, } }
[ "func", "NewErrorFromPanic", "(", "err", "interface", "{", "}", ")", "*", "Error", "{", "// Parse the filename and line from the originating line of app code.", "// /Users/robfig/code/gocode/src/revel/examples/booking/app/controllers/hotels.go:191 (0x44735)", "stack", ":=", "string", "(", "debug", ".", "Stack", "(", ")", ")", "\n", "frame", ",", "basePath", ":=", "findRelevantStackFrame", "(", "stack", ")", "\n", "if", "frame", "==", "-", "1", "{", "return", "nil", "\n", "}", "\n\n", "stack", "=", "stack", "[", "frame", ":", "]", "\n", "stackElement", ":=", "stack", "[", ":", "strings", ".", "Index", "(", "stack", ",", "\"", "\\n", "\"", ")", "]", "\n", "colonIndex", ":=", "strings", ".", "LastIndex", "(", "stackElement", ",", "\"", "\"", ")", "\n", "filename", ":=", "stackElement", "[", ":", "colonIndex", "]", "\n", "var", "line", "int", "\n", "fmt", ".", "Sscan", "(", "stackElement", "[", "colonIndex", "+", "1", ":", "]", ",", "&", "line", ")", "\n\n", "// Show an error page.", "description", ":=", "\"", "\"", "\n", "if", "err", "!=", "nil", "{", "description", "=", "fmt", ".", "Sprint", "(", "err", ")", "\n", "}", "\n", "lines", ",", "readErr", ":=", "ReadLines", "(", "filename", ")", "\n", "if", "readErr", "!=", "nil", "{", "utilLog", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "filename", ",", "\"", "\"", ",", "readErr", ")", "\n", "}", "\n", "return", "&", "Error", "{", "Title", ":", "\"", "\"", ",", "Path", ":", "filename", "[", "len", "(", "basePath", ")", ":", "]", ",", "Line", ":", "line", ",", "Description", ":", "description", ",", "SourceLines", ":", "lines", ",", "Stack", ":", "stack", ",", "}", "\n", "}" ]
// NewErrorFromPanic method finds the deepest stack from in user code and // provide a code listing of that, on the line that eventually triggered // the panic. Returns nil if no relevant stack frame can be found.
[ "NewErrorFromPanic", "method", "finds", "the", "deepest", "stack", "from", "in", "user", "code", "and", "provide", "a", "code", "listing", "of", "that", "on", "the", "line", "that", "eventually", "triggered", "the", "panic", ".", "Returns", "nil", "if", "no", "relevant", "stack", "frame", "can", "be", "found", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/errors.go#L36-L70
train
revel/revel
errors.go
ContextSource
func (e *Error) ContextSource() []SourceLine { if e.SourceLines == nil { return nil } start := (e.Line - 1) - 5 if start < 0 { start = 0 } end := (e.Line - 1) + 5 if end > len(e.SourceLines) { end = len(e.SourceLines) } lines := make([]SourceLine, end-start) for i, src := range e.SourceLines[start:end] { fileLine := start + i + 1 lines[i] = SourceLine{src, fileLine, fileLine == e.Line} } return lines }
go
func (e *Error) ContextSource() []SourceLine { if e.SourceLines == nil { return nil } start := (e.Line - 1) - 5 if start < 0 { start = 0 } end := (e.Line - 1) + 5 if end > len(e.SourceLines) { end = len(e.SourceLines) } lines := make([]SourceLine, end-start) for i, src := range e.SourceLines[start:end] { fileLine := start + i + 1 lines[i] = SourceLine{src, fileLine, fileLine == e.Line} } return lines }
[ "func", "(", "e", "*", "Error", ")", "ContextSource", "(", ")", "[", "]", "SourceLine", "{", "if", "e", ".", "SourceLines", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "start", ":=", "(", "e", ".", "Line", "-", "1", ")", "-", "5", "\n", "if", "start", "<", "0", "{", "start", "=", "0", "\n", "}", "\n", "end", ":=", "(", "e", ".", "Line", "-", "1", ")", "+", "5", "\n", "if", "end", ">", "len", "(", "e", ".", "SourceLines", ")", "{", "end", "=", "len", "(", "e", ".", "SourceLines", ")", "\n", "}", "\n\n", "lines", ":=", "make", "(", "[", "]", "SourceLine", ",", "end", "-", "start", ")", "\n", "for", "i", ",", "src", ":=", "range", "e", ".", "SourceLines", "[", "start", ":", "end", "]", "{", "fileLine", ":=", "start", "+", "i", "+", "1", "\n", "lines", "[", "i", "]", "=", "SourceLine", "{", "src", ",", "fileLine", ",", "fileLine", "==", "e", ".", "Line", "}", "\n", "}", "\n", "return", "lines", "\n", "}" ]
// ContextSource method returns a snippet of the source around // where the error occurred.
[ "ContextSource", "method", "returns", "a", "snippet", "of", "the", "source", "around", "where", "the", "error", "occurred", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/errors.go#L97-L116
train
revel/revel
errors.go
SetLink
func (e *Error) SetLink(errorLink string) { errorLink = strings.Replace(errorLink, "{{Path}}", e.Path, -1) errorLink = strings.Replace(errorLink, "{{Line}}", strconv.Itoa(e.Line), -1) e.Link = "<a href=" + errorLink + ">" + e.Path + ":" + strconv.Itoa(e.Line) + "</a>" }
go
func (e *Error) SetLink(errorLink string) { errorLink = strings.Replace(errorLink, "{{Path}}", e.Path, -1) errorLink = strings.Replace(errorLink, "{{Line}}", strconv.Itoa(e.Line), -1) e.Link = "<a href=" + errorLink + ">" + e.Path + ":" + strconv.Itoa(e.Line) + "</a>" }
[ "func", "(", "e", "*", "Error", ")", "SetLink", "(", "errorLink", "string", ")", "{", "errorLink", "=", "strings", ".", "Replace", "(", "errorLink", ",", "\"", "\"", ",", "e", ".", "Path", ",", "-", "1", ")", "\n", "errorLink", "=", "strings", ".", "Replace", "(", "errorLink", ",", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "e", ".", "Line", ")", ",", "-", "1", ")", "\n\n", "e", ".", "Link", "=", "\"", "\"", "+", "errorLink", "+", "\"", "\"", "+", "e", ".", "Path", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "e", ".", "Line", ")", "+", "\"", "\"", "\n", "}" ]
// SetLink method prepares a link and assign to Error.Link attribute
[ "SetLink", "method", "prepares", "a", "link", "and", "assign", "to", "Error", ".", "Link", "attribute" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/errors.go#L119-L124
train
revel/revel
errors.go
findRelevantStackFrame
func findRelevantStackFrame(stack string) (int, string) { // Find first item in SourcePath that isn't in RevelPath. // If first item is in RevelPath, keep track of position, trim and check again. partialStack := stack sourcePath := filepath.ToSlash(SourcePath) revelPath := filepath.ToSlash(RevelPath) sumFrame := 0 for { frame := strings.Index(partialStack, sourcePath) revelFrame := strings.Index(partialStack, revelPath) if frame == -1 { break } else if frame != revelFrame { return sumFrame + frame, SourcePath } else { // Need to at least trim off the first character so this frame isn't caught again. partialStack = partialStack[frame+1:] sumFrame += frame + 1 } } for _, module := range Modules { if frame := strings.Index(stack, filepath.ToSlash(module.Path)); frame != -1 { return frame, module.Path } } return -1, "" }
go
func findRelevantStackFrame(stack string) (int, string) { // Find first item in SourcePath that isn't in RevelPath. // If first item is in RevelPath, keep track of position, trim and check again. partialStack := stack sourcePath := filepath.ToSlash(SourcePath) revelPath := filepath.ToSlash(RevelPath) sumFrame := 0 for { frame := strings.Index(partialStack, sourcePath) revelFrame := strings.Index(partialStack, revelPath) if frame == -1 { break } else if frame != revelFrame { return sumFrame + frame, SourcePath } else { // Need to at least trim off the first character so this frame isn't caught again. partialStack = partialStack[frame+1:] sumFrame += frame + 1 } } for _, module := range Modules { if frame := strings.Index(stack, filepath.ToSlash(module.Path)); frame != -1 { return frame, module.Path } } return -1, "" }
[ "func", "findRelevantStackFrame", "(", "stack", "string", ")", "(", "int", ",", "string", ")", "{", "// Find first item in SourcePath that isn't in RevelPath.", "// If first item is in RevelPath, keep track of position, trim and check again.", "partialStack", ":=", "stack", "\n", "sourcePath", ":=", "filepath", ".", "ToSlash", "(", "SourcePath", ")", "\n", "revelPath", ":=", "filepath", ".", "ToSlash", "(", "RevelPath", ")", "\n", "sumFrame", ":=", "0", "\n", "for", "{", "frame", ":=", "strings", ".", "Index", "(", "partialStack", ",", "sourcePath", ")", "\n", "revelFrame", ":=", "strings", ".", "Index", "(", "partialStack", ",", "revelPath", ")", "\n\n", "if", "frame", "==", "-", "1", "{", "break", "\n", "}", "else", "if", "frame", "!=", "revelFrame", "{", "return", "sumFrame", "+", "frame", ",", "SourcePath", "\n", "}", "else", "{", "// Need to at least trim off the first character so this frame isn't caught again.", "partialStack", "=", "partialStack", "[", "frame", "+", "1", ":", "]", "\n", "sumFrame", "+=", "frame", "+", "1", "\n", "}", "\n", "}", "\n", "for", "_", ",", "module", ":=", "range", "Modules", "{", "if", "frame", ":=", "strings", ".", "Index", "(", "stack", ",", "filepath", ".", "ToSlash", "(", "module", ".", "Path", ")", ")", ";", "frame", "!=", "-", "1", "{", "return", "frame", ",", "module", ".", "Path", "\n", "}", "\n", "}", "\n", "return", "-", "1", ",", "\"", "\"", "\n", "}" ]
// Return the character index of the first relevant stack frame, or -1 if none were found. // Additionally it returns the base path of the tree in which the identified code resides.
[ "Return", "the", "character", "index", "of", "the", "first", "relevant", "stack", "frame", "or", "-", "1", "if", "none", "were", "found", ".", "Additionally", "it", "returns", "the", "base", "path", "of", "the", "tree", "in", "which", "the", "identified", "code", "resides", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/errors.go#L128-L155
train
revel/revel
logger/wrap_handlers.go
HandlerFunc
func HandlerFunc(log func(message string, time time.Time, level LogLevel, call CallStack, context ContextMap) error) LogHandler { return remoteHandler(log) }
go
func HandlerFunc(log func(message string, time time.Time, level LogLevel, call CallStack, context ContextMap) error) LogHandler { return remoteHandler(log) }
[ "func", "HandlerFunc", "(", "log", "func", "(", "message", "string", ",", "time", "time", ".", "Time", ",", "level", "LogLevel", ",", "call", "CallStack", ",", "context", "ContextMap", ")", "error", ")", "LogHandler", "{", "return", "remoteHandler", "(", "log", ")", "\n", "}" ]
// This function allows you to do a full declaration for the log, // it is recommended you use FuncHandler instead
[ "This", "function", "allows", "you", "to", "do", "a", "full", "declaration", "for", "the", "log", "it", "is", "recommended", "you", "use", "FuncHandler", "instead" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/wrap_handlers.go#L27-L29
train
revel/revel
logger/wrap_handlers.go
Log
func (c remoteHandler) Log(record *Record) error { return c(record.Message, record.Time, record.Level, record.Call, record.Context) }
go
func (c remoteHandler) Log(record *Record) error { return c(record.Message, record.Time, record.Level, record.Call, record.Context) }
[ "func", "(", "c", "remoteHandler", ")", "Log", "(", "record", "*", "Record", ")", "error", "{", "return", "c", "(", "record", ".", "Message", ",", "record", ".", "Time", ",", "record", ".", "Level", ",", "record", ".", "Call", ",", "record", ".", "Context", ")", "\n", "}" ]
// The Log implementation
[ "The", "Log", "implementation" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/wrap_handlers.go#L35-L37
train
revel/revel
logger/wrap_handlers.go
LazyHandler
func LazyHandler(h LogHandler) LogHandler { return FuncHandler(func(r *Record) error { for k, v := range r.Context { if lz, ok := v.(Lazy); ok { value, err := evaluateLazy(lz) if err != nil { r.Context[errorKey] = "bad lazy " + k } else { v = value } } } return h.Log(r) }) }
go
func LazyHandler(h LogHandler) LogHandler { return FuncHandler(func(r *Record) error { for k, v := range r.Context { if lz, ok := v.(Lazy); ok { value, err := evaluateLazy(lz) if err != nil { r.Context[errorKey] = "bad lazy " + k } else { v = value } } } return h.Log(r) }) }
[ "func", "LazyHandler", "(", "h", "LogHandler", ")", "LogHandler", "{", "return", "FuncHandler", "(", "func", "(", "r", "*", "Record", ")", "error", "{", "for", "k", ",", "v", ":=", "range", "r", ".", "Context", "{", "if", "lz", ",", "ok", ":=", "v", ".", "(", "Lazy", ")", ";", "ok", "{", "value", ",", "err", ":=", "evaluateLazy", "(", "lz", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "Context", "[", "errorKey", "]", "=", "\"", "\"", "+", "k", "\n", "}", "else", "{", "v", "=", "value", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "h", ".", "Log", "(", "r", ")", "\n", "}", ")", "\n", "}" ]
// LazyHandler writes all values to the wrapped handler after evaluating // any lazy functions in the record's context. It is already wrapped // around StreamHandler and SyslogHandler in this library, you'll only need // it if you write your own Handler.
[ "LazyHandler", "writes", "all", "values", "to", "the", "wrapped", "handler", "after", "evaluating", "any", "lazy", "functions", "in", "the", "record", "s", "context", ".", "It", "is", "already", "wrapped", "around", "StreamHandler", "and", "SyslogHandler", "in", "this", "library", "you", "ll", "only", "need", "it", "if", "you", "write", "your", "own", "Handler", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/wrap_handlers.go#L55-L70
train
revel/revel
logger/utils.go
GetLogger
func GetLogger(name string, logger MultiLogger) (l *log.Logger) { switch name { case "trace": // TODO trace is deprecated, replaced by debug l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlDebug}, "", 0) case "debug": l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlDebug}, "", 0) case "info": l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlInfo}, "", 0) case "warn": l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlWarn}, "", 0) case "error": l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlError}, "", 0) case "request": l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlInfo}, "", 0) } return l }
go
func GetLogger(name string, logger MultiLogger) (l *log.Logger) { switch name { case "trace": // TODO trace is deprecated, replaced by debug l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlDebug}, "", 0) case "debug": l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlDebug}, "", 0) case "info": l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlInfo}, "", 0) case "warn": l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlWarn}, "", 0) case "error": l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlError}, "", 0) case "request": l = log.New(loggerRewrite{Logger: logger, Level: log15.LvlInfo}, "", 0) } return l }
[ "func", "GetLogger", "(", "name", "string", ",", "logger", "MultiLogger", ")", "(", "l", "*", "log", ".", "Logger", ")", "{", "switch", "name", "{", "case", "\"", "\"", ":", "// TODO trace is deprecated, replaced by debug", "l", "=", "log", ".", "New", "(", "loggerRewrite", "{", "Logger", ":", "logger", ",", "Level", ":", "log15", ".", "LvlDebug", "}", ",", "\"", "\"", ",", "0", ")", "\n", "case", "\"", "\"", ":", "l", "=", "log", ".", "New", "(", "loggerRewrite", "{", "Logger", ":", "logger", ",", "Level", ":", "log15", ".", "LvlDebug", "}", ",", "\"", "\"", ",", "0", ")", "\n", "case", "\"", "\"", ":", "l", "=", "log", ".", "New", "(", "loggerRewrite", "{", "Logger", ":", "logger", ",", "Level", ":", "log15", ".", "LvlInfo", "}", ",", "\"", "\"", ",", "0", ")", "\n", "case", "\"", "\"", ":", "l", "=", "log", ".", "New", "(", "loggerRewrite", "{", "Logger", ":", "logger", ",", "Level", ":", "log15", ".", "LvlWarn", "}", ",", "\"", "\"", ",", "0", ")", "\n", "case", "\"", "\"", ":", "l", "=", "log", ".", "New", "(", "loggerRewrite", "{", "Logger", ":", "logger", ",", "Level", ":", "log15", ".", "LvlError", "}", ",", "\"", "\"", ",", "0", ")", "\n", "case", "\"", "\"", ":", "l", "=", "log", ".", "New", "(", "loggerRewrite", "{", "Logger", ":", "logger", ",", "Level", ":", "log15", ".", "LvlInfo", "}", ",", "\"", "\"", ",", "0", ")", "\n", "}", "\n\n", "return", "l", "\n\n", "}" ]
// Returns the logger for the name
[ "Returns", "the", "logger", "for", "the", "name" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/utils.go#L27-L45
train
revel/revel
logger/utils.go
Write
func (lr loggerRewrite) Write(p []byte) (n int, err error) { if !lr.hideDeprecated { p = append(log_deprecated, p...) } n = len(p) if len(p) > 0 && p[n-1] == '\n' { p = p[:n-1] n-- } switch lr.Level { case log15.LvlInfo: lr.Logger.Info(string(p)) case log15.LvlDebug: lr.Logger.Debug(string(p)) case log15.LvlWarn: lr.Logger.Warn(string(p)) case log15.LvlError: lr.Logger.Error(string(p)) case log15.LvlCrit: lr.Logger.Crit(string(p)) } return }
go
func (lr loggerRewrite) Write(p []byte) (n int, err error) { if !lr.hideDeprecated { p = append(log_deprecated, p...) } n = len(p) if len(p) > 0 && p[n-1] == '\n' { p = p[:n-1] n-- } switch lr.Level { case log15.LvlInfo: lr.Logger.Info(string(p)) case log15.LvlDebug: lr.Logger.Debug(string(p)) case log15.LvlWarn: lr.Logger.Warn(string(p)) case log15.LvlError: lr.Logger.Error(string(p)) case log15.LvlCrit: lr.Logger.Crit(string(p)) } return }
[ "func", "(", "lr", "loggerRewrite", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "!", "lr", ".", "hideDeprecated", "{", "p", "=", "append", "(", "log_deprecated", ",", "p", "...", ")", "\n", "}", "\n", "n", "=", "len", "(", "p", ")", "\n", "if", "len", "(", "p", ")", ">", "0", "&&", "p", "[", "n", "-", "1", "]", "==", "'\\n'", "{", "p", "=", "p", "[", ":", "n", "-", "1", "]", "\n", "n", "--", "\n", "}", "\n\n", "switch", "lr", ".", "Level", "{", "case", "log15", ".", "LvlInfo", ":", "lr", ".", "Logger", ".", "Info", "(", "string", "(", "p", ")", ")", "\n", "case", "log15", ".", "LvlDebug", ":", "lr", ".", "Logger", ".", "Debug", "(", "string", "(", "p", ")", ")", "\n", "case", "log15", ".", "LvlWarn", ":", "lr", ".", "Logger", ".", "Warn", "(", "string", "(", "p", ")", ")", "\n", "case", "log15", ".", "LvlError", ":", "lr", ".", "Logger", ".", "Error", "(", "string", "(", "p", ")", ")", "\n", "case", "log15", ".", "LvlCrit", ":", "lr", ".", "Logger", ".", "Crit", "(", "string", "(", "p", ")", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// Implements the Write of the logger
[ "Implements", "the", "Write", "of", "the", "logger" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/utils.go#L79-L103
train
revel/revel
logger/composite_multihandler.go
SetHandlers
func (h *CompositeMultiHandler) SetHandlers(handler LogHandler, options *LogOptions) { if len(options.Levels) == 0 { options.Levels = LvlAllList } // Set all levels for _, lvl := range options.Levels { h.SetHandler(handler, options.ReplaceExistingHandler, lvl) } }
go
func (h *CompositeMultiHandler) SetHandlers(handler LogHandler, options *LogOptions) { if len(options.Levels) == 0 { options.Levels = LvlAllList } // Set all levels for _, lvl := range options.Levels { h.SetHandler(handler, options.ReplaceExistingHandler, lvl) } }
[ "func", "(", "h", "*", "CompositeMultiHandler", ")", "SetHandlers", "(", "handler", "LogHandler", ",", "options", "*", "LogOptions", ")", "{", "if", "len", "(", "options", ".", "Levels", ")", "==", "0", "{", "options", ".", "Levels", "=", "LvlAllList", "\n", "}", "\n\n", "// Set all levels", "for", "_", ",", "lvl", ":=", "range", "options", ".", "Levels", "{", "h", ".", "SetHandler", "(", "handler", ",", "options", ".", "ReplaceExistingHandler", ",", "lvl", ")", "\n", "}", "\n\n", "}" ]
// For the multi handler set the handler, using the LogOptions defined
[ "For", "the", "multi", "handler", "set", "the", "handler", "using", "the", "LogOptions", "defined" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/composite_multihandler.go#L82-L92
train
revel/revel
logger/composite_multihandler.go
SetJsonFile
func (h *CompositeMultiHandler) SetJsonFile(filePath string, options *LogOptions) { writer := &lumberjack.Logger{ Filename: filePath, MaxSize: options.GetIntDefault("maxSizeMB", 1024), // megabytes MaxAge: options.GetIntDefault("maxAgeDays", 7), //days MaxBackups: options.GetIntDefault("maxBackups", 7), Compress: options.GetBoolDefault("compress", true), } h.SetJson(writer, options) }
go
func (h *CompositeMultiHandler) SetJsonFile(filePath string, options *LogOptions) { writer := &lumberjack.Logger{ Filename: filePath, MaxSize: options.GetIntDefault("maxSizeMB", 1024), // megabytes MaxAge: options.GetIntDefault("maxAgeDays", 7), //days MaxBackups: options.GetIntDefault("maxBackups", 7), Compress: options.GetBoolDefault("compress", true), } h.SetJson(writer, options) }
[ "func", "(", "h", "*", "CompositeMultiHandler", ")", "SetJsonFile", "(", "filePath", "string", ",", "options", "*", "LogOptions", ")", "{", "writer", ":=", "&", "lumberjack", ".", "Logger", "{", "Filename", ":", "filePath", ",", "MaxSize", ":", "options", ".", "GetIntDefault", "(", "\"", "\"", ",", "1024", ")", ",", "// megabytes", "MaxAge", ":", "options", ".", "GetIntDefault", "(", "\"", "\"", ",", "7", ")", ",", "//days", "MaxBackups", ":", "options", ".", "GetIntDefault", "(", "\"", "\"", ",", "7", ")", ",", "Compress", ":", "options", ".", "GetBoolDefault", "(", "\"", "\"", ",", "true", ")", ",", "}", "\n", "h", ".", "SetJson", "(", "writer", ",", "options", ")", "\n", "}" ]
// Use built in rolling function
[ "Use", "built", "in", "rolling", "function" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/composite_multihandler.go#L105-L114
train
revel/revel
compress.go
CloseNotify
func (c CompressResponseWriter) CloseNotify() <-chan bool { if c.parentNotify != nil { return c.parentNotify } return c.closeNotify }
go
func (c CompressResponseWriter) CloseNotify() <-chan bool { if c.parentNotify != nil { return c.parentNotify } return c.closeNotify }
[ "func", "(", "c", "CompressResponseWriter", ")", "CloseNotify", "(", ")", "<-", "chan", "bool", "{", "if", "c", ".", "parentNotify", "!=", "nil", "{", "return", "c", ".", "parentNotify", "\n", "}", "\n", "return", "c", ".", "closeNotify", "\n", "}" ]
// Called to notify the writer is closing
[ "Called", "to", "notify", "the", "writer", "is", "closing" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L88-L93
train
revel/revel
compress.go
prepareHeaders
func (c *CompressResponseWriter) prepareHeaders() { if c.compressionType != "" { responseMime := "" if t := c.Header.Get("Content-Type"); len(t) > 0 { responseMime = t[0] } responseMime = strings.TrimSpace(strings.SplitN(responseMime, ";", 2)[0]) shouldEncode := false if len(c.Header.Get("Content-Encoding")) == 0 { for _, compressableMime := range compressableMimes { if responseMime == compressableMime { shouldEncode = true c.Header.Set("Content-Encoding", c.compressionType) c.Header.Del("Content-Length") break } } } if !shouldEncode { c.compressWriter = nil c.compressionType = "" } } c.Header.Release() }
go
func (c *CompressResponseWriter) prepareHeaders() { if c.compressionType != "" { responseMime := "" if t := c.Header.Get("Content-Type"); len(t) > 0 { responseMime = t[0] } responseMime = strings.TrimSpace(strings.SplitN(responseMime, ";", 2)[0]) shouldEncode := false if len(c.Header.Get("Content-Encoding")) == 0 { for _, compressableMime := range compressableMimes { if responseMime == compressableMime { shouldEncode = true c.Header.Set("Content-Encoding", c.compressionType) c.Header.Del("Content-Length") break } } } if !shouldEncode { c.compressWriter = nil c.compressionType = "" } } c.Header.Release() }
[ "func", "(", "c", "*", "CompressResponseWriter", ")", "prepareHeaders", "(", ")", "{", "if", "c", ".", "compressionType", "!=", "\"", "\"", "{", "responseMime", ":=", "\"", "\"", "\n", "if", "t", ":=", "c", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ";", "len", "(", "t", ")", ">", "0", "{", "responseMime", "=", "t", "[", "0", "]", "\n", "}", "\n", "responseMime", "=", "strings", ".", "TrimSpace", "(", "strings", ".", "SplitN", "(", "responseMime", ",", "\"", "\"", ",", "2", ")", "[", "0", "]", ")", "\n", "shouldEncode", ":=", "false", "\n\n", "if", "len", "(", "c", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", "==", "0", "{", "for", "_", ",", "compressableMime", ":=", "range", "compressableMimes", "{", "if", "responseMime", "==", "compressableMime", "{", "shouldEncode", "=", "true", "\n", "c", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "c", ".", "compressionType", ")", "\n", "c", ".", "Header", ".", "Del", "(", "\"", "\"", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "!", "shouldEncode", "{", "c", ".", "compressWriter", "=", "nil", "\n", "c", ".", "compressionType", "=", "\"", "\"", "\n", "}", "\n", "}", "\n", "c", ".", "Header", ".", "Release", "(", ")", "\n", "}" ]
// Prepare the headers
[ "Prepare", "the", "headers" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L101-L127
train
revel/revel
compress.go
WriteHeader
func (c *CompressResponseWriter) WriteHeader(status int) { if c.closed { return } c.headersWritten = true c.prepareHeaders() c.Header.SetStatus(status) }
go
func (c *CompressResponseWriter) WriteHeader(status int) { if c.closed { return } c.headersWritten = true c.prepareHeaders() c.Header.SetStatus(status) }
[ "func", "(", "c", "*", "CompressResponseWriter", ")", "WriteHeader", "(", "status", "int", ")", "{", "if", "c", ".", "closed", "{", "return", "\n", "}", "\n", "c", ".", "headersWritten", "=", "true", "\n", "c", ".", "prepareHeaders", "(", ")", "\n", "c", ".", "Header", ".", "SetStatus", "(", "status", ")", "\n", "}" ]
// Write the headers
[ "Write", "the", "headers" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L130-L137
train
revel/revel
compress.go
Close
func (c *CompressResponseWriter) Close() error { if c.closed { return nil } if !c.headersWritten { c.prepareHeaders() } if c.compressionType != "" { c.Header.Del("Content-Length") if err := c.compressWriter.Close(); err != nil { // TODO When writing directly to stream, an error will be generated compressLog.Error("Close: Error closing compress writer", "type", c.compressionType, "error", err) } } // Non-blocking write to the closenotifier, if we for some reason should // get called multiple times select { case c.closeNotify <- true: default: } c.closed = true return nil }
go
func (c *CompressResponseWriter) Close() error { if c.closed { return nil } if !c.headersWritten { c.prepareHeaders() } if c.compressionType != "" { c.Header.Del("Content-Length") if err := c.compressWriter.Close(); err != nil { // TODO When writing directly to stream, an error will be generated compressLog.Error("Close: Error closing compress writer", "type", c.compressionType, "error", err) } } // Non-blocking write to the closenotifier, if we for some reason should // get called multiple times select { case c.closeNotify <- true: default: } c.closed = true return nil }
[ "func", "(", "c", "*", "CompressResponseWriter", ")", "Close", "(", ")", "error", "{", "if", "c", ".", "closed", "{", "return", "nil", "\n", "}", "\n", "if", "!", "c", ".", "headersWritten", "{", "c", ".", "prepareHeaders", "(", ")", "\n", "}", "\n", "if", "c", ".", "compressionType", "!=", "\"", "\"", "{", "c", ".", "Header", ".", "Del", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "c", ".", "compressWriter", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "// TODO When writing directly to stream, an error will be generated", "compressLog", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "c", ".", "compressionType", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "}", "\n", "// Non-blocking write to the closenotifier, if we for some reason should", "// get called multiple times", "select", "{", "case", "c", ".", "closeNotify", "<-", "true", ":", "default", ":", "}", "\n", "c", ".", "closed", "=", "true", "\n", "return", "nil", "\n", "}" ]
// Close the writer
[ "Close", "the", "writer" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L140-L163
train
revel/revel
compress.go
Write
func (c *CompressResponseWriter) Write(b []byte) (int, error) { if c.closed { return 0, io.ErrClosedPipe } // Abort if parent has been closed if c.parentNotify != nil { select { case <-c.parentNotify: return 0, io.ErrClosedPipe default: } } // Abort if we ourselves have been closed if c.closed { return 0, io.ErrClosedPipe } if !c.headersWritten { c.prepareHeaders() c.headersWritten = true } if c.compressionType != "" { return c.compressWriter.Write(b) } return c.OriginalWriter.Write(b) }
go
func (c *CompressResponseWriter) Write(b []byte) (int, error) { if c.closed { return 0, io.ErrClosedPipe } // Abort if parent has been closed if c.parentNotify != nil { select { case <-c.parentNotify: return 0, io.ErrClosedPipe default: } } // Abort if we ourselves have been closed if c.closed { return 0, io.ErrClosedPipe } if !c.headersWritten { c.prepareHeaders() c.headersWritten = true } if c.compressionType != "" { return c.compressWriter.Write(b) } return c.OriginalWriter.Write(b) }
[ "func", "(", "c", "*", "CompressResponseWriter", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "c", ".", "closed", "{", "return", "0", ",", "io", ".", "ErrClosedPipe", "\n", "}", "\n", "// Abort if parent has been closed", "if", "c", ".", "parentNotify", "!=", "nil", "{", "select", "{", "case", "<-", "c", ".", "parentNotify", ":", "return", "0", ",", "io", ".", "ErrClosedPipe", "\n", "default", ":", "}", "\n", "}", "\n", "// Abort if we ourselves have been closed", "if", "c", ".", "closed", "{", "return", "0", ",", "io", ".", "ErrClosedPipe", "\n", "}", "\n\n", "if", "!", "c", ".", "headersWritten", "{", "c", ".", "prepareHeaders", "(", ")", "\n", "c", ".", "headersWritten", "=", "true", "\n", "}", "\n", "if", "c", ".", "compressionType", "!=", "\"", "\"", "{", "return", "c", ".", "compressWriter", ".", "Write", "(", "b", ")", "\n", "}", "\n", "return", "c", ".", "OriginalWriter", ".", "Write", "(", "b", ")", "\n", "}" ]
// Write to the underling buffer
[ "Write", "to", "the", "underling", "buffer" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L166-L191
train
revel/revel
compress.go
detectCompressionType
func detectCompressionType(req *Request, resp *Response) (found bool, compressionType string, compressionKind WriteFlusher) { if Config.BoolDefault("results.compressed", false) { acceptedEncodings := strings.Split(req.GetHttpHeader("Accept-Encoding"), ",") largestQ := 0.0 chosenEncoding := len(compressionTypes) // I have fixed one edge case for issue #914 // But it's better to cover all possible edge cases or // Adapt to https://github.com/golang/gddo/blob/master/httputil/header/header.go#L172 for _, encoding := range acceptedEncodings { encoding = strings.TrimSpace(encoding) encodingParts := strings.SplitN(encoding, ";", 2) // If we are the format "gzip;q=0.8" if len(encodingParts) > 1 { q := strings.TrimSpace(encodingParts[1]) if len(q) == 0 || !strings.HasPrefix(q, "q=") { continue } // Strip off the q= num, err := strconv.ParseFloat(q[2:], 32) if err != nil { continue } if num >= largestQ && num > 0 { if encodingParts[0] == "*" { chosenEncoding = 0 largestQ = num continue } for i, encoding := range compressionTypes { if encoding == encodingParts[0] { if i < chosenEncoding { largestQ = num chosenEncoding = i } break } } } } else { // If we can accept anything, chose our preferred method. if encodingParts[0] == "*" { chosenEncoding = 0 largestQ = 1 break } // This is for just plain "gzip" for i, encoding := range compressionTypes { if encoding == encodingParts[0] { if i < chosenEncoding { largestQ = 1.0 chosenEncoding = i } break } } } } if largestQ == 0 { return } compressionType = compressionTypes[chosenEncoding] switch compressionType { case "gzip": compressionKind = gzip.NewWriter(resp.GetWriter()) found = true case "deflate": compressionKind = zlib.NewWriter(resp.GetWriter()) found = true } } return }
go
func detectCompressionType(req *Request, resp *Response) (found bool, compressionType string, compressionKind WriteFlusher) { if Config.BoolDefault("results.compressed", false) { acceptedEncodings := strings.Split(req.GetHttpHeader("Accept-Encoding"), ",") largestQ := 0.0 chosenEncoding := len(compressionTypes) // I have fixed one edge case for issue #914 // But it's better to cover all possible edge cases or // Adapt to https://github.com/golang/gddo/blob/master/httputil/header/header.go#L172 for _, encoding := range acceptedEncodings { encoding = strings.TrimSpace(encoding) encodingParts := strings.SplitN(encoding, ";", 2) // If we are the format "gzip;q=0.8" if len(encodingParts) > 1 { q := strings.TrimSpace(encodingParts[1]) if len(q) == 0 || !strings.HasPrefix(q, "q=") { continue } // Strip off the q= num, err := strconv.ParseFloat(q[2:], 32) if err != nil { continue } if num >= largestQ && num > 0 { if encodingParts[0] == "*" { chosenEncoding = 0 largestQ = num continue } for i, encoding := range compressionTypes { if encoding == encodingParts[0] { if i < chosenEncoding { largestQ = num chosenEncoding = i } break } } } } else { // If we can accept anything, chose our preferred method. if encodingParts[0] == "*" { chosenEncoding = 0 largestQ = 1 break } // This is for just plain "gzip" for i, encoding := range compressionTypes { if encoding == encodingParts[0] { if i < chosenEncoding { largestQ = 1.0 chosenEncoding = i } break } } } } if largestQ == 0 { return } compressionType = compressionTypes[chosenEncoding] switch compressionType { case "gzip": compressionKind = gzip.NewWriter(resp.GetWriter()) found = true case "deflate": compressionKind = zlib.NewWriter(resp.GetWriter()) found = true } } return }
[ "func", "detectCompressionType", "(", "req", "*", "Request", ",", "resp", "*", "Response", ")", "(", "found", "bool", ",", "compressionType", "string", ",", "compressionKind", "WriteFlusher", ")", "{", "if", "Config", ".", "BoolDefault", "(", "\"", "\"", ",", "false", ")", "{", "acceptedEncodings", ":=", "strings", ".", "Split", "(", "req", ".", "GetHttpHeader", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n\n", "largestQ", ":=", "0.0", "\n", "chosenEncoding", ":=", "len", "(", "compressionTypes", ")", "\n\n", "// I have fixed one edge case for issue #914", "// But it's better to cover all possible edge cases or", "// Adapt to https://github.com/golang/gddo/blob/master/httputil/header/header.go#L172", "for", "_", ",", "encoding", ":=", "range", "acceptedEncodings", "{", "encoding", "=", "strings", ".", "TrimSpace", "(", "encoding", ")", "\n", "encodingParts", ":=", "strings", ".", "SplitN", "(", "encoding", ",", "\"", "\"", ",", "2", ")", "\n\n", "// If we are the format \"gzip;q=0.8\"", "if", "len", "(", "encodingParts", ")", ">", "1", "{", "q", ":=", "strings", ".", "TrimSpace", "(", "encodingParts", "[", "1", "]", ")", "\n", "if", "len", "(", "q", ")", "==", "0", "||", "!", "strings", ".", "HasPrefix", "(", "q", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n\n", "// Strip off the q=", "num", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "q", "[", "2", ":", "]", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "if", "num", ">=", "largestQ", "&&", "num", ">", "0", "{", "if", "encodingParts", "[", "0", "]", "==", "\"", "\"", "{", "chosenEncoding", "=", "0", "\n", "largestQ", "=", "num", "\n", "continue", "\n", "}", "\n", "for", "i", ",", "encoding", ":=", "range", "compressionTypes", "{", "if", "encoding", "==", "encodingParts", "[", "0", "]", "{", "if", "i", "<", "chosenEncoding", "{", "largestQ", "=", "num", "\n", "chosenEncoding", "=", "i", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "else", "{", "// If we can accept anything, chose our preferred method.", "if", "encodingParts", "[", "0", "]", "==", "\"", "\"", "{", "chosenEncoding", "=", "0", "\n", "largestQ", "=", "1", "\n", "break", "\n", "}", "\n", "// This is for just plain \"gzip\"", "for", "i", ",", "encoding", ":=", "range", "compressionTypes", "{", "if", "encoding", "==", "encodingParts", "[", "0", "]", "{", "if", "i", "<", "chosenEncoding", "{", "largestQ", "=", "1.0", "\n", "chosenEncoding", "=", "i", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "largestQ", "==", "0", "{", "return", "\n", "}", "\n\n", "compressionType", "=", "compressionTypes", "[", "chosenEncoding", "]", "\n\n", "switch", "compressionType", "{", "case", "\"", "\"", ":", "compressionKind", "=", "gzip", ".", "NewWriter", "(", "resp", ".", "GetWriter", "(", ")", ")", "\n", "found", "=", "true", "\n", "case", "\"", "\"", ":", "compressionKind", "=", "zlib", ".", "NewWriter", "(", "resp", ".", "GetWriter", "(", ")", ")", "\n", "found", "=", "true", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// DetectCompressionType method detects the compression type // from header "Accept-Encoding"
[ "DetectCompressionType", "method", "detects", "the", "compression", "type", "from", "header", "Accept", "-", "Encoding" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L195-L274
train
revel/revel
compress.go
NewBufferedServerHeader
func NewBufferedServerHeader(o ServerHeader) *BufferedServerHeader { return &BufferedServerHeader{original: o, headerMap: map[string][]string{}} }
go
func NewBufferedServerHeader(o ServerHeader) *BufferedServerHeader { return &BufferedServerHeader{original: o, headerMap: map[string][]string{}} }
[ "func", "NewBufferedServerHeader", "(", "o", "ServerHeader", ")", "*", "BufferedServerHeader", "{", "return", "&", "BufferedServerHeader", "{", "original", ":", "o", ",", "headerMap", ":", "map", "[", "string", "]", "[", "]", "string", "{", "}", "}", "\n", "}" ]
// Creates a new instance based on the ServerHeader
[ "Creates", "a", "new", "instance", "based", "on", "the", "ServerHeader" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L287-L289
train
revel/revel
compress.go
Del
func (bsh *BufferedServerHeader) Del(key string) { if bsh.released { bsh.original.Del(key) } else { delete(bsh.headerMap, key) } }
go
func (bsh *BufferedServerHeader) Del(key string) { if bsh.released { bsh.original.Del(key) } else { delete(bsh.headerMap, key) } }
[ "func", "(", "bsh", "*", "BufferedServerHeader", ")", "Del", "(", "key", "string", ")", "{", "if", "bsh", ".", "released", "{", "bsh", ".", "original", ".", "Del", "(", "key", ")", "\n", "}", "else", "{", "delete", "(", "bsh", ".", "headerMap", ",", "key", ")", "\n", "}", "\n", "}" ]
// Delete this key
[ "Delete", "this", "key" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L328-L334
train
revel/revel
compress.go
Get
func (bsh *BufferedServerHeader) Get(key string) (value []string) { if bsh.released { value = bsh.original.Get(key) } else { if v, found := bsh.headerMap[key]; found && len(v) > 0 { value = v } else { value = bsh.original.Get(key) } } return }
go
func (bsh *BufferedServerHeader) Get(key string) (value []string) { if bsh.released { value = bsh.original.Get(key) } else { if v, found := bsh.headerMap[key]; found && len(v) > 0 { value = v } else { value = bsh.original.Get(key) } } return }
[ "func", "(", "bsh", "*", "BufferedServerHeader", ")", "Get", "(", "key", "string", ")", "(", "value", "[", "]", "string", ")", "{", "if", "bsh", ".", "released", "{", "value", "=", "bsh", ".", "original", ".", "Get", "(", "key", ")", "\n", "}", "else", "{", "if", "v", ",", "found", ":=", "bsh", ".", "headerMap", "[", "key", "]", ";", "found", "&&", "len", "(", "v", ")", ">", "0", "{", "value", "=", "v", "\n", "}", "else", "{", "value", "=", "bsh", ".", "original", ".", "Get", "(", "key", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Get this key
[ "Get", "this", "key" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L337-L348
train
revel/revel
compress.go
GetKeys
func (bsh *BufferedServerHeader) GetKeys() (value []string) { if bsh.released { value = bsh.original.GetKeys() } else { value = bsh.original.GetKeys() for key := range bsh.headerMap { found := false for _,v := range value { if v==key { found = true break } } if !found { value = append(value,key) } } } return }
go
func (bsh *BufferedServerHeader) GetKeys() (value []string) { if bsh.released { value = bsh.original.GetKeys() } else { value = bsh.original.GetKeys() for key := range bsh.headerMap { found := false for _,v := range value { if v==key { found = true break } } if !found { value = append(value,key) } } } return }
[ "func", "(", "bsh", "*", "BufferedServerHeader", ")", "GetKeys", "(", ")", "(", "value", "[", "]", "string", ")", "{", "if", "bsh", ".", "released", "{", "value", "=", "bsh", ".", "original", ".", "GetKeys", "(", ")", "\n", "}", "else", "{", "value", "=", "bsh", ".", "original", ".", "GetKeys", "(", ")", "\n", "for", "key", ":=", "range", "bsh", ".", "headerMap", "{", "found", ":=", "false", "\n", "for", "_", ",", "v", ":=", "range", "value", "{", "if", "v", "==", "key", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "value", "=", "append", "(", "value", ",", "key", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Get all header keys
[ "Get", "all", "header", "keys" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L351-L370
train
revel/revel
compress.go
SetStatus
func (bsh *BufferedServerHeader) SetStatus(statusCode int) { if bsh.released { bsh.original.SetStatus(statusCode) } else { bsh.status = statusCode } }
go
func (bsh *BufferedServerHeader) SetStatus(statusCode int) { if bsh.released { bsh.original.SetStatus(statusCode) } else { bsh.status = statusCode } }
[ "func", "(", "bsh", "*", "BufferedServerHeader", ")", "SetStatus", "(", "statusCode", "int", ")", "{", "if", "bsh", ".", "released", "{", "bsh", ".", "original", ".", "SetStatus", "(", "statusCode", ")", "\n", "}", "else", "{", "bsh", ".", "status", "=", "statusCode", "\n", "}", "\n", "}" ]
// Set the status
[ "Set", "the", "status" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L373-L379
train
revel/revel
compress.go
Release
func (bsh *BufferedServerHeader) Release() { bsh.released = true for k, v := range bsh.headerMap { for _, r := range v { bsh.original.Set(k, r) } } for _, c := range bsh.cookieList { bsh.original.SetCookie(c) } if bsh.status > 0 { bsh.original.SetStatus(bsh.status) } }
go
func (bsh *BufferedServerHeader) Release() { bsh.released = true for k, v := range bsh.headerMap { for _, r := range v { bsh.original.Set(k, r) } } for _, c := range bsh.cookieList { bsh.original.SetCookie(c) } if bsh.status > 0 { bsh.original.SetStatus(bsh.status) } }
[ "func", "(", "bsh", "*", "BufferedServerHeader", ")", "Release", "(", ")", "{", "bsh", ".", "released", "=", "true", "\n", "for", "k", ",", "v", ":=", "range", "bsh", ".", "headerMap", "{", "for", "_", ",", "r", ":=", "range", "v", "{", "bsh", ".", "original", ".", "Set", "(", "k", ",", "r", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "bsh", ".", "cookieList", "{", "bsh", ".", "original", ".", "SetCookie", "(", "c", ")", "\n", "}", "\n", "if", "bsh", ".", "status", ">", "0", "{", "bsh", ".", "original", ".", "SetStatus", "(", "bsh", ".", "status", ")", "\n", "}", "\n", "}" ]
// Release the header and push the results to the original
[ "Release", "the", "header", "and", "push", "the", "results", "to", "the", "original" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L382-L395
train
revel/revel
watcher.go
eagerRebuildEnabled
func (w *Watcher) eagerRebuildEnabled() bool { return Config.BoolDefault("mode.dev", true) && Config.BoolDefault("watch", true) && Config.StringDefault("watch.mode", "normal") == "eager" }
go
func (w *Watcher) eagerRebuildEnabled() bool { return Config.BoolDefault("mode.dev", true) && Config.BoolDefault("watch", true) && Config.StringDefault("watch.mode", "normal") == "eager" }
[ "func", "(", "w", "*", "Watcher", ")", "eagerRebuildEnabled", "(", ")", "bool", "{", "return", "Config", ".", "BoolDefault", "(", "\"", "\"", ",", "true", ")", "&&", "Config", ".", "BoolDefault", "(", "\"", "\"", ",", "true", ")", "&&", "Config", ".", "StringDefault", "(", "\"", "\"", ",", "\"", "\"", ")", "==", "\"", "\"", "\n", "}" ]
// If watch.mode is set to eager, the application is rebuilt immediately // when a source file is changed. // This feature is available only in dev mode.
[ "If", "watch", ".", "mode", "is", "set", "to", "eager", "the", "application", "is", "rebuilt", "immediately", "when", "a", "source", "file", "is", "changed", ".", "This", "feature", "is", "available", "only", "in", "dev", "mode", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/watcher.go#L270-L274
train
revel/revel
util.go
ExecuteTemplate
func ExecuteTemplate(tmpl ExecutableTemplate, data interface{}) string { var b bytes.Buffer if err := tmpl.Execute(&b, data); err != nil { utilLog.Error("ExecuteTemplate: Execute failed", "error", err) } return b.String() }
go
func ExecuteTemplate(tmpl ExecutableTemplate, data interface{}) string { var b bytes.Buffer if err := tmpl.Execute(&b, data); err != nil { utilLog.Error("ExecuteTemplate: Execute failed", "error", err) } return b.String() }
[ "func", "ExecuteTemplate", "(", "tmpl", "ExecutableTemplate", ",", "data", "interface", "{", "}", ")", "string", "{", "var", "b", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "tmpl", ".", "Execute", "(", "&", "b", ",", "data", ")", ";", "err", "!=", "nil", "{", "utilLog", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "b", ".", "String", "(", ")", "\n", "}" ]
// ExecuteTemplate execute a template and returns the result as a string.
[ "ExecuteTemplate", "execute", "a", "template", "and", "returns", "the", "result", "as", "a", "string", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/util.go#L43-L49
train
revel/revel
util.go
MustReadLines
func MustReadLines(filename string) []string { r, err := ReadLines(filename) if err != nil { panic(err) } return r }
go
func MustReadLines(filename string) []string { r, err := ReadLines(filename) if err != nil { panic(err) } return r }
[ "func", "MustReadLines", "(", "filename", "string", ")", "[", "]", "string", "{", "r", ",", "err", ":=", "ReadLines", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "r", "\n", "}" ]
// MustReadLines reads the lines of the given file. Panics in the case of error.
[ "MustReadLines", "reads", "the", "lines", "of", "the", "given", "file", ".", "Panics", "in", "the", "case", "of", "error", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/util.go#L52-L58
train
revel/revel
util.go
ReadLines
func ReadLines(filename string) ([]string, error) { dataBytes, err := ioutil.ReadFile(filename) if err != nil { return nil, err } return strings.Split(string(dataBytes), "\n"), nil }
go
func ReadLines(filename string) ([]string, error) { dataBytes, err := ioutil.ReadFile(filename) if err != nil { return nil, err } return strings.Split(string(dataBytes), "\n"), nil }
[ "func", "ReadLines", "(", "filename", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "dataBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "strings", ".", "Split", "(", "string", "(", "dataBytes", ")", ",", "\"", "\\n", "\"", ")", ",", "nil", "\n", "}" ]
// ReadLines reads the lines of the given file. Panics in the case of error.
[ "ReadLines", "reads", "the", "lines", "of", "the", "given", "file", ".", "Panics", "in", "the", "case", "of", "error", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/util.go#L61-L67
train
revel/revel
util.go
FindMethod
func FindMethod(recvType reflect.Type, funcVal reflect.Value) *reflect.Method { // It is not possible to get the name of the method from the Func. // Instead, compare it to each method of the Controller. for i := 0; i < recvType.NumMethod(); i++ { method := recvType.Method(i) if method.Func.Pointer() == funcVal.Pointer() { return &method } } return nil }
go
func FindMethod(recvType reflect.Type, funcVal reflect.Value) *reflect.Method { // It is not possible to get the name of the method from the Func. // Instead, compare it to each method of the Controller. for i := 0; i < recvType.NumMethod(); i++ { method := recvType.Method(i) if method.Func.Pointer() == funcVal.Pointer() { return &method } } return nil }
[ "func", "FindMethod", "(", "recvType", "reflect", ".", "Type", ",", "funcVal", "reflect", ".", "Value", ")", "*", "reflect", ".", "Method", "{", "// It is not possible to get the name of the method from the Func.", "// Instead, compare it to each method of the Controller.", "for", "i", ":=", "0", ";", "i", "<", "recvType", ".", "NumMethod", "(", ")", ";", "i", "++", "{", "method", ":=", "recvType", ".", "Method", "(", "i", ")", "\n", "if", "method", ".", "Func", ".", "Pointer", "(", ")", "==", "funcVal", ".", "Pointer", "(", ")", "{", "return", "&", "method", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FindMethod returns the reflect.Method, given a Receiver type and Func value.
[ "FindMethod", "returns", "the", "reflect", ".", "Method", "given", "a", "Receiver", "type", "and", "Func", "value", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/util.go#L79-L89
train
revel/revel
util.go
DirExists
func DirExists(filename string) bool { fileInfo, err := os.Stat(filename) return err == nil && fileInfo.IsDir() }
go
func DirExists(filename string) bool { fileInfo, err := os.Stat(filename) return err == nil && fileInfo.IsDir() }
[ "func", "DirExists", "(", "filename", "string", ")", "bool", "{", "fileInfo", ",", "err", ":=", "os", ".", "Stat", "(", "filename", ")", "\n", "return", "err", "==", "nil", "&&", "fileInfo", ".", "IsDir", "(", ")", "\n", "}" ]
// DirExists returns true if the given path exists and is a directory.
[ "DirExists", "returns", "true", "if", "the", "given", "path", "exists", "and", "is", "a", "directory", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/util.go#L133-L136
train
revel/revel
util.go
Walk
func Walk(root string, walkFn filepath.WalkFunc) error { return fsWalk(root, root, walkFn) }
go
func Walk(root string, walkFn filepath.WalkFunc) error { return fsWalk(root, root, walkFn) }
[ "func", "Walk", "(", "root", "string", ",", "walkFn", "filepath", ".", "WalkFunc", ")", "error", "{", "return", "fsWalk", "(", "root", ",", "root", ",", "walkFn", ")", "\n", "}" ]
// Walk method extends filepath.Walk to also follow symlinks. // Always returns the path of the file or directory.
[ "Walk", "method", "extends", "filepath", ".", "Walk", "to", "also", "follow", "symlinks", ".", "Always", "returns", "the", "path", "of", "the", "file", "or", "directory", "." ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/util.go#L221-L223
train
revel/revel
util.go
createDir
func createDir(path string) error { if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { if err = os.MkdirAll(path, 0755); err != nil { return fmt.Errorf("Failed to create directory '%v': %v", path, err) } } else { return fmt.Errorf("Failed to create directory '%v': %v", path, err) } } return nil }
go
func createDir(path string) error { if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { if err = os.MkdirAll(path, 0755); err != nil { return fmt.Errorf("Failed to create directory '%v': %v", path, err) } } else { return fmt.Errorf("Failed to create directory '%v': %v", path, err) } } return nil }
[ "func", "createDir", "(", "path", "string", ")", "error", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "if", "err", "=", "os", ".", "MkdirAll", "(", "path", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// createDir method creates nested directories if not exists
[ "createDir", "method", "creates", "nested", "directories", "if", "not", "exists" ]
a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e
https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/util.go#L226-L237
train
openshift/source-to-image
pkg/cmd/cli/util/util.go
AddCommonFlags
func AddCommonFlags(c *cobra.Command, cfg *api.Config) { c.Flags().BoolVarP(&(cfg.Quiet), "quiet", "q", false, "Operate quietly. Suppress all non-error output.") c.Flags().BoolVar(&(cfg.Incremental), "incremental", false, "Perform an incremental build") c.Flags().BoolVar(&(cfg.RemovePreviousImage), "rm", false, "Remove the previous image during incremental builds") c.Flags().StringVar(&(cfg.CallbackURL), "callback-url", "", "Specify a URL to invoke via HTTP POST upon build completion") c.Flags().VarP(&(cfg.BuilderPullPolicy), "pull-policy", "p", "Specify when to pull the builder image (always, never or if-not-present)") c.Flags().Var(&(cfg.PreviousImagePullPolicy), "incremental-pull-policy", "Specify when to pull the previous image for incremental builds (always, never or if-not-present)") c.Flags().Var(&(cfg.RuntimeImagePullPolicy), "runtime-pull-policy", "Specify when to pull the runtime image (always, never or if-not-present)") c.Flags().BoolVar(&(cfg.PreserveWorkingDir), "save-temp-dir", false, "Save the temporary directory used by S2I instead of deleting it") c.Flags().StringVarP(&(cfg.DockerCfgPath), "dockercfg-path", "", filepath.Join(os.Getenv("HOME"), ".docker/config.json"), "Specify the path to the Docker configuration file") c.Flags().StringVarP(&(cfg.Destination), "destination", "d", "", "Specify a destination location for untar operation") }
go
func AddCommonFlags(c *cobra.Command, cfg *api.Config) { c.Flags().BoolVarP(&(cfg.Quiet), "quiet", "q", false, "Operate quietly. Suppress all non-error output.") c.Flags().BoolVar(&(cfg.Incremental), "incremental", false, "Perform an incremental build") c.Flags().BoolVar(&(cfg.RemovePreviousImage), "rm", false, "Remove the previous image during incremental builds") c.Flags().StringVar(&(cfg.CallbackURL), "callback-url", "", "Specify a URL to invoke via HTTP POST upon build completion") c.Flags().VarP(&(cfg.BuilderPullPolicy), "pull-policy", "p", "Specify when to pull the builder image (always, never or if-not-present)") c.Flags().Var(&(cfg.PreviousImagePullPolicy), "incremental-pull-policy", "Specify when to pull the previous image for incremental builds (always, never or if-not-present)") c.Flags().Var(&(cfg.RuntimeImagePullPolicy), "runtime-pull-policy", "Specify when to pull the runtime image (always, never or if-not-present)") c.Flags().BoolVar(&(cfg.PreserveWorkingDir), "save-temp-dir", false, "Save the temporary directory used by S2I instead of deleting it") c.Flags().StringVarP(&(cfg.DockerCfgPath), "dockercfg-path", "", filepath.Join(os.Getenv("HOME"), ".docker/config.json"), "Specify the path to the Docker configuration file") c.Flags().StringVarP(&(cfg.Destination), "destination", "d", "", "Specify a destination location for untar operation") }
[ "func", "AddCommonFlags", "(", "c", "*", "cobra", ".", "Command", ",", "cfg", "*", "api", ".", "Config", ")", "{", "c", ".", "Flags", "(", ")", ".", "BoolVarP", "(", "&", "(", "cfg", ".", "Quiet", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "c", ".", "Flags", "(", ")", ".", "BoolVar", "(", "&", "(", "cfg", ".", "Incremental", ")", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "c", ".", "Flags", "(", ")", ".", "BoolVar", "(", "&", "(", "cfg", ".", "RemovePreviousImage", ")", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "c", ".", "Flags", "(", ")", ".", "StringVar", "(", "&", "(", "cfg", ".", "CallbackURL", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Flags", "(", ")", ".", "VarP", "(", "&", "(", "cfg", ".", "BuilderPullPolicy", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Flags", "(", ")", ".", "Var", "(", "&", "(", "cfg", ".", "PreviousImagePullPolicy", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Flags", "(", ")", ".", "Var", "(", "&", "(", "cfg", ".", "RuntimeImagePullPolicy", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Flags", "(", ")", ".", "BoolVar", "(", "&", "(", "cfg", ".", "PreserveWorkingDir", ")", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "c", ".", "Flags", "(", ")", ".", "StringVarP", "(", "&", "(", "cfg", ".", "DockerCfgPath", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "filepath", ".", "Join", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "c", ".", "Flags", "(", ")", ".", "StringVarP", "(", "&", "(", "cfg", ".", "Destination", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// AddCommonFlags adds the common flags for usage, build and rebuild commands
[ "AddCommonFlags", "adds", "the", "common", "flags", "for", "usage", "build", "and", "rebuild", "commands" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/cmd/cli/util/util.go#L16-L37
train
openshift/source-to-image
pkg/build/strategies/sti/sti.go
New
func New(client dockerpkg.Client, config *api.Config, fs fs.FileSystem, overrides build.Overrides) (*STI, error) { excludePattern, err := regexp.Compile(config.ExcludeRegExp) if err != nil { return nil, err } docker := dockerpkg.New(client, config.PullAuthentication) var incrementalDocker dockerpkg.Docker if config.Incremental { incrementalDocker = dockerpkg.New(client, config.IncrementalAuthentication) } inst := scripts.NewInstaller( config.BuilderImage, config.ScriptsURL, config.ScriptDownloadProxyConfig, docker, config.PullAuthentication, fs, ) tarHandler := tar.NewParanoid(fs) tarHandler.SetExclusionPattern(excludePattern) builder := &STI{ installer: inst, config: config, docker: docker, incrementalDocker: incrementalDocker, git: git.New(fs, cmd.NewCommandRunner()), fs: fs, tar: tarHandler, callbackInvoker: util.NewCallbackInvoker(), requiredScripts: scripts.RequiredScripts, optionalScripts: scripts.OptionalScripts, optionalRuntimeScripts: []string{constants.AssembleRuntime}, externalScripts: map[string]bool{}, installedScripts: map[string]bool{}, scriptsURL: map[string]string{}, newLabels: map[string]string{}, } if len(config.RuntimeImage) > 0 { builder.runtimeDocker = dockerpkg.New(client, config.RuntimeAuthentication) builder.runtimeInstaller = scripts.NewInstaller( config.RuntimeImage, config.ScriptsURL, config.ScriptDownloadProxyConfig, builder.runtimeDocker, config.RuntimeAuthentication, builder.fs, ) } // The sources are downloaded using the Git downloader. // TODO: Add more SCM in future. // TODO: explicit decision made to customize processing for usage specifically vs. // leveraging overrides; also, we ultimately want to simplify s2i usage a good bit, // which would lead to replacing this quick short circuit (so this change is tactical) builder.source = overrides.Downloader if builder.source == nil && !config.Usage { downloader, err := scm.DownloaderForSource(builder.fs, config.Source, config.ForceCopy) if err != nil { return nil, err } builder.source = downloader } builder.garbage = build.NewDefaultCleaner(builder.fs, builder.docker) builder.layered, err = layered.New(client, config, builder.fs, builder, overrides) if err != nil { return nil, err } // Set interfaces builder.preparer = builder // later on, if we support say .gitignore func in addition to .dockerignore // func, setting ignorer will be based on config setting builder.ignorer = &ignore.DockerIgnorer{} builder.artifacts = builder builder.scripts = builder builder.postExecutor = builder builder.initPostExecutorSteps() return builder, nil }
go
func New(client dockerpkg.Client, config *api.Config, fs fs.FileSystem, overrides build.Overrides) (*STI, error) { excludePattern, err := regexp.Compile(config.ExcludeRegExp) if err != nil { return nil, err } docker := dockerpkg.New(client, config.PullAuthentication) var incrementalDocker dockerpkg.Docker if config.Incremental { incrementalDocker = dockerpkg.New(client, config.IncrementalAuthentication) } inst := scripts.NewInstaller( config.BuilderImage, config.ScriptsURL, config.ScriptDownloadProxyConfig, docker, config.PullAuthentication, fs, ) tarHandler := tar.NewParanoid(fs) tarHandler.SetExclusionPattern(excludePattern) builder := &STI{ installer: inst, config: config, docker: docker, incrementalDocker: incrementalDocker, git: git.New(fs, cmd.NewCommandRunner()), fs: fs, tar: tarHandler, callbackInvoker: util.NewCallbackInvoker(), requiredScripts: scripts.RequiredScripts, optionalScripts: scripts.OptionalScripts, optionalRuntimeScripts: []string{constants.AssembleRuntime}, externalScripts: map[string]bool{}, installedScripts: map[string]bool{}, scriptsURL: map[string]string{}, newLabels: map[string]string{}, } if len(config.RuntimeImage) > 0 { builder.runtimeDocker = dockerpkg.New(client, config.RuntimeAuthentication) builder.runtimeInstaller = scripts.NewInstaller( config.RuntimeImage, config.ScriptsURL, config.ScriptDownloadProxyConfig, builder.runtimeDocker, config.RuntimeAuthentication, builder.fs, ) } // The sources are downloaded using the Git downloader. // TODO: Add more SCM in future. // TODO: explicit decision made to customize processing for usage specifically vs. // leveraging overrides; also, we ultimately want to simplify s2i usage a good bit, // which would lead to replacing this quick short circuit (so this change is tactical) builder.source = overrides.Downloader if builder.source == nil && !config.Usage { downloader, err := scm.DownloaderForSource(builder.fs, config.Source, config.ForceCopy) if err != nil { return nil, err } builder.source = downloader } builder.garbage = build.NewDefaultCleaner(builder.fs, builder.docker) builder.layered, err = layered.New(client, config, builder.fs, builder, overrides) if err != nil { return nil, err } // Set interfaces builder.preparer = builder // later on, if we support say .gitignore func in addition to .dockerignore // func, setting ignorer will be based on config setting builder.ignorer = &ignore.DockerIgnorer{} builder.artifacts = builder builder.scripts = builder builder.postExecutor = builder builder.initPostExecutorSteps() return builder, nil }
[ "func", "New", "(", "client", "dockerpkg", ".", "Client", ",", "config", "*", "api", ".", "Config", ",", "fs", "fs", ".", "FileSystem", ",", "overrides", "build", ".", "Overrides", ")", "(", "*", "STI", ",", "error", ")", "{", "excludePattern", ",", "err", ":=", "regexp", ".", "Compile", "(", "config", ".", "ExcludeRegExp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "docker", ":=", "dockerpkg", ".", "New", "(", "client", ",", "config", ".", "PullAuthentication", ")", "\n", "var", "incrementalDocker", "dockerpkg", ".", "Docker", "\n", "if", "config", ".", "Incremental", "{", "incrementalDocker", "=", "dockerpkg", ".", "New", "(", "client", ",", "config", ".", "IncrementalAuthentication", ")", "\n", "}", "\n\n", "inst", ":=", "scripts", ".", "NewInstaller", "(", "config", ".", "BuilderImage", ",", "config", ".", "ScriptsURL", ",", "config", ".", "ScriptDownloadProxyConfig", ",", "docker", ",", "config", ".", "PullAuthentication", ",", "fs", ",", ")", "\n", "tarHandler", ":=", "tar", ".", "NewParanoid", "(", "fs", ")", "\n", "tarHandler", ".", "SetExclusionPattern", "(", "excludePattern", ")", "\n\n", "builder", ":=", "&", "STI", "{", "installer", ":", "inst", ",", "config", ":", "config", ",", "docker", ":", "docker", ",", "incrementalDocker", ":", "incrementalDocker", ",", "git", ":", "git", ".", "New", "(", "fs", ",", "cmd", ".", "NewCommandRunner", "(", ")", ")", ",", "fs", ":", "fs", ",", "tar", ":", "tarHandler", ",", "callbackInvoker", ":", "util", ".", "NewCallbackInvoker", "(", ")", ",", "requiredScripts", ":", "scripts", ".", "RequiredScripts", ",", "optionalScripts", ":", "scripts", ".", "OptionalScripts", ",", "optionalRuntimeScripts", ":", "[", "]", "string", "{", "constants", ".", "AssembleRuntime", "}", ",", "externalScripts", ":", "map", "[", "string", "]", "bool", "{", "}", ",", "installedScripts", ":", "map", "[", "string", "]", "bool", "{", "}", ",", "scriptsURL", ":", "map", "[", "string", "]", "string", "{", "}", ",", "newLabels", ":", "map", "[", "string", "]", "string", "{", "}", ",", "}", "\n\n", "if", "len", "(", "config", ".", "RuntimeImage", ")", ">", "0", "{", "builder", ".", "runtimeDocker", "=", "dockerpkg", ".", "New", "(", "client", ",", "config", ".", "RuntimeAuthentication", ")", "\n\n", "builder", ".", "runtimeInstaller", "=", "scripts", ".", "NewInstaller", "(", "config", ".", "RuntimeImage", ",", "config", ".", "ScriptsURL", ",", "config", ".", "ScriptDownloadProxyConfig", ",", "builder", ".", "runtimeDocker", ",", "config", ".", "RuntimeAuthentication", ",", "builder", ".", "fs", ",", ")", "\n", "}", "\n\n", "// The sources are downloaded using the Git downloader.", "// TODO: Add more SCM in future.", "// TODO: explicit decision made to customize processing for usage specifically vs.", "// leveraging overrides; also, we ultimately want to simplify s2i usage a good bit,", "// which would lead to replacing this quick short circuit (so this change is tactical)", "builder", ".", "source", "=", "overrides", ".", "Downloader", "\n", "if", "builder", ".", "source", "==", "nil", "&&", "!", "config", ".", "Usage", "{", "downloader", ",", "err", ":=", "scm", ".", "DownloaderForSource", "(", "builder", ".", "fs", ",", "config", ".", "Source", ",", "config", ".", "ForceCopy", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "builder", ".", "source", "=", "downloader", "\n", "}", "\n", "builder", ".", "garbage", "=", "build", ".", "NewDefaultCleaner", "(", "builder", ".", "fs", ",", "builder", ".", "docker", ")", "\n\n", "builder", ".", "layered", ",", "err", "=", "layered", ".", "New", "(", "client", ",", "config", ",", "builder", ".", "fs", ",", "builder", ",", "overrides", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Set interfaces", "builder", ".", "preparer", "=", "builder", "\n", "// later on, if we support say .gitignore func in addition to .dockerignore", "// func, setting ignorer will be based on config setting", "builder", ".", "ignorer", "=", "&", "ignore", ".", "DockerIgnorer", "{", "}", "\n", "builder", ".", "artifacts", "=", "builder", "\n", "builder", ".", "scripts", "=", "builder", "\n", "builder", ".", "postExecutor", "=", "builder", "\n", "builder", ".", "initPostExecutorSteps", "(", ")", "\n\n", "return", "builder", ",", "nil", "\n", "}" ]
// New returns the instance of STI builder strategy for the given config. // If the layeredBuilder parameter is specified, then the builder provided will // be used for the case that the base Docker image does not have 'tar' or 'bash' // installed.
[ "New", "returns", "the", "instance", "of", "STI", "builder", "strategy", "for", "the", "given", "config", ".", "If", "the", "layeredBuilder", "parameter", "is", "specified", "then", "the", "builder", "provided", "will", "be", "used", "for", "the", "case", "that", "the", "base", "Docker", "image", "does", "not", "have", "tar", "or", "bash", "installed", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/sti.go#L98-L183
train
openshift/source-to-image
pkg/build/strategies/sti/sti.go
SetScripts
func (builder *STI) SetScripts(required, optional []string) { builder.requiredScripts = required builder.optionalScripts = optional }
go
func (builder *STI) SetScripts(required, optional []string) { builder.requiredScripts = required builder.optionalScripts = optional }
[ "func", "(", "builder", "*", "STI", ")", "SetScripts", "(", "required", ",", "optional", "[", "]", "string", ")", "{", "builder", ".", "requiredScripts", "=", "required", "\n", "builder", ".", "optionalScripts", "=", "optional", "\n", "}" ]
// SetScripts allows to override default required and optional scripts
[ "SetScripts", "allows", "to", "override", "default", "required", "and", "optional", "scripts" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/sti.go#L434-L437
train
openshift/source-to-image
pkg/build/strategies/sti/sti.go
PostExecute
func (builder *STI) PostExecute(containerID, destination string) error { builder.postExecutorStepsContext.containerID = containerID builder.postExecutorStepsContext.destination = destination stageSteps := builder.postExecutorFirstStageSteps if builder.postExecutorStage > 0 { stageSteps = builder.postExecutorSecondStageSteps } for _, step := range stageSteps { if err := step.execute(builder.postExecutorStepsContext); err != nil { glog.V(0).Info("error: Execution of post execute step failed") return err } } return nil }
go
func (builder *STI) PostExecute(containerID, destination string) error { builder.postExecutorStepsContext.containerID = containerID builder.postExecutorStepsContext.destination = destination stageSteps := builder.postExecutorFirstStageSteps if builder.postExecutorStage > 0 { stageSteps = builder.postExecutorSecondStageSteps } for _, step := range stageSteps { if err := step.execute(builder.postExecutorStepsContext); err != nil { glog.V(0).Info("error: Execution of post execute step failed") return err } } return nil }
[ "func", "(", "builder", "*", "STI", ")", "PostExecute", "(", "containerID", ",", "destination", "string", ")", "error", "{", "builder", ".", "postExecutorStepsContext", ".", "containerID", "=", "containerID", "\n", "builder", ".", "postExecutorStepsContext", ".", "destination", "=", "destination", "\n\n", "stageSteps", ":=", "builder", ".", "postExecutorFirstStageSteps", "\n", "if", "builder", ".", "postExecutorStage", ">", "0", "{", "stageSteps", "=", "builder", ".", "postExecutorSecondStageSteps", "\n", "}", "\n\n", "for", "_", ",", "step", ":=", "range", "stageSteps", "{", "if", "err", ":=", "step", ".", "execute", "(", "builder", ".", "postExecutorStepsContext", ")", ";", "err", "!=", "nil", "{", "glog", ".", "V", "(", "0", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// PostExecute allows to execute post-build actions after the Docker // container execution finishes.
[ "PostExecute", "allows", "to", "execute", "post", "-", "build", "actions", "after", "the", "Docker", "container", "execution", "finishes", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/sti.go#L441-L458
train
openshift/source-to-image
pkg/build/strategies/sti/sti.go
CreateBuildEnvironment
func CreateBuildEnvironment(sourcePath string, cfgEnv api.EnvironmentList) []string { s2iEnv, err := scripts.GetEnvironment(filepath.Join(sourcePath, constants.Source)) if err != nil { glog.V(3).Infof("No user environment provided (%v)", err) } return append(scripts.ConvertEnvironmentList(s2iEnv), scripts.ConvertEnvironmentList(cfgEnv)...) }
go
func CreateBuildEnvironment(sourcePath string, cfgEnv api.EnvironmentList) []string { s2iEnv, err := scripts.GetEnvironment(filepath.Join(sourcePath, constants.Source)) if err != nil { glog.V(3).Infof("No user environment provided (%v)", err) } return append(scripts.ConvertEnvironmentList(s2iEnv), scripts.ConvertEnvironmentList(cfgEnv)...) }
[ "func", "CreateBuildEnvironment", "(", "sourcePath", "string", ",", "cfgEnv", "api", ".", "EnvironmentList", ")", "[", "]", "string", "{", "s2iEnv", ",", "err", ":=", "scripts", ".", "GetEnvironment", "(", "filepath", ".", "Join", "(", "sourcePath", ",", "constants", ".", "Source", ")", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "V", "(", "3", ")", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "append", "(", "scripts", ".", "ConvertEnvironmentList", "(", "s2iEnv", ")", ",", "scripts", ".", "ConvertEnvironmentList", "(", "cfgEnv", ")", "...", ")", "\n", "}" ]
// CreateBuildEnvironment constructs the environment variables to be provided to the assemble // script and committed in the new image.
[ "CreateBuildEnvironment", "constructs", "the", "environment", "variables", "to", "be", "provided", "to", "the", "assemble", "script", "and", "committed", "in", "the", "new", "image", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/sti.go#L462-L469
train
openshift/source-to-image
pkg/build/strategies/sti/sti.go
Exists
func (builder *STI) Exists(config *api.Config) bool { if !config.Incremental { return false } policy := config.PreviousImagePullPolicy if len(policy) == 0 { policy = api.DefaultPreviousImagePullPolicy } tag := util.FirstNonEmpty(config.IncrementalFromTag, config.Tag) startTime := time.Now() result, err := dockerpkg.PullImage(tag, builder.incrementalDocker, policy) builder.result.BuildInfo.Stages = api.RecordStageAndStepInfo(builder.result.BuildInfo.Stages, api.StagePullImages, api.StepPullPreviousImage, startTime, time.Now()) if err != nil { builder.result.BuildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonPullPreviousImageFailed, utilstatus.ReasonMessagePullPreviousImageFailed, ) glog.V(2).Infof("Unable to pull previously built image %q: %v", tag, err) return false } return result.Image != nil && builder.installedScripts[constants.SaveArtifacts] }
go
func (builder *STI) Exists(config *api.Config) bool { if !config.Incremental { return false } policy := config.PreviousImagePullPolicy if len(policy) == 0 { policy = api.DefaultPreviousImagePullPolicy } tag := util.FirstNonEmpty(config.IncrementalFromTag, config.Tag) startTime := time.Now() result, err := dockerpkg.PullImage(tag, builder.incrementalDocker, policy) builder.result.BuildInfo.Stages = api.RecordStageAndStepInfo(builder.result.BuildInfo.Stages, api.StagePullImages, api.StepPullPreviousImage, startTime, time.Now()) if err != nil { builder.result.BuildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonPullPreviousImageFailed, utilstatus.ReasonMessagePullPreviousImageFailed, ) glog.V(2).Infof("Unable to pull previously built image %q: %v", tag, err) return false } return result.Image != nil && builder.installedScripts[constants.SaveArtifacts] }
[ "func", "(", "builder", "*", "STI", ")", "Exists", "(", "config", "*", "api", ".", "Config", ")", "bool", "{", "if", "!", "config", ".", "Incremental", "{", "return", "false", "\n", "}", "\n\n", "policy", ":=", "config", ".", "PreviousImagePullPolicy", "\n", "if", "len", "(", "policy", ")", "==", "0", "{", "policy", "=", "api", ".", "DefaultPreviousImagePullPolicy", "\n", "}", "\n\n", "tag", ":=", "util", ".", "FirstNonEmpty", "(", "config", ".", "IncrementalFromTag", ",", "config", ".", "Tag", ")", "\n\n", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "result", ",", "err", ":=", "dockerpkg", ".", "PullImage", "(", "tag", ",", "builder", ".", "incrementalDocker", ",", "policy", ")", "\n", "builder", ".", "result", ".", "BuildInfo", ".", "Stages", "=", "api", ".", "RecordStageAndStepInfo", "(", "builder", ".", "result", ".", "BuildInfo", ".", "Stages", ",", "api", ".", "StagePullImages", ",", "api", ".", "StepPullPreviousImage", ",", "startTime", ",", "time", ".", "Now", "(", ")", ")", "\n\n", "if", "err", "!=", "nil", "{", "builder", ".", "result", ".", "BuildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "utilstatus", ".", "ReasonPullPreviousImageFailed", ",", "utilstatus", ".", "ReasonMessagePullPreviousImageFailed", ",", ")", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "tag", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n\n", "return", "result", ".", "Image", "!=", "nil", "&&", "builder", ".", "installedScripts", "[", "constants", ".", "SaveArtifacts", "]", "\n", "}" ]
// Exists determines if the current build supports incremental workflow. // It checks if the previous image exists in the system and if so, then it // verifies that the save-artifacts script is present.
[ "Exists", "determines", "if", "the", "current", "build", "supports", "incremental", "workflow", ".", "It", "checks", "if", "the", "previous", "image", "exists", "in", "the", "system", "and", "if", "so", "then", "it", "verifies", "that", "the", "save", "-", "artifacts", "script", "is", "present", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/sti.go#L474-L500
train
openshift/source-to-image
pkg/build/strategies/sti/sti.go
uploadInjections
func (builder *STI) uploadInjections(config *api.Config, rmScript, containerID string) error { glog.V(2).Info("starting the injections uploading ...") for _, s := range config.Injections { if err := builder.docker.UploadToContainer(builder.fs, s.Source, s.Destination, containerID); err != nil { return util.HandleInjectionError(s, err) } } if err := builder.docker.UploadToContainer(builder.fs, rmScript, rmInjectionsScript, containerID); err != nil { return util.HandleInjectionError(api.VolumeSpec{Source: rmScript, Destination: rmInjectionsScript}, err) } return nil }
go
func (builder *STI) uploadInjections(config *api.Config, rmScript, containerID string) error { glog.V(2).Info("starting the injections uploading ...") for _, s := range config.Injections { if err := builder.docker.UploadToContainer(builder.fs, s.Source, s.Destination, containerID); err != nil { return util.HandleInjectionError(s, err) } } if err := builder.docker.UploadToContainer(builder.fs, rmScript, rmInjectionsScript, containerID); err != nil { return util.HandleInjectionError(api.VolumeSpec{Source: rmScript, Destination: rmInjectionsScript}, err) } return nil }
[ "func", "(", "builder", "*", "STI", ")", "uploadInjections", "(", "config", "*", "api", ".", "Config", ",", "rmScript", ",", "containerID", "string", ")", "error", "{", "glog", ".", "V", "(", "2", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "for", "_", ",", "s", ":=", "range", "config", ".", "Injections", "{", "if", "err", ":=", "builder", ".", "docker", ".", "UploadToContainer", "(", "builder", ".", "fs", ",", "s", ".", "Source", ",", "s", ".", "Destination", ",", "containerID", ")", ";", "err", "!=", "nil", "{", "return", "util", ".", "HandleInjectionError", "(", "s", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "builder", ".", "docker", ".", "UploadToContainer", "(", "builder", ".", "fs", ",", "rmScript", ",", "rmInjectionsScript", ",", "containerID", ")", ";", "err", "!=", "nil", "{", "return", "util", ".", "HandleInjectionError", "(", "api", ".", "VolumeSpec", "{", "Source", ":", "rmScript", ",", "Destination", ":", "rmInjectionsScript", "}", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// uploadInjections uploads the injected volumes to the s2i container, along with the source // removal script to truncate volumes that should not be kept.
[ "uploadInjections", "uploads", "the", "injected", "volumes", "to", "the", "s2i", "container", "along", "with", "the", "source", "removal", "script", "to", "truncate", "volumes", "that", "should", "not", "be", "kept", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/sti.go#L734-L745
train
openshift/source-to-image
pkg/build/strategies/sti/sti.go
uploadInjectionResult
func (builder *STI) uploadInjectionResult(startErr error, containerID string) error { resultFile, err := util.CreateInjectionResultFile(startErr) if len(resultFile) > 0 { defer os.Remove(resultFile) } if err != nil { return err } err = builder.docker.UploadToContainer(builder.fs, resultFile, injectionResultFile, containerID) if err != nil { return util.HandleInjectionError(api.VolumeSpec{Source: resultFile, Destination: injectionResultFile}, err) } return startErr }
go
func (builder *STI) uploadInjectionResult(startErr error, containerID string) error { resultFile, err := util.CreateInjectionResultFile(startErr) if len(resultFile) > 0 { defer os.Remove(resultFile) } if err != nil { return err } err = builder.docker.UploadToContainer(builder.fs, resultFile, injectionResultFile, containerID) if err != nil { return util.HandleInjectionError(api.VolumeSpec{Source: resultFile, Destination: injectionResultFile}, err) } return startErr }
[ "func", "(", "builder", "*", "STI", ")", "uploadInjectionResult", "(", "startErr", "error", ",", "containerID", "string", ")", "error", "{", "resultFile", ",", "err", ":=", "util", ".", "CreateInjectionResultFile", "(", "startErr", ")", "\n", "if", "len", "(", "resultFile", ")", ">", "0", "{", "defer", "os", ".", "Remove", "(", "resultFile", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "builder", ".", "docker", ".", "UploadToContainer", "(", "builder", ".", "fs", ",", "resultFile", ",", "injectionResultFile", ",", "containerID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "util", ".", "HandleInjectionError", "(", "api", ".", "VolumeSpec", "{", "Source", ":", "resultFile", ",", "Destination", ":", "injectionResultFile", "}", ",", "err", ")", "\n", "}", "\n", "return", "startErr", "\n", "}" ]
// uploadInjectionResult uploads a result file to the s2i container, indicating // that the injections have completed. If a non-nil error is passed in, it is returned // to ensure the error status of the injection upload is reported.
[ "uploadInjectionResult", "uploads", "a", "result", "file", "to", "the", "s2i", "container", "indicating", "that", "the", "injections", "have", "completed", ".", "If", "a", "non", "-", "nil", "error", "is", "passed", "in", "it", "is", "returned", "to", "ensure", "the", "error", "status", "of", "the", "injection", "upload", "is", "reported", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/sti.go#L801-L814
train
openshift/source-to-image
pkg/build/strategies/layered/layered.go
New
func New(client docker.Client, config *api.Config, fs fs.FileSystem, scripts build.ScriptsHandler, overrides build.Overrides) (*Layered, error) { excludePattern, err := regexp.Compile(config.ExcludeRegExp) if err != nil { return nil, err } d := docker.New(client, config.PullAuthentication) tarHandler := tar.New(fs) tarHandler.SetExclusionPattern(excludePattern) return &Layered{ docker: d, config: config, fs: fs, tar: tarHandler, scripts: scripts, }, nil }
go
func New(client docker.Client, config *api.Config, fs fs.FileSystem, scripts build.ScriptsHandler, overrides build.Overrides) (*Layered, error) { excludePattern, err := regexp.Compile(config.ExcludeRegExp) if err != nil { return nil, err } d := docker.New(client, config.PullAuthentication) tarHandler := tar.New(fs) tarHandler.SetExclusionPattern(excludePattern) return &Layered{ docker: d, config: config, fs: fs, tar: tarHandler, scripts: scripts, }, nil }
[ "func", "New", "(", "client", "docker", ".", "Client", ",", "config", "*", "api", ".", "Config", ",", "fs", "fs", ".", "FileSystem", ",", "scripts", "build", ".", "ScriptsHandler", ",", "overrides", "build", ".", "Overrides", ")", "(", "*", "Layered", ",", "error", ")", "{", "excludePattern", ",", "err", ":=", "regexp", ".", "Compile", "(", "config", ".", "ExcludeRegExp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "d", ":=", "docker", ".", "New", "(", "client", ",", "config", ".", "PullAuthentication", ")", "\n", "tarHandler", ":=", "tar", ".", "New", "(", "fs", ")", "\n", "tarHandler", ".", "SetExclusionPattern", "(", "excludePattern", ")", "\n\n", "return", "&", "Layered", "{", "docker", ":", "d", ",", "config", ":", "config", ",", "fs", ":", "fs", ",", "tar", ":", "tarHandler", ",", "scripts", ":", "scripts", ",", "}", ",", "nil", "\n", "}" ]
// New creates a Layered builder.
[ "New", "creates", "a", "Layered", "builder", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/layered/layered.go#L45-L62
train
openshift/source-to-image
pkg/build/strategies/layered/layered.go
getDestination
func getDestination(config *api.Config) string { destination := config.Destination if len(destination) == 0 { destination = defaultDestination } return destination }
go
func getDestination(config *api.Config) string { destination := config.Destination if len(destination) == 0 { destination = defaultDestination } return destination }
[ "func", "getDestination", "(", "config", "*", "api", ".", "Config", ")", "string", "{", "destination", ":=", "config", ".", "Destination", "\n", "if", "len", "(", "destination", ")", "==", "0", "{", "destination", "=", "defaultDestination", "\n", "}", "\n", "return", "destination", "\n", "}" ]
// getDestination returns the destination directory from the config.
[ "getDestination", "returns", "the", "destination", "directory", "from", "the", "config", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/layered/layered.go#L65-L71
train
openshift/source-to-image
pkg/build/strategies/layered/layered.go
checkValidDirWithContents
func checkValidDirWithContents(name string) bool { items, err := ioutil.ReadDir(name) if os.IsNotExist(err) { glog.Warningf("Unable to access directory %q: %v", name, err) } return !(err != nil || len(items) == 0) }
go
func checkValidDirWithContents(name string) bool { items, err := ioutil.ReadDir(name) if os.IsNotExist(err) { glog.Warningf("Unable to access directory %q: %v", name, err) } return !(err != nil || len(items) == 0) }
[ "func", "checkValidDirWithContents", "(", "name", "string", ")", "bool", "{", "items", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "name", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "glog", ".", "Warningf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "return", "!", "(", "err", "!=", "nil", "||", "len", "(", "items", ")", "==", "0", ")", "\n", "}" ]
// checkValidDirWithContents returns true if the parameter provided is a valid, // accessible and non-empty directory.
[ "checkValidDirWithContents", "returns", "true", "if", "the", "parameter", "provided", "is", "a", "valid", "accessible", "and", "non", "-", "empty", "directory", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/layered/layered.go#L75-L81
train
openshift/source-to-image
pkg/scripts/install.go
Get
func (s *URLScriptHandler) Get(script string) *api.InstallResult { if len(s.URL) == 0 { return nil } scriptURL, err := url.ParseRequestURI(s.URL + "/" + script) if err != nil { glog.Infof("invalid script url %q: %v", s.URL, err) return nil } return &api.InstallResult{ Script: script, URL: scriptURL.String(), } }
go
func (s *URLScriptHandler) Get(script string) *api.InstallResult { if len(s.URL) == 0 { return nil } scriptURL, err := url.ParseRequestURI(s.URL + "/" + script) if err != nil { glog.Infof("invalid script url %q: %v", s.URL, err) return nil } return &api.InstallResult{ Script: script, URL: scriptURL.String(), } }
[ "func", "(", "s", "*", "URLScriptHandler", ")", "Get", "(", "script", "string", ")", "*", "api", ".", "InstallResult", "{", "if", "len", "(", "s", ".", "URL", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "scriptURL", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "s", ".", "URL", "+", "\"", "\"", "+", "script", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Infof", "(", "\"", "\"", ",", "s", ".", "URL", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "&", "api", ".", "InstallResult", "{", "Script", ":", "script", ",", "URL", ":", "scriptURL", ".", "String", "(", ")", ",", "}", "\n", "}" ]
// Get parses the provided URL and the script name.
[ "Get", "parses", "the", "provided", "URL", "and", "the", "script", "name", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/install.go#L73-L86
train
openshift/source-to-image
pkg/scripts/install.go
Install
func (s *URLScriptHandler) Install(r *api.InstallResult) error { downloadURL, err := url.Parse(r.URL) if err != nil { return err } dst := filepath.Join(s.DestinationDir, constants.UploadScripts, r.Script) if _, err := s.Download.Download(downloadURL, dst); err != nil { if e, ok := err.(s2ierr.Error); ok { if e.ErrorCode == s2ierr.ScriptsInsideImageError { r.Installed = true return nil } } return err } if err := s.FS.Chmod(dst, 0755); err != nil { return err } r.Installed = true r.Downloaded = true return nil }
go
func (s *URLScriptHandler) Install(r *api.InstallResult) error { downloadURL, err := url.Parse(r.URL) if err != nil { return err } dst := filepath.Join(s.DestinationDir, constants.UploadScripts, r.Script) if _, err := s.Download.Download(downloadURL, dst); err != nil { if e, ok := err.(s2ierr.Error); ok { if e.ErrorCode == s2ierr.ScriptsInsideImageError { r.Installed = true return nil } } return err } if err := s.FS.Chmod(dst, 0755); err != nil { return err } r.Installed = true r.Downloaded = true return nil }
[ "func", "(", "s", "*", "URLScriptHandler", ")", "Install", "(", "r", "*", "api", ".", "InstallResult", ")", "error", "{", "downloadURL", ",", "err", ":=", "url", ".", "Parse", "(", "r", ".", "URL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "dst", ":=", "filepath", ".", "Join", "(", "s", ".", "DestinationDir", ",", "constants", ".", "UploadScripts", ",", "r", ".", "Script", ")", "\n", "if", "_", ",", "err", ":=", "s", ".", "Download", ".", "Download", "(", "downloadURL", ",", "dst", ")", ";", "err", "!=", "nil", "{", "if", "e", ",", "ok", ":=", "err", ".", "(", "s2ierr", ".", "Error", ")", ";", "ok", "{", "if", "e", ".", "ErrorCode", "==", "s2ierr", ".", "ScriptsInsideImageError", "{", "r", ".", "Installed", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "if", "err", ":=", "s", ".", "FS", ".", "Chmod", "(", "dst", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "r", ".", "Installed", "=", "true", "\n", "r", ".", "Downloaded", "=", "true", "\n", "return", "nil", "\n", "}" ]
// Install downloads the script and fix its permissions.
[ "Install", "downloads", "the", "script", "and", "fix", "its", "permissions", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/install.go#L89-L110
train
openshift/source-to-image
pkg/scripts/install.go
Get
func (s *SourceScriptHandler) Get(script string) *api.InstallResult { location := filepath.Join(s.DestinationDir, constants.SourceScripts, script) if s.fs.Exists(location) { return &api.InstallResult{Script: script, URL: location} } // TODO: The '.sti/bin' path inside the source code directory is deprecated // and this should (and will) be removed soon. location = filepath.FromSlash(strings.Replace(filepath.ToSlash(location), "s2i/bin", "sti/bin", 1)) if s.fs.Exists(location) { glog.Info("DEPRECATED: Use .s2i/bin instead of .sti/bin") return &api.InstallResult{Script: script, URL: location} } return nil }
go
func (s *SourceScriptHandler) Get(script string) *api.InstallResult { location := filepath.Join(s.DestinationDir, constants.SourceScripts, script) if s.fs.Exists(location) { return &api.InstallResult{Script: script, URL: location} } // TODO: The '.sti/bin' path inside the source code directory is deprecated // and this should (and will) be removed soon. location = filepath.FromSlash(strings.Replace(filepath.ToSlash(location), "s2i/bin", "sti/bin", 1)) if s.fs.Exists(location) { glog.Info("DEPRECATED: Use .s2i/bin instead of .sti/bin") return &api.InstallResult{Script: script, URL: location} } return nil }
[ "func", "(", "s", "*", "SourceScriptHandler", ")", "Get", "(", "script", "string", ")", "*", "api", ".", "InstallResult", "{", "location", ":=", "filepath", ".", "Join", "(", "s", ".", "DestinationDir", ",", "constants", ".", "SourceScripts", ",", "script", ")", "\n", "if", "s", ".", "fs", ".", "Exists", "(", "location", ")", "{", "return", "&", "api", ".", "InstallResult", "{", "Script", ":", "script", ",", "URL", ":", "location", "}", "\n", "}", "\n", "// TODO: The '.sti/bin' path inside the source code directory is deprecated", "// and this should (and will) be removed soon.", "location", "=", "filepath", ".", "FromSlash", "(", "strings", ".", "Replace", "(", "filepath", ".", "ToSlash", "(", "location", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "1", ")", ")", "\n", "if", "s", ".", "fs", ".", "Exists", "(", "location", ")", "{", "glog", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "&", "api", ".", "InstallResult", "{", "Script", ":", "script", ",", "URL", ":", "location", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Get verifies if the script is present in the source directory and get the // installation result.
[ "Get", "verifies", "if", "the", "script", "is", "present", "in", "the", "source", "directory", "and", "get", "the", "installation", "result", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/install.go#L121-L134
train
openshift/source-to-image
pkg/scripts/install.go
Install
func (s *SourceScriptHandler) Install(r *api.InstallResult) error { dst := filepath.Join(s.DestinationDir, constants.UploadScripts, r.Script) if err := s.fs.Rename(r.URL, dst); err != nil { return err } if err := s.fs.Chmod(dst, 0755); err != nil { return err } // Make the path to scripts nicer in logs parts := strings.Split(filepath.ToSlash(r.URL), "/") if len(parts) > 3 { r.URL = filepath.FromSlash(sourcesRootAbbrev + "/" + strings.Join(parts[len(parts)-3:], "/")) } r.Installed = true r.Downloaded = true return nil }
go
func (s *SourceScriptHandler) Install(r *api.InstallResult) error { dst := filepath.Join(s.DestinationDir, constants.UploadScripts, r.Script) if err := s.fs.Rename(r.URL, dst); err != nil { return err } if err := s.fs.Chmod(dst, 0755); err != nil { return err } // Make the path to scripts nicer in logs parts := strings.Split(filepath.ToSlash(r.URL), "/") if len(parts) > 3 { r.URL = filepath.FromSlash(sourcesRootAbbrev + "/" + strings.Join(parts[len(parts)-3:], "/")) } r.Installed = true r.Downloaded = true return nil }
[ "func", "(", "s", "*", "SourceScriptHandler", ")", "Install", "(", "r", "*", "api", ".", "InstallResult", ")", "error", "{", "dst", ":=", "filepath", ".", "Join", "(", "s", ".", "DestinationDir", ",", "constants", ".", "UploadScripts", ",", "r", ".", "Script", ")", "\n", "if", "err", ":=", "s", ".", "fs", ".", "Rename", "(", "r", ".", "URL", ",", "dst", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "s", ".", "fs", ".", "Chmod", "(", "dst", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Make the path to scripts nicer in logs", "parts", ":=", "strings", ".", "Split", "(", "filepath", ".", "ToSlash", "(", "r", ".", "URL", ")", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", ">", "3", "{", "r", ".", "URL", "=", "filepath", ".", "FromSlash", "(", "sourcesRootAbbrev", "+", "\"", "\"", "+", "strings", ".", "Join", "(", "parts", "[", "len", "(", "parts", ")", "-", "3", ":", "]", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "r", ".", "Installed", "=", "true", "\n", "r", ".", "Downloaded", "=", "true", "\n", "return", "nil", "\n", "}" ]
// Install copies the script into upload directory and fix its permissions.
[ "Install", "copies", "the", "script", "into", "upload", "directory", "and", "fix", "its", "permissions", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/install.go#L142-L158
train
openshift/source-to-image
pkg/scripts/install.go
Add
func (m *DefaultScriptSourceManager) Add(s ScriptHandler) { if len(m.sources) == 0 { m.sources = []ScriptHandler{} } m.sources = append(m.sources, s) }
go
func (m *DefaultScriptSourceManager) Add(s ScriptHandler) { if len(m.sources) == 0 { m.sources = []ScriptHandler{} } m.sources = append(m.sources, s) }
[ "func", "(", "m", "*", "DefaultScriptSourceManager", ")", "Add", "(", "s", "ScriptHandler", ")", "{", "if", "len", "(", "m", ".", "sources", ")", "==", "0", "{", "m", ".", "sources", "=", "[", "]", "ScriptHandler", "{", "}", "\n", "}", "\n", "m", ".", "sources", "=", "append", "(", "m", ".", "sources", ",", "s", ")", "\n", "}" ]
// Add registers a new script source handler.
[ "Add", "registers", "a", "new", "script", "source", "handler", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/install.go#L186-L191
train
openshift/source-to-image
pkg/scripts/install.go
NewInstaller
func NewInstaller(image string, scriptsURL string, proxyConfig *api.ProxyConfig, docker docker.Docker, auth api.AuthConfig, fs fs.FileSystem) Installer { m := DefaultScriptSourceManager{ Image: image, ScriptsURL: scriptsURL, dockerAuth: auth, docker: docker, fs: fs, download: NewDownloader(proxyConfig), } // Order is important here, first we try to get the scripts from provided URL, // then we look into sources and check for .s2i/bin scripts. if len(m.ScriptsURL) > 0 { m.Add(&URLScriptHandler{URL: m.ScriptsURL, Download: m.download, FS: m.fs, Name: ScriptURLHandler}) } m.Add(&SourceScriptHandler{fs: m.fs}) if m.docker != nil { // If the detection handlers above fail, try to get the script url from the // docker image itself. defaultURL, err := m.docker.GetScriptsURL(m.Image) if err == nil && defaultURL != "" { m.Add(&URLScriptHandler{URL: defaultURL, Download: m.download, FS: m.fs, Name: ImageURLHandler}) } } return &m }
go
func NewInstaller(image string, scriptsURL string, proxyConfig *api.ProxyConfig, docker docker.Docker, auth api.AuthConfig, fs fs.FileSystem) Installer { m := DefaultScriptSourceManager{ Image: image, ScriptsURL: scriptsURL, dockerAuth: auth, docker: docker, fs: fs, download: NewDownloader(proxyConfig), } // Order is important here, first we try to get the scripts from provided URL, // then we look into sources and check for .s2i/bin scripts. if len(m.ScriptsURL) > 0 { m.Add(&URLScriptHandler{URL: m.ScriptsURL, Download: m.download, FS: m.fs, Name: ScriptURLHandler}) } m.Add(&SourceScriptHandler{fs: m.fs}) if m.docker != nil { // If the detection handlers above fail, try to get the script url from the // docker image itself. defaultURL, err := m.docker.GetScriptsURL(m.Image) if err == nil && defaultURL != "" { m.Add(&URLScriptHandler{URL: defaultURL, Download: m.download, FS: m.fs, Name: ImageURLHandler}) } } return &m }
[ "func", "NewInstaller", "(", "image", "string", ",", "scriptsURL", "string", ",", "proxyConfig", "*", "api", ".", "ProxyConfig", ",", "docker", "docker", ".", "Docker", ",", "auth", "api", ".", "AuthConfig", ",", "fs", "fs", ".", "FileSystem", ")", "Installer", "{", "m", ":=", "DefaultScriptSourceManager", "{", "Image", ":", "image", ",", "ScriptsURL", ":", "scriptsURL", ",", "dockerAuth", ":", "auth", ",", "docker", ":", "docker", ",", "fs", ":", "fs", ",", "download", ":", "NewDownloader", "(", "proxyConfig", ")", ",", "}", "\n", "// Order is important here, first we try to get the scripts from provided URL,", "// then we look into sources and check for .s2i/bin scripts.", "if", "len", "(", "m", ".", "ScriptsURL", ")", ">", "0", "{", "m", ".", "Add", "(", "&", "URLScriptHandler", "{", "URL", ":", "m", ".", "ScriptsURL", ",", "Download", ":", "m", ".", "download", ",", "FS", ":", "m", ".", "fs", ",", "Name", ":", "ScriptURLHandler", "}", ")", "\n", "}", "\n\n", "m", ".", "Add", "(", "&", "SourceScriptHandler", "{", "fs", ":", "m", ".", "fs", "}", ")", "\n\n", "if", "m", ".", "docker", "!=", "nil", "{", "// If the detection handlers above fail, try to get the script url from the", "// docker image itself.", "defaultURL", ",", "err", ":=", "m", ".", "docker", ".", "GetScriptsURL", "(", "m", ".", "Image", ")", "\n", "if", "err", "==", "nil", "&&", "defaultURL", "!=", "\"", "\"", "{", "m", ".", "Add", "(", "&", "URLScriptHandler", "{", "URL", ":", "defaultURL", ",", "Download", ":", "m", ".", "download", ",", "FS", ":", "m", ".", "fs", ",", "Name", ":", "ImageURLHandler", "}", ")", "\n", "}", "\n", "}", "\n", "return", "&", "m", "\n", "}" ]
// NewInstaller returns a new instance of the default Installer implementation
[ "NewInstaller", "returns", "a", "new", "instance", "of", "the", "default", "Installer", "implementation" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/install.go#L194-L220
train
openshift/source-to-image
pkg/scripts/install.go
InstallRequired
func (m *DefaultScriptSourceManager) InstallRequired(scripts []string, dstDir string) ([]api.InstallResult, error) { result := m.InstallOptional(scripts, dstDir) failedScripts := []string{} var err error for _, r := range result { if r.Error != nil { failedScripts = append(failedScripts, r.Script) } } if len(failedScripts) > 0 { err = s2ierr.NewInstallRequiredError(failedScripts, constants.ScriptsURLLabel) } return result, err }
go
func (m *DefaultScriptSourceManager) InstallRequired(scripts []string, dstDir string) ([]api.InstallResult, error) { result := m.InstallOptional(scripts, dstDir) failedScripts := []string{} var err error for _, r := range result { if r.Error != nil { failedScripts = append(failedScripts, r.Script) } } if len(failedScripts) > 0 { err = s2ierr.NewInstallRequiredError(failedScripts, constants.ScriptsURLLabel) } return result, err }
[ "func", "(", "m", "*", "DefaultScriptSourceManager", ")", "InstallRequired", "(", "scripts", "[", "]", "string", ",", "dstDir", "string", ")", "(", "[", "]", "api", ".", "InstallResult", ",", "error", ")", "{", "result", ":=", "m", ".", "InstallOptional", "(", "scripts", ",", "dstDir", ")", "\n", "failedScripts", ":=", "[", "]", "string", "{", "}", "\n", "var", "err", "error", "\n", "for", "_", ",", "r", ":=", "range", "result", "{", "if", "r", ".", "Error", "!=", "nil", "{", "failedScripts", "=", "append", "(", "failedScripts", ",", "r", ".", "Script", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "failedScripts", ")", ">", "0", "{", "err", "=", "s2ierr", ".", "NewInstallRequiredError", "(", "failedScripts", ",", "constants", ".", "ScriptsURLLabel", ")", "\n", "}", "\n", "return", "result", ",", "err", "\n", "}" ]
// InstallRequired Downloads and installs required scripts into dstDir, the result is a // map of scripts with detailed information about each of the scripts install process // with error if installing some of them failed
[ "InstallRequired", "Downloads", "and", "installs", "required", "scripts", "into", "dstDir", "the", "result", "is", "a", "map", "of", "scripts", "with", "detailed", "information", "about", "each", "of", "the", "scripts", "install", "process", "with", "error", "if", "installing", "some", "of", "them", "failed" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/install.go#L225-L238
train
openshift/source-to-image
pkg/scripts/install.go
InstallOptional
func (m *DefaultScriptSourceManager) InstallOptional(scripts []string, dstDir string) []api.InstallResult { result := []api.InstallResult{} for _, script := range scripts { installed := false failedSources := []string{} for _, e := range m.sources { detected := false h := e.(ScriptHandler) h.SetDestinationDir(dstDir) if r := h.Get(script); r != nil { if err := h.Install(r); err != nil { failedSources = append(failedSources, h.String()) // all this means is this source didn't have this particular script glog.V(4).Infof("script %q found by the %s, but failed to install: %v", script, h, err) } else { r.FailedSources = failedSources result = append(result, *r) installed = true detected = true glog.V(4).Infof("Using %q installed from %q", script, r.URL) } } if detected { break } } if !installed { result = append(result, api.InstallResult{ FailedSources: failedSources, Script: script, Error: fmt.Errorf("script %q not installed", script), }) } } return result }
go
func (m *DefaultScriptSourceManager) InstallOptional(scripts []string, dstDir string) []api.InstallResult { result := []api.InstallResult{} for _, script := range scripts { installed := false failedSources := []string{} for _, e := range m.sources { detected := false h := e.(ScriptHandler) h.SetDestinationDir(dstDir) if r := h.Get(script); r != nil { if err := h.Install(r); err != nil { failedSources = append(failedSources, h.String()) // all this means is this source didn't have this particular script glog.V(4).Infof("script %q found by the %s, but failed to install: %v", script, h, err) } else { r.FailedSources = failedSources result = append(result, *r) installed = true detected = true glog.V(4).Infof("Using %q installed from %q", script, r.URL) } } if detected { break } } if !installed { result = append(result, api.InstallResult{ FailedSources: failedSources, Script: script, Error: fmt.Errorf("script %q not installed", script), }) } } return result }
[ "func", "(", "m", "*", "DefaultScriptSourceManager", ")", "InstallOptional", "(", "scripts", "[", "]", "string", ",", "dstDir", "string", ")", "[", "]", "api", ".", "InstallResult", "{", "result", ":=", "[", "]", "api", ".", "InstallResult", "{", "}", "\n", "for", "_", ",", "script", ":=", "range", "scripts", "{", "installed", ":=", "false", "\n", "failedSources", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "e", ":=", "range", "m", ".", "sources", "{", "detected", ":=", "false", "\n", "h", ":=", "e", ".", "(", "ScriptHandler", ")", "\n", "h", ".", "SetDestinationDir", "(", "dstDir", ")", "\n", "if", "r", ":=", "h", ".", "Get", "(", "script", ")", ";", "r", "!=", "nil", "{", "if", "err", ":=", "h", ".", "Install", "(", "r", ")", ";", "err", "!=", "nil", "{", "failedSources", "=", "append", "(", "failedSources", ",", "h", ".", "String", "(", ")", ")", "\n", "// all this means is this source didn't have this particular script", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "script", ",", "h", ",", "err", ")", "\n", "}", "else", "{", "r", ".", "FailedSources", "=", "failedSources", "\n", "result", "=", "append", "(", "result", ",", "*", "r", ")", "\n", "installed", "=", "true", "\n", "detected", "=", "true", "\n", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "script", ",", "r", ".", "URL", ")", "\n", "}", "\n", "}", "\n", "if", "detected", "{", "break", "\n", "}", "\n", "}", "\n", "if", "!", "installed", "{", "result", "=", "append", "(", "result", ",", "api", ".", "InstallResult", "{", "FailedSources", ":", "failedSources", ",", "Script", ":", "script", ",", "Error", ":", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "script", ")", ",", "}", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// InstallOptional downloads and installs a set of scripts into dstDir, the result is a // map of scripts with detailed information about each of the scripts install process
[ "InstallOptional", "downloads", "and", "installs", "a", "set", "of", "scripts", "into", "dstDir", "the", "result", "is", "a", "map", "of", "scripts", "with", "detailed", "information", "about", "each", "of", "the", "scripts", "install", "process" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/install.go#L242-L277
train
openshift/source-to-image
pkg/scm/downloaders/git/clone.go
Download
func (c *Clone) Download(config *api.Config) (*git.SourceInfo, error) { targetSourceDir := filepath.Join(config.WorkingDir, constants.Source) config.WorkingSourceDir = targetSourceDir ref := config.Source.URL.Fragment if ref == "" { ref = "HEAD" } if len(config.ContextDir) > 0 { targetSourceDir = filepath.Join(config.WorkingDir, constants.ContextTmp) glog.V(1).Infof("Downloading %q (%q) ...", config.Source, config.ContextDir) } else { glog.V(1).Infof("Downloading %q ...", config.Source) } if !config.IgnoreSubmodules { glog.V(2).Infof("Cloning sources into %q", targetSourceDir) } else { glog.V(2).Infof("Cloning sources (ignoring submodules) into %q", targetSourceDir) } cloneConfig := git.CloneConfig{Quiet: true} err := c.Clone(config.Source, targetSourceDir, cloneConfig) if err != nil { glog.V(0).Infof("error: git clone failed: %v", err) return nil, err } err = c.Checkout(targetSourceDir, ref) if err != nil { return nil, err } glog.V(1).Infof("Checked out %q", ref) if !config.IgnoreSubmodules { err = c.SubmoduleUpdate(targetSourceDir, true, true) if err != nil { return nil, err } glog.V(1).Infof("Updated submodules for %q", ref) } // Record Git's knowledge about file permissions if runtime.GOOS == "windows" { filemodes, err := c.LsTree(filepath.Join(targetSourceDir, config.ContextDir), ref, true) if err != nil { return nil, err } for _, filemode := range filemodes { c.Chmod(filepath.Join(targetSourceDir, config.ContextDir, filemode.Name()), os.FileMode(filemode.Mode())&os.ModePerm) } } info := c.GetInfo(targetSourceDir) if len(config.ContextDir) > 0 { originalTargetDir := filepath.Join(config.WorkingDir, constants.Source) c.RemoveDirectory(originalTargetDir) path := filepath.Join(targetSourceDir, config.ContextDir) err := c.CopyContents(path, originalTargetDir) if err != nil { return nil, err } c.RemoveDirectory(targetSourceDir) } if len(config.ContextDir) > 0 { info.ContextDir = config.ContextDir } return info, nil }
go
func (c *Clone) Download(config *api.Config) (*git.SourceInfo, error) { targetSourceDir := filepath.Join(config.WorkingDir, constants.Source) config.WorkingSourceDir = targetSourceDir ref := config.Source.URL.Fragment if ref == "" { ref = "HEAD" } if len(config.ContextDir) > 0 { targetSourceDir = filepath.Join(config.WorkingDir, constants.ContextTmp) glog.V(1).Infof("Downloading %q (%q) ...", config.Source, config.ContextDir) } else { glog.V(1).Infof("Downloading %q ...", config.Source) } if !config.IgnoreSubmodules { glog.V(2).Infof("Cloning sources into %q", targetSourceDir) } else { glog.V(2).Infof("Cloning sources (ignoring submodules) into %q", targetSourceDir) } cloneConfig := git.CloneConfig{Quiet: true} err := c.Clone(config.Source, targetSourceDir, cloneConfig) if err != nil { glog.V(0).Infof("error: git clone failed: %v", err) return nil, err } err = c.Checkout(targetSourceDir, ref) if err != nil { return nil, err } glog.V(1).Infof("Checked out %q", ref) if !config.IgnoreSubmodules { err = c.SubmoduleUpdate(targetSourceDir, true, true) if err != nil { return nil, err } glog.V(1).Infof("Updated submodules for %q", ref) } // Record Git's knowledge about file permissions if runtime.GOOS == "windows" { filemodes, err := c.LsTree(filepath.Join(targetSourceDir, config.ContextDir), ref, true) if err != nil { return nil, err } for _, filemode := range filemodes { c.Chmod(filepath.Join(targetSourceDir, config.ContextDir, filemode.Name()), os.FileMode(filemode.Mode())&os.ModePerm) } } info := c.GetInfo(targetSourceDir) if len(config.ContextDir) > 0 { originalTargetDir := filepath.Join(config.WorkingDir, constants.Source) c.RemoveDirectory(originalTargetDir) path := filepath.Join(targetSourceDir, config.ContextDir) err := c.CopyContents(path, originalTargetDir) if err != nil { return nil, err } c.RemoveDirectory(targetSourceDir) } if len(config.ContextDir) > 0 { info.ContextDir = config.ContextDir } return info, nil }
[ "func", "(", "c", "*", "Clone", ")", "Download", "(", "config", "*", "api", ".", "Config", ")", "(", "*", "git", ".", "SourceInfo", ",", "error", ")", "{", "targetSourceDir", ":=", "filepath", ".", "Join", "(", "config", ".", "WorkingDir", ",", "constants", ".", "Source", ")", "\n", "config", ".", "WorkingSourceDir", "=", "targetSourceDir", "\n\n", "ref", ":=", "config", ".", "Source", ".", "URL", ".", "Fragment", "\n", "if", "ref", "==", "\"", "\"", "{", "ref", "=", "\"", "\"", "\n", "}", "\n\n", "if", "len", "(", "config", ".", "ContextDir", ")", ">", "0", "{", "targetSourceDir", "=", "filepath", ".", "Join", "(", "config", ".", "WorkingDir", ",", "constants", ".", "ContextTmp", ")", "\n", "glog", ".", "V", "(", "1", ")", ".", "Infof", "(", "\"", "\"", ",", "config", ".", "Source", ",", "config", ".", "ContextDir", ")", "\n", "}", "else", "{", "glog", ".", "V", "(", "1", ")", ".", "Infof", "(", "\"", "\"", ",", "config", ".", "Source", ")", "\n", "}", "\n\n", "if", "!", "config", ".", "IgnoreSubmodules", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "targetSourceDir", ")", "\n", "}", "else", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "targetSourceDir", ")", "\n", "}", "\n\n", "cloneConfig", ":=", "git", ".", "CloneConfig", "{", "Quiet", ":", "true", "}", "\n", "err", ":=", "c", ".", "Clone", "(", "config", ".", "Source", ",", "targetSourceDir", ",", "cloneConfig", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "V", "(", "0", ")", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "c", ".", "Checkout", "(", "targetSourceDir", ",", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "glog", ".", "V", "(", "1", ")", ".", "Infof", "(", "\"", "\"", ",", "ref", ")", "\n", "if", "!", "config", ".", "IgnoreSubmodules", "{", "err", "=", "c", ".", "SubmoduleUpdate", "(", "targetSourceDir", ",", "true", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "glog", ".", "V", "(", "1", ")", ".", "Infof", "(", "\"", "\"", ",", "ref", ")", "\n", "}", "\n\n", "// Record Git's knowledge about file permissions", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "filemodes", ",", "err", ":=", "c", ".", "LsTree", "(", "filepath", ".", "Join", "(", "targetSourceDir", ",", "config", ".", "ContextDir", ")", ",", "ref", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "filemode", ":=", "range", "filemodes", "{", "c", ".", "Chmod", "(", "filepath", ".", "Join", "(", "targetSourceDir", ",", "config", ".", "ContextDir", ",", "filemode", ".", "Name", "(", ")", ")", ",", "os", ".", "FileMode", "(", "filemode", ".", "Mode", "(", ")", ")", "&", "os", ".", "ModePerm", ")", "\n", "}", "\n", "}", "\n\n", "info", ":=", "c", ".", "GetInfo", "(", "targetSourceDir", ")", "\n", "if", "len", "(", "config", ".", "ContextDir", ")", ">", "0", "{", "originalTargetDir", ":=", "filepath", ".", "Join", "(", "config", ".", "WorkingDir", ",", "constants", ".", "Source", ")", "\n", "c", ".", "RemoveDirectory", "(", "originalTargetDir", ")", "\n", "path", ":=", "filepath", ".", "Join", "(", "targetSourceDir", ",", "config", ".", "ContextDir", ")", "\n", "err", ":=", "c", ".", "CopyContents", "(", "path", ",", "originalTargetDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ".", "RemoveDirectory", "(", "targetSourceDir", ")", "\n", "}", "\n\n", "if", "len", "(", "config", ".", "ContextDir", ")", ">", "0", "{", "info", ".", "ContextDir", "=", "config", ".", "ContextDir", "\n", "}", "\n\n", "return", "info", ",", "nil", "\n", "}" ]
// Download downloads the application source code from the Git repository // and checkout the Ref specified in the config.
[ "Download", "downloads", "the", "application", "source", "code", "from", "the", "Git", "repository", "and", "checkout", "the", "Ref", "specified", "in", "the", "config", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scm/downloaders/git/clone.go#L23-L93
train
openshift/source-to-image
pkg/build/strategies/strategies.go
Strategy
func Strategy(client docker.Client, config *api.Config, overrides build.Overrides) (build.Builder, api.BuildInfo, error) { var builder build.Builder var buildInfo api.BuildInfo var err error fileSystem := fs.NewFileSystem() startTime := time.Now() if len(config.AsDockerfile) != 0 { builder, err = dockerfile.New(config, fileSystem) if err != nil { buildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed, ) return nil, buildInfo, err } return builder, buildInfo, nil } dkr := docker.New(client, config.PullAuthentication) image, err := docker.GetBuilderImage(dkr, config) buildInfo.Stages = api.RecordStageAndStepInfo(buildInfo.Stages, api.StagePullImages, api.StepPullBuilderImage, startTime, time.Now()) if err != nil { buildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonPullBuilderImageFailed, utilstatus.ReasonMessagePullBuilderImageFailed, ) return nil, buildInfo, err } config.HasOnBuild = image.OnBuild if config.AssembleUser, err = docker.GetAssembleUser(dkr, config); err != nil { buildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonPullBuilderImageFailed, utilstatus.ReasonMessagePullBuilderImageFailed, ) return nil, buildInfo, err } // if we're blocking onbuild, just do a normal s2i build flow // which won't do a docker build and invoke the onbuild commands if image.OnBuild && !config.BlockOnBuild { builder, err = onbuild.New(client, config, fileSystem, overrides) if err != nil { buildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed, ) return nil, buildInfo, err } return builder, buildInfo, nil } builder, err = sti.New(client, config, fileSystem, overrides) if err != nil { buildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed, ) return nil, buildInfo, err } return builder, buildInfo, err }
go
func Strategy(client docker.Client, config *api.Config, overrides build.Overrides) (build.Builder, api.BuildInfo, error) { var builder build.Builder var buildInfo api.BuildInfo var err error fileSystem := fs.NewFileSystem() startTime := time.Now() if len(config.AsDockerfile) != 0 { builder, err = dockerfile.New(config, fileSystem) if err != nil { buildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed, ) return nil, buildInfo, err } return builder, buildInfo, nil } dkr := docker.New(client, config.PullAuthentication) image, err := docker.GetBuilderImage(dkr, config) buildInfo.Stages = api.RecordStageAndStepInfo(buildInfo.Stages, api.StagePullImages, api.StepPullBuilderImage, startTime, time.Now()) if err != nil { buildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonPullBuilderImageFailed, utilstatus.ReasonMessagePullBuilderImageFailed, ) return nil, buildInfo, err } config.HasOnBuild = image.OnBuild if config.AssembleUser, err = docker.GetAssembleUser(dkr, config); err != nil { buildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonPullBuilderImageFailed, utilstatus.ReasonMessagePullBuilderImageFailed, ) return nil, buildInfo, err } // if we're blocking onbuild, just do a normal s2i build flow // which won't do a docker build and invoke the onbuild commands if image.OnBuild && !config.BlockOnBuild { builder, err = onbuild.New(client, config, fileSystem, overrides) if err != nil { buildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed, ) return nil, buildInfo, err } return builder, buildInfo, nil } builder, err = sti.New(client, config, fileSystem, overrides) if err != nil { buildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed, ) return nil, buildInfo, err } return builder, buildInfo, err }
[ "func", "Strategy", "(", "client", "docker", ".", "Client", ",", "config", "*", "api", ".", "Config", ",", "overrides", "build", ".", "Overrides", ")", "(", "build", ".", "Builder", ",", "api", ".", "BuildInfo", ",", "error", ")", "{", "var", "builder", "build", ".", "Builder", "\n", "var", "buildInfo", "api", ".", "BuildInfo", "\n", "var", "err", "error", "\n\n", "fileSystem", ":=", "fs", ".", "NewFileSystem", "(", ")", "\n\n", "startTime", ":=", "time", ".", "Now", "(", ")", "\n\n", "if", "len", "(", "config", ".", "AsDockerfile", ")", "!=", "0", "{", "builder", ",", "err", "=", "dockerfile", ".", "New", "(", "config", ",", "fileSystem", ")", "\n", "if", "err", "!=", "nil", "{", "buildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "utilstatus", ".", "ReasonGenericS2IBuildFailed", ",", "utilstatus", ".", "ReasonMessageGenericS2iBuildFailed", ",", ")", "\n", "return", "nil", ",", "buildInfo", ",", "err", "\n", "}", "\n", "return", "builder", ",", "buildInfo", ",", "nil", "\n", "}", "\n\n", "dkr", ":=", "docker", ".", "New", "(", "client", ",", "config", ".", "PullAuthentication", ")", "\n", "image", ",", "err", ":=", "docker", ".", "GetBuilderImage", "(", "dkr", ",", "config", ")", "\n", "buildInfo", ".", "Stages", "=", "api", ".", "RecordStageAndStepInfo", "(", "buildInfo", ".", "Stages", ",", "api", ".", "StagePullImages", ",", "api", ".", "StepPullBuilderImage", ",", "startTime", ",", "time", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "buildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "utilstatus", ".", "ReasonPullBuilderImageFailed", ",", "utilstatus", ".", "ReasonMessagePullBuilderImageFailed", ",", ")", "\n", "return", "nil", ",", "buildInfo", ",", "err", "\n", "}", "\n", "config", ".", "HasOnBuild", "=", "image", ".", "OnBuild", "\n\n", "if", "config", ".", "AssembleUser", ",", "err", "=", "docker", ".", "GetAssembleUser", "(", "dkr", ",", "config", ")", ";", "err", "!=", "nil", "{", "buildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "utilstatus", ".", "ReasonPullBuilderImageFailed", ",", "utilstatus", ".", "ReasonMessagePullBuilderImageFailed", ",", ")", "\n", "return", "nil", ",", "buildInfo", ",", "err", "\n", "}", "\n\n", "// if we're blocking onbuild, just do a normal s2i build flow", "// which won't do a docker build and invoke the onbuild commands", "if", "image", ".", "OnBuild", "&&", "!", "config", ".", "BlockOnBuild", "{", "builder", ",", "err", "=", "onbuild", ".", "New", "(", "client", ",", "config", ",", "fileSystem", ",", "overrides", ")", "\n", "if", "err", "!=", "nil", "{", "buildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "utilstatus", ".", "ReasonGenericS2IBuildFailed", ",", "utilstatus", ".", "ReasonMessageGenericS2iBuildFailed", ",", ")", "\n", "return", "nil", ",", "buildInfo", ",", "err", "\n", "}", "\n", "return", "builder", ",", "buildInfo", ",", "nil", "\n", "}", "\n\n", "builder", ",", "err", "=", "sti", ".", "New", "(", "client", ",", "config", ",", "fileSystem", ",", "overrides", ")", "\n", "if", "err", "!=", "nil", "{", "buildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "utilstatus", ".", "ReasonGenericS2IBuildFailed", ",", "utilstatus", ".", "ReasonMessageGenericS2iBuildFailed", ",", ")", "\n", "return", "nil", ",", "buildInfo", ",", "err", "\n", "}", "\n", "return", "builder", ",", "buildInfo", ",", "err", "\n", "}" ]
// Strategy creates the appropriate build strategy for the provided config, using // the overrides provided. Not all strategies support all overrides.
[ "Strategy", "creates", "the", "appropriate", "build", "strategy", "for", "the", "provided", "config", "using", "the", "overrides", "provided", ".", "Not", "all", "strategies", "support", "all", "overrides", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/strategies.go#L24-L88
train
openshift/source-to-image
pkg/run/run.go
New
func New(client docker.Client, config *api.Config) *DockerRunner { d := docker.New(client, config.PullAuthentication) return &DockerRunner{d} }
go
func New(client docker.Client, config *api.Config) *DockerRunner { d := docker.New(client, config.PullAuthentication) return &DockerRunner{d} }
[ "func", "New", "(", "client", "docker", ".", "Client", ",", "config", "*", "api", ".", "Config", ")", "*", "DockerRunner", "{", "d", ":=", "docker", ".", "New", "(", "client", ",", "config", ".", "PullAuthentication", ")", "\n", "return", "&", "DockerRunner", "{", "d", "}", "\n", "}" ]
// New creates a DockerRunner for executing the methods associated with running // the produced image in a docker container for verification purposes.
[ "New", "creates", "a", "DockerRunner", "for", "executing", "the", "methods", "associated", "with", "running", "the", "produced", "image", "in", "a", "docker", "container", "for", "verification", "purposes", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/run/run.go#L26-L29
train
openshift/source-to-image
pkg/run/run.go
Run
func (b *DockerRunner) Run(config *api.Config) error { glog.V(4).Infof("Attempting to run image %s \n", config.Tag) outReader, outWriter := io.Pipe() errReader, errWriter := io.Pipe() opts := docker.RunContainerOptions{ Image: config.Tag, Stdout: outWriter, Stderr: errWriter, TargetImage: true, CGroupLimits: config.CGroupLimits, CapDrop: config.DropCapabilities, } docker.StreamContainerIO(errReader, nil, func(s string) { glog.Error(s) }) docker.StreamContainerIO(outReader, nil, func(s string) { glog.Info(s) }) err := b.ContainerClient.RunContainer(opts) // If we get a ContainerError, the original message reports the // container name. The container is temporary and its name is // meaningless, therefore we make the error message more helpful by // replacing the container name with the image tag. if e, ok := err.(s2ierr.ContainerError); ok { return s2ierr.NewContainerError(config.Tag, e.ErrorCode, e.Output) } return err }
go
func (b *DockerRunner) Run(config *api.Config) error { glog.V(4).Infof("Attempting to run image %s \n", config.Tag) outReader, outWriter := io.Pipe() errReader, errWriter := io.Pipe() opts := docker.RunContainerOptions{ Image: config.Tag, Stdout: outWriter, Stderr: errWriter, TargetImage: true, CGroupLimits: config.CGroupLimits, CapDrop: config.DropCapabilities, } docker.StreamContainerIO(errReader, nil, func(s string) { glog.Error(s) }) docker.StreamContainerIO(outReader, nil, func(s string) { glog.Info(s) }) err := b.ContainerClient.RunContainer(opts) // If we get a ContainerError, the original message reports the // container name. The container is temporary and its name is // meaningless, therefore we make the error message more helpful by // replacing the container name with the image tag. if e, ok := err.(s2ierr.ContainerError); ok { return s2ierr.NewContainerError(config.Tag, e.ErrorCode, e.Output) } return err }
[ "func", "(", "b", "*", "DockerRunner", ")", "Run", "(", "config", "*", "api", ".", "Config", ")", "error", "{", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\\n", "\"", ",", "config", ".", "Tag", ")", "\n\n", "outReader", ",", "outWriter", ":=", "io", ".", "Pipe", "(", ")", "\n", "errReader", ",", "errWriter", ":=", "io", ".", "Pipe", "(", ")", "\n\n", "opts", ":=", "docker", ".", "RunContainerOptions", "{", "Image", ":", "config", ".", "Tag", ",", "Stdout", ":", "outWriter", ",", "Stderr", ":", "errWriter", ",", "TargetImage", ":", "true", ",", "CGroupLimits", ":", "config", ".", "CGroupLimits", ",", "CapDrop", ":", "config", ".", "DropCapabilities", ",", "}", "\n\n", "docker", ".", "StreamContainerIO", "(", "errReader", ",", "nil", ",", "func", "(", "s", "string", ")", "{", "glog", ".", "Error", "(", "s", ")", "}", ")", "\n", "docker", ".", "StreamContainerIO", "(", "outReader", ",", "nil", ",", "func", "(", "s", "string", ")", "{", "glog", ".", "Info", "(", "s", ")", "}", ")", "\n\n", "err", ":=", "b", ".", "ContainerClient", ".", "RunContainer", "(", "opts", ")", "\n", "// If we get a ContainerError, the original message reports the", "// container name. The container is temporary and its name is", "// meaningless, therefore we make the error message more helpful by", "// replacing the container name with the image tag.", "if", "e", ",", "ok", ":=", "err", ".", "(", "s2ierr", ".", "ContainerError", ")", ";", "ok", "{", "return", "s2ierr", ".", "NewContainerError", "(", "config", ".", "Tag", ",", "e", ".", "ErrorCode", ",", "e", ".", "Output", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Run invokes the Docker API to run the image defined in config as a new // container. The container's stdout and stderr will be logged with glog.
[ "Run", "invokes", "the", "Docker", "API", "to", "run", "the", "image", "defined", "in", "config", "as", "a", "new", "container", ".", "The", "container", "s", "stdout", "and", "stderr", "will", "be", "logged", "with", "glog", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/run/run.go#L33-L60
train
openshift/source-to-image
pkg/build/strategies/sti/usage.go
NewUsage
func NewUsage(client docker.Client, config *api.Config) (*Usage, error) { b, err := New(client, config, fs.NewFileSystem(), build.Overrides{}) if err != nil { return nil, err } usage := Usage{ handler: b, config: config, garbage: b.garbage, } return &usage, nil }
go
func NewUsage(client docker.Client, config *api.Config) (*Usage, error) { b, err := New(client, config, fs.NewFileSystem(), build.Overrides{}) if err != nil { return nil, err } usage := Usage{ handler: b, config: config, garbage: b.garbage, } return &usage, nil }
[ "func", "NewUsage", "(", "client", "docker", ".", "Client", ",", "config", "*", "api", ".", "Config", ")", "(", "*", "Usage", ",", "error", ")", "{", "b", ",", "err", ":=", "New", "(", "client", ",", "config", ",", "fs", ".", "NewFileSystem", "(", ")", ",", "build", ".", "Overrides", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "usage", ":=", "Usage", "{", "handler", ":", "b", ",", "config", ":", "config", ",", "garbage", ":", "b", ".", "garbage", ",", "}", "\n", "return", "&", "usage", ",", "nil", "\n", "}" ]
// NewUsage creates a new instance of the default Usage implementation
[ "NewUsage", "creates", "a", "new", "instance", "of", "the", "default", "Usage", "implementation" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/usage.go#L26-L37
train
openshift/source-to-image
pkg/build/strategies/sti/usage.go
Show
func (u *Usage) Show() error { b := u.handler defer u.garbage.Cleanup(u.config) b.SetScripts([]string{constants.Usage}, []string{}) if err := b.Prepare(u.config); err != nil { return err } return b.Execute(constants.Usage, "", u.config) }
go
func (u *Usage) Show() error { b := u.handler defer u.garbage.Cleanup(u.config) b.SetScripts([]string{constants.Usage}, []string{}) if err := b.Prepare(u.config); err != nil { return err } return b.Execute(constants.Usage, "", u.config) }
[ "func", "(", "u", "*", "Usage", ")", "Show", "(", ")", "error", "{", "b", ":=", "u", ".", "handler", "\n", "defer", "u", ".", "garbage", ".", "Cleanup", "(", "u", ".", "config", ")", "\n\n", "b", ".", "SetScripts", "(", "[", "]", "string", "{", "constants", ".", "Usage", "}", ",", "[", "]", "string", "{", "}", ")", "\n\n", "if", "err", ":=", "b", ".", "Prepare", "(", "u", ".", "config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "b", ".", "Execute", "(", "constants", ".", "Usage", ",", "\"", "\"", ",", "u", ".", "config", ")", "\n", "}" ]
// Show starts the builder container and invokes the usage script on it // to print usage information for the script.
[ "Show", "starts", "the", "builder", "container", "and", "invokes", "the", "usage", "script", "on", "it", "to", "print", "usage", "information", "for", "the", "script", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/usage.go#L41-L52
train
openshift/source-to-image
pkg/build/strategies/onbuild/onbuild.go
New
func New(client docker.Client, config *api.Config, fs fs.FileSystem, overrides build.Overrides) (*OnBuild, error) { dockerHandler := docker.New(client, config.PullAuthentication) builder := &OnBuild{ docker: dockerHandler, git: git.New(fs, cmd.NewCommandRunner()), fs: fs, tar: tar.New(fs), } // Use STI Prepare() and download the 'run' script optionally. s, err := sti.New(client, config, fs, overrides) if err != nil { return nil, err } s.SetScripts([]string{}, []string{constants.Assemble, constants.Run}) downloader := overrides.Downloader if downloader == nil { downloader, err = scm.DownloaderForSource(builder.fs, config.Source, config.ForceCopy) if err != nil { return nil, err } } builder.source = onBuildSourceHandler{ Downloader: downloader, Preparer: s, Ignorer: &ignore.DockerIgnorer{}, } builder.garbage = build.NewDefaultCleaner(builder.fs, builder.docker) return builder, nil }
go
func New(client docker.Client, config *api.Config, fs fs.FileSystem, overrides build.Overrides) (*OnBuild, error) { dockerHandler := docker.New(client, config.PullAuthentication) builder := &OnBuild{ docker: dockerHandler, git: git.New(fs, cmd.NewCommandRunner()), fs: fs, tar: tar.New(fs), } // Use STI Prepare() and download the 'run' script optionally. s, err := sti.New(client, config, fs, overrides) if err != nil { return nil, err } s.SetScripts([]string{}, []string{constants.Assemble, constants.Run}) downloader := overrides.Downloader if downloader == nil { downloader, err = scm.DownloaderForSource(builder.fs, config.Source, config.ForceCopy) if err != nil { return nil, err } } builder.source = onBuildSourceHandler{ Downloader: downloader, Preparer: s, Ignorer: &ignore.DockerIgnorer{}, } builder.garbage = build.NewDefaultCleaner(builder.fs, builder.docker) return builder, nil }
[ "func", "New", "(", "client", "docker", ".", "Client", ",", "config", "*", "api", ".", "Config", ",", "fs", "fs", ".", "FileSystem", ",", "overrides", "build", ".", "Overrides", ")", "(", "*", "OnBuild", ",", "error", ")", "{", "dockerHandler", ":=", "docker", ".", "New", "(", "client", ",", "config", ".", "PullAuthentication", ")", "\n", "builder", ":=", "&", "OnBuild", "{", "docker", ":", "dockerHandler", ",", "git", ":", "git", ".", "New", "(", "fs", ",", "cmd", ".", "NewCommandRunner", "(", ")", ")", ",", "fs", ":", "fs", ",", "tar", ":", "tar", ".", "New", "(", "fs", ")", ",", "}", "\n", "// Use STI Prepare() and download the 'run' script optionally.", "s", ",", "err", ":=", "sti", ".", "New", "(", "client", ",", "config", ",", "fs", ",", "overrides", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "s", ".", "SetScripts", "(", "[", "]", "string", "{", "}", ",", "[", "]", "string", "{", "constants", ".", "Assemble", ",", "constants", ".", "Run", "}", ")", "\n\n", "downloader", ":=", "overrides", ".", "Downloader", "\n", "if", "downloader", "==", "nil", "{", "downloader", ",", "err", "=", "scm", ".", "DownloaderForSource", "(", "builder", ".", "fs", ",", "config", ".", "Source", ",", "config", ".", "ForceCopy", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "builder", ".", "source", "=", "onBuildSourceHandler", "{", "Downloader", ":", "downloader", ",", "Preparer", ":", "s", ",", "Ignorer", ":", "&", "ignore", ".", "DockerIgnorer", "{", "}", ",", "}", "\n\n", "builder", ".", "garbage", "=", "build", ".", "NewDefaultCleaner", "(", "builder", ".", "fs", ",", "builder", ".", "docker", ")", "\n", "return", "builder", ",", "nil", "\n", "}" ]
// New returns a new instance of OnBuild builder
[ "New", "returns", "a", "new", "instance", "of", "OnBuild", "builder" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/onbuild/onbuild.go#L43-L74
train
openshift/source-to-image
pkg/build/strategies/onbuild/onbuild.go
Build
func (builder *OnBuild) Build(config *api.Config) (*api.Result, error) { buildResult := &api.Result{} if config.BlockOnBuild { buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonOnBuildForbidden, utilstatus.ReasonMessageOnBuildForbidden, ) return buildResult, fmt.Errorf("builder image uses ONBUILD instructions but ONBUILD is not allowed") } glog.V(2).Info("Preparing the source code for build") // Change the installation directory for this config to store scripts inside // the application root directory. if err := builder.source.Prepare(config); err != nil { return buildResult, err } // If necessary, copy the STI scripts into application root directory builder.copySTIScripts(config) glog.V(2).Info("Creating application Dockerfile") if err := builder.CreateDockerfile(config); err != nil { buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonDockerfileCreateFailed, utilstatus.ReasonMessageDockerfileCreateFailed, ) return buildResult, err } glog.V(2).Info("Creating application source code image") tarStream := builder.tar.CreateTarStreamReader(filepath.Join(config.WorkingDir, "upload", "src"), false) defer tarStream.Close() outReader, outWriter := io.Pipe() go io.Copy(os.Stdout, outReader) opts := docker.BuildImageOptions{ Name: config.Tag, Stdin: tarStream, Stdout: outWriter, CGroupLimits: config.CGroupLimits, } glog.V(2).Info("Building the application source") if err := builder.docker.BuildImage(opts); err != nil { buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonDockerImageBuildFailed, utilstatus.ReasonMessageDockerImageBuildFailed, ) return buildResult, err } glog.V(2).Info("Cleaning up temporary containers") builder.garbage.Cleanup(config) var imageID string var err error if len(opts.Name) > 0 { if imageID, err = builder.docker.GetImageID(opts.Name); err != nil { buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed, ) return buildResult, err } } return &api.Result{ Success: true, WorkingDir: config.WorkingDir, ImageID: imageID, }, nil }
go
func (builder *OnBuild) Build(config *api.Config) (*api.Result, error) { buildResult := &api.Result{} if config.BlockOnBuild { buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonOnBuildForbidden, utilstatus.ReasonMessageOnBuildForbidden, ) return buildResult, fmt.Errorf("builder image uses ONBUILD instructions but ONBUILD is not allowed") } glog.V(2).Info("Preparing the source code for build") // Change the installation directory for this config to store scripts inside // the application root directory. if err := builder.source.Prepare(config); err != nil { return buildResult, err } // If necessary, copy the STI scripts into application root directory builder.copySTIScripts(config) glog.V(2).Info("Creating application Dockerfile") if err := builder.CreateDockerfile(config); err != nil { buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonDockerfileCreateFailed, utilstatus.ReasonMessageDockerfileCreateFailed, ) return buildResult, err } glog.V(2).Info("Creating application source code image") tarStream := builder.tar.CreateTarStreamReader(filepath.Join(config.WorkingDir, "upload", "src"), false) defer tarStream.Close() outReader, outWriter := io.Pipe() go io.Copy(os.Stdout, outReader) opts := docker.BuildImageOptions{ Name: config.Tag, Stdin: tarStream, Stdout: outWriter, CGroupLimits: config.CGroupLimits, } glog.V(2).Info("Building the application source") if err := builder.docker.BuildImage(opts); err != nil { buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonDockerImageBuildFailed, utilstatus.ReasonMessageDockerImageBuildFailed, ) return buildResult, err } glog.V(2).Info("Cleaning up temporary containers") builder.garbage.Cleanup(config) var imageID string var err error if len(opts.Name) > 0 { if imageID, err = builder.docker.GetImageID(opts.Name); err != nil { buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason( utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed, ) return buildResult, err } } return &api.Result{ Success: true, WorkingDir: config.WorkingDir, ImageID: imageID, }, nil }
[ "func", "(", "builder", "*", "OnBuild", ")", "Build", "(", "config", "*", "api", ".", "Config", ")", "(", "*", "api", ".", "Result", ",", "error", ")", "{", "buildResult", ":=", "&", "api", ".", "Result", "{", "}", "\n\n", "if", "config", ".", "BlockOnBuild", "{", "buildResult", ".", "BuildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "utilstatus", ".", "ReasonOnBuildForbidden", ",", "utilstatus", ".", "ReasonMessageOnBuildForbidden", ",", ")", "\n", "return", "buildResult", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "glog", ".", "V", "(", "2", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "// Change the installation directory for this config to store scripts inside", "// the application root directory.", "if", "err", ":=", "builder", ".", "source", ".", "Prepare", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "buildResult", ",", "err", "\n", "}", "\n\n", "// If necessary, copy the STI scripts into application root directory", "builder", ".", "copySTIScripts", "(", "config", ")", "\n\n", "glog", ".", "V", "(", "2", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "builder", ".", "CreateDockerfile", "(", "config", ")", ";", "err", "!=", "nil", "{", "buildResult", ".", "BuildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "utilstatus", ".", "ReasonDockerfileCreateFailed", ",", "utilstatus", ".", "ReasonMessageDockerfileCreateFailed", ",", ")", "\n", "return", "buildResult", ",", "err", "\n", "}", "\n\n", "glog", ".", "V", "(", "2", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "tarStream", ":=", "builder", ".", "tar", ".", "CreateTarStreamReader", "(", "filepath", ".", "Join", "(", "config", ".", "WorkingDir", ",", "\"", "\"", ",", "\"", "\"", ")", ",", "false", ")", "\n", "defer", "tarStream", ".", "Close", "(", ")", "\n\n", "outReader", ",", "outWriter", ":=", "io", ".", "Pipe", "(", ")", "\n", "go", "io", ".", "Copy", "(", "os", ".", "Stdout", ",", "outReader", ")", "\n\n", "opts", ":=", "docker", ".", "BuildImageOptions", "{", "Name", ":", "config", ".", "Tag", ",", "Stdin", ":", "tarStream", ",", "Stdout", ":", "outWriter", ",", "CGroupLimits", ":", "config", ".", "CGroupLimits", ",", "}", "\n\n", "glog", ".", "V", "(", "2", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "builder", ".", "docker", ".", "BuildImage", "(", "opts", ")", ";", "err", "!=", "nil", "{", "buildResult", ".", "BuildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "utilstatus", ".", "ReasonDockerImageBuildFailed", ",", "utilstatus", ".", "ReasonMessageDockerImageBuildFailed", ",", ")", "\n", "return", "buildResult", ",", "err", "\n", "}", "\n\n", "glog", ".", "V", "(", "2", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "builder", ".", "garbage", ".", "Cleanup", "(", "config", ")", "\n\n", "var", "imageID", "string", "\n", "var", "err", "error", "\n", "if", "len", "(", "opts", ".", "Name", ")", ">", "0", "{", "if", "imageID", ",", "err", "=", "builder", ".", "docker", ".", "GetImageID", "(", "opts", ".", "Name", ")", ";", "err", "!=", "nil", "{", "buildResult", ".", "BuildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "utilstatus", ".", "ReasonGenericS2IBuildFailed", ",", "utilstatus", ".", "ReasonMessageGenericS2iBuildFailed", ",", ")", "\n", "return", "buildResult", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "&", "api", ".", "Result", "{", "Success", ":", "true", ",", "WorkingDir", ":", "config", ".", "WorkingDir", ",", "ImageID", ":", "imageID", ",", "}", ",", "nil", "\n", "}" ]
// Build executes the ONBUILD kind of build
[ "Build", "executes", "the", "ONBUILD", "kind", "of", "build" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/onbuild/onbuild.go#L77-L149
train
openshift/source-to-image
pkg/build/strategies/onbuild/onbuild.go
CreateDockerfile
func (builder *OnBuild) CreateDockerfile(config *api.Config) error { buffer := bytes.Buffer{} uploadDir := filepath.Join(config.WorkingDir, "upload", "src") buffer.WriteString(fmt.Sprintf("FROM %s\n", config.BuilderImage)) entrypoint, err := GuessEntrypoint(builder.fs, uploadDir) if err != nil { return err } env, err := scripts.GetEnvironment(filepath.Join(config.WorkingDir, constants.Source)) if err != nil { glog.V(1).Infof("Environment: %v", err) } else { buffer.WriteString(scripts.ConvertEnvironmentToDocker(env)) } // If there is an assemble script present, run it as part of the build process // as the last thing. if builder.hasAssembleScript(config) { buffer.WriteString("RUN sh assemble\n") } // FIXME: This assumes that the WORKDIR is set to the application source root // directory. buffer.WriteString(fmt.Sprintf(`ENTRYPOINT ["./%s"]`+"\n", entrypoint)) return builder.fs.WriteFile(filepath.Join(uploadDir, "Dockerfile"), buffer.Bytes()) }
go
func (builder *OnBuild) CreateDockerfile(config *api.Config) error { buffer := bytes.Buffer{} uploadDir := filepath.Join(config.WorkingDir, "upload", "src") buffer.WriteString(fmt.Sprintf("FROM %s\n", config.BuilderImage)) entrypoint, err := GuessEntrypoint(builder.fs, uploadDir) if err != nil { return err } env, err := scripts.GetEnvironment(filepath.Join(config.WorkingDir, constants.Source)) if err != nil { glog.V(1).Infof("Environment: %v", err) } else { buffer.WriteString(scripts.ConvertEnvironmentToDocker(env)) } // If there is an assemble script present, run it as part of the build process // as the last thing. if builder.hasAssembleScript(config) { buffer.WriteString("RUN sh assemble\n") } // FIXME: This assumes that the WORKDIR is set to the application source root // directory. buffer.WriteString(fmt.Sprintf(`ENTRYPOINT ["./%s"]`+"\n", entrypoint)) return builder.fs.WriteFile(filepath.Join(uploadDir, "Dockerfile"), buffer.Bytes()) }
[ "func", "(", "builder", "*", "OnBuild", ")", "CreateDockerfile", "(", "config", "*", "api", ".", "Config", ")", "error", "{", "buffer", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "uploadDir", ":=", "filepath", ".", "Join", "(", "config", ".", "WorkingDir", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "config", ".", "BuilderImage", ")", ")", "\n", "entrypoint", ",", "err", ":=", "GuessEntrypoint", "(", "builder", ".", "fs", ",", "uploadDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "env", ",", "err", ":=", "scripts", ".", "GetEnvironment", "(", "filepath", ".", "Join", "(", "config", ".", "WorkingDir", ",", "constants", ".", "Source", ")", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "V", "(", "1", ")", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "buffer", ".", "WriteString", "(", "scripts", ".", "ConvertEnvironmentToDocker", "(", "env", ")", ")", "\n", "}", "\n", "// If there is an assemble script present, run it as part of the build process", "// as the last thing.", "if", "builder", ".", "hasAssembleScript", "(", "config", ")", "{", "buffer", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "// FIXME: This assumes that the WORKDIR is set to the application source root", "// directory.", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "`ENTRYPOINT [\"./%s\"]`", "+", "\"", "\\n", "\"", ",", "entrypoint", ")", ")", "\n", "return", "builder", ".", "fs", ".", "WriteFile", "(", "filepath", ".", "Join", "(", "uploadDir", ",", "\"", "\"", ")", ",", "buffer", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// CreateDockerfile creates the ONBUILD Dockerfile
[ "CreateDockerfile", "creates", "the", "ONBUILD", "Dockerfile" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/onbuild/onbuild.go#L152-L175
train
openshift/source-to-image
pkg/build/strategies/onbuild/onbuild.go
hasAssembleScript
func (builder *OnBuild) hasAssembleScript(config *api.Config) bool { assemblePath := filepath.Join(config.WorkingDir, "upload", "src", constants.Assemble) _, err := builder.fs.Stat(assemblePath) return err == nil }
go
func (builder *OnBuild) hasAssembleScript(config *api.Config) bool { assemblePath := filepath.Join(config.WorkingDir, "upload", "src", constants.Assemble) _, err := builder.fs.Stat(assemblePath) return err == nil }
[ "func", "(", "builder", "*", "OnBuild", ")", "hasAssembleScript", "(", "config", "*", "api", ".", "Config", ")", "bool", "{", "assemblePath", ":=", "filepath", ".", "Join", "(", "config", ".", "WorkingDir", ",", "\"", "\"", ",", "\"", "\"", ",", "constants", ".", "Assemble", ")", "\n", "_", ",", "err", ":=", "builder", ".", "fs", ".", "Stat", "(", "assemblePath", ")", "\n", "return", "err", "==", "nil", "\n", "}" ]
// hasAssembleScript checks if the the assemble script is available
[ "hasAssembleScript", "checks", "if", "the", "the", "assemble", "script", "is", "available" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/onbuild/onbuild.go#L191-L195
train
openshift/source-to-image
pkg/cmd/cli/cmd/usage.go
NewCmdUsage
func NewCmdUsage(cfg *api.Config) *cobra.Command { oldScriptsFlag := "" oldDestination := "" usageCmd := &cobra.Command{ Use: "usage <image>", Short: "Print usage of the assemble script associated with the image", Long: "Create and start a container from the image and invoke its usage script.", Run: func(cmd *cobra.Command, args []string) { if len(args) == 0 { cmd.Help() return } cfg.Usage = true cfg.BuilderImage = args[0] if len(oldScriptsFlag) != 0 { glog.Warning("DEPRECATED: Flag --scripts is deprecated, use --scripts-url instead") cfg.ScriptsURL = oldScriptsFlag } if len(cfg.BuilderPullPolicy) == 0 { cfg.BuilderPullPolicy = api.DefaultBuilderPullPolicy } if len(cfg.PreviousImagePullPolicy) == 0 { cfg.PreviousImagePullPolicy = api.DefaultPreviousImagePullPolicy } client, err := docker.NewEngineAPIClient(cfg.DockerConfig) s2ierr.CheckError(err) uh, err := sti.NewUsage(client, cfg) s2ierr.CheckError(err) err = uh.Show() s2ierr.CheckError(err) }, } usageCmd.Flags().StringVarP(&(oldDestination), "location", "l", "", "Specify a destination location for untar operation") cmdutil.AddCommonFlags(usageCmd, cfg) return usageCmd }
go
func NewCmdUsage(cfg *api.Config) *cobra.Command { oldScriptsFlag := "" oldDestination := "" usageCmd := &cobra.Command{ Use: "usage <image>", Short: "Print usage of the assemble script associated with the image", Long: "Create and start a container from the image and invoke its usage script.", Run: func(cmd *cobra.Command, args []string) { if len(args) == 0 { cmd.Help() return } cfg.Usage = true cfg.BuilderImage = args[0] if len(oldScriptsFlag) != 0 { glog.Warning("DEPRECATED: Flag --scripts is deprecated, use --scripts-url instead") cfg.ScriptsURL = oldScriptsFlag } if len(cfg.BuilderPullPolicy) == 0 { cfg.BuilderPullPolicy = api.DefaultBuilderPullPolicy } if len(cfg.PreviousImagePullPolicy) == 0 { cfg.PreviousImagePullPolicy = api.DefaultPreviousImagePullPolicy } client, err := docker.NewEngineAPIClient(cfg.DockerConfig) s2ierr.CheckError(err) uh, err := sti.NewUsage(client, cfg) s2ierr.CheckError(err) err = uh.Show() s2ierr.CheckError(err) }, } usageCmd.Flags().StringVarP(&(oldDestination), "location", "l", "", "Specify a destination location for untar operation") cmdutil.AddCommonFlags(usageCmd, cfg) return usageCmd }
[ "func", "NewCmdUsage", "(", "cfg", "*", "api", ".", "Config", ")", "*", "cobra", ".", "Command", "{", "oldScriptsFlag", ":=", "\"", "\"", "\n", "oldDestination", ":=", "\"", "\"", "\n\n", "usageCmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Long", ":", "\"", "\"", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "==", "0", "{", "cmd", ".", "Help", "(", ")", "\n", "return", "\n", "}", "\n\n", "cfg", ".", "Usage", "=", "true", "\n", "cfg", ".", "BuilderImage", "=", "args", "[", "0", "]", "\n\n", "if", "len", "(", "oldScriptsFlag", ")", "!=", "0", "{", "glog", ".", "Warning", "(", "\"", "\"", ")", "\n", "cfg", ".", "ScriptsURL", "=", "oldScriptsFlag", "\n", "}", "\n\n", "if", "len", "(", "cfg", ".", "BuilderPullPolicy", ")", "==", "0", "{", "cfg", ".", "BuilderPullPolicy", "=", "api", ".", "DefaultBuilderPullPolicy", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "PreviousImagePullPolicy", ")", "==", "0", "{", "cfg", ".", "PreviousImagePullPolicy", "=", "api", ".", "DefaultPreviousImagePullPolicy", "\n", "}", "\n\n", "client", ",", "err", ":=", "docker", ".", "NewEngineAPIClient", "(", "cfg", ".", "DockerConfig", ")", "\n", "s2ierr", ".", "CheckError", "(", "err", ")", "\n", "uh", ",", "err", ":=", "sti", ".", "NewUsage", "(", "client", ",", "cfg", ")", "\n", "s2ierr", ".", "CheckError", "(", "err", ")", "\n", "err", "=", "uh", ".", "Show", "(", ")", "\n", "s2ierr", ".", "CheckError", "(", "err", ")", "\n", "}", ",", "}", "\n", "usageCmd", ".", "Flags", "(", ")", ".", "StringVarP", "(", "&", "(", "oldDestination", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmdutil", ".", "AddCommonFlags", "(", "usageCmd", ",", "cfg", ")", "\n", "return", "usageCmd", "\n", "}" ]
// NewCmdUsage implements the S2I cli usage command.
[ "NewCmdUsage", "implements", "the", "S2I", "cli", "usage", "command", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/cmd/cli/cmd/usage.go#L14-L55
train
openshift/source-to-image
pkg/docker/docker.go
InspectImage
func (d stiDocker) InspectImage(name string) (*dockertypes.ImageInspect, error) { ctx, cancel := getDefaultContext() defer cancel() resp, _, err := d.client.ImageInspectWithRaw(ctx, name) if err != nil { return nil, err } return &resp, nil }
go
func (d stiDocker) InspectImage(name string) (*dockertypes.ImageInspect, error) { ctx, cancel := getDefaultContext() defer cancel() resp, _, err := d.client.ImageInspectWithRaw(ctx, name) if err != nil { return nil, err } return &resp, nil }
[ "func", "(", "d", "stiDocker", ")", "InspectImage", "(", "name", "string", ")", "(", "*", "dockertypes", ".", "ImageInspect", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "getDefaultContext", "(", ")", "\n", "defer", "cancel", "(", ")", "\n", "resp", ",", "_", ",", "err", ":=", "d", ".", "client", ".", "ImageInspectWithRaw", "(", "ctx", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "resp", ",", "nil", "\n", "}" ]
// InspectImage returns the image information and its raw representation.
[ "InspectImage", "returns", "the", "image", "information", "and", "its", "raw", "representation", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L145-L153
train
openshift/source-to-image
pkg/docker/docker.go
asDockerConfig
func (rco RunContainerOptions) asDockerConfig() dockercontainer.Config { return dockercontainer.Config{ Image: getImageName(rco.Image), User: rco.User, Env: rco.Env, Entrypoint: rco.Entrypoint, OpenStdin: rco.Stdin != nil, StdinOnce: rco.Stdin != nil, AttachStdout: rco.Stdout != nil, } }
go
func (rco RunContainerOptions) asDockerConfig() dockercontainer.Config { return dockercontainer.Config{ Image: getImageName(rco.Image), User: rco.User, Env: rco.Env, Entrypoint: rco.Entrypoint, OpenStdin: rco.Stdin != nil, StdinOnce: rco.Stdin != nil, AttachStdout: rco.Stdout != nil, } }
[ "func", "(", "rco", "RunContainerOptions", ")", "asDockerConfig", "(", ")", "dockercontainer", ".", "Config", "{", "return", "dockercontainer", ".", "Config", "{", "Image", ":", "getImageName", "(", "rco", ".", "Image", ")", ",", "User", ":", "rco", ".", "User", ",", "Env", ":", "rco", ".", "Env", ",", "Entrypoint", ":", "rco", ".", "Entrypoint", ",", "OpenStdin", ":", "rco", ".", "Stdin", "!=", "nil", ",", "StdinOnce", ":", "rco", ".", "Stdin", "!=", "nil", ",", "AttachStdout", ":", "rco", ".", "Stdout", "!=", "nil", ",", "}", "\n", "}" ]
// asDockerConfig converts a RunContainerOptions into a Config understood by the // docker client
[ "asDockerConfig", "converts", "a", "RunContainerOptions", "into", "a", "Config", "understood", "by", "the", "docker", "client" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L208-L218
train
openshift/source-to-image
pkg/docker/docker.go
asDockerHostConfig
func (rco RunContainerOptions) asDockerHostConfig() dockercontainer.HostConfig { hostConfig := dockercontainer.HostConfig{ CapDrop: rco.CapDrop, PublishAllPorts: rco.TargetImage, NetworkMode: dockercontainer.NetworkMode(rco.NetworkMode), Binds: rco.Binds, ExtraHosts: rco.AddHost, SecurityOpt: rco.SecurityOpt, } if rco.CGroupLimits != nil { hostConfig.Resources.Memory = rco.CGroupLimits.MemoryLimitBytes hostConfig.Resources.MemorySwap = rco.CGroupLimits.MemorySwap hostConfig.Resources.CgroupParent = rco.CGroupLimits.Parent } return hostConfig }
go
func (rco RunContainerOptions) asDockerHostConfig() dockercontainer.HostConfig { hostConfig := dockercontainer.HostConfig{ CapDrop: rco.CapDrop, PublishAllPorts: rco.TargetImage, NetworkMode: dockercontainer.NetworkMode(rco.NetworkMode), Binds: rco.Binds, ExtraHosts: rco.AddHost, SecurityOpt: rco.SecurityOpt, } if rco.CGroupLimits != nil { hostConfig.Resources.Memory = rco.CGroupLimits.MemoryLimitBytes hostConfig.Resources.MemorySwap = rco.CGroupLimits.MemorySwap hostConfig.Resources.CgroupParent = rco.CGroupLimits.Parent } return hostConfig }
[ "func", "(", "rco", "RunContainerOptions", ")", "asDockerHostConfig", "(", ")", "dockercontainer", ".", "HostConfig", "{", "hostConfig", ":=", "dockercontainer", ".", "HostConfig", "{", "CapDrop", ":", "rco", ".", "CapDrop", ",", "PublishAllPorts", ":", "rco", ".", "TargetImage", ",", "NetworkMode", ":", "dockercontainer", ".", "NetworkMode", "(", "rco", ".", "NetworkMode", ")", ",", "Binds", ":", "rco", ".", "Binds", ",", "ExtraHosts", ":", "rco", ".", "AddHost", ",", "SecurityOpt", ":", "rco", ".", "SecurityOpt", ",", "}", "\n", "if", "rco", ".", "CGroupLimits", "!=", "nil", "{", "hostConfig", ".", "Resources", ".", "Memory", "=", "rco", ".", "CGroupLimits", ".", "MemoryLimitBytes", "\n", "hostConfig", ".", "Resources", ".", "MemorySwap", "=", "rco", ".", "CGroupLimits", ".", "MemorySwap", "\n", "hostConfig", ".", "Resources", ".", "CgroupParent", "=", "rco", ".", "CGroupLimits", ".", "Parent", "\n", "}", "\n", "return", "hostConfig", "\n", "}" ]
// asDockerHostConfig converts a RunContainerOptions into a HostConfig // understood by the docker client
[ "asDockerHostConfig", "converts", "a", "RunContainerOptions", "into", "a", "HostConfig", "understood", "by", "the", "docker", "client" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L222-L237
train
openshift/source-to-image
pkg/docker/docker.go
asDockerCreateContainerOptions
func (rco RunContainerOptions) asDockerCreateContainerOptions() dockertypes.ContainerCreateConfig { config := rco.asDockerConfig() hostConfig := rco.asDockerHostConfig() return dockertypes.ContainerCreateConfig{ Name: containerName(rco.Image), Config: &config, HostConfig: &hostConfig, } }
go
func (rco RunContainerOptions) asDockerCreateContainerOptions() dockertypes.ContainerCreateConfig { config := rco.asDockerConfig() hostConfig := rco.asDockerHostConfig() return dockertypes.ContainerCreateConfig{ Name: containerName(rco.Image), Config: &config, HostConfig: &hostConfig, } }
[ "func", "(", "rco", "RunContainerOptions", ")", "asDockerCreateContainerOptions", "(", ")", "dockertypes", ".", "ContainerCreateConfig", "{", "config", ":=", "rco", ".", "asDockerConfig", "(", ")", "\n", "hostConfig", ":=", "rco", ".", "asDockerHostConfig", "(", ")", "\n", "return", "dockertypes", ".", "ContainerCreateConfig", "{", "Name", ":", "containerName", "(", "rco", ".", "Image", ")", ",", "Config", ":", "&", "config", ",", "HostConfig", ":", "&", "hostConfig", ",", "}", "\n", "}" ]
// asDockerCreateContainerOptions converts a RunContainerOptions into a // ContainerCreateConfig understood by the docker client
[ "asDockerCreateContainerOptions", "converts", "a", "RunContainerOptions", "into", "a", "ContainerCreateConfig", "understood", "by", "the", "docker", "client" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L241-L249
train
openshift/source-to-image
pkg/docker/docker.go
asDockerAttachToContainerOptions
func (rco RunContainerOptions) asDockerAttachToContainerOptions() dockertypes.ContainerAttachOptions { return dockertypes.ContainerAttachOptions{ Stdin: rco.Stdin != nil, Stdout: rco.Stdout != nil, Stderr: rco.Stderr != nil, Stream: rco.Stdout != nil, } }
go
func (rco RunContainerOptions) asDockerAttachToContainerOptions() dockertypes.ContainerAttachOptions { return dockertypes.ContainerAttachOptions{ Stdin: rco.Stdin != nil, Stdout: rco.Stdout != nil, Stderr: rco.Stderr != nil, Stream: rco.Stdout != nil, } }
[ "func", "(", "rco", "RunContainerOptions", ")", "asDockerAttachToContainerOptions", "(", ")", "dockertypes", ".", "ContainerAttachOptions", "{", "return", "dockertypes", ".", "ContainerAttachOptions", "{", "Stdin", ":", "rco", ".", "Stdin", "!=", "nil", ",", "Stdout", ":", "rco", ".", "Stdout", "!=", "nil", ",", "Stderr", ":", "rco", ".", "Stderr", "!=", "nil", ",", "Stream", ":", "rco", ".", "Stdout", "!=", "nil", ",", "}", "\n", "}" ]
// asDockerAttachToContainerOptions converts a RunContainerOptions into a // ContainerAttachOptions understood by the docker client
[ "asDockerAttachToContainerOptions", "converts", "a", "RunContainerOptions", "into", "a", "ContainerAttachOptions", "understood", "by", "the", "docker", "client" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L253-L260
train
openshift/source-to-image
pkg/docker/docker.go
NewEngineAPIClient
func NewEngineAPIClient(config *api.DockerConfig) (*dockerapi.Client, error) { var httpClient *http.Client if config.UseTLS || config.TLSVerify { tlscOptions := tlsconfig.Options{ InsecureSkipVerify: !config.TLSVerify, } if _, err := os.Stat(config.CAFile); !os.IsNotExist(err) { tlscOptions.CAFile = config.CAFile } if _, err := os.Stat(config.CertFile); !os.IsNotExist(err) { tlscOptions.CertFile = config.CertFile } if _, err := os.Stat(config.KeyFile); !os.IsNotExist(err) { tlscOptions.KeyFile = config.KeyFile } tlsc, err := tlsconfig.Client(tlscOptions) if err != nil { return nil, err } httpClient = &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsc, }, } } return dockerapi.NewClient(config.Endpoint, os.Getenv("DOCKER_API_VERSION"), httpClient, nil) }
go
func NewEngineAPIClient(config *api.DockerConfig) (*dockerapi.Client, error) { var httpClient *http.Client if config.UseTLS || config.TLSVerify { tlscOptions := tlsconfig.Options{ InsecureSkipVerify: !config.TLSVerify, } if _, err := os.Stat(config.CAFile); !os.IsNotExist(err) { tlscOptions.CAFile = config.CAFile } if _, err := os.Stat(config.CertFile); !os.IsNotExist(err) { tlscOptions.CertFile = config.CertFile } if _, err := os.Stat(config.KeyFile); !os.IsNotExist(err) { tlscOptions.KeyFile = config.KeyFile } tlsc, err := tlsconfig.Client(tlscOptions) if err != nil { return nil, err } httpClient = &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsc, }, } } return dockerapi.NewClient(config.Endpoint, os.Getenv("DOCKER_API_VERSION"), httpClient, nil) }
[ "func", "NewEngineAPIClient", "(", "config", "*", "api", ".", "DockerConfig", ")", "(", "*", "dockerapi", ".", "Client", ",", "error", ")", "{", "var", "httpClient", "*", "http", ".", "Client", "\n\n", "if", "config", ".", "UseTLS", "||", "config", ".", "TLSVerify", "{", "tlscOptions", ":=", "tlsconfig", ".", "Options", "{", "InsecureSkipVerify", ":", "!", "config", ".", "TLSVerify", ",", "}", "\n\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "config", ".", "CAFile", ")", ";", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "tlscOptions", ".", "CAFile", "=", "config", ".", "CAFile", "\n", "}", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "config", ".", "CertFile", ")", ";", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "tlscOptions", ".", "CertFile", "=", "config", ".", "CertFile", "\n", "}", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "config", ".", "KeyFile", ")", ";", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "tlscOptions", ".", "KeyFile", "=", "config", ".", "KeyFile", "\n", "}", "\n\n", "tlsc", ",", "err", ":=", "tlsconfig", ".", "Client", "(", "tlscOptions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "httpClient", "=", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "tlsc", ",", "}", ",", "}", "\n", "}", "\n", "return", "dockerapi", ".", "NewClient", "(", "config", ".", "Endpoint", ",", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "httpClient", ",", "nil", ")", "\n", "}" ]
// NewEngineAPIClient creates a new Docker engine API client
[ "NewEngineAPIClient", "creates", "a", "new", "Docker", "engine", "API", "client" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L282-L312
train
openshift/source-to-image
pkg/docker/docker.go
New
func New(client Client, auth api.AuthConfig) Docker { return &stiDocker{ client: client, pullAuth: dockertypes.AuthConfig{ Username: auth.Username, Password: auth.Password, Email: auth.Email, ServerAddress: auth.ServerAddress, }, } }
go
func New(client Client, auth api.AuthConfig) Docker { return &stiDocker{ client: client, pullAuth: dockertypes.AuthConfig{ Username: auth.Username, Password: auth.Password, Email: auth.Email, ServerAddress: auth.ServerAddress, }, } }
[ "func", "New", "(", "client", "Client", ",", "auth", "api", ".", "AuthConfig", ")", "Docker", "{", "return", "&", "stiDocker", "{", "client", ":", "client", ",", "pullAuth", ":", "dockertypes", ".", "AuthConfig", "{", "Username", ":", "auth", ".", "Username", ",", "Password", ":", "auth", ".", "Password", ",", "Email", ":", "auth", ".", "Email", ",", "ServerAddress", ":", "auth", ".", "ServerAddress", ",", "}", ",", "}", "\n", "}" ]
// New creates a new implementation of the STI Docker interface
[ "New", "creates", "a", "new", "implementation", "of", "the", "STI", "Docker", "interface" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L315-L325
train
openshift/source-to-image
pkg/docker/docker.go
GetImageEntrypoint
func (d *stiDocker) GetImageEntrypoint(name string) ([]string, error) { image, err := d.InspectImage(name) if err != nil { return nil, err } return image.Config.Entrypoint, nil }
go
func (d *stiDocker) GetImageEntrypoint(name string) ([]string, error) { image, err := d.InspectImage(name) if err != nil { return nil, err } return image.Config.Entrypoint, nil }
[ "func", "(", "d", "*", "stiDocker", ")", "GetImageEntrypoint", "(", "name", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "image", ",", "err", ":=", "d", ".", "InspectImage", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "image", ".", "Config", ".", "Entrypoint", ",", "nil", "\n", "}" ]
// GetImageEntrypoint returns the ENTRYPOINT property for the given image name.
[ "GetImageEntrypoint", "returns", "the", "ENTRYPOINT", "property", "for", "the", "given", "image", "name", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L352-L358
train
openshift/source-to-image
pkg/docker/docker.go
IsImageInLocalRegistry
func (d *stiDocker) IsImageInLocalRegistry(name string) (bool, error) { name = getImageName(name) resp, err := d.InspectImage(name) if resp != nil { return true, nil } if err != nil && !dockerapi.IsErrNotFound(err) { return false, s2ierr.NewInspectImageError(name, err) } return false, nil }
go
func (d *stiDocker) IsImageInLocalRegistry(name string) (bool, error) { name = getImageName(name) resp, err := d.InspectImage(name) if resp != nil { return true, nil } if err != nil && !dockerapi.IsErrNotFound(err) { return false, s2ierr.NewInspectImageError(name, err) } return false, nil }
[ "func", "(", "d", "*", "stiDocker", ")", "IsImageInLocalRegistry", "(", "name", "string", ")", "(", "bool", ",", "error", ")", "{", "name", "=", "getImageName", "(", "name", ")", "\n", "resp", ",", "err", ":=", "d", ".", "InspectImage", "(", "name", ")", "\n", "if", "resp", "!=", "nil", "{", "return", "true", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "&&", "!", "dockerapi", ".", "IsErrNotFound", "(", "err", ")", "{", "return", "false", ",", "s2ierr", ".", "NewInspectImageError", "(", "name", ",", "err", ")", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// IsImageInLocalRegistry determines whether the supplied image is in the local registry.
[ "IsImageInLocalRegistry", "determines", "whether", "the", "supplied", "image", "is", "in", "the", "local", "registry", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L412-L422
train
openshift/source-to-image
pkg/docker/docker.go
GetImageUser
func (d *stiDocker) GetImageUser(name string) (string, error) { name = getImageName(name) resp, err := d.InspectImage(name) if err != nil { glog.V(4).Infof("error inspecting image %s: %v", name, err) return "", s2ierr.NewInspectImageError(name, err) } user := resp.Config.User return user, nil }
go
func (d *stiDocker) GetImageUser(name string) (string, error) { name = getImageName(name) resp, err := d.InspectImage(name) if err != nil { glog.V(4).Infof("error inspecting image %s: %v", name, err) return "", s2ierr.NewInspectImageError(name, err) } user := resp.Config.User return user, nil }
[ "func", "(", "d", "*", "stiDocker", ")", "GetImageUser", "(", "name", "string", ")", "(", "string", ",", "error", ")", "{", "name", "=", "getImageName", "(", "name", ")", "\n", "resp", ",", "err", ":=", "d", ".", "InspectImage", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "return", "\"", "\"", ",", "s2ierr", ".", "NewInspectImageError", "(", "name", ",", "err", ")", "\n", "}", "\n", "user", ":=", "resp", ".", "Config", ".", "User", "\n", "return", "user", ",", "nil", "\n", "}" ]
// GetImageUser finds and retrieves the user associated with // an image if one has been specified
[ "GetImageUser", "finds", "and", "retrieves", "the", "user", "associated", "with", "an", "image", "if", "one", "has", "been", "specified" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L426-L435
train
openshift/source-to-image
pkg/docker/docker.go
Version
func (d *stiDocker) Version() (dockertypes.Version, error) { ctx, cancel := getDefaultContext() defer cancel() return d.client.ServerVersion(ctx) }
go
func (d *stiDocker) Version() (dockertypes.Version, error) { ctx, cancel := getDefaultContext() defer cancel() return d.client.ServerVersion(ctx) }
[ "func", "(", "d", "*", "stiDocker", ")", "Version", "(", ")", "(", "dockertypes", ".", "Version", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "getDefaultContext", "(", ")", "\n", "defer", "cancel", "(", ")", "\n", "return", "d", ".", "client", ".", "ServerVersion", "(", "ctx", ")", "\n", "}" ]
// Version returns information of the docker client and server host
[ "Version", "returns", "information", "of", "the", "docker", "client", "and", "server", "host" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L438-L442
train
openshift/source-to-image
pkg/docker/docker.go
IsImageOnBuild
func (d *stiDocker) IsImageOnBuild(name string) bool { onbuild, err := d.GetOnBuild(name) return err == nil && len(onbuild) > 0 }
go
func (d *stiDocker) IsImageOnBuild(name string) bool { onbuild, err := d.GetOnBuild(name) return err == nil && len(onbuild) > 0 }
[ "func", "(", "d", "*", "stiDocker", ")", "IsImageOnBuild", "(", "name", "string", ")", "bool", "{", "onbuild", ",", "err", ":=", "d", ".", "GetOnBuild", "(", "name", ")", "\n", "return", "err", "==", "nil", "&&", "len", "(", "onbuild", ")", ">", "0", "\n", "}" ]
// IsImageOnBuild provides information about whether the Docker image has // OnBuild instruction recorded in the Image Config.
[ "IsImageOnBuild", "provides", "information", "about", "whether", "the", "Docker", "image", "has", "OnBuild", "instruction", "recorded", "in", "the", "Image", "Config", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L446-L449
train
openshift/source-to-image
pkg/docker/docker.go
CheckAndPullImage
func (d *stiDocker) CheckAndPullImage(name string) (*api.Image, error) { name = getImageName(name) displayName := name if !glog.Is(3) { // For less verbose log levels (less than 3), shorten long iamge names like: // "centos/php-56-centos7@sha256:51c3e2b08bd9fadefccd6ec42288680d6d7f861bdbfbd2d8d24960621e4e27f5" // to include just enough characters to differentiate the build from others in the docker repository: // "centos/php-56-centos7@sha256:51c3e2b08bd..." // 18 characters is somewhat arbitrary, but should be enough to avoid a name collision. split := strings.Split(name, "@") if len(split) > 1 && len(split[1]) > 18 { displayName = split[0] + "@" + split[1][:18] + "..." } } image, err := d.CheckImage(name) if err != nil && !strings.Contains(err.(s2ierr.Error).Details.Error(), "No such image") { return nil, err } if image == nil { glog.V(1).Infof("Image %q not available locally, pulling ...", displayName) return d.PullImage(name) } glog.V(3).Infof("Using locally available image %q", displayName) return image, nil }
go
func (d *stiDocker) CheckAndPullImage(name string) (*api.Image, error) { name = getImageName(name) displayName := name if !glog.Is(3) { // For less verbose log levels (less than 3), shorten long iamge names like: // "centos/php-56-centos7@sha256:51c3e2b08bd9fadefccd6ec42288680d6d7f861bdbfbd2d8d24960621e4e27f5" // to include just enough characters to differentiate the build from others in the docker repository: // "centos/php-56-centos7@sha256:51c3e2b08bd..." // 18 characters is somewhat arbitrary, but should be enough to avoid a name collision. split := strings.Split(name, "@") if len(split) > 1 && len(split[1]) > 18 { displayName = split[0] + "@" + split[1][:18] + "..." } } image, err := d.CheckImage(name) if err != nil && !strings.Contains(err.(s2ierr.Error).Details.Error(), "No such image") { return nil, err } if image == nil { glog.V(1).Infof("Image %q not available locally, pulling ...", displayName) return d.PullImage(name) } glog.V(3).Infof("Using locally available image %q", displayName) return image, nil }
[ "func", "(", "d", "*", "stiDocker", ")", "CheckAndPullImage", "(", "name", "string", ")", "(", "*", "api", ".", "Image", ",", "error", ")", "{", "name", "=", "getImageName", "(", "name", ")", "\n", "displayName", ":=", "name", "\n\n", "if", "!", "glog", ".", "Is", "(", "3", ")", "{", "// For less verbose log levels (less than 3), shorten long iamge names like:", "// \"centos/php-56-centos7@sha256:51c3e2b08bd9fadefccd6ec42288680d6d7f861bdbfbd2d8d24960621e4e27f5\"", "// to include just enough characters to differentiate the build from others in the docker repository:", "// \"centos/php-56-centos7@sha256:51c3e2b08bd...\"", "// 18 characters is somewhat arbitrary, but should be enough to avoid a name collision.", "split", ":=", "strings", ".", "Split", "(", "name", ",", "\"", "\"", ")", "\n", "if", "len", "(", "split", ")", ">", "1", "&&", "len", "(", "split", "[", "1", "]", ")", ">", "18", "{", "displayName", "=", "split", "[", "0", "]", "+", "\"", "\"", "+", "split", "[", "1", "]", "[", ":", "18", "]", "+", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "image", ",", "err", ":=", "d", ".", "CheckImage", "(", "name", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "strings", ".", "Contains", "(", "err", ".", "(", "s2ierr", ".", "Error", ")", ".", "Details", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "image", "==", "nil", "{", "glog", ".", "V", "(", "1", ")", ".", "Infof", "(", "\"", "\"", ",", "displayName", ")", "\n", "return", "d", ".", "PullImage", "(", "name", ")", "\n", "}", "\n\n", "glog", ".", "V", "(", "3", ")", ".", "Infof", "(", "\"", "\"", ",", "displayName", ")", "\n", "return", "image", ",", "nil", "\n", "}" ]
// CheckAndPullImage pulls an image into the local registry if not present // and returns the image metadata
[ "CheckAndPullImage", "pulls", "an", "image", "into", "the", "local", "registry", "if", "not", "present", "and", "returns", "the", "image", "metadata" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L465-L492
train
openshift/source-to-image
pkg/docker/docker.go
CheckImage
func (d *stiDocker) CheckImage(name string) (*api.Image, error) { name = getImageName(name) inspect, err := d.InspectImage(name) if err != nil { glog.V(4).Infof("error inspecting image %s: %v", name, err) return nil, s2ierr.NewInspectImageError(name, err) } if inspect != nil { image := &api.Image{} updateImageWithInspect(image, inspect) return image, nil } return nil, nil }
go
func (d *stiDocker) CheckImage(name string) (*api.Image, error) { name = getImageName(name) inspect, err := d.InspectImage(name) if err != nil { glog.V(4).Infof("error inspecting image %s: %v", name, err) return nil, s2ierr.NewInspectImageError(name, err) } if inspect != nil { image := &api.Image{} updateImageWithInspect(image, inspect) return image, nil } return nil, nil }
[ "func", "(", "d", "*", "stiDocker", ")", "CheckImage", "(", "name", "string", ")", "(", "*", "api", ".", "Image", ",", "error", ")", "{", "name", "=", "getImageName", "(", "name", ")", "\n", "inspect", ",", "err", ":=", "d", ".", "InspectImage", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "return", "nil", ",", "s2ierr", ".", "NewInspectImageError", "(", "name", ",", "err", ")", "\n", "}", "\n", "if", "inspect", "!=", "nil", "{", "image", ":=", "&", "api", ".", "Image", "{", "}", "\n", "updateImageWithInspect", "(", "image", ",", "inspect", ")", "\n", "return", "image", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "nil", "\n", "}" ]
// CheckImage checks image from the local registry.
[ "CheckImage", "checks", "image", "from", "the", "local", "registry", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L495-L509
train
openshift/source-to-image
pkg/docker/docker.go
PullImage
func (d *stiDocker) PullImage(name string) (*api.Image, error) { name = getImageName(name) // RegistryAuth is the base64 encoded credentials for the registry base64Auth, err := base64EncodeAuth(d.pullAuth) if err != nil { return nil, s2ierr.NewPullImageError(name, err) } var retriableError = false for retries := 0; retries <= DefaultPullRetryCount; retries++ { err = util.TimeoutAfter(DefaultDockerTimeout, fmt.Sprintf("pulling image %q", name), func(timer *time.Timer) error { resp, pullErr := d.client.ImagePull(context.Background(), name, dockertypes.ImagePullOptions{RegistryAuth: base64Auth}) if pullErr != nil { return pullErr } defer resp.Close() decoder := json.NewDecoder(resp) for { if !timer.Stop() { return &util.TimeoutError{} } timer.Reset(DefaultDockerTimeout) var msg dockermessage.JSONMessage pullErr = decoder.Decode(&msg) if pullErr == io.EOF { return nil } if pullErr != nil { return pullErr } if msg.Error != nil { return msg.Error } if msg.Progress != nil { glog.V(4).Infof("pulling image %s: %s", name, msg.Progress.String()) } } }) if err == nil { break } glog.V(0).Infof("pulling image error : %v", err) errMsg := fmt.Sprintf("%s", err) for _, errorString := range RetriableErrors { if strings.Contains(errMsg, errorString) { retriableError = true break } } if !retriableError { return nil, s2ierr.NewPullImageError(name, err) } glog.V(0).Infof("retrying in %s ...", DefaultPullRetryDelay) time.Sleep(DefaultPullRetryDelay) } inspectResp, err := d.InspectImage(name) if err != nil { return nil, s2ierr.NewPullImageError(name, err) } if inspectResp != nil { image := &api.Image{} updateImageWithInspect(image, inspectResp) return image, nil } return nil, nil }
go
func (d *stiDocker) PullImage(name string) (*api.Image, error) { name = getImageName(name) // RegistryAuth is the base64 encoded credentials for the registry base64Auth, err := base64EncodeAuth(d.pullAuth) if err != nil { return nil, s2ierr.NewPullImageError(name, err) } var retriableError = false for retries := 0; retries <= DefaultPullRetryCount; retries++ { err = util.TimeoutAfter(DefaultDockerTimeout, fmt.Sprintf("pulling image %q", name), func(timer *time.Timer) error { resp, pullErr := d.client.ImagePull(context.Background(), name, dockertypes.ImagePullOptions{RegistryAuth: base64Auth}) if pullErr != nil { return pullErr } defer resp.Close() decoder := json.NewDecoder(resp) for { if !timer.Stop() { return &util.TimeoutError{} } timer.Reset(DefaultDockerTimeout) var msg dockermessage.JSONMessage pullErr = decoder.Decode(&msg) if pullErr == io.EOF { return nil } if pullErr != nil { return pullErr } if msg.Error != nil { return msg.Error } if msg.Progress != nil { glog.V(4).Infof("pulling image %s: %s", name, msg.Progress.String()) } } }) if err == nil { break } glog.V(0).Infof("pulling image error : %v", err) errMsg := fmt.Sprintf("%s", err) for _, errorString := range RetriableErrors { if strings.Contains(errMsg, errorString) { retriableError = true break } } if !retriableError { return nil, s2ierr.NewPullImageError(name, err) } glog.V(0).Infof("retrying in %s ...", DefaultPullRetryDelay) time.Sleep(DefaultPullRetryDelay) } inspectResp, err := d.InspectImage(name) if err != nil { return nil, s2ierr.NewPullImageError(name, err) } if inspectResp != nil { image := &api.Image{} updateImageWithInspect(image, inspectResp) return image, nil } return nil, nil }
[ "func", "(", "d", "*", "stiDocker", ")", "PullImage", "(", "name", "string", ")", "(", "*", "api", ".", "Image", ",", "error", ")", "{", "name", "=", "getImageName", "(", "name", ")", "\n\n", "// RegistryAuth is the base64 encoded credentials for the registry", "base64Auth", ",", "err", ":=", "base64EncodeAuth", "(", "d", ".", "pullAuth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "s2ierr", ".", "NewPullImageError", "(", "name", ",", "err", ")", "\n", "}", "\n", "var", "retriableError", "=", "false", "\n\n", "for", "retries", ":=", "0", ";", "retries", "<=", "DefaultPullRetryCount", ";", "retries", "++", "{", "err", "=", "util", ".", "TimeoutAfter", "(", "DefaultDockerTimeout", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ",", "func", "(", "timer", "*", "time", ".", "Timer", ")", "error", "{", "resp", ",", "pullErr", ":=", "d", ".", "client", ".", "ImagePull", "(", "context", ".", "Background", "(", ")", ",", "name", ",", "dockertypes", ".", "ImagePullOptions", "{", "RegistryAuth", ":", "base64Auth", "}", ")", "\n", "if", "pullErr", "!=", "nil", "{", "return", "pullErr", "\n", "}", "\n", "defer", "resp", ".", "Close", "(", ")", "\n\n", "decoder", ":=", "json", ".", "NewDecoder", "(", "resp", ")", "\n", "for", "{", "if", "!", "timer", ".", "Stop", "(", ")", "{", "return", "&", "util", ".", "TimeoutError", "{", "}", "\n", "}", "\n", "timer", ".", "Reset", "(", "DefaultDockerTimeout", ")", "\n\n", "var", "msg", "dockermessage", ".", "JSONMessage", "\n", "pullErr", "=", "decoder", ".", "Decode", "(", "&", "msg", ")", "\n", "if", "pullErr", "==", "io", ".", "EOF", "{", "return", "nil", "\n", "}", "\n", "if", "pullErr", "!=", "nil", "{", "return", "pullErr", "\n", "}", "\n\n", "if", "msg", ".", "Error", "!=", "nil", "{", "return", "msg", ".", "Error", "\n", "}", "\n", "if", "msg", ".", "Progress", "!=", "nil", "{", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "name", ",", "msg", ".", "Progress", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "glog", ".", "V", "(", "0", ")", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "errMsg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", "\n", "for", "_", ",", "errorString", ":=", "range", "RetriableErrors", "{", "if", "strings", ".", "Contains", "(", "errMsg", ",", "errorString", ")", "{", "retriableError", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "retriableError", "{", "return", "nil", ",", "s2ierr", ".", "NewPullImageError", "(", "name", ",", "err", ")", "\n", "}", "\n\n", "glog", ".", "V", "(", "0", ")", ".", "Infof", "(", "\"", "\"", ",", "DefaultPullRetryDelay", ")", "\n", "time", ".", "Sleep", "(", "DefaultPullRetryDelay", ")", "\n", "}", "\n\n", "inspectResp", ",", "err", ":=", "d", ".", "InspectImage", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "s2ierr", ".", "NewPullImageError", "(", "name", ",", "err", ")", "\n", "}", "\n", "if", "inspectResp", "!=", "nil", "{", "image", ":=", "&", "api", ".", "Image", "{", "}", "\n", "updateImageWithInspect", "(", "image", ",", "inspectResp", ")", "\n", "return", "image", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// PullImage pulls an image into the local registry
[ "PullImage", "pulls", "an", "image", "into", "the", "local", "registry" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L520-L592
train
openshift/source-to-image
pkg/docker/docker.go
RemoveContainer
func (d *stiDocker) RemoveContainer(id string) error { ctx, cancel := getDefaultContext() defer cancel() opts := dockertypes.ContainerRemoveOptions{ RemoveVolumes: true, } return d.client.ContainerRemove(ctx, id, opts) }
go
func (d *stiDocker) RemoveContainer(id string) error { ctx, cancel := getDefaultContext() defer cancel() opts := dockertypes.ContainerRemoveOptions{ RemoveVolumes: true, } return d.client.ContainerRemove(ctx, id, opts) }
[ "func", "(", "d", "*", "stiDocker", ")", "RemoveContainer", "(", "id", "string", ")", "error", "{", "ctx", ",", "cancel", ":=", "getDefaultContext", "(", ")", "\n", "defer", "cancel", "(", ")", "\n", "opts", ":=", "dockertypes", ".", "ContainerRemoveOptions", "{", "RemoveVolumes", ":", "true", ",", "}", "\n", "return", "d", ".", "client", ".", "ContainerRemove", "(", "ctx", ",", "id", ",", "opts", ")", "\n", "}" ]
// RemoveContainer removes a container and its associated volumes.
[ "RemoveContainer", "removes", "a", "container", "and", "its", "associated", "volumes", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L611-L618
train
openshift/source-to-image
pkg/docker/docker.go
KillContainer
func (d *stiDocker) KillContainer(id string) error { ctx, cancel := getDefaultContext() defer cancel() return d.client.ContainerKill(ctx, id, "SIGKILL") }
go
func (d *stiDocker) KillContainer(id string) error { ctx, cancel := getDefaultContext() defer cancel() return d.client.ContainerKill(ctx, id, "SIGKILL") }
[ "func", "(", "d", "*", "stiDocker", ")", "KillContainer", "(", "id", "string", ")", "error", "{", "ctx", ",", "cancel", ":=", "getDefaultContext", "(", ")", "\n", "defer", "cancel", "(", ")", "\n", "return", "d", ".", "client", ".", "ContainerKill", "(", "ctx", ",", "id", ",", "\"", "\"", ")", "\n", "}" ]
// KillContainer kills a container.
[ "KillContainer", "kills", "a", "container", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L621-L625
train
openshift/source-to-image
pkg/docker/docker.go
GetLabels
func (d *stiDocker) GetLabels(name string) (map[string]string, error) { name = getImageName(name) resp, err := d.InspectImage(name) if err != nil { glog.V(4).Infof("error inspecting image %s: %v", name, err) return nil, s2ierr.NewInspectImageError(name, err) } return resp.Config.Labels, nil }
go
func (d *stiDocker) GetLabels(name string) (map[string]string, error) { name = getImageName(name) resp, err := d.InspectImage(name) if err != nil { glog.V(4).Infof("error inspecting image %s: %v", name, err) return nil, s2ierr.NewInspectImageError(name, err) } return resp.Config.Labels, nil }
[ "func", "(", "d", "*", "stiDocker", ")", "GetLabels", "(", "name", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "name", "=", "getImageName", "(", "name", ")", "\n", "resp", ",", "err", ":=", "d", ".", "InspectImage", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "return", "nil", ",", "s2ierr", ".", "NewInspectImageError", "(", "name", ",", "err", ")", "\n", "}", "\n", "return", "resp", ".", "Config", ".", "Labels", ",", "nil", "\n", "}" ]
// GetLabels retrieves the labels of the given image.
[ "GetLabels", "retrieves", "the", "labels", "of", "the", "given", "image", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L628-L636
train
openshift/source-to-image
pkg/docker/docker.go
getImageName
func getImageName(name string) string { _, tag, id := parseRepositoryTag(name) if len(tag) == 0 && len(id) == 0 { //_, tag, _ := parseRepositoryTag(name) //if len(tag) == 0 { return strings.Join([]string{name, DefaultTag}, ":") } return name }
go
func getImageName(name string) string { _, tag, id := parseRepositoryTag(name) if len(tag) == 0 && len(id) == 0 { //_, tag, _ := parseRepositoryTag(name) //if len(tag) == 0 { return strings.Join([]string{name, DefaultTag}, ":") } return name }
[ "func", "getImageName", "(", "name", "string", ")", "string", "{", "_", ",", "tag", ",", "id", ":=", "parseRepositoryTag", "(", "name", ")", "\n", "if", "len", "(", "tag", ")", "==", "0", "&&", "len", "(", "id", ")", "==", "0", "{", "//_, tag, _ := parseRepositoryTag(name)", "//if len(tag) == 0 {", "return", "strings", ".", "Join", "(", "[", "]", "string", "{", "name", ",", "DefaultTag", "}", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "name", "\n", "}" ]
// getImageName checks the image name and adds DefaultTag if none is specified
[ "getImageName", "checks", "the", "image", "name", "and", "adds", "DefaultTag", "if", "none", "is", "specified" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L639-L648
train
openshift/source-to-image
pkg/docker/docker.go
getLabel
func getLabel(image *api.Image, name string) string { if value, ok := image.Config.Labels[name]; ok { return value } return "" }
go
func getLabel(image *api.Image, name string) string { if value, ok := image.Config.Labels[name]; ok { return value } return "" }
[ "func", "getLabel", "(", "image", "*", "api", ".", "Image", ",", "name", "string", ")", "string", "{", "if", "value", ",", "ok", ":=", "image", ".", "Config", ".", "Labels", "[", "name", "]", ";", "ok", "{", "return", "value", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// getLabel gets label's value from the image metadata
[ "getLabel", "gets", "label", "s", "value", "from", "the", "image", "metadata" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L651-L656
train
openshift/source-to-image
pkg/docker/docker.go
getVariable
func getVariable(image *api.Image, name string) string { envName := name + "=" for _, v := range image.Config.Env { if strings.HasPrefix(v, envName) { return strings.TrimSpace(v[len(envName):]) } } return "" }
go
func getVariable(image *api.Image, name string) string { envName := name + "=" for _, v := range image.Config.Env { if strings.HasPrefix(v, envName) { return strings.TrimSpace(v[len(envName):]) } } return "" }
[ "func", "getVariable", "(", "image", "*", "api", ".", "Image", ",", "name", "string", ")", "string", "{", "envName", ":=", "name", "+", "\"", "\"", "\n", "for", "_", ",", "v", ":=", "range", "image", ".", "Config", ".", "Env", "{", "if", "strings", ".", "HasPrefix", "(", "v", ",", "envName", ")", "{", "return", "strings", ".", "TrimSpace", "(", "v", "[", "len", "(", "envName", ")", ":", "]", ")", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", "\n", "}" ]
// getVariable gets environment variable's value from the image metadata
[ "getVariable", "gets", "environment", "variable", "s", "value", "from", "the", "image", "metadata" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L659-L668
train
openshift/source-to-image
pkg/docker/docker.go
GetScriptsURL
func (d *stiDocker) GetScriptsURL(image string) (string, error) { imageMetadata, err := d.CheckAndPullImage(image) if err != nil { return "", err } return getScriptsURL(imageMetadata), nil }
go
func (d *stiDocker) GetScriptsURL(image string) (string, error) { imageMetadata, err := d.CheckAndPullImage(image) if err != nil { return "", err } return getScriptsURL(imageMetadata), nil }
[ "func", "(", "d", "*", "stiDocker", ")", "GetScriptsURL", "(", "image", "string", ")", "(", "string", ",", "error", ")", "{", "imageMetadata", ",", "err", ":=", "d", ".", "CheckAndPullImage", "(", "image", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "getScriptsURL", "(", "imageMetadata", ")", ",", "nil", "\n", "}" ]
// GetScriptsURL finds a scripts-url label on the given image.
[ "GetScriptsURL", "finds", "a", "scripts", "-", "url", "label", "on", "the", "given", "image", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L671-L678
train
openshift/source-to-image
pkg/docker/docker.go
getScriptsURL
func getScriptsURL(image *api.Image) string { if image == nil { return "" } scriptsURL := getLabel(image, constants.ScriptsURLLabel) // For backward compatibility, support the old label schema if len(scriptsURL) == 0 { scriptsURL = getLabel(image, constants.DeprecatedScriptsURLLabel) if len(scriptsURL) > 0 { glog.V(0).Infof("warning: Image %s uses deprecated label '%s', please migrate it to %s instead!", image.ID, constants.DeprecatedScriptsURLLabel, constants.ScriptsURLLabel) } } if len(scriptsURL) == 0 { scriptsURL = getVariable(image, constants.ScriptsURLEnvironment) if len(scriptsURL) != 0 { glog.V(0).Infof("warning: Image %s uses deprecated environment variable %s, please migrate it to %s label instead!", image.ID, constants.ScriptsURLEnvironment, constants.ScriptsURLLabel) } } if len(scriptsURL) == 0 { glog.V(0).Infof("warning: Image %s does not contain a value for the %s label", image.ID, constants.ScriptsURLLabel) } else { glog.V(2).Infof("Image %s contains %s set to %q", image.ID, constants.ScriptsURLLabel, scriptsURL) } return scriptsURL }
go
func getScriptsURL(image *api.Image) string { if image == nil { return "" } scriptsURL := getLabel(image, constants.ScriptsURLLabel) // For backward compatibility, support the old label schema if len(scriptsURL) == 0 { scriptsURL = getLabel(image, constants.DeprecatedScriptsURLLabel) if len(scriptsURL) > 0 { glog.V(0).Infof("warning: Image %s uses deprecated label '%s', please migrate it to %s instead!", image.ID, constants.DeprecatedScriptsURLLabel, constants.ScriptsURLLabel) } } if len(scriptsURL) == 0 { scriptsURL = getVariable(image, constants.ScriptsURLEnvironment) if len(scriptsURL) != 0 { glog.V(0).Infof("warning: Image %s uses deprecated environment variable %s, please migrate it to %s label instead!", image.ID, constants.ScriptsURLEnvironment, constants.ScriptsURLLabel) } } if len(scriptsURL) == 0 { glog.V(0).Infof("warning: Image %s does not contain a value for the %s label", image.ID, constants.ScriptsURLLabel) } else { glog.V(2).Infof("Image %s contains %s set to %q", image.ID, constants.ScriptsURLLabel, scriptsURL) } return scriptsURL }
[ "func", "getScriptsURL", "(", "image", "*", "api", ".", "Image", ")", "string", "{", "if", "image", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "scriptsURL", ":=", "getLabel", "(", "image", ",", "constants", ".", "ScriptsURLLabel", ")", "\n\n", "// For backward compatibility, support the old label schema", "if", "len", "(", "scriptsURL", ")", "==", "0", "{", "scriptsURL", "=", "getLabel", "(", "image", ",", "constants", ".", "DeprecatedScriptsURLLabel", ")", "\n", "if", "len", "(", "scriptsURL", ")", ">", "0", "{", "glog", ".", "V", "(", "0", ")", ".", "Infof", "(", "\"", "\"", ",", "image", ".", "ID", ",", "constants", ".", "DeprecatedScriptsURLLabel", ",", "constants", ".", "ScriptsURLLabel", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "scriptsURL", ")", "==", "0", "{", "scriptsURL", "=", "getVariable", "(", "image", ",", "constants", ".", "ScriptsURLEnvironment", ")", "\n", "if", "len", "(", "scriptsURL", ")", "!=", "0", "{", "glog", ".", "V", "(", "0", ")", ".", "Infof", "(", "\"", "\"", ",", "image", ".", "ID", ",", "constants", ".", "ScriptsURLEnvironment", ",", "constants", ".", "ScriptsURLLabel", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "scriptsURL", ")", "==", "0", "{", "glog", ".", "V", "(", "0", ")", ".", "Infof", "(", "\"", "\"", ",", "image", ".", "ID", ",", "constants", ".", "ScriptsURLLabel", ")", "\n", "}", "else", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "image", ".", "ID", ",", "constants", ".", "ScriptsURLLabel", ",", "scriptsURL", ")", "\n", "}", "\n\n", "return", "scriptsURL", "\n", "}" ]
// getScriptsURL finds a scripts url label in the image metadata
[ "getScriptsURL", "finds", "a", "scripts", "url", "label", "in", "the", "image", "metadata" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L706-L734
train
openshift/source-to-image
pkg/docker/docker.go
getDestination
func getDestination(image *api.Image) string { if val := getLabel(image, constants.DestinationLabel); len(val) != 0 { return val } // For backward compatibility, support the old label schema if val := getLabel(image, constants.DeprecatedDestinationLabel); len(val) != 0 { glog.V(0).Infof("warning: Image %s uses deprecated label '%s', please migrate it to %s instead!", image.ID, constants.DeprecatedDestinationLabel, constants.DestinationLabel) return val } if val := getVariable(image, constants.LocationEnvironment); len(val) != 0 { glog.V(0).Infof("warning: Image %s uses deprecated environment variable %s, please migrate it to %s label instead!", image.ID, constants.LocationEnvironment, constants.DestinationLabel) return val } // default directory if none is specified return DefaultDestination }
go
func getDestination(image *api.Image) string { if val := getLabel(image, constants.DestinationLabel); len(val) != 0 { return val } // For backward compatibility, support the old label schema if val := getLabel(image, constants.DeprecatedDestinationLabel); len(val) != 0 { glog.V(0).Infof("warning: Image %s uses deprecated label '%s', please migrate it to %s instead!", image.ID, constants.DeprecatedDestinationLabel, constants.DestinationLabel) return val } if val := getVariable(image, constants.LocationEnvironment); len(val) != 0 { glog.V(0).Infof("warning: Image %s uses deprecated environment variable %s, please migrate it to %s label instead!", image.ID, constants.LocationEnvironment, constants.DestinationLabel) return val } // default directory if none is specified return DefaultDestination }
[ "func", "getDestination", "(", "image", "*", "api", ".", "Image", ")", "string", "{", "if", "val", ":=", "getLabel", "(", "image", ",", "constants", ".", "DestinationLabel", ")", ";", "len", "(", "val", ")", "!=", "0", "{", "return", "val", "\n", "}", "\n", "// For backward compatibility, support the old label schema", "if", "val", ":=", "getLabel", "(", "image", ",", "constants", ".", "DeprecatedDestinationLabel", ")", ";", "len", "(", "val", ")", "!=", "0", "{", "glog", ".", "V", "(", "0", ")", ".", "Infof", "(", "\"", "\"", ",", "image", ".", "ID", ",", "constants", ".", "DeprecatedDestinationLabel", ",", "constants", ".", "DestinationLabel", ")", "\n", "return", "val", "\n", "}", "\n", "if", "val", ":=", "getVariable", "(", "image", ",", "constants", ".", "LocationEnvironment", ")", ";", "len", "(", "val", ")", "!=", "0", "{", "glog", ".", "V", "(", "0", ")", ".", "Infof", "(", "\"", "\"", ",", "image", ".", "ID", ",", "constants", ".", "LocationEnvironment", ",", "constants", ".", "DestinationLabel", ")", "\n", "return", "val", "\n", "}", "\n\n", "// default directory if none is specified", "return", "DefaultDestination", "\n", "}" ]
// getDestination finds a destination label in the image metadata
[ "getDestination", "finds", "a", "destination", "label", "in", "the", "image", "metadata" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L737-L755
train
openshift/source-to-image
pkg/docker/docker.go
holdHijackedConnection
func (d *stiDocker) holdHijackedConnection(tty bool, opts *RunContainerOptions, resp dockertypes.HijackedResponse) error { receiveStdout := make(chan error, 1) if opts.Stdout != nil || opts.Stderr != nil { go func() { err := d.redirectResponseToOutputStream(tty, opts.Stdout, opts.Stderr, resp.Reader) if opts.Stdout != nil { opts.Stdout.Close() opts.Stdout = nil } if opts.Stderr != nil { opts.Stderr.Close() opts.Stderr = nil } receiveStdout <- err }() } else { receiveStdout <- nil } if opts.Stdin != nil { _, err := io.Copy(resp.Conn, opts.Stdin) opts.Stdin.Close() opts.Stdin = nil if err != nil { <-receiveStdout return err } } err := resp.CloseWrite() if err != nil { <-receiveStdout return err } // Hang around until the streaming is over - either when the server closes // the connection, or someone locally closes resp. return <-receiveStdout }
go
func (d *stiDocker) holdHijackedConnection(tty bool, opts *RunContainerOptions, resp dockertypes.HijackedResponse) error { receiveStdout := make(chan error, 1) if opts.Stdout != nil || opts.Stderr != nil { go func() { err := d.redirectResponseToOutputStream(tty, opts.Stdout, opts.Stderr, resp.Reader) if opts.Stdout != nil { opts.Stdout.Close() opts.Stdout = nil } if opts.Stderr != nil { opts.Stderr.Close() opts.Stderr = nil } receiveStdout <- err }() } else { receiveStdout <- nil } if opts.Stdin != nil { _, err := io.Copy(resp.Conn, opts.Stdin) opts.Stdin.Close() opts.Stdin = nil if err != nil { <-receiveStdout return err } } err := resp.CloseWrite() if err != nil { <-receiveStdout return err } // Hang around until the streaming is over - either when the server closes // the connection, or someone locally closes resp. return <-receiveStdout }
[ "func", "(", "d", "*", "stiDocker", ")", "holdHijackedConnection", "(", "tty", "bool", ",", "opts", "*", "RunContainerOptions", ",", "resp", "dockertypes", ".", "HijackedResponse", ")", "error", "{", "receiveStdout", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "if", "opts", ".", "Stdout", "!=", "nil", "||", "opts", ".", "Stderr", "!=", "nil", "{", "go", "func", "(", ")", "{", "err", ":=", "d", ".", "redirectResponseToOutputStream", "(", "tty", ",", "opts", ".", "Stdout", ",", "opts", ".", "Stderr", ",", "resp", ".", "Reader", ")", "\n", "if", "opts", ".", "Stdout", "!=", "nil", "{", "opts", ".", "Stdout", ".", "Close", "(", ")", "\n", "opts", ".", "Stdout", "=", "nil", "\n", "}", "\n", "if", "opts", ".", "Stderr", "!=", "nil", "{", "opts", ".", "Stderr", ".", "Close", "(", ")", "\n", "opts", ".", "Stderr", "=", "nil", "\n", "}", "\n", "receiveStdout", "<-", "err", "\n", "}", "(", ")", "\n", "}", "else", "{", "receiveStdout", "<-", "nil", "\n", "}", "\n\n", "if", "opts", ".", "Stdin", "!=", "nil", "{", "_", ",", "err", ":=", "io", ".", "Copy", "(", "resp", ".", "Conn", ",", "opts", ".", "Stdin", ")", "\n", "opts", ".", "Stdin", ".", "Close", "(", ")", "\n", "opts", ".", "Stdin", "=", "nil", "\n", "if", "err", "!=", "nil", "{", "<-", "receiveStdout", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "err", ":=", "resp", ".", "CloseWrite", "(", ")", "\n", "if", "err", "!=", "nil", "{", "<-", "receiveStdout", "\n", "return", "err", "\n", "}", "\n\n", "// Hang around until the streaming is over - either when the server closes", "// the connection, or someone locally closes resp.", "return", "<-", "receiveStdout", "\n", "}" ]
// holdHijackedConnection pumps data up to the container's stdin, and runs a // goroutine to pump data down from the container's stdout and stderr. it holds // open the HijackedResponse until all of this is done. Caller's responsibility // to close resp, as well as outputStream and errorStream if appropriate.
[ "holdHijackedConnection", "pumps", "data", "up", "to", "the", "container", "s", "stdin", "and", "runs", "a", "goroutine", "to", "pump", "data", "down", "from", "the", "container", "s", "stdout", "and", "stderr", ".", "it", "holds", "open", "the", "HijackedResponse", "until", "all", "of", "this", "is", "done", ".", "Caller", "s", "responsibility", "to", "close", "resp", "as", "well", "as", "outputStream", "and", "errorStream", "if", "appropriate", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L859-L896
train
openshift/source-to-image
pkg/docker/docker.go
GetImageID
func (d *stiDocker) GetImageID(name string) (string, error) { name = getImageName(name) image, err := d.InspectImage(name) if err != nil { return "", err } return image.ID, nil }
go
func (d *stiDocker) GetImageID(name string) (string, error) { name = getImageName(name) image, err := d.InspectImage(name) if err != nil { return "", err } return image.ID, nil }
[ "func", "(", "d", "*", "stiDocker", ")", "GetImageID", "(", "name", "string", ")", "(", "string", ",", "error", ")", "{", "name", "=", "getImageName", "(", "name", ")", "\n", "image", ",", "err", ":=", "d", ".", "InspectImage", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "image", ".", "ID", ",", "nil", "\n", "}" ]
// GetImageID retrieves the ID of the image identified by name
[ "GetImageID", "retrieves", "the", "ID", "of", "the", "image", "identified", "by", "name" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L1079-L1086
train
openshift/source-to-image
pkg/docker/docker.go
CommitContainer
func (d *stiDocker) CommitContainer(opts CommitContainerOptions) (string, error) { dockerOpts := dockertypes.ContainerCommitOptions{ Reference: opts.Repository, } if opts.Command != nil || opts.Entrypoint != nil { config := dockercontainer.Config{ Cmd: opts.Command, Entrypoint: opts.Entrypoint, Env: opts.Env, Labels: opts.Labels, User: opts.User, } dockerOpts.Config = &config glog.V(2).Infof("Committing container with dockerOpts: %+v, config: %+v", dockerOpts, *util.SafeForLoggingContainerConfig(&config)) } resp, err := d.client.ContainerCommit(context.Background(), opts.ContainerID, dockerOpts) if err == nil { return resp.ID, nil } return "", err }
go
func (d *stiDocker) CommitContainer(opts CommitContainerOptions) (string, error) { dockerOpts := dockertypes.ContainerCommitOptions{ Reference: opts.Repository, } if opts.Command != nil || opts.Entrypoint != nil { config := dockercontainer.Config{ Cmd: opts.Command, Entrypoint: opts.Entrypoint, Env: opts.Env, Labels: opts.Labels, User: opts.User, } dockerOpts.Config = &config glog.V(2).Infof("Committing container with dockerOpts: %+v, config: %+v", dockerOpts, *util.SafeForLoggingContainerConfig(&config)) } resp, err := d.client.ContainerCommit(context.Background(), opts.ContainerID, dockerOpts) if err == nil { return resp.ID, nil } return "", err }
[ "func", "(", "d", "*", "stiDocker", ")", "CommitContainer", "(", "opts", "CommitContainerOptions", ")", "(", "string", ",", "error", ")", "{", "dockerOpts", ":=", "dockertypes", ".", "ContainerCommitOptions", "{", "Reference", ":", "opts", ".", "Repository", ",", "}", "\n", "if", "opts", ".", "Command", "!=", "nil", "||", "opts", ".", "Entrypoint", "!=", "nil", "{", "config", ":=", "dockercontainer", ".", "Config", "{", "Cmd", ":", "opts", ".", "Command", ",", "Entrypoint", ":", "opts", ".", "Entrypoint", ",", "Env", ":", "opts", ".", "Env", ",", "Labels", ":", "opts", ".", "Labels", ",", "User", ":", "opts", ".", "User", ",", "}", "\n", "dockerOpts", ".", "Config", "=", "&", "config", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "dockerOpts", ",", "*", "util", ".", "SafeForLoggingContainerConfig", "(", "&", "config", ")", ")", "\n", "}", "\n\n", "resp", ",", "err", ":=", "d", ".", "client", ".", "ContainerCommit", "(", "context", ".", "Background", "(", ")", ",", "opts", ".", "ContainerID", ",", "dockerOpts", ")", "\n", "if", "err", "==", "nil", "{", "return", "resp", ".", "ID", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "err", "\n", "}" ]
// CommitContainer commits a container to an image with a specific tag. // The new image ID is returned
[ "CommitContainer", "commits", "a", "container", "to", "an", "image", "with", "a", "specific", "tag", ".", "The", "new", "image", "ID", "is", "returned" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L1090-L1111
train
openshift/source-to-image
pkg/docker/docker.go
RemoveImage
func (d *stiDocker) RemoveImage(imageID string) error { ctx, cancel := getDefaultContext() defer cancel() _, err := d.client.ImageRemove(ctx, imageID, dockertypes.ImageRemoveOptions{}) return err }
go
func (d *stiDocker) RemoveImage(imageID string) error { ctx, cancel := getDefaultContext() defer cancel() _, err := d.client.ImageRemove(ctx, imageID, dockertypes.ImageRemoveOptions{}) return err }
[ "func", "(", "d", "*", "stiDocker", ")", "RemoveImage", "(", "imageID", "string", ")", "error", "{", "ctx", ",", "cancel", ":=", "getDefaultContext", "(", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "err", ":=", "d", ".", "client", ".", "ImageRemove", "(", "ctx", ",", "imageID", ",", "dockertypes", ".", "ImageRemoveOptions", "{", "}", ")", "\n", "return", "err", "\n", "}" ]
// RemoveImage removes the image with specified ID
[ "RemoveImage", "removes", "the", "image", "with", "specified", "ID" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L1114-L1119
train
openshift/source-to-image
pkg/docker/docker.go
BuildImage
func (d *stiDocker) BuildImage(opts BuildImageOptions) error { dockerOpts := dockertypes.ImageBuildOptions{ Tags: []string{opts.Name}, NoCache: true, SuppressOutput: false, Remove: true, ForceRemove: true, } if opts.CGroupLimits != nil { dockerOpts.Memory = opts.CGroupLimits.MemoryLimitBytes dockerOpts.MemorySwap = opts.CGroupLimits.MemorySwap dockerOpts.CgroupParent = opts.CGroupLimits.Parent } glog.V(2).Infof("Building container using config: %+v", dockerOpts) resp, err := d.client.ImageBuild(context.Background(), opts.Stdin, dockerOpts) if err != nil { return err } defer resp.Body.Close() // since can't pass in output stream to engine-api, need to copy contents of // the output stream they create into our output stream _, err = io.Copy(opts.Stdout, resp.Body) if opts.Stdout != nil { opts.Stdout.Close() } return err }
go
func (d *stiDocker) BuildImage(opts BuildImageOptions) error { dockerOpts := dockertypes.ImageBuildOptions{ Tags: []string{opts.Name}, NoCache: true, SuppressOutput: false, Remove: true, ForceRemove: true, } if opts.CGroupLimits != nil { dockerOpts.Memory = opts.CGroupLimits.MemoryLimitBytes dockerOpts.MemorySwap = opts.CGroupLimits.MemorySwap dockerOpts.CgroupParent = opts.CGroupLimits.Parent } glog.V(2).Infof("Building container using config: %+v", dockerOpts) resp, err := d.client.ImageBuild(context.Background(), opts.Stdin, dockerOpts) if err != nil { return err } defer resp.Body.Close() // since can't pass in output stream to engine-api, need to copy contents of // the output stream they create into our output stream _, err = io.Copy(opts.Stdout, resp.Body) if opts.Stdout != nil { opts.Stdout.Close() } return err }
[ "func", "(", "d", "*", "stiDocker", ")", "BuildImage", "(", "opts", "BuildImageOptions", ")", "error", "{", "dockerOpts", ":=", "dockertypes", ".", "ImageBuildOptions", "{", "Tags", ":", "[", "]", "string", "{", "opts", ".", "Name", "}", ",", "NoCache", ":", "true", ",", "SuppressOutput", ":", "false", ",", "Remove", ":", "true", ",", "ForceRemove", ":", "true", ",", "}", "\n", "if", "opts", ".", "CGroupLimits", "!=", "nil", "{", "dockerOpts", ".", "Memory", "=", "opts", ".", "CGroupLimits", ".", "MemoryLimitBytes", "\n", "dockerOpts", ".", "MemorySwap", "=", "opts", ".", "CGroupLimits", ".", "MemorySwap", "\n", "dockerOpts", ".", "CgroupParent", "=", "opts", ".", "CGroupLimits", ".", "Parent", "\n", "}", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "dockerOpts", ")", "\n", "resp", ",", "err", ":=", "d", ".", "client", ".", "ImageBuild", "(", "context", ".", "Background", "(", ")", ",", "opts", ".", "Stdin", ",", "dockerOpts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "// since can't pass in output stream to engine-api, need to copy contents of", "// the output stream they create into our output stream", "_", ",", "err", "=", "io", ".", "Copy", "(", "opts", ".", "Stdout", ",", "resp", ".", "Body", ")", "\n", "if", "opts", ".", "Stdout", "!=", "nil", "{", "opts", ".", "Stdout", ".", "Close", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// BuildImage builds the image according to specified options
[ "BuildImage", "builds", "the", "image", "according", "to", "specified", "options" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L1122-L1148
train
openshift/source-to-image
pkg/build/strategies/onbuild/entrypoint.go
isValidEntrypoint
func isValidEntrypoint(fs fs.FileSystem, path string) bool { stat, err := fs.Stat(path) if err != nil { return false } found := false for _, pattern := range validEntrypoints { if pattern.MatchString(stat.Name()) { found = true break } } if !found { return false } mode := stat.Mode() return mode&0111 != 0 }
go
func isValidEntrypoint(fs fs.FileSystem, path string) bool { stat, err := fs.Stat(path) if err != nil { return false } found := false for _, pattern := range validEntrypoints { if pattern.MatchString(stat.Name()) { found = true break } } if !found { return false } mode := stat.Mode() return mode&0111 != 0 }
[ "func", "isValidEntrypoint", "(", "fs", "fs", ".", "FileSystem", ",", "path", "string", ")", "bool", "{", "stat", ",", "err", ":=", "fs", ".", "Stat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "found", ":=", "false", "\n", "for", "_", ",", "pattern", ":=", "range", "validEntrypoints", "{", "if", "pattern", ".", "MatchString", "(", "stat", ".", "Name", "(", ")", ")", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "return", "false", "\n", "}", "\n", "mode", ":=", "stat", ".", "Mode", "(", ")", "\n", "return", "mode", "&", "0111", "!=", "0", "\n", "}" ]
// isValidEntrypoint checks if the given file exists and if it is a regular // file. Valid ENTRYPOINT must be an executable file, so the executable bit must // be set.
[ "isValidEntrypoint", "checks", "if", "the", "given", "file", "exists", "and", "if", "it", "is", "a", "regular", "file", ".", "Valid", "ENTRYPOINT", "must", "be", "an", "executable", "file", "so", "the", "executable", "bit", "must", "be", "set", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/onbuild/entrypoint.go#L43-L60
train
openshift/source-to-image
pkg/cmd/cli/cmd/version.go
NewCmdVersion
func NewCmdVersion() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Display version", Long: "Display version", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("s2i %v\n", version.Get()) }, } }
go
func NewCmdVersion() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Display version", Long: "Display version", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("s2i %v\n", version.Get()) }, } }
[ "func", "NewCmdVersion", "(", ")", "*", "cobra", ".", "Command", "{", "return", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Long", ":", "\"", "\"", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "version", ".", "Get", "(", ")", ")", "\n", "}", ",", "}", "\n", "}" ]
// NewCmdVersion implements the S2i cli version command.
[ "NewCmdVersion", "implements", "the", "S2i", "cli", "version", "command", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/cmd/cli/cmd/version.go#L12-L21
train
openshift/source-to-image
pkg/ignore/ignore.go
Ignore
func (b *DockerIgnorer) Ignore(config *api.Config) error { /* so, to duplicate the .dockerignore capabilities (https://docs.docker.com/reference/builder/#dockerignore-file) we have a flow that follows: 0) First note, .dockerignore rules are NOT recursive (unlike .gitignore) .. you have to list subdir explicitly 1) Read in the exclusion patterns 2) Skip over comments (noted by #) 3) note overrides (via exclamation sign i.e. !) and reinstate files (don't remove) as needed 4) leverage Glob matching to build list, as .dockerignore is documented as following filepath.Match / filepath.Glob 5) del files 1 to 4 is in getListOfFilesToIgnore */ filesToDel, lerr := getListOfFilesToIgnore(config.WorkingSourceDir) if lerr != nil { return lerr } if filesToDel == nil { return nil } // delete compiled list of files for _, fileToDel := range filesToDel { glog.V(5).Infof("attempting to remove file %s \n", fileToDel) rerr := os.RemoveAll(fileToDel) if rerr != nil { glog.Errorf("error removing file %s because of %v \n", fileToDel, rerr) return rerr } } return nil }
go
func (b *DockerIgnorer) Ignore(config *api.Config) error { /* so, to duplicate the .dockerignore capabilities (https://docs.docker.com/reference/builder/#dockerignore-file) we have a flow that follows: 0) First note, .dockerignore rules are NOT recursive (unlike .gitignore) .. you have to list subdir explicitly 1) Read in the exclusion patterns 2) Skip over comments (noted by #) 3) note overrides (via exclamation sign i.e. !) and reinstate files (don't remove) as needed 4) leverage Glob matching to build list, as .dockerignore is documented as following filepath.Match / filepath.Glob 5) del files 1 to 4 is in getListOfFilesToIgnore */ filesToDel, lerr := getListOfFilesToIgnore(config.WorkingSourceDir) if lerr != nil { return lerr } if filesToDel == nil { return nil } // delete compiled list of files for _, fileToDel := range filesToDel { glog.V(5).Infof("attempting to remove file %s \n", fileToDel) rerr := os.RemoveAll(fileToDel) if rerr != nil { glog.Errorf("error removing file %s because of %v \n", fileToDel, rerr) return rerr } } return nil }
[ "func", "(", "b", "*", "DockerIgnorer", ")", "Ignore", "(", "config", "*", "api", ".", "Config", ")", "error", "{", "/*\n\t\t so, to duplicate the .dockerignore capabilities (https://docs.docker.com/reference/builder/#dockerignore-file)\n\t\t we have a flow that follows:\n\t\t0) First note, .dockerignore rules are NOT recursive (unlike .gitignore) .. you have to list subdir explicitly\n\t\t1) Read in the exclusion patterns\n\t\t2) Skip over comments (noted by #)\n\t\t3) note overrides (via exclamation sign i.e. !) and reinstate files (don't remove) as needed\n\t\t4) leverage Glob matching to build list, as .dockerignore is documented as following filepath.Match / filepath.Glob\n\t\t5) del files\n\t\t 1 to 4 is in getListOfFilesToIgnore\n\t*/", "filesToDel", ",", "lerr", ":=", "getListOfFilesToIgnore", "(", "config", ".", "WorkingSourceDir", ")", "\n", "if", "lerr", "!=", "nil", "{", "return", "lerr", "\n", "}", "\n\n", "if", "filesToDel", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// delete compiled list of files", "for", "_", ",", "fileToDel", ":=", "range", "filesToDel", "{", "glog", ".", "V", "(", "5", ")", ".", "Infof", "(", "\"", "\\n", "\"", ",", "fileToDel", ")", "\n", "rerr", ":=", "os", ".", "RemoveAll", "(", "fileToDel", ")", "\n", "if", "rerr", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "fileToDel", ",", "rerr", ")", "\n", "return", "rerr", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Ignore removes files from the workspace based on the contents of the // .s2iignore file
[ "Ignore", "removes", "files", "from", "the", "workspace", "based", "on", "the", "contents", "of", "the", ".", "s2iignore", "file" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/ignore/ignore.go#L22-L54
train
openshift/source-to-image
pkg/api/describe/describer.go
Config
func Config(client docker.Client, config *api.Config) string { out, err := tabbedString(func(out io.Writer) error { if len(config.DisplayName) > 0 { fmt.Fprintf(out, "Application Name:\t%s\n", config.DisplayName) } if len(config.Description) > 0 { fmt.Fprintf(out, "Description:\t%s\n", config.Description) } if len(config.AsDockerfile) == 0 { describeBuilderImage(client, config, out) describeRuntimeImage(config, out) } fmt.Fprintf(out, "Source:\t%s\n", config.Source) if len(config.ContextDir) > 0 { fmt.Fprintf(out, "Context Directory:\t%s\n", config.ContextDir) } fmt.Fprintf(out, "Output Image Tag:\t%s\n", config.Tag) printEnv(out, config.Environment) if len(config.EnvironmentFile) > 0 { fmt.Fprintf(out, "Environment File:\t%s\n", config.EnvironmentFile) } printLabels(out, config.Labels) fmt.Fprintf(out, "Incremental Build:\t%s\n", printBool(config.Incremental)) if config.Incremental { fmt.Fprintf(out, "Incremental Image Pull User:\t%s\n", config.IncrementalAuthentication.Username) } fmt.Fprintf(out, "Remove Old Build:\t%s\n", printBool(config.RemovePreviousImage)) fmt.Fprintf(out, "Builder Pull Policy:\t%s\n", config.BuilderPullPolicy) fmt.Fprintf(out, "Previous Image Pull Policy:\t%s\n", config.PreviousImagePullPolicy) fmt.Fprintf(out, "Quiet:\t%s\n", printBool(config.Quiet)) fmt.Fprintf(out, "Layered Build:\t%s\n", printBool(config.LayeredBuild)) if len(config.Destination) > 0 { fmt.Fprintf(out, "Artifacts Destination:\t%s\n", config.Destination) } if len(config.CallbackURL) > 0 { fmt.Fprintf(out, "Callback URL:\t%s\n", config.CallbackURL) } if len(config.ScriptsURL) > 0 { fmt.Fprintf(out, "S2I Scripts URL:\t%s\n", config.ScriptsURL) } if len(config.WorkingDir) > 0 { fmt.Fprintf(out, "Workdir:\t%s\n", config.WorkingDir) } if config.DockerNetworkMode != "" { fmt.Fprintf(out, "Docker NetworkMode:\t%s\n", config.DockerNetworkMode) } fmt.Fprintf(out, "Docker Endpoint:\t%s\n", config.DockerConfig.Endpoint) if _, err := os.Open(config.DockerCfgPath); err == nil { fmt.Fprintf(out, "Docker Pull Config:\t%s\n", config.DockerCfgPath) fmt.Fprintf(out, "Docker Pull User:\t%s\n", config.PullAuthentication.Username) } if len(config.Injections) > 0 { result := []string{} for _, i := range config.Injections { result = append(result, fmt.Sprintf("%s->%s", i.Source, i.Destination)) } fmt.Fprintf(out, "Injections:\t%s\n", strings.Join(result, ",")) } if len(config.BuildVolumes) > 0 { result := []string{} for _, i := range config.BuildVolumes { if runtime.GOOS == "windows" { // We need to avoid the colon in the Windows drive letter result = append(result, i[0:2]+strings.Replace(i[3:], ":", "->", 1)) } else { result = append(result, strings.Replace(i, ":", "->", 1)) } } fmt.Fprintf(out, "Bind mounts:\t%s\n", strings.Join(result, ",")) } return nil }) if err != nil { fmt.Printf("error: %v", err) } return out }
go
func Config(client docker.Client, config *api.Config) string { out, err := tabbedString(func(out io.Writer) error { if len(config.DisplayName) > 0 { fmt.Fprintf(out, "Application Name:\t%s\n", config.DisplayName) } if len(config.Description) > 0 { fmt.Fprintf(out, "Description:\t%s\n", config.Description) } if len(config.AsDockerfile) == 0 { describeBuilderImage(client, config, out) describeRuntimeImage(config, out) } fmt.Fprintf(out, "Source:\t%s\n", config.Source) if len(config.ContextDir) > 0 { fmt.Fprintf(out, "Context Directory:\t%s\n", config.ContextDir) } fmt.Fprintf(out, "Output Image Tag:\t%s\n", config.Tag) printEnv(out, config.Environment) if len(config.EnvironmentFile) > 0 { fmt.Fprintf(out, "Environment File:\t%s\n", config.EnvironmentFile) } printLabels(out, config.Labels) fmt.Fprintf(out, "Incremental Build:\t%s\n", printBool(config.Incremental)) if config.Incremental { fmt.Fprintf(out, "Incremental Image Pull User:\t%s\n", config.IncrementalAuthentication.Username) } fmt.Fprintf(out, "Remove Old Build:\t%s\n", printBool(config.RemovePreviousImage)) fmt.Fprintf(out, "Builder Pull Policy:\t%s\n", config.BuilderPullPolicy) fmt.Fprintf(out, "Previous Image Pull Policy:\t%s\n", config.PreviousImagePullPolicy) fmt.Fprintf(out, "Quiet:\t%s\n", printBool(config.Quiet)) fmt.Fprintf(out, "Layered Build:\t%s\n", printBool(config.LayeredBuild)) if len(config.Destination) > 0 { fmt.Fprintf(out, "Artifacts Destination:\t%s\n", config.Destination) } if len(config.CallbackURL) > 0 { fmt.Fprintf(out, "Callback URL:\t%s\n", config.CallbackURL) } if len(config.ScriptsURL) > 0 { fmt.Fprintf(out, "S2I Scripts URL:\t%s\n", config.ScriptsURL) } if len(config.WorkingDir) > 0 { fmt.Fprintf(out, "Workdir:\t%s\n", config.WorkingDir) } if config.DockerNetworkMode != "" { fmt.Fprintf(out, "Docker NetworkMode:\t%s\n", config.DockerNetworkMode) } fmt.Fprintf(out, "Docker Endpoint:\t%s\n", config.DockerConfig.Endpoint) if _, err := os.Open(config.DockerCfgPath); err == nil { fmt.Fprintf(out, "Docker Pull Config:\t%s\n", config.DockerCfgPath) fmt.Fprintf(out, "Docker Pull User:\t%s\n", config.PullAuthentication.Username) } if len(config.Injections) > 0 { result := []string{} for _, i := range config.Injections { result = append(result, fmt.Sprintf("%s->%s", i.Source, i.Destination)) } fmt.Fprintf(out, "Injections:\t%s\n", strings.Join(result, ",")) } if len(config.BuildVolumes) > 0 { result := []string{} for _, i := range config.BuildVolumes { if runtime.GOOS == "windows" { // We need to avoid the colon in the Windows drive letter result = append(result, i[0:2]+strings.Replace(i[3:], ":", "->", 1)) } else { result = append(result, strings.Replace(i, ":", "->", 1)) } } fmt.Fprintf(out, "Bind mounts:\t%s\n", strings.Join(result, ",")) } return nil }) if err != nil { fmt.Printf("error: %v", err) } return out }
[ "func", "Config", "(", "client", "docker", ".", "Client", ",", "config", "*", "api", ".", "Config", ")", "string", "{", "out", ",", "err", ":=", "tabbedString", "(", "func", "(", "out", "io", ".", "Writer", ")", "error", "{", "if", "len", "(", "config", ".", "DisplayName", ")", ">", "0", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "DisplayName", ")", "\n", "}", "\n", "if", "len", "(", "config", ".", "Description", ")", ">", "0", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "Description", ")", "\n", "}", "\n", "if", "len", "(", "config", ".", "AsDockerfile", ")", "==", "0", "{", "describeBuilderImage", "(", "client", ",", "config", ",", "out", ")", "\n", "describeRuntimeImage", "(", "config", ",", "out", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "Source", ")", "\n", "if", "len", "(", "config", ".", "ContextDir", ")", ">", "0", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "ContextDir", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "Tag", ")", "\n", "printEnv", "(", "out", ",", "config", ".", "Environment", ")", "\n", "if", "len", "(", "config", ".", "EnvironmentFile", ")", ">", "0", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "EnvironmentFile", ")", "\n", "}", "\n", "printLabels", "(", "out", ",", "config", ".", "Labels", ")", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "printBool", "(", "config", ".", "Incremental", ")", ")", "\n", "if", "config", ".", "Incremental", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "IncrementalAuthentication", ".", "Username", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "printBool", "(", "config", ".", "RemovePreviousImage", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "BuilderPullPolicy", ")", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "PreviousImagePullPolicy", ")", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "printBool", "(", "config", ".", "Quiet", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "printBool", "(", "config", ".", "LayeredBuild", ")", ")", "\n", "if", "len", "(", "config", ".", "Destination", ")", ">", "0", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "Destination", ")", "\n", "}", "\n", "if", "len", "(", "config", ".", "CallbackURL", ")", ">", "0", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "CallbackURL", ")", "\n", "}", "\n", "if", "len", "(", "config", ".", "ScriptsURL", ")", ">", "0", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "ScriptsURL", ")", "\n", "}", "\n", "if", "len", "(", "config", ".", "WorkingDir", ")", ">", "0", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "WorkingDir", ")", "\n", "}", "\n", "if", "config", ".", "DockerNetworkMode", "!=", "\"", "\"", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "DockerNetworkMode", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "DockerConfig", ".", "Endpoint", ")", "\n\n", "if", "_", ",", "err", ":=", "os", ".", "Open", "(", "config", ".", "DockerCfgPath", ")", ";", "err", "==", "nil", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "DockerCfgPath", ")", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "config", ".", "PullAuthentication", ".", "Username", ")", "\n", "}", "\n\n", "if", "len", "(", "config", ".", "Injections", ")", ">", "0", "{", "result", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "i", ":=", "range", "config", ".", "Injections", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ".", "Source", ",", "i", ".", "Destination", ")", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "strings", ".", "Join", "(", "result", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "len", "(", "config", ".", "BuildVolumes", ")", ">", "0", "{", "result", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "i", ":=", "range", "config", ".", "BuildVolumes", "{", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "// We need to avoid the colon in the Windows drive letter", "result", "=", "append", "(", "result", ",", "i", "[", "0", ":", "2", "]", "+", "strings", ".", "Replace", "(", "i", "[", "3", ":", "]", ",", "\"", "\"", ",", "\"", "\"", ",", "1", ")", ")", "\n", "}", "else", "{", "result", "=", "append", "(", "result", ",", "strings", ".", "Replace", "(", "i", ",", "\"", "\"", ",", "\"", "\"", ",", "1", ")", ")", "\n", "}", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\t", "\\n", "\"", ",", "strings", ".", "Join", "(", "result", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Config returns the Config object in nice readable, tabbed format.
[ "Config", "returns", "the", "Config", "object", "in", "nice", "readable", "tabbed", "format", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/api/describe/describer.go#L18-L97
train
openshift/source-to-image
pkg/build/strategies/sti/postexecutorstep.go
checkAndGetNewLabels
func checkAndGetNewLabels(builder *STI, docker dockerpkg.Docker, tar s2itar.Tar, containerID string) error { glog.V(3).Infof("Checking for new Labels to apply... ") // metadata filename and its path inside the container metadataFilename := "image_metadata.json" sourceFilepath := filepath.Join("/tmp/.s2i", metadataFilename) // create the 'downloadPath' folder if it doesn't exist downloadPath := filepath.Join(builder.config.WorkingDir, "metadata") glog.V(3).Infof("Creating the download path '%s'", downloadPath) if err := os.MkdirAll(downloadPath, 0700); err != nil { glog.Errorf("Error creating dir %q for '%s': %v", downloadPath, metadataFilename, err) return err } // download & extract the file from container if _, err := downloadAndExtractFileFromContainer(docker, tar, sourceFilepath, downloadPath, containerID); err != nil { glog.V(3).Infof("unable to download and extract '%s' ... continuing", metadataFilename) return nil } // open the file filePath := filepath.Join(downloadPath, metadataFilename) fd, err := os.Open(filePath) if fd == nil || err != nil { return fmt.Errorf("unable to open file '%s' : %v", downloadPath, err) } defer fd.Close() // read the file to a string str, err := ioutil.ReadAll(fd) if err != nil { return fmt.Errorf("error reading file '%s' in to a string: %v", filePath, err) } glog.V(3).Infof("new Labels File contents : \n%s\n", str) // string into a map var data map[string]interface{} if err = json.Unmarshal([]byte(str), &data); err != nil { return fmt.Errorf("JSON Unmarshal Error with '%s' file : %v", metadataFilename, err) } // update newLabels[] labels := data["labels"] for _, l := range labels.([]interface{}) { for k, v := range l.(map[string]interface{}) { builder.newLabels[k] = v.(string) } } return nil }
go
func checkAndGetNewLabels(builder *STI, docker dockerpkg.Docker, tar s2itar.Tar, containerID string) error { glog.V(3).Infof("Checking for new Labels to apply... ") // metadata filename and its path inside the container metadataFilename := "image_metadata.json" sourceFilepath := filepath.Join("/tmp/.s2i", metadataFilename) // create the 'downloadPath' folder if it doesn't exist downloadPath := filepath.Join(builder.config.WorkingDir, "metadata") glog.V(3).Infof("Creating the download path '%s'", downloadPath) if err := os.MkdirAll(downloadPath, 0700); err != nil { glog.Errorf("Error creating dir %q for '%s': %v", downloadPath, metadataFilename, err) return err } // download & extract the file from container if _, err := downloadAndExtractFileFromContainer(docker, tar, sourceFilepath, downloadPath, containerID); err != nil { glog.V(3).Infof("unable to download and extract '%s' ... continuing", metadataFilename) return nil } // open the file filePath := filepath.Join(downloadPath, metadataFilename) fd, err := os.Open(filePath) if fd == nil || err != nil { return fmt.Errorf("unable to open file '%s' : %v", downloadPath, err) } defer fd.Close() // read the file to a string str, err := ioutil.ReadAll(fd) if err != nil { return fmt.Errorf("error reading file '%s' in to a string: %v", filePath, err) } glog.V(3).Infof("new Labels File contents : \n%s\n", str) // string into a map var data map[string]interface{} if err = json.Unmarshal([]byte(str), &data); err != nil { return fmt.Errorf("JSON Unmarshal Error with '%s' file : %v", metadataFilename, err) } // update newLabels[] labels := data["labels"] for _, l := range labels.([]interface{}) { for k, v := range l.(map[string]interface{}) { builder.newLabels[k] = v.(string) } } return nil }
[ "func", "checkAndGetNewLabels", "(", "builder", "*", "STI", ",", "docker", "dockerpkg", ".", "Docker", ",", "tar", "s2itar", ".", "Tar", ",", "containerID", "string", ")", "error", "{", "glog", ".", "V", "(", "3", ")", ".", "Infof", "(", "\"", "\"", ")", "\n\n", "// metadata filename and its path inside the container", "metadataFilename", ":=", "\"", "\"", "\n", "sourceFilepath", ":=", "filepath", ".", "Join", "(", "\"", "\"", ",", "metadataFilename", ")", "\n\n", "// create the 'downloadPath' folder if it doesn't exist", "downloadPath", ":=", "filepath", ".", "Join", "(", "builder", ".", "config", ".", "WorkingDir", ",", "\"", "\"", ")", "\n", "glog", ".", "V", "(", "3", ")", ".", "Infof", "(", "\"", "\"", ",", "downloadPath", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "downloadPath", ",", "0700", ")", ";", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "downloadPath", ",", "metadataFilename", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "// download & extract the file from container", "if", "_", ",", "err", ":=", "downloadAndExtractFileFromContainer", "(", "docker", ",", "tar", ",", "sourceFilepath", ",", "downloadPath", ",", "containerID", ")", ";", "err", "!=", "nil", "{", "glog", ".", "V", "(", "3", ")", ".", "Infof", "(", "\"", "\"", ",", "metadataFilename", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// open the file", "filePath", ":=", "filepath", ".", "Join", "(", "downloadPath", ",", "metadataFilename", ")", "\n", "fd", ",", "err", ":=", "os", ".", "Open", "(", "filePath", ")", "\n", "if", "fd", "==", "nil", "||", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "downloadPath", ",", "err", ")", "\n", "}", "\n", "defer", "fd", ".", "Close", "(", ")", "\n\n", "// read the file to a string", "str", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "fd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filePath", ",", "err", ")", "\n", "}", "\n", "glog", ".", "V", "(", "3", ")", ".", "Infof", "(", "\"", "\\n", "\\n", "\"", ",", "str", ")", "\n\n", "// string into a map", "var", "data", "map", "[", "string", "]", "interface", "{", "}", "\n\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "str", ")", ",", "&", "data", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "metadataFilename", ",", "err", ")", "\n", "}", "\n\n", "// update newLabels[]", "labels", ":=", "data", "[", "\"", "\"", "]", "\n", "for", "_", ",", "l", ":=", "range", "labels", ".", "(", "[", "]", "interface", "{", "}", ")", "{", "for", "k", ",", "v", ":=", "range", "l", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "builder", ".", "newLabels", "[", "k", "]", "=", "v", ".", "(", "string", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// check for new labels and apply to the output image.
[ "check", "for", "new", "labels", "and", "apply", "to", "the", "output", "image", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/postexecutorstep.go#L522-L574
train