id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
162,000 | 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",
"(",
")",
"{",
"ret... | // Load a single message file | [
"Load",
"a",
"single",
"message",
"file"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/i18n.go#L142-L171 |
162,001 | 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",
... | // 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",
"qualit... | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/i18n.go#L225-L231 |
162,002 | 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",
"+",
"\"",
"\"",
")",
... | // 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 |
162,003 | 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",
... | // 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",
"li... | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/terminal_format.go#L203-L235 |
162,004 | 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",
"]",
... | // 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 |
162,005 | 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",
... | // 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"... | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/errors.go#L36-L70 |
162,006 | 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",... | // 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 |
162,007 | 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",
".",... | // 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 |
162,008 | 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",
... | // 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",
... | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/errors.go#L128-L155 |
162,009 | 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",
"(",
"... | // 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 |
162,010 | 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",
".",
"... | // The Log implementation | [
"The",
"Log",
"implementation"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/wrap_handlers.go#L35-L37 |
162,011 | 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"... | // 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",... | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/wrap_handlers.go#L55-L70 |
162,012 | 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",
"("... | // 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 |
162,013 | 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",... | // 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 |
162,014 | 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",
"... | // 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 |
162,015 | 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",
... | // Use built in rolling function | [
"Use",
"built",
"in",
"rolling",
"function"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/logger/composite_multihandler.go#L105-L114 |
162,016 | 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 |
162,017 | 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",
"(",
"\"",
"\"",... | // Prepare the headers | [
"Prepare",
"the",
"headers"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L101-L127 |
162,018 | 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",
... | // Write the headers | [
"Write",
"the",
"headers"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L130-L137 |
162,019 | 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... | // Close the writer | [
"Close",
"the",
"writer"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L140-L163 |
162,020 | 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 ha... | // Write to the underling buffer | [
"Write",
"to",
"the",
"underling",
"buffer"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L166-L191 |
162,021 | 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",
"(",
"\"",
"\"",
","... | // 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 |
162,022 | 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 |
162,023 | 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",
","... | // Delete this key | [
"Delete",
"this",
"key"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L328-L334 |
162,024 | 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",
"}",
"... | // Get this key | [
"Get",
"this",
"key"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L337-L348 |
162,025 | 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... | // Get all header keys | [
"Get",
"all",
"header",
"keys"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L351-L370 |
162,026 | 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",
"=... | // Set the status | [
"Set",
"the",
"status"
] | a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e | https://github.com/revel/revel/blob/a3d7a7c23ca885cc5036d3641ede49ce4a14ee2e/compress.go#L373-L379 |
162,027 | 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",
".... | // 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 |
162,028 | 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",
"."... | // 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 |
162,029 | 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",
"!... | // 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 |
162,030 | 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 |
162,031 | 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",
... | // 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 |
162,032 | 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.",
"... | // 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 |
162,033 | 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 |
162,034 | 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 |
162,035 | 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",
".",
"... | // 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 |
162,036 | 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",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"... | // 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 |
162,037 | 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",
",",
... | // 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",
"t... | 2ba8a349386aff03c26729096b0225a691355fe9 | https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/sti.go#L98-L183 |
162,038 | 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 |
162,039 | 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",
".",
... | // 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 |
162,040 | 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",
",",
"co... | // 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 |
162,041 | 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",
... | // 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",
"-",
... | 2ba8a349386aff03c26729096b0225a691355fe9 | https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/sti.go#L474-L500 |
162,042 | 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"... | // 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 |
162,043 | 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",
"(... | // 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",
"ensur... | 2ba8a349386aff03c26729096b0225a691355fe9 | https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/sti/sti.go#L801-L814 |
162,044 | 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",
... | // 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 |
162,045 | 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"... | // 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 |
162,046 | 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",
"(",
"\"",
"\"",
... | // 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 |
162,047 | 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",
":=",
"... | // 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 |
162,048 | 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"... | // 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 |
162,049 | 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"... | // 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 |
162,050 | 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",
".",
"... | // 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 |
162,051 | 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",
... | // 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 |
162,052 | 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",
")",
"Instal... | // 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 |
162,053 | 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",
... | // 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... | 2ba8a349386aff03c26729096b0225a691355fe9 | https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/install.go#L225-L238 |
162,054 | 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",
"{",
"}",
"\... | // 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 |
162,055 | 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",
",",
"cons... | // 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 |
162,056 | 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"... | // 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 |
162,057 | 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",
"&",
"DockerR... | // 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 |
162,058 | 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",
",",
"ou... | // 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 |
162,059 | 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",
"(",
... | // 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 |
162,060 | 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",
"{",... | // 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 |
162,061 | 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",
":=",
... | // 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 |
162,062 | 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",
".",
"B... | // 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 |
162,063 | 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",
".",
"Worki... | // 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 |
162,064 | 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",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"const... | // 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 |
162,065 | 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",
":",... | // 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 |
162,066 | 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",
"r... | // 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 |
162,067 | 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",
".",
"... | // 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 |
162,068 | 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",
"... | // 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 |
162,069 | 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",
"(",
"... | // 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 |
162,070 | 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... | // 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 |
162,071 | 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",
".",
... | // 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 |
162,072 | 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",
".",
"Usern... | // 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 |
162,073 | 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",
"{",
... | // 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 |
162,074 | 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",
... | // 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 |
162,075 | 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",
")",
"... | // 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 |
162,076 | 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"... | // 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 |
162,077 | 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... | // 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 |
162,078 | 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",
"!",
"glo... | // 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 |
162,079 | 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",
"(... | // 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 |
162,080 | 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",
... | // 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 |
162,081 | 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",
".",
"ContainerRemoveOption... | // 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 |
162,082 | 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",
"(... | // KillContainer kills a container. | [
"KillContainer",
"kills",
"a",
"container",
"."
] | 2ba8a349386aff03c26729096b0225a691355fe9 | https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L621-L625 |
162,083 | 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",
".",
"InspectIma... | // 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 |
162,084 | 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, _ :=... | // 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 |
162,085 | 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",
"r... | // 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 |
162,086 | 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",... | // 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 |
162,087 | 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",
"{",
"r... | // 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 |
162,088 | 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",
")",
"\... | // 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 |
162,089 | 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",
"}"... | // 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 |
162,090 | 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",
",",
... | // 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",
"HijackedRe... | 2ba8a349386aff03c26729096b0225a691355fe9 | https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/docker/docker.go#L859-L896 |
162,091 | 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",
")",
"\... | // 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 |
162,092 | 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",
"... | // 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 |
162,093 | 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",
".",
... | // 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 |
162,094 | 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",
... | // 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 |
162,095 | 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... | // 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 |
162,096 | 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",
"*",
"c... | // 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 |
162,097 | 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) Firs... | // 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 |
162,098 | 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",
"(",
"con... | // 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 |
162,099 | 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",
"(",
"\"",
"\"",
... | // 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.