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
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
17,900 |
hhkbp2/go-logging
|
logger.go
|
NewManager
|
func NewManager(logger Logger) *Manager {
return &Manager{
root: logger,
loggers: make(map[string]Node),
loggerMaker: defaultLoggerMaker,
}
}
|
go
|
func NewManager(logger Logger) *Manager {
return &Manager{
root: logger,
loggers: make(map[string]Node),
loggerMaker: defaultLoggerMaker,
}
}
|
[
"func",
"NewManager",
"(",
"logger",
"Logger",
")",
"*",
"Manager",
"{",
"return",
"&",
"Manager",
"{",
"root",
":",
"logger",
",",
"loggers",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"Node",
")",
",",
"loggerMaker",
":",
"defaultLoggerMaker",
",",
"}",
"\n",
"}"
] |
// Initialize the manager with the root node of the logger hierarchy.
|
[
"Initialize",
"the",
"manager",
"with",
"the",
"root",
"node",
"of",
"the",
"logger",
"hierarchy",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/logger.go#L552-L558
|
17,901 |
hhkbp2/go-logging
|
logger.go
|
SetLoggerMaker
|
func (self *Manager) SetLoggerMaker(maker LoggerMaker) {
self.lock.Lock()
defer self.lock.Unlock()
self.loggerMaker = maker
}
|
go
|
func (self *Manager) SetLoggerMaker(maker LoggerMaker) {
self.lock.Lock()
defer self.lock.Unlock()
self.loggerMaker = maker
}
|
[
"func",
"(",
"self",
"*",
"Manager",
")",
"SetLoggerMaker",
"(",
"maker",
"LoggerMaker",
")",
"{",
"self",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"self",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"self",
".",
"loggerMaker",
"=",
"maker",
"\n",
"}"
] |
// Set the logger maker to be used when instantiating
// a logger with this manager.
|
[
"Set",
"the",
"logger",
"maker",
"to",
"be",
"used",
"when",
"instantiating",
"a",
"logger",
"with",
"this",
"manager",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/logger.go#L562-L566
|
17,902 |
hhkbp2/go-logging
|
logger.go
|
fixupParents
|
func (self *Manager) fixupParents(logger Logger) {
name := logger.GetName()
index := strings.LastIndex(name, ".")
var parent Logger
for (index > 0) && (parent == nil) {
parentStr := name[:index]
node, ok := self.loggers[parentStr]
if !ok {
self.loggers[parentStr] = NewPlaceHolder(logger)
} else {
switch node.Type() {
case NodePlaceHolder:
placeHolder, _ := node.(*PlaceHolder)
placeHolder.Append(logger)
case NodeLogger:
parent = logger
default:
panic("invalid node type")
}
}
index = strings.LastIndex(parentStr, ".")
}
if parent == nil {
parent = root
}
logger.SetParent(parent)
}
|
go
|
func (self *Manager) fixupParents(logger Logger) {
name := logger.GetName()
index := strings.LastIndex(name, ".")
var parent Logger
for (index > 0) && (parent == nil) {
parentStr := name[:index]
node, ok := self.loggers[parentStr]
if !ok {
self.loggers[parentStr] = NewPlaceHolder(logger)
} else {
switch node.Type() {
case NodePlaceHolder:
placeHolder, _ := node.(*PlaceHolder)
placeHolder.Append(logger)
case NodeLogger:
parent = logger
default:
panic("invalid node type")
}
}
index = strings.LastIndex(parentStr, ".")
}
if parent == nil {
parent = root
}
logger.SetParent(parent)
}
|
[
"func",
"(",
"self",
"*",
"Manager",
")",
"fixupParents",
"(",
"logger",
"Logger",
")",
"{",
"name",
":=",
"logger",
".",
"GetName",
"(",
")",
"\n",
"index",
":=",
"strings",
".",
"LastIndex",
"(",
"name",
",",
"\"",
"\"",
")",
"\n",
"var",
"parent",
"Logger",
"\n",
"for",
"(",
"index",
">",
"0",
")",
"&&",
"(",
"parent",
"==",
"nil",
")",
"{",
"parentStr",
":=",
"name",
"[",
":",
"index",
"]",
"\n",
"node",
",",
"ok",
":=",
"self",
".",
"loggers",
"[",
"parentStr",
"]",
"\n",
"if",
"!",
"ok",
"{",
"self",
".",
"loggers",
"[",
"parentStr",
"]",
"=",
"NewPlaceHolder",
"(",
"logger",
")",
"\n",
"}",
"else",
"{",
"switch",
"node",
".",
"Type",
"(",
")",
"{",
"case",
"NodePlaceHolder",
":",
"placeHolder",
",",
"_",
":=",
"node",
".",
"(",
"*",
"PlaceHolder",
")",
"\n",
"placeHolder",
".",
"Append",
"(",
"logger",
")",
"\n",
"case",
"NodeLogger",
":",
"parent",
"=",
"logger",
"\n",
"default",
":",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"index",
"=",
"strings",
".",
"LastIndex",
"(",
"parentStr",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"parent",
"==",
"nil",
"{",
"parent",
"=",
"root",
"\n",
"}",
"\n",
"logger",
".",
"SetParent",
"(",
"parent",
")",
"\n",
"}"
] |
// Ensure that there are either loggers or placeholders all the way from
// the specified logger to the root of the logger hierarchy.
|
[
"Ensure",
"that",
"there",
"are",
"either",
"loggers",
"or",
"placeholders",
"all",
"the",
"way",
"from",
"the",
"specified",
"logger",
"to",
"the",
"root",
"of",
"the",
"logger",
"hierarchy",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/logger.go#L606-L632
|
17,903 |
hhkbp2/go-logging
|
logger.go
|
fixupChildren
|
func (self *Manager) fixupChildren(placeHolder *PlaceHolder, logger Logger) {
name := logger.GetName()
for e := placeHolder.Loggers.Front(); e != nil; e = e.Next() {
l, _ := e.Value.(Logger)
parent := l.GetParent()
if !strings.HasPrefix(parent.GetName(), name) {
logger.SetParent(parent)
l.SetParent(logger)
}
}
}
|
go
|
func (self *Manager) fixupChildren(placeHolder *PlaceHolder, logger Logger) {
name := logger.GetName()
for e := placeHolder.Loggers.Front(); e != nil; e = e.Next() {
l, _ := e.Value.(Logger)
parent := l.GetParent()
if !strings.HasPrefix(parent.GetName(), name) {
logger.SetParent(parent)
l.SetParent(logger)
}
}
}
|
[
"func",
"(",
"self",
"*",
"Manager",
")",
"fixupChildren",
"(",
"placeHolder",
"*",
"PlaceHolder",
",",
"logger",
"Logger",
")",
"{",
"name",
":=",
"logger",
".",
"GetName",
"(",
")",
"\n",
"for",
"e",
":=",
"placeHolder",
".",
"Loggers",
".",
"Front",
"(",
")",
";",
"e",
"!=",
"nil",
";",
"e",
"=",
"e",
".",
"Next",
"(",
")",
"{",
"l",
",",
"_",
":=",
"e",
".",
"Value",
".",
"(",
"Logger",
")",
"\n",
"parent",
":=",
"l",
".",
"GetParent",
"(",
")",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"parent",
".",
"GetName",
"(",
")",
",",
"name",
")",
"{",
"logger",
".",
"SetParent",
"(",
"parent",
")",
"\n",
"l",
".",
"SetParent",
"(",
"logger",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Ensure that children of the PlaceHolder placeHolder are connected to the
// specified logger.
|
[
"Ensure",
"that",
"children",
"of",
"the",
"PlaceHolder",
"placeHolder",
"are",
"connected",
"to",
"the",
"specified",
"logger",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/logger.go#L636-L646
|
17,904 |
hhkbp2/go-logging
|
record.go
|
NewLogRecord
|
func NewLogRecord(
name string,
level LogLevelType,
pathName string,
fileName string,
lineNo uint32,
funcName string,
format string,
useFormat bool,
args []interface{}) *LogRecord {
return &LogRecord{
CreatedTime: time.Now(),
Name: name,
Level: level,
PathName: pathName,
FileName: fileName,
LineNo: lineNo,
FuncName: funcName,
Format: format,
UseFormat: useFormat,
Args: args,
Message: "",
}
}
|
go
|
func NewLogRecord(
name string,
level LogLevelType,
pathName string,
fileName string,
lineNo uint32,
funcName string,
format string,
useFormat bool,
args []interface{}) *LogRecord {
return &LogRecord{
CreatedTime: time.Now(),
Name: name,
Level: level,
PathName: pathName,
FileName: fileName,
LineNo: lineNo,
FuncName: funcName,
Format: format,
UseFormat: useFormat,
Args: args,
Message: "",
}
}
|
[
"func",
"NewLogRecord",
"(",
"name",
"string",
",",
"level",
"LogLevelType",
",",
"pathName",
"string",
",",
"fileName",
"string",
",",
"lineNo",
"uint32",
",",
"funcName",
"string",
",",
"format",
"string",
",",
"useFormat",
"bool",
",",
"args",
"[",
"]",
"interface",
"{",
"}",
")",
"*",
"LogRecord",
"{",
"return",
"&",
"LogRecord",
"{",
"CreatedTime",
":",
"time",
".",
"Now",
"(",
")",
",",
"Name",
":",
"name",
",",
"Level",
":",
"level",
",",
"PathName",
":",
"pathName",
",",
"FileName",
":",
"fileName",
",",
"LineNo",
":",
"lineNo",
",",
"FuncName",
":",
"funcName",
",",
"Format",
":",
"format",
",",
"UseFormat",
":",
"useFormat",
",",
"Args",
":",
"args",
",",
"Message",
":",
"\"",
"\"",
",",
"}",
"\n",
"}"
] |
// Initialize a logging record with interesting information.
|
[
"Initialize",
"a",
"logging",
"record",
"with",
"interesting",
"information",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/record.go#L32-L56
|
17,905 |
hhkbp2/go-logging
|
record.go
|
String
|
func (self *LogRecord) String() string {
return fmt.Sprintf("<LogRecord: %s, %s, %s, %d, \"%s\">",
self.Name, self.Level, self.PathName, self.LineNo, self.Message)
}
|
go
|
func (self *LogRecord) String() string {
return fmt.Sprintf("<LogRecord: %s, %s, %s, %d, \"%s\">",
self.Name, self.Level, self.PathName, self.LineNo, self.Message)
}
|
[
"func",
"(",
"self",
"*",
"LogRecord",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"self",
".",
"Name",
",",
"self",
".",
"Level",
",",
"self",
".",
"PathName",
",",
"self",
".",
"LineNo",
",",
"self",
".",
"Message",
")",
"\n",
"}"
] |
// Return the string representation for this LogRecord.
|
[
"Return",
"the",
"string",
"representation",
"for",
"this",
"LogRecord",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/record.go#L59-L62
|
17,906 |
hhkbp2/go-logging
|
record.go
|
GetMessage
|
func (self *LogRecord) GetMessage() string {
if len(self.Message) == 0 {
if self.UseFormat {
self.Message = fmt.Sprintf(self.Format, self.Args...)
} else {
self.Message = fmt.Sprint(self.Args...)
}
}
return self.Message
}
|
go
|
func (self *LogRecord) GetMessage() string {
if len(self.Message) == 0 {
if self.UseFormat {
self.Message = fmt.Sprintf(self.Format, self.Args...)
} else {
self.Message = fmt.Sprint(self.Args...)
}
}
return self.Message
}
|
[
"func",
"(",
"self",
"*",
"LogRecord",
")",
"GetMessage",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"self",
".",
"Message",
")",
"==",
"0",
"{",
"if",
"self",
".",
"UseFormat",
"{",
"self",
".",
"Message",
"=",
"fmt",
".",
"Sprintf",
"(",
"self",
".",
"Format",
",",
"self",
".",
"Args",
"...",
")",
"\n",
"}",
"else",
"{",
"self",
".",
"Message",
"=",
"fmt",
".",
"Sprint",
"(",
"self",
".",
"Args",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"self",
".",
"Message",
"\n",
"}"
] |
// Return the message for this LogRecord.
// The message is composed of the Message and any user-supplied arguments.
|
[
"Return",
"the",
"message",
"for",
"this",
"LogRecord",
".",
"The",
"message",
"is",
"composed",
"of",
"the",
"Message",
"and",
"any",
"user",
"-",
"supplied",
"arguments",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/record.go#L66-L75
|
17,907 |
hhkbp2/go-logging
|
handler_stream.go
|
NewStreamHandler
|
func NewStreamHandler(
name string, level LogLevelType, stream Stream) *StreamHandler {
object := &StreamHandler{
BaseHandler: NewBaseHandler(name, level),
stream: stream,
}
Closer.AddHandler(object)
return object
}
|
go
|
func NewStreamHandler(
name string, level LogLevelType, stream Stream) *StreamHandler {
object := &StreamHandler{
BaseHandler: NewBaseHandler(name, level),
stream: stream,
}
Closer.AddHandler(object)
return object
}
|
[
"func",
"NewStreamHandler",
"(",
"name",
"string",
",",
"level",
"LogLevelType",
",",
"stream",
"Stream",
")",
"*",
"StreamHandler",
"{",
"object",
":=",
"&",
"StreamHandler",
"{",
"BaseHandler",
":",
"NewBaseHandler",
"(",
"name",
",",
"level",
")",
",",
"stream",
":",
"stream",
",",
"}",
"\n",
"Closer",
".",
"AddHandler",
"(",
"object",
")",
"\n",
"return",
"object",
"\n",
"}"
] |
// Initialize a stream handler with name, logging level and underlying stream.
|
[
"Initialize",
"a",
"stream",
"handler",
"with",
"name",
"logging",
"level",
"and",
"underlying",
"stream",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/handler_stream.go#L24-L33
|
17,908 |
hhkbp2/go-logging
|
handler_stream.go
|
Emit2
|
func (self *StreamHandler) Emit2(
handler Handler, record *LogRecord) error {
message := handler.Format(record)
if err := self.stream.Write(message); err != nil {
return err
}
return nil
}
|
go
|
func (self *StreamHandler) Emit2(
handler Handler, record *LogRecord) error {
message := handler.Format(record)
if err := self.stream.Write(message); err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"self",
"*",
"StreamHandler",
")",
"Emit2",
"(",
"handler",
"Handler",
",",
"record",
"*",
"LogRecord",
")",
"error",
"{",
"message",
":=",
"handler",
".",
"Format",
"(",
"record",
")",
"\n",
"if",
"err",
":=",
"self",
".",
"stream",
".",
"Write",
"(",
"message",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// A helper function to emit a record.
// If a formatter is specified, it is used to format the record.
// The record is then written to the stream with a trailing newline.
|
[
"A",
"helper",
"function",
"to",
"emit",
"a",
"record",
".",
"If",
"a",
"formatter",
"is",
"specified",
"it",
"is",
"used",
"to",
"format",
"the",
"record",
".",
"The",
"record",
"is",
"then",
"written",
"to",
"the",
"stream",
"with",
"a",
"trailing",
"newline",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/handler_stream.go#L53-L61
|
17,909 |
hhkbp2/go-logging
|
handler_null.go
|
NewNullHandler
|
func NewNullHandler() *NullHandler {
object := &NullHandler{
BaseHandler: NewBaseHandler("", LevelNotset),
}
Closer.AddHandler(object)
return object
}
|
go
|
func NewNullHandler() *NullHandler {
object := &NullHandler{
BaseHandler: NewBaseHandler("", LevelNotset),
}
Closer.AddHandler(object)
return object
}
|
[
"func",
"NewNullHandler",
"(",
")",
"*",
"NullHandler",
"{",
"object",
":=",
"&",
"NullHandler",
"{",
"BaseHandler",
":",
"NewBaseHandler",
"(",
"\"",
"\"",
",",
"LevelNotset",
")",
",",
"}",
"\n",
"Closer",
".",
"AddHandler",
"(",
"object",
")",
"\n",
"return",
"object",
"\n",
"}"
] |
// Initialize a NullHandler.
|
[
"Initialize",
"a",
"NullHandler",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/handler_null.go#L15-L21
|
17,910 |
hhkbp2/go-logging
|
formatter.go
|
initFormatRegexp
|
func initFormatRegexp() *regexp.Regexp {
var buf bytes.Buffer
buf.WriteString("(%(?:%")
for attr, _ := range attrToFunc {
buf.WriteString("|")
buf.WriteString(regexp.QuoteMeta(attr[1:]))
}
buf.WriteString("))")
re := buf.String()
return regexp.MustCompile(re)
}
|
go
|
func initFormatRegexp() *regexp.Regexp {
var buf bytes.Buffer
buf.WriteString("(%(?:%")
for attr, _ := range attrToFunc {
buf.WriteString("|")
buf.WriteString(regexp.QuoteMeta(attr[1:]))
}
buf.WriteString("))")
re := buf.String()
return regexp.MustCompile(re)
}
|
[
"func",
"initFormatRegexp",
"(",
")",
"*",
"regexp",
".",
"Regexp",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"for",
"attr",
",",
"_",
":=",
"range",
"attrToFunc",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"regexp",
".",
"QuoteMeta",
"(",
"attr",
"[",
"1",
":",
"]",
")",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"re",
":=",
"buf",
".",
"String",
"(",
")",
"\n",
"return",
"regexp",
".",
"MustCompile",
"(",
"re",
")",
"\n",
"}"
] |
// Initialize global regexp for attribute matching.
|
[
"Initialize",
"global",
"regexp",
"for",
"attribute",
"matching",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/formatter.go#L57-L67
|
17,911 |
hhkbp2/go-logging
|
formatter.go
|
NewStandardFormatter
|
func NewStandardFormatter(format string, dateFormat string) *StandardFormatter {
toFormatTime := false
size := 0
f1 := func(match string) string {
if match == "%%" {
return "%"
}
if match == "%(asctime)s" {
toFormatTime = true
}
size++
return "%s"
}
strFormat := formatRe.ReplaceAllStringFunc(format, f1)
funs := make([]ExtractAttr, 0, size)
f2 := func(match string) string {
extractFunc, ok := attrToFunc[match]
if ok {
funs = append(funs, extractFunc)
}
return match
}
formatRe.ReplaceAllStringFunc(format, f2)
getFormatArgsFunc := func(record *LogRecord) []interface{} {
result := make([]interface{}, 0, len(funs))
for _, f := range funs {
result = append(result, f(record))
}
return result
}
var dateFormatter *strftime.Formatter
if toFormatTime {
dateFormatter = strftime.NewFormatter(dateFormat)
}
return &StandardFormatter{
format: format,
strFormat: strFormat + "\n",
getFormatArgsFunc: getFormatArgsFunc,
toFormatTime: toFormatTime,
dateFormat: dateFormat,
dateFormatter: dateFormatter,
}
}
|
go
|
func NewStandardFormatter(format string, dateFormat string) *StandardFormatter {
toFormatTime := false
size := 0
f1 := func(match string) string {
if match == "%%" {
return "%"
}
if match == "%(asctime)s" {
toFormatTime = true
}
size++
return "%s"
}
strFormat := formatRe.ReplaceAllStringFunc(format, f1)
funs := make([]ExtractAttr, 0, size)
f2 := func(match string) string {
extractFunc, ok := attrToFunc[match]
if ok {
funs = append(funs, extractFunc)
}
return match
}
formatRe.ReplaceAllStringFunc(format, f2)
getFormatArgsFunc := func(record *LogRecord) []interface{} {
result := make([]interface{}, 0, len(funs))
for _, f := range funs {
result = append(result, f(record))
}
return result
}
var dateFormatter *strftime.Formatter
if toFormatTime {
dateFormatter = strftime.NewFormatter(dateFormat)
}
return &StandardFormatter{
format: format,
strFormat: strFormat + "\n",
getFormatArgsFunc: getFormatArgsFunc,
toFormatTime: toFormatTime,
dateFormat: dateFormat,
dateFormatter: dateFormatter,
}
}
|
[
"func",
"NewStandardFormatter",
"(",
"format",
"string",
",",
"dateFormat",
"string",
")",
"*",
"StandardFormatter",
"{",
"toFormatTime",
":=",
"false",
"\n",
"size",
":=",
"0",
"\n",
"f1",
":=",
"func",
"(",
"match",
"string",
")",
"string",
"{",
"if",
"match",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"match",
"==",
"\"",
"\"",
"{",
"toFormatTime",
"=",
"true",
"\n",
"}",
"\n",
"size",
"++",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"strFormat",
":=",
"formatRe",
".",
"ReplaceAllStringFunc",
"(",
"format",
",",
"f1",
")",
"\n",
"funs",
":=",
"make",
"(",
"[",
"]",
"ExtractAttr",
",",
"0",
",",
"size",
")",
"\n",
"f2",
":=",
"func",
"(",
"match",
"string",
")",
"string",
"{",
"extractFunc",
",",
"ok",
":=",
"attrToFunc",
"[",
"match",
"]",
"\n",
"if",
"ok",
"{",
"funs",
"=",
"append",
"(",
"funs",
",",
"extractFunc",
")",
"\n",
"}",
"\n",
"return",
"match",
"\n",
"}",
"\n",
"formatRe",
".",
"ReplaceAllStringFunc",
"(",
"format",
",",
"f2",
")",
"\n",
"getFormatArgsFunc",
":=",
"func",
"(",
"record",
"*",
"LogRecord",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"result",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"0",
",",
"len",
"(",
"funs",
")",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"funs",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"f",
"(",
"record",
")",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}",
"\n",
"var",
"dateFormatter",
"*",
"strftime",
".",
"Formatter",
"\n",
"if",
"toFormatTime",
"{",
"dateFormatter",
"=",
"strftime",
".",
"NewFormatter",
"(",
"dateFormat",
")",
"\n",
"}",
"\n",
"return",
"&",
"StandardFormatter",
"{",
"format",
":",
"format",
",",
"strFormat",
":",
"strFormat",
"+",
"\"",
"\\n",
"\"",
",",
"getFormatArgsFunc",
":",
"getFormatArgsFunc",
",",
"toFormatTime",
":",
"toFormatTime",
",",
"dateFormat",
":",
"dateFormat",
",",
"dateFormatter",
":",
"dateFormatter",
",",
"}",
"\n",
"}"
] |
// Initialize the formatter with specified format strings.
// Allow for specialized date formatting with the dateFormat arguement.
|
[
"Initialize",
"the",
"formatter",
"with",
"specified",
"format",
"strings",
".",
"Allow",
"for",
"specialized",
"date",
"formatting",
"with",
"the",
"dateFormat",
"arguement",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/formatter.go#L112-L154
|
17,912 |
hhkbp2/go-logging
|
formatter.go
|
FormatAll
|
func (self *StandardFormatter) FormatAll(record *LogRecord) string {
return fmt.Sprintf(self.strFormat, self.getFormatArgsFunc(record)...)
}
|
go
|
func (self *StandardFormatter) FormatAll(record *LogRecord) string {
return fmt.Sprintf(self.strFormat, self.getFormatArgsFunc(record)...)
}
|
[
"func",
"(",
"self",
"*",
"StandardFormatter",
")",
"FormatAll",
"(",
"record",
"*",
"LogRecord",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"self",
".",
"strFormat",
",",
"self",
".",
"getFormatArgsFunc",
"(",
"record",
")",
"...",
")",
"\n",
"}"
] |
// Helper function using regexp to replace every valid format attribute string
// to the record's specific value.
|
[
"Helper",
"function",
"using",
"regexp",
"to",
"replace",
"every",
"valid",
"format",
"attribute",
"string",
"to",
"the",
"record",
"s",
"specific",
"value",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/formatter.go#L183-L185
|
17,913 |
hhkbp2/go-logging
|
formatter.go
|
Format
|
func (self *BufferingFormatter) Format(records []*LogRecord) string {
var buf bytes.Buffer
if len(records) > 0 {
buf.WriteString(self.FormatHeader(records))
for _, record := range records {
buf.WriteString(self.lineFormatter.Format(record))
}
buf.WriteString(self.FormatFooter(records))
}
return buf.String()
}
|
go
|
func (self *BufferingFormatter) Format(records []*LogRecord) string {
var buf bytes.Buffer
if len(records) > 0 {
buf.WriteString(self.FormatHeader(records))
for _, record := range records {
buf.WriteString(self.lineFormatter.Format(record))
}
buf.WriteString(self.FormatFooter(records))
}
return buf.String()
}
|
[
"func",
"(",
"self",
"*",
"BufferingFormatter",
")",
"Format",
"(",
"records",
"[",
"]",
"*",
"LogRecord",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"len",
"(",
"records",
")",
">",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"self",
".",
"FormatHeader",
"(",
"records",
")",
")",
"\n",
"for",
"_",
",",
"record",
":=",
"range",
"records",
"{",
"buf",
".",
"WriteString",
"(",
"self",
".",
"lineFormatter",
".",
"Format",
"(",
"record",
")",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"self",
".",
"FormatFooter",
"(",
"records",
")",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// Format the specified records and return the result as a a string.
|
[
"Format",
"the",
"specified",
"records",
"and",
"return",
"the",
"result",
"as",
"a",
"a",
"string",
"."
] |
65fcbf8cf388a708c9c36def03633ec62056d3f5
|
https://github.com/hhkbp2/go-logging/blob/65fcbf8cf388a708c9c36def03633ec62056d3f5/formatter.go#L210-L220
|
17,914 |
cgrates/fsock
|
fsock.go
|
NewFSock
|
func NewFSock(fsaddr, fspaswd string, reconnects int, eventHandlers map[string][]func(string, string), eventFilters map[string][]string, l *syslog.Writer, connId string) (fsock *FSock, err error) {
fsock = &FSock{
fsMutex: new(sync.RWMutex),
connId: connId,
fsaddress: fsaddr,
fspaswd: fspaswd,
eventHandlers: eventHandlers,
eventFilters: eventFilters,
backgroundChans: make(map[string]chan string),
cmdChan: make(chan string),
reconnects: reconnects,
delayFunc: DelayFunc(),
logger: l,
}
if err = fsock.Connect(); err != nil {
return nil, err
}
return
}
|
go
|
func NewFSock(fsaddr, fspaswd string, reconnects int, eventHandlers map[string][]func(string, string), eventFilters map[string][]string, l *syslog.Writer, connId string) (fsock *FSock, err error) {
fsock = &FSock{
fsMutex: new(sync.RWMutex),
connId: connId,
fsaddress: fsaddr,
fspaswd: fspaswd,
eventHandlers: eventHandlers,
eventFilters: eventFilters,
backgroundChans: make(map[string]chan string),
cmdChan: make(chan string),
reconnects: reconnects,
delayFunc: DelayFunc(),
logger: l,
}
if err = fsock.Connect(); err != nil {
return nil, err
}
return
}
|
[
"func",
"NewFSock",
"(",
"fsaddr",
",",
"fspaswd",
"string",
",",
"reconnects",
"int",
",",
"eventHandlers",
"map",
"[",
"string",
"]",
"[",
"]",
"func",
"(",
"string",
",",
"string",
")",
",",
"eventFilters",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"l",
"*",
"syslog",
".",
"Writer",
",",
"connId",
"string",
")",
"(",
"fsock",
"*",
"FSock",
",",
"err",
"error",
")",
"{",
"fsock",
"=",
"&",
"FSock",
"{",
"fsMutex",
":",
"new",
"(",
"sync",
".",
"RWMutex",
")",
",",
"connId",
":",
"connId",
",",
"fsaddress",
":",
"fsaddr",
",",
"fspaswd",
":",
"fspaswd",
",",
"eventHandlers",
":",
"eventHandlers",
",",
"eventFilters",
":",
"eventFilters",
",",
"backgroundChans",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"chan",
"string",
")",
",",
"cmdChan",
":",
"make",
"(",
"chan",
"string",
")",
",",
"reconnects",
":",
"reconnects",
",",
"delayFunc",
":",
"DelayFunc",
"(",
")",
",",
"logger",
":",
"l",
",",
"}",
"\n",
"if",
"err",
"=",
"fsock",
".",
"Connect",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Connects to FS and starts buffering input
|
[
"Connects",
"to",
"FS",
"and",
"starts",
"buffering",
"input"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L37-L55
|
17,915 |
cgrates/fsock
|
fsock.go
|
Connected
|
func (self *FSock) Connected() (ok bool) {
self.fsMutex.RLock()
ok = (self.conn != nil)
self.fsMutex.RUnlock()
return
}
|
go
|
func (self *FSock) Connected() (ok bool) {
self.fsMutex.RLock()
ok = (self.conn != nil)
self.fsMutex.RUnlock()
return
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"Connected",
"(",
")",
"(",
"ok",
"bool",
")",
"{",
"self",
".",
"fsMutex",
".",
"RLock",
"(",
")",
"\n",
"ok",
"=",
"(",
"self",
".",
"conn",
"!=",
"nil",
")",
"\n",
"self",
".",
"fsMutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// Connected checks if socket connected. Can be extended with pings
|
[
"Connected",
"checks",
"if",
"socket",
"connected",
".",
"Can",
"be",
"extended",
"with",
"pings"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L129-L134
|
17,916 |
cgrates/fsock
|
fsock.go
|
auth
|
func (self *FSock) auth() error {
self.send(fmt.Sprintf("auth %s\n\n", self.fspaswd))
if rply, err := self.readHeaders(); err != nil {
return err
} else if !strings.Contains(rply, "Reply-Text: +OK accepted") {
return fmt.Errorf("Unexpected auth reply received: <%s>", rply)
}
return nil
}
|
go
|
func (self *FSock) auth() error {
self.send(fmt.Sprintf("auth %s\n\n", self.fspaswd))
if rply, err := self.readHeaders(); err != nil {
return err
} else if !strings.Contains(rply, "Reply-Text: +OK accepted") {
return fmt.Errorf("Unexpected auth reply received: <%s>", rply)
}
return nil
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"auth",
"(",
")",
"error",
"{",
"self",
".",
"send",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"self",
".",
"fspaswd",
")",
")",
"\n",
"if",
"rply",
",",
"err",
":=",
"self",
".",
"readHeaders",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"!",
"strings",
".",
"Contains",
"(",
"rply",
",",
"\"",
"\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rply",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Auth to FS
|
[
"Auth",
"to",
"FS"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L188-L196
|
17,917 |
cgrates/fsock
|
fsock.go
|
SendCmd
|
func (self *FSock) SendCmd(cmdStr string) (string, error) {
return self.sendCmd(cmdStr + "\n")
}
|
go
|
func (self *FSock) SendCmd(cmdStr string) (string, error) {
return self.sendCmd(cmdStr + "\n")
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"SendCmd",
"(",
"cmdStr",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"self",
".",
"sendCmd",
"(",
"cmdStr",
"+",
"\"",
"\\n",
"\"",
")",
"\n",
"}"
] |
// Generic proxy for commands
|
[
"Generic",
"proxy",
"for",
"commands"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L212-L214
|
17,918 |
cgrates/fsock
|
fsock.go
|
SendApiCmd
|
func (self *FSock) SendApiCmd(cmdStr string) (string, error) {
return self.sendCmd("api " + cmdStr + "\n")
}
|
go
|
func (self *FSock) SendApiCmd(cmdStr string) (string, error) {
return self.sendCmd("api " + cmdStr + "\n")
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"SendApiCmd",
"(",
"cmdStr",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"self",
".",
"sendCmd",
"(",
"\"",
"\"",
"+",
"cmdStr",
"+",
"\"",
"\\n",
"\"",
")",
"\n",
"}"
] |
// Send API command
|
[
"Send",
"API",
"command"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L227-L229
|
17,919 |
cgrates/fsock
|
fsock.go
|
SendBgapiCmd
|
func (self *FSock) SendBgapiCmd(cmdStr string) (out chan string, err error) {
jobUuid := genUUID()
out = make(chan string)
self.fsMutex.Lock()
self.backgroundChans[jobUuid] = out
self.fsMutex.Unlock()
_, err = self.sendCmd(fmt.Sprintf("bgapi %s\nJob-UUID:%s\n", cmdStr, jobUuid))
if err != nil {
return nil, err
}
return
}
|
go
|
func (self *FSock) SendBgapiCmd(cmdStr string) (out chan string, err error) {
jobUuid := genUUID()
out = make(chan string)
self.fsMutex.Lock()
self.backgroundChans[jobUuid] = out
self.fsMutex.Unlock()
_, err = self.sendCmd(fmt.Sprintf("bgapi %s\nJob-UUID:%s\n", cmdStr, jobUuid))
if err != nil {
return nil, err
}
return
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"SendBgapiCmd",
"(",
"cmdStr",
"string",
")",
"(",
"out",
"chan",
"string",
",",
"err",
"error",
")",
"{",
"jobUuid",
":=",
"genUUID",
"(",
")",
"\n",
"out",
"=",
"make",
"(",
"chan",
"string",
")",
"\n\n",
"self",
".",
"fsMutex",
".",
"Lock",
"(",
")",
"\n",
"self",
".",
"backgroundChans",
"[",
"jobUuid",
"]",
"=",
"out",
"\n",
"self",
".",
"fsMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"_",
",",
"err",
"=",
"self",
".",
"sendCmd",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"cmdStr",
",",
"jobUuid",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Send BGAPI command
|
[
"Send",
"BGAPI",
"command"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L232-L245
|
17,920 |
cgrates/fsock
|
fsock.go
|
ReadEvents
|
func (self *FSock) ReadEvents() (err error) {
var opened bool
for {
if err, opened = <-self.errReadEvents; !opened {
return nil
} else if err == io.EOF { // Disconnected, try reconnect
if err = self.ReconnectIfNeeded(); err != nil {
break
}
}
}
return err
}
|
go
|
func (self *FSock) ReadEvents() (err error) {
var opened bool
for {
if err, opened = <-self.errReadEvents; !opened {
return nil
} else if err == io.EOF { // Disconnected, try reconnect
if err = self.ReconnectIfNeeded(); err != nil {
break
}
}
}
return err
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"ReadEvents",
"(",
")",
"(",
"err",
"error",
")",
"{",
"var",
"opened",
"bool",
"\n",
"for",
"{",
"if",
"err",
",",
"opened",
"=",
"<-",
"self",
".",
"errReadEvents",
";",
"!",
"opened",
"{",
"return",
"nil",
"\n",
"}",
"else",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"// Disconnected, try reconnect",
"if",
"err",
"=",
"self",
".",
"ReconnectIfNeeded",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// ReadEvents reads events from socket, attempt reconnect if disconnected
|
[
"ReadEvents",
"reads",
"events",
"from",
"socket",
"attempt",
"reconnect",
"if",
"disconnected"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L275-L287
|
17,921 |
cgrates/fsock
|
fsock.go
|
readHeaders
|
func (self *FSock) readHeaders() (header string, err error) {
bytesRead := make([]byte, 0)
var readLine []byte
for {
readLine, err = self.buffer.ReadBytes('\n')
if err != nil {
if self.logger != nil {
self.logger.Err(fmt.Sprintf("<FSock> Error reading headers: <%s>", err.Error()))
}
self.Disconnect()
return "", err
}
// No Error, add received to localread buffer
if len(bytes.TrimSpace(readLine)) == 0 {
break
}
bytesRead = append(bytesRead, readLine...)
}
return string(bytesRead), nil
}
|
go
|
func (self *FSock) readHeaders() (header string, err error) {
bytesRead := make([]byte, 0)
var readLine []byte
for {
readLine, err = self.buffer.ReadBytes('\n')
if err != nil {
if self.logger != nil {
self.logger.Err(fmt.Sprintf("<FSock> Error reading headers: <%s>", err.Error()))
}
self.Disconnect()
return "", err
}
// No Error, add received to localread buffer
if len(bytes.TrimSpace(readLine)) == 0 {
break
}
bytesRead = append(bytesRead, readLine...)
}
return string(bytesRead), nil
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"readHeaders",
"(",
")",
"(",
"header",
"string",
",",
"err",
"error",
")",
"{",
"bytesRead",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
")",
"\n",
"var",
"readLine",
"[",
"]",
"byte",
"\n\n",
"for",
"{",
"readLine",
",",
"err",
"=",
"self",
".",
"buffer",
".",
"ReadBytes",
"(",
"'\\n'",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"self",
".",
"logger",
"!=",
"nil",
"{",
"self",
".",
"logger",
".",
"Err",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"self",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"// No Error, add received to localread buffer",
"if",
"len",
"(",
"bytes",
".",
"TrimSpace",
"(",
"readLine",
")",
")",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"bytesRead",
"=",
"append",
"(",
"bytesRead",
",",
"readLine",
"...",
")",
"\n",
"}",
"\n",
"return",
"string",
"(",
"bytesRead",
")",
",",
"nil",
"\n",
"}"
] |
// Reads headers until delimiter reached
|
[
"Reads",
"headers",
"until",
"delimiter",
"reached"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L297-L317
|
17,922 |
cgrates/fsock
|
fsock.go
|
readBody
|
func (self *FSock) readBody(noBytes int) (body string, err error) {
bytesRead := make([]byte, noBytes)
var readByte byte
for i := 0; i < noBytes; i++ {
if readByte, err = self.buffer.ReadByte(); err != nil {
if self.logger != nil {
self.logger.Err(fmt.Sprintf("<FSock> Error reading message body: <%s>", err.Error()))
}
self.Disconnect()
return "", err
}
// No Error, add received to local read buffer
bytesRead[i] = readByte
}
return string(bytesRead), nil
}
|
go
|
func (self *FSock) readBody(noBytes int) (body string, err error) {
bytesRead := make([]byte, noBytes)
var readByte byte
for i := 0; i < noBytes; i++ {
if readByte, err = self.buffer.ReadByte(); err != nil {
if self.logger != nil {
self.logger.Err(fmt.Sprintf("<FSock> Error reading message body: <%s>", err.Error()))
}
self.Disconnect()
return "", err
}
// No Error, add received to local read buffer
bytesRead[i] = readByte
}
return string(bytesRead), nil
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"readBody",
"(",
"noBytes",
"int",
")",
"(",
"body",
"string",
",",
"err",
"error",
")",
"{",
"bytesRead",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"noBytes",
")",
"\n",
"var",
"readByte",
"byte",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"noBytes",
";",
"i",
"++",
"{",
"if",
"readByte",
",",
"err",
"=",
"self",
".",
"buffer",
".",
"ReadByte",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"self",
".",
"logger",
"!=",
"nil",
"{",
"self",
".",
"logger",
".",
"Err",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"self",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"// No Error, add received to local read buffer",
"bytesRead",
"[",
"i",
"]",
"=",
"readByte",
"\n",
"}",
"\n",
"return",
"string",
"(",
"bytesRead",
")",
",",
"nil",
"\n",
"}"
] |
// Reads the body from buffer, ln is given by content-length of headers
|
[
"Reads",
"the",
"body",
"from",
"buffer",
"ln",
"is",
"given",
"by",
"content",
"-",
"length",
"of",
"headers"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L320-L336
|
17,923 |
cgrates/fsock
|
fsock.go
|
readEvents
|
func (self *FSock) readEvents() {
for {
select {
case <-self.stopReadEvents:
return
default: // Unlock waiting here
}
hdr, body, err := self.readEvent()
if err != nil {
self.errReadEvents <- err
return
}
if strings.Contains(hdr, "api/response") {
self.cmdChan <- body
} else if strings.Contains(hdr, "command/reply") {
self.cmdChan <- headerVal(hdr, "Reply-Text")
} else if body != "" { // We got a body, could be event, try dispatching it
self.dispatchEvent(body)
}
}
}
|
go
|
func (self *FSock) readEvents() {
for {
select {
case <-self.stopReadEvents:
return
default: // Unlock waiting here
}
hdr, body, err := self.readEvent()
if err != nil {
self.errReadEvents <- err
return
}
if strings.Contains(hdr, "api/response") {
self.cmdChan <- body
} else if strings.Contains(hdr, "command/reply") {
self.cmdChan <- headerVal(hdr, "Reply-Text")
} else if body != "" { // We got a body, could be event, try dispatching it
self.dispatchEvent(body)
}
}
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"readEvents",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"self",
".",
"stopReadEvents",
":",
"return",
"\n",
"default",
":",
"// Unlock waiting here",
"}",
"\n",
"hdr",
",",
"body",
",",
"err",
":=",
"self",
".",
"readEvent",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"self",
".",
"errReadEvents",
"<-",
"err",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"hdr",
",",
"\"",
"\"",
")",
"{",
"self",
".",
"cmdChan",
"<-",
"body",
"\n",
"}",
"else",
"if",
"strings",
".",
"Contains",
"(",
"hdr",
",",
"\"",
"\"",
")",
"{",
"self",
".",
"cmdChan",
"<-",
"headerVal",
"(",
"hdr",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"body",
"!=",
"\"",
"\"",
"{",
"// We got a body, could be event, try dispatching it",
"self",
".",
"dispatchEvent",
"(",
"body",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Read events from network buffer, stop when exitChan is closed, report on errReadEvents on error and exit
// Receive exitChan and errReadEvents as parameters so we avoid concurrency on using self.
|
[
"Read",
"events",
"from",
"network",
"buffer",
"stop",
"when",
"exitChan",
"is",
"closed",
"report",
"on",
"errReadEvents",
"on",
"error",
"and",
"exit",
"Receive",
"exitChan",
"and",
"errReadEvents",
"as",
"parameters",
"so",
"we",
"avoid",
"concurrency",
"on",
"using",
"self",
"."
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L359-L379
|
17,924 |
cgrates/fsock
|
fsock.go
|
eventsPlain
|
func (self *FSock) eventsPlain(events []string) error {
// if len(events) == 0 {
// return nil
// }
eventsCmd := "event plain"
customEvents := ""
for _, ev := range events {
if ev == "ALL" {
eventsCmd = "event plain all"
break
}
if strings.HasPrefix(ev, "CUSTOM") {
customEvents += ev[6:] // will capture here also space between CUSTOM and event
continue
}
eventsCmd += " " + ev
}
if eventsCmd != "event plain all" {
eventsCmd += " BACKGROUND_JOB" // For bgapi
if len(customEvents) != 0 { // Add CUSTOM events subscribing in the end otherwise unexpected events are received
eventsCmd += " " + "CUSTOM" + customEvents
}
}
eventsCmd += "\n\n"
self.send(eventsCmd)
if rply, err := self.readHeaders(); err != nil {
return err
} else if !strings.Contains(rply, "Reply-Text: +OK") {
self.Disconnect()
return fmt.Errorf("Unexpected events-subscribe reply received: <%s>", rply)
}
return nil
}
|
go
|
func (self *FSock) eventsPlain(events []string) error {
// if len(events) == 0 {
// return nil
// }
eventsCmd := "event plain"
customEvents := ""
for _, ev := range events {
if ev == "ALL" {
eventsCmd = "event plain all"
break
}
if strings.HasPrefix(ev, "CUSTOM") {
customEvents += ev[6:] // will capture here also space between CUSTOM and event
continue
}
eventsCmd += " " + ev
}
if eventsCmd != "event plain all" {
eventsCmd += " BACKGROUND_JOB" // For bgapi
if len(customEvents) != 0 { // Add CUSTOM events subscribing in the end otherwise unexpected events are received
eventsCmd += " " + "CUSTOM" + customEvents
}
}
eventsCmd += "\n\n"
self.send(eventsCmd)
if rply, err := self.readHeaders(); err != nil {
return err
} else if !strings.Contains(rply, "Reply-Text: +OK") {
self.Disconnect()
return fmt.Errorf("Unexpected events-subscribe reply received: <%s>", rply)
}
return nil
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"eventsPlain",
"(",
"events",
"[",
"]",
"string",
")",
"error",
"{",
"// if len(events) == 0 {",
"// \treturn nil",
"// }",
"eventsCmd",
":=",
"\"",
"\"",
"\n",
"customEvents",
":=",
"\"",
"\"",
"\n",
"for",
"_",
",",
"ev",
":=",
"range",
"events",
"{",
"if",
"ev",
"==",
"\"",
"\"",
"{",
"eventsCmd",
"=",
"\"",
"\"",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"ev",
",",
"\"",
"\"",
")",
"{",
"customEvents",
"+=",
"ev",
"[",
"6",
":",
"]",
"// will capture here also space between CUSTOM and event",
"\n",
"continue",
"\n",
"}",
"\n",
"eventsCmd",
"+=",
"\"",
"\"",
"+",
"ev",
"\n",
"}",
"\n",
"if",
"eventsCmd",
"!=",
"\"",
"\"",
"{",
"eventsCmd",
"+=",
"\"",
"\"",
"// For bgapi",
"\n",
"if",
"len",
"(",
"customEvents",
")",
"!=",
"0",
"{",
"// Add CUSTOM events subscribing in the end otherwise unexpected events are received",
"eventsCmd",
"+=",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"customEvents",
"\n",
"}",
"\n",
"}",
"\n",
"eventsCmd",
"+=",
"\"",
"\\n",
"\\n",
"\"",
"\n",
"self",
".",
"send",
"(",
"eventsCmd",
")",
"\n",
"if",
"rply",
",",
"err",
":=",
"self",
".",
"readHeaders",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"!",
"strings",
".",
"Contains",
"(",
"rply",
",",
"\"",
"\"",
")",
"{",
"self",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rply",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Subscribe to events
|
[
"Subscribe",
"to",
"events"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L382-L414
|
17,925 |
cgrates/fsock
|
fsock.go
|
dispatchEvent
|
func (self *FSock) dispatchEvent(event string) {
eventName := headerVal(event, "Event-Name")
if eventName == "BACKGROUND_JOB" { // for bgapi BACKGROUND_JOB
go self.doBackgroudJob(event)
return
}
if eventName == "CUSTOM" {
eventSubclass := headerVal(event, "Event-Subclass")
if len(eventSubclass) != 0 {
eventName += " " + urlDecode(eventSubclass)
}
}
for _, handleName := range []string{eventName, "ALL"} {
if _, hasHandlers := self.eventHandlers[handleName]; hasHandlers {
// We have handlers, dispatch to all of them
for _, handlerFunc := range self.eventHandlers[handleName] {
go handlerFunc(event, self.connId)
}
return
}
}
if self.logger != nil {
fmt.Printf("No dispatcher, event name: %s, handlers: %+v\n", eventName, self.eventHandlers)
self.logger.Warning(fmt.Sprintf("<FSock> No dispatcher for event: <%+v>", event))
}
}
|
go
|
func (self *FSock) dispatchEvent(event string) {
eventName := headerVal(event, "Event-Name")
if eventName == "BACKGROUND_JOB" { // for bgapi BACKGROUND_JOB
go self.doBackgroudJob(event)
return
}
if eventName == "CUSTOM" {
eventSubclass := headerVal(event, "Event-Subclass")
if len(eventSubclass) != 0 {
eventName += " " + urlDecode(eventSubclass)
}
}
for _, handleName := range []string{eventName, "ALL"} {
if _, hasHandlers := self.eventHandlers[handleName]; hasHandlers {
// We have handlers, dispatch to all of them
for _, handlerFunc := range self.eventHandlers[handleName] {
go handlerFunc(event, self.connId)
}
return
}
}
if self.logger != nil {
fmt.Printf("No dispatcher, event name: %s, handlers: %+v\n", eventName, self.eventHandlers)
self.logger.Warning(fmt.Sprintf("<FSock> No dispatcher for event: <%+v>", event))
}
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"dispatchEvent",
"(",
"event",
"string",
")",
"{",
"eventName",
":=",
"headerVal",
"(",
"event",
",",
"\"",
"\"",
")",
"\n",
"if",
"eventName",
"==",
"\"",
"\"",
"{",
"// for bgapi BACKGROUND_JOB",
"go",
"self",
".",
"doBackgroudJob",
"(",
"event",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"eventName",
"==",
"\"",
"\"",
"{",
"eventSubclass",
":=",
"headerVal",
"(",
"event",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"eventSubclass",
")",
"!=",
"0",
"{",
"eventName",
"+=",
"\"",
"\"",
"+",
"urlDecode",
"(",
"eventSubclass",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"handleName",
":=",
"range",
"[",
"]",
"string",
"{",
"eventName",
",",
"\"",
"\"",
"}",
"{",
"if",
"_",
",",
"hasHandlers",
":=",
"self",
".",
"eventHandlers",
"[",
"handleName",
"]",
";",
"hasHandlers",
"{",
"// We have handlers, dispatch to all of them",
"for",
"_",
",",
"handlerFunc",
":=",
"range",
"self",
".",
"eventHandlers",
"[",
"handleName",
"]",
"{",
"go",
"handlerFunc",
"(",
"event",
",",
"self",
".",
"connId",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"self",
".",
"logger",
"!=",
"nil",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"eventName",
",",
"self",
".",
"eventHandlers",
")",
"\n",
"self",
".",
"logger",
".",
"Warning",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"event",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Dispatch events to handlers in async mode
|
[
"Dispatch",
"events",
"to",
"handlers",
"in",
"async",
"mode"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L437-L464
|
17,926 |
cgrates/fsock
|
fsock.go
|
doBackgroudJob
|
func (self *FSock) doBackgroudJob(event string) { // add mutex protection
evMap := EventToMap(event)
jobUuid, has := evMap["Job-UUID"]
if !has {
self.logger.Err("<FSock> BACKGROUND_JOB with no Job-UUID")
return
}
var out chan string
self.fsMutex.RLock()
out, has = self.backgroundChans[jobUuid]
self.fsMutex.RUnlock()
if !has {
self.logger.Err(fmt.Sprintf("<FSock> BACKGROUND_JOB with UUID %s lost!", jobUuid))
return // not a requested bgapi
}
self.fsMutex.Lock()
delete(self.backgroundChans, jobUuid)
self.fsMutex.Unlock()
out <- evMap[EventBodyTag]
}
|
go
|
func (self *FSock) doBackgroudJob(event string) { // add mutex protection
evMap := EventToMap(event)
jobUuid, has := evMap["Job-UUID"]
if !has {
self.logger.Err("<FSock> BACKGROUND_JOB with no Job-UUID")
return
}
var out chan string
self.fsMutex.RLock()
out, has = self.backgroundChans[jobUuid]
self.fsMutex.RUnlock()
if !has {
self.logger.Err(fmt.Sprintf("<FSock> BACKGROUND_JOB with UUID %s lost!", jobUuid))
return // not a requested bgapi
}
self.fsMutex.Lock()
delete(self.backgroundChans, jobUuid)
self.fsMutex.Unlock()
out <- evMap[EventBodyTag]
}
|
[
"func",
"(",
"self",
"*",
"FSock",
")",
"doBackgroudJob",
"(",
"event",
"string",
")",
"{",
"// add mutex protection",
"evMap",
":=",
"EventToMap",
"(",
"event",
")",
"\n",
"jobUuid",
",",
"has",
":=",
"evMap",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"has",
"{",
"self",
".",
"logger",
".",
"Err",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"var",
"out",
"chan",
"string",
"\n",
"self",
".",
"fsMutex",
".",
"RLock",
"(",
")",
"\n",
"out",
",",
"has",
"=",
"self",
".",
"backgroundChans",
"[",
"jobUuid",
"]",
"\n",
"self",
".",
"fsMutex",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"!",
"has",
"{",
"self",
".",
"logger",
".",
"Err",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"jobUuid",
")",
")",
"\n",
"return",
"// not a requested bgapi",
"\n",
"}",
"\n\n",
"self",
".",
"fsMutex",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"self",
".",
"backgroundChans",
",",
"jobUuid",
")",
"\n",
"self",
".",
"fsMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"out",
"<-",
"evMap",
"[",
"EventBodyTag",
"]",
"\n",
"}"
] |
// bgapi event lisen fuction
|
[
"bgapi",
"event",
"lisen",
"fuction"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L467-L489
|
17,927 |
cgrates/fsock
|
fsock.go
|
NewFSockPool
|
func NewFSockPool(maxFSocks int, fsaddr, fspasswd string, reconnects int, maxWaitConn time.Duration,
eventHandlers map[string][]func(string, string), eventFilters map[string][]string, l *syslog.Writer, connId string) (*FSockPool, error) {
pool := &FSockPool{
connId: connId,
fsAddr: fsaddr,
fsPasswd: fspasswd,
reconnects: reconnects,
maxWaitConn: maxWaitConn,
eventHandlers: eventHandlers,
eventFilters: eventFilters,
logger: l,
allowedConns: make(chan struct{}, maxFSocks),
fSocks: make(chan *FSock, maxFSocks),
}
for i := 0; i < maxFSocks; i++ {
pool.allowedConns <- struct{}{} // Empty initiate so we do not need to wait later when we pop
}
return pool, nil
}
|
go
|
func NewFSockPool(maxFSocks int, fsaddr, fspasswd string, reconnects int, maxWaitConn time.Duration,
eventHandlers map[string][]func(string, string), eventFilters map[string][]string, l *syslog.Writer, connId string) (*FSockPool, error) {
pool := &FSockPool{
connId: connId,
fsAddr: fsaddr,
fsPasswd: fspasswd,
reconnects: reconnects,
maxWaitConn: maxWaitConn,
eventHandlers: eventHandlers,
eventFilters: eventFilters,
logger: l,
allowedConns: make(chan struct{}, maxFSocks),
fSocks: make(chan *FSock, maxFSocks),
}
for i := 0; i < maxFSocks; i++ {
pool.allowedConns <- struct{}{} // Empty initiate so we do not need to wait later when we pop
}
return pool, nil
}
|
[
"func",
"NewFSockPool",
"(",
"maxFSocks",
"int",
",",
"fsaddr",
",",
"fspasswd",
"string",
",",
"reconnects",
"int",
",",
"maxWaitConn",
"time",
".",
"Duration",
",",
"eventHandlers",
"map",
"[",
"string",
"]",
"[",
"]",
"func",
"(",
"string",
",",
"string",
")",
",",
"eventFilters",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"l",
"*",
"syslog",
".",
"Writer",
",",
"connId",
"string",
")",
"(",
"*",
"FSockPool",
",",
"error",
")",
"{",
"pool",
":=",
"&",
"FSockPool",
"{",
"connId",
":",
"connId",
",",
"fsAddr",
":",
"fsaddr",
",",
"fsPasswd",
":",
"fspasswd",
",",
"reconnects",
":",
"reconnects",
",",
"maxWaitConn",
":",
"maxWaitConn",
",",
"eventHandlers",
":",
"eventHandlers",
",",
"eventFilters",
":",
"eventFilters",
",",
"logger",
":",
"l",
",",
"allowedConns",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"maxFSocks",
")",
",",
"fSocks",
":",
"make",
"(",
"chan",
"*",
"FSock",
",",
"maxFSocks",
")",
",",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"maxFSocks",
";",
"i",
"++",
"{",
"pool",
".",
"allowedConns",
"<-",
"struct",
"{",
"}",
"{",
"}",
"// Empty initiate so we do not need to wait later when we pop",
"\n",
"}",
"\n",
"return",
"pool",
",",
"nil",
"\n",
"}"
] |
// Instantiates a new FSockPool
|
[
"Instantiates",
"a",
"new",
"FSockPool"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/fsock.go#L492-L510
|
17,928 |
cgrates/fsock
|
utils.go
|
FSEventStrToMap
|
func FSEventStrToMap(fsevstr string, headers []string) map[string]string {
fsevent := make(map[string]string)
filtered := (len(headers) != 0)
for _, strLn := range strings.Split(fsevstr, "\n") {
if hdrVal := strings.SplitN(strLn, ": ", 2); len(hdrVal) == 2 {
if filtered && isSliceMember(headers, hdrVal[0]) {
continue // Loop again since we only work on filtered fields
}
fsevent[hdrVal[0]] = urlDecode(strings.TrimSpace(strings.TrimRight(hdrVal[1], "\n")))
}
}
return fsevent
}
|
go
|
func FSEventStrToMap(fsevstr string, headers []string) map[string]string {
fsevent := make(map[string]string)
filtered := (len(headers) != 0)
for _, strLn := range strings.Split(fsevstr, "\n") {
if hdrVal := strings.SplitN(strLn, ": ", 2); len(hdrVal) == 2 {
if filtered && isSliceMember(headers, hdrVal[0]) {
continue // Loop again since we only work on filtered fields
}
fsevent[hdrVal[0]] = urlDecode(strings.TrimSpace(strings.TrimRight(hdrVal[1], "\n")))
}
}
return fsevent
}
|
[
"func",
"FSEventStrToMap",
"(",
"fsevstr",
"string",
",",
"headers",
"[",
"]",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"fsevent",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"filtered",
":=",
"(",
"len",
"(",
"headers",
")",
"!=",
"0",
")",
"\n",
"for",
"_",
",",
"strLn",
":=",
"range",
"strings",
".",
"Split",
"(",
"fsevstr",
",",
"\"",
"\\n",
"\"",
")",
"{",
"if",
"hdrVal",
":=",
"strings",
".",
"SplitN",
"(",
"strLn",
",",
"\"",
"\"",
",",
"2",
")",
";",
"len",
"(",
"hdrVal",
")",
"==",
"2",
"{",
"if",
"filtered",
"&&",
"isSliceMember",
"(",
"headers",
",",
"hdrVal",
"[",
"0",
"]",
")",
"{",
"continue",
"// Loop again since we only work on filtered fields",
"\n",
"}",
"\n",
"fsevent",
"[",
"hdrVal",
"[",
"0",
"]",
"]",
"=",
"urlDecode",
"(",
"strings",
".",
"TrimSpace",
"(",
"strings",
".",
"TrimRight",
"(",
"hdrVal",
"[",
"1",
"]",
",",
"\"",
"\\n",
"\"",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"fsevent",
"\n",
"}"
] |
// Convert fseventStr into fseventMap
|
[
"Convert",
"fseventStr",
"into",
"fseventMap"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/utils.go#L25-L37
|
17,929 |
cgrates/fsock
|
utils.go
|
MapChanData
|
func MapChanData(chanInfoStr string) (chansInfoMap []map[string]string) {
chansInfoMap = make([]map[string]string, 0)
spltChanInfo := strings.Split(chanInfoStr, "\n")
if len(spltChanInfo) <= 4 {
return
}
hdrs := strings.Split(spltChanInfo[0], ",")
for _, chanInfoLn := range spltChanInfo[1 : len(spltChanInfo)-3] {
chanInfo := splitIgnoreGroups(chanInfoLn, ",")
if len(hdrs) != len(chanInfo) {
continue
}
chnMp := make(map[string]string)
for iHdr, hdr := range hdrs {
chnMp[hdr] = chanInfo[iHdr]
}
chansInfoMap = append(chansInfoMap, chnMp)
}
return
}
|
go
|
func MapChanData(chanInfoStr string) (chansInfoMap []map[string]string) {
chansInfoMap = make([]map[string]string, 0)
spltChanInfo := strings.Split(chanInfoStr, "\n")
if len(spltChanInfo) <= 4 {
return
}
hdrs := strings.Split(spltChanInfo[0], ",")
for _, chanInfoLn := range spltChanInfo[1 : len(spltChanInfo)-3] {
chanInfo := splitIgnoreGroups(chanInfoLn, ",")
if len(hdrs) != len(chanInfo) {
continue
}
chnMp := make(map[string]string)
for iHdr, hdr := range hdrs {
chnMp[hdr] = chanInfo[iHdr]
}
chansInfoMap = append(chansInfoMap, chnMp)
}
return
}
|
[
"func",
"MapChanData",
"(",
"chanInfoStr",
"string",
")",
"(",
"chansInfoMap",
"[",
"]",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"chansInfoMap",
"=",
"make",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"string",
",",
"0",
")",
"\n",
"spltChanInfo",
":=",
"strings",
".",
"Split",
"(",
"chanInfoStr",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"if",
"len",
"(",
"spltChanInfo",
")",
"<=",
"4",
"{",
"return",
"\n",
"}",
"\n",
"hdrs",
":=",
"strings",
".",
"Split",
"(",
"spltChanInfo",
"[",
"0",
"]",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"chanInfoLn",
":=",
"range",
"spltChanInfo",
"[",
"1",
":",
"len",
"(",
"spltChanInfo",
")",
"-",
"3",
"]",
"{",
"chanInfo",
":=",
"splitIgnoreGroups",
"(",
"chanInfoLn",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"hdrs",
")",
"!=",
"len",
"(",
"chanInfo",
")",
"{",
"continue",
"\n",
"}",
"\n",
"chnMp",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"iHdr",
",",
"hdr",
":=",
"range",
"hdrs",
"{",
"chnMp",
"[",
"hdr",
"]",
"=",
"chanInfo",
"[",
"iHdr",
"]",
"\n",
"}",
"\n",
"chansInfoMap",
"=",
"append",
"(",
"chansInfoMap",
",",
"chnMp",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Converts string received from fsock into a list of channel info, each represented in a map
|
[
"Converts",
"string",
"received",
"from",
"fsock",
"into",
"a",
"list",
"of",
"channel",
"info",
"each",
"represented",
"in",
"a",
"map"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/utils.go#L40-L59
|
17,930 |
cgrates/fsock
|
utils.go
|
genUUID
|
func genUUID() string {
b := make([]byte, 16)
_, err := io.ReadFull(rand.Reader, b)
if err != nil {
log.Fatal(err)
}
b[6] = (b[6] & 0x0F) | 0x40
b[8] = (b[8] &^ 0x40) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10],
b[10:])
}
|
go
|
func genUUID() string {
b := make([]byte, 16)
_, err := io.ReadFull(rand.Reader, b)
if err != nil {
log.Fatal(err)
}
b[6] = (b[6] & 0x0F) | 0x40
b[8] = (b[8] &^ 0x40) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10],
b[10:])
}
|
[
"func",
"genUUID",
"(",
")",
"string",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"16",
")",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"rand",
".",
"Reader",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"b",
"[",
"6",
"]",
"=",
"(",
"b",
"[",
"6",
"]",
"&",
"0x0F",
")",
"|",
"0x40",
"\n",
"b",
"[",
"8",
"]",
"=",
"(",
"b",
"[",
"8",
"]",
"&^",
"0x40",
")",
"|",
"0x80",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
"[",
":",
"4",
"]",
",",
"b",
"[",
"4",
":",
"6",
"]",
",",
"b",
"[",
"6",
":",
"8",
"]",
",",
"b",
"[",
"8",
":",
"10",
"]",
",",
"b",
"[",
"10",
":",
"]",
")",
"\n",
"}"
] |
// helper function for uuid generation
|
[
"helper",
"function",
"for",
"uuid",
"generation"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/utils.go#L82-L92
|
17,931 |
cgrates/fsock
|
utils.go
|
headerVal
|
func headerVal(hdrs, hdr string) string {
var hdrSIdx, hdrEIdx int
if hdrSIdx = strings.Index(hdrs, hdr); hdrSIdx == -1 {
return ""
} else if hdrEIdx = strings.Index(hdrs[hdrSIdx:], "\n"); hdrEIdx == -1 {
hdrEIdx = len(hdrs[hdrSIdx:])
}
splt := strings.SplitN(hdrs[hdrSIdx:hdrSIdx+hdrEIdx], ": ", 2)
if len(splt) != 2 {
return ""
}
return strings.TrimSpace(strings.TrimRight(splt[1], "\n"))
}
|
go
|
func headerVal(hdrs, hdr string) string {
var hdrSIdx, hdrEIdx int
if hdrSIdx = strings.Index(hdrs, hdr); hdrSIdx == -1 {
return ""
} else if hdrEIdx = strings.Index(hdrs[hdrSIdx:], "\n"); hdrEIdx == -1 {
hdrEIdx = len(hdrs[hdrSIdx:])
}
splt := strings.SplitN(hdrs[hdrSIdx:hdrSIdx+hdrEIdx], ": ", 2)
if len(splt) != 2 {
return ""
}
return strings.TrimSpace(strings.TrimRight(splt[1], "\n"))
}
|
[
"func",
"headerVal",
"(",
"hdrs",
",",
"hdr",
"string",
")",
"string",
"{",
"var",
"hdrSIdx",
",",
"hdrEIdx",
"int",
"\n",
"if",
"hdrSIdx",
"=",
"strings",
".",
"Index",
"(",
"hdrs",
",",
"hdr",
")",
";",
"hdrSIdx",
"==",
"-",
"1",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"hdrEIdx",
"=",
"strings",
".",
"Index",
"(",
"hdrs",
"[",
"hdrSIdx",
":",
"]",
",",
"\"",
"\\n",
"\"",
")",
";",
"hdrEIdx",
"==",
"-",
"1",
"{",
"hdrEIdx",
"=",
"len",
"(",
"hdrs",
"[",
"hdrSIdx",
":",
"]",
")",
"\n",
"}",
"\n",
"splt",
":=",
"strings",
".",
"SplitN",
"(",
"hdrs",
"[",
"hdrSIdx",
":",
"hdrSIdx",
"+",
"hdrEIdx",
"]",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"splt",
")",
"!=",
"2",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"strings",
".",
"TrimSpace",
"(",
"strings",
".",
"TrimRight",
"(",
"splt",
"[",
"1",
"]",
",",
"\"",
"\\n",
"\"",
")",
")",
"\n",
"}"
] |
// Extracts value of a header from anywhere in content string
|
[
"Extracts",
"value",
"of",
"a",
"header",
"from",
"anywhere",
"in",
"content",
"string"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/utils.go#L189-L201
|
17,932 |
cgrates/fsock
|
utils.go
|
urlDecode
|
func urlDecode(hdrVal string) string {
if valUnescaped, errUnescaping := url.QueryUnescape(hdrVal); errUnescaping == nil {
hdrVal = valUnescaped
}
return hdrVal
}
|
go
|
func urlDecode(hdrVal string) string {
if valUnescaped, errUnescaping := url.QueryUnescape(hdrVal); errUnescaping == nil {
hdrVal = valUnescaped
}
return hdrVal
}
|
[
"func",
"urlDecode",
"(",
"hdrVal",
"string",
")",
"string",
"{",
"if",
"valUnescaped",
",",
"errUnescaping",
":=",
"url",
".",
"QueryUnescape",
"(",
"hdrVal",
")",
";",
"errUnescaping",
"==",
"nil",
"{",
"hdrVal",
"=",
"valUnescaped",
"\n",
"}",
"\n",
"return",
"hdrVal",
"\n",
"}"
] |
// FS event header values are urlencoded. Use this to decode them. On error, use original value
|
[
"FS",
"event",
"header",
"values",
"are",
"urlencoded",
".",
"Use",
"this",
"to",
"decode",
"them",
".",
"On",
"error",
"use",
"original",
"value"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/utils.go#L204-L209
|
17,933 |
cgrates/fsock
|
utils.go
|
isSliceMember
|
func isSliceMember(ss []string, s string) bool {
sort.Strings(ss)
i := sort.SearchStrings(ss, s)
return (i < len(ss) && ss[i] == s)
}
|
go
|
func isSliceMember(ss []string, s string) bool {
sort.Strings(ss)
i := sort.SearchStrings(ss, s)
return (i < len(ss) && ss[i] == s)
}
|
[
"func",
"isSliceMember",
"(",
"ss",
"[",
"]",
"string",
",",
"s",
"string",
")",
"bool",
"{",
"sort",
".",
"Strings",
"(",
"ss",
")",
"\n",
"i",
":=",
"sort",
".",
"SearchStrings",
"(",
"ss",
",",
"s",
")",
"\n",
"return",
"(",
"i",
"<",
"len",
"(",
"ss",
")",
"&&",
"ss",
"[",
"i",
"]",
"==",
"s",
")",
"\n",
"}"
] |
// Binary string search in slice
|
[
"Binary",
"string",
"search",
"in",
"slice"
] |
880b6b2d10e6fcd66b0148471255438b82fb78b0
|
https://github.com/cgrates/fsock/blob/880b6b2d10e6fcd66b0148471255438b82fb78b0/utils.go#L222-L226
|
17,934 |
rylio/queue
|
queue.go
|
NewQueue
|
func NewQueue(handler Handler, concurrencyLimit int) *Queue {
q := &Queue{
&queue{
Handler: handler,
ConcurrencyLimit: concurrencyLimit,
push: make(chan interface{}),
pop: make(chan struct{}),
suspend: make(chan bool),
stop: make(chan struct{}),
},
}
go q.run()
runtime.SetFinalizer(q, (*Queue).Stop)
return q
}
|
go
|
func NewQueue(handler Handler, concurrencyLimit int) *Queue {
q := &Queue{
&queue{
Handler: handler,
ConcurrencyLimit: concurrencyLimit,
push: make(chan interface{}),
pop: make(chan struct{}),
suspend: make(chan bool),
stop: make(chan struct{}),
},
}
go q.run()
runtime.SetFinalizer(q, (*Queue).Stop)
return q
}
|
[
"func",
"NewQueue",
"(",
"handler",
"Handler",
",",
"concurrencyLimit",
"int",
")",
"*",
"Queue",
"{",
"q",
":=",
"&",
"Queue",
"{",
"&",
"queue",
"{",
"Handler",
":",
"handler",
",",
"ConcurrencyLimit",
":",
"concurrencyLimit",
",",
"push",
":",
"make",
"(",
"chan",
"interface",
"{",
"}",
")",
",",
"pop",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"suspend",
":",
"make",
"(",
"chan",
"bool",
")",
",",
"stop",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
",",
"}",
"\n\n",
"go",
"q",
".",
"run",
"(",
")",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"q",
",",
"(",
"*",
"Queue",
")",
".",
"Stop",
")",
"\n",
"return",
"q",
"\n",
"}"
] |
// NewQueue must be called to initialize a new queue.
// The first argument is a Handler
// The second argument is an int which specifies how many operation can run in parallel in the queue, zero means unlimited.
|
[
"NewQueue",
"must",
"be",
"called",
"to",
"initialize",
"a",
"new",
"queue",
".",
"The",
"first",
"argument",
"is",
"a",
"Handler",
"The",
"second",
"argument",
"is",
"an",
"int",
"which",
"specifies",
"how",
"many",
"operation",
"can",
"run",
"in",
"parallel",
"in",
"the",
"queue",
"zero",
"means",
"unlimited",
"."
] |
9aab6b722ecdf21660568142d77b62182161e9ce
|
https://github.com/rylio/queue/blob/9aab6b722ecdf21660568142d77b62182161e9ce/queue.go#L35-L51
|
17,935 |
rylio/queue
|
queue.go
|
Len
|
func (q *Queue) Len() (_, _ int) {
return q.count, len(q.buffer)
}
|
go
|
func (q *Queue) Len() (_, _ int) {
return q.count, len(q.buffer)
}
|
[
"func",
"(",
"q",
"*",
"Queue",
")",
"Len",
"(",
")",
"(",
"_",
",",
"_",
"int",
")",
"{",
"return",
"q",
".",
"count",
",",
"len",
"(",
"q",
".",
"buffer",
")",
"\n",
"}"
] |
// Count returns the number of currently executing tasks and the number of tasks waiting to be executed
|
[
"Count",
"returns",
"the",
"number",
"of",
"currently",
"executing",
"tasks",
"and",
"the",
"number",
"of",
"tasks",
"waiting",
"to",
"be",
"executed"
] |
9aab6b722ecdf21660568142d77b62182161e9ce
|
https://github.com/rylio/queue/blob/9aab6b722ecdf21660568142d77b62182161e9ce/queue.go#L73-L76
|
17,936 |
docker/engine-api
|
client/plugin_inspect.go
|
PluginInspectWithRaw
|
func (cli *Client) PluginInspectWithRaw(ctx context.Context, name string) (*types.Plugin, []byte, error) {
resp, err := cli.get(ctx, "/plugins/"+name, nil, nil)
if err != nil {
return nil, nil, err
}
defer ensureReaderClosed(resp)
body, err := ioutil.ReadAll(resp.body)
if err != nil {
return nil, nil, err
}
var p types.Plugin
rdr := bytes.NewReader(body)
err = json.NewDecoder(rdr).Decode(&p)
return &p, body, err
}
|
go
|
func (cli *Client) PluginInspectWithRaw(ctx context.Context, name string) (*types.Plugin, []byte, error) {
resp, err := cli.get(ctx, "/plugins/"+name, nil, nil)
if err != nil {
return nil, nil, err
}
defer ensureReaderClosed(resp)
body, err := ioutil.ReadAll(resp.body)
if err != nil {
return nil, nil, err
}
var p types.Plugin
rdr := bytes.NewReader(body)
err = json.NewDecoder(rdr).Decode(&p)
return &p, body, err
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"PluginInspectWithRaw",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
")",
"(",
"*",
"types",
".",
"Plugin",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"cli",
".",
"get",
"(",
"ctx",
",",
"\"",
"\"",
"+",
"name",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"defer",
"ensureReaderClosed",
"(",
"resp",
")",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"p",
"types",
".",
"Plugin",
"\n",
"rdr",
":=",
"bytes",
".",
"NewReader",
"(",
"body",
")",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"rdr",
")",
".",
"Decode",
"(",
"&",
"p",
")",
"\n",
"return",
"&",
"p",
",",
"body",
",",
"err",
"\n",
"}"
] |
// PluginInspectWithRaw inspects an existing plugin
|
[
"PluginInspectWithRaw",
"inspects",
"an",
"existing",
"plugin"
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/plugin_inspect.go#L15-L30
|
17,937 |
docker/engine-api
|
client/service_update.go
|
ServiceUpdate
|
func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) error {
var (
headers map[string][]string
query = url.Values{}
)
if options.EncodedRegistryAuth != "" {
headers = map[string][]string{
"X-Registry-Auth": []string{options.EncodedRegistryAuth},
}
}
query.Set("version", strconv.FormatUint(version.Index, 10))
resp, err := cli.post(ctx, "/services/"+serviceID+"/update", query, service, headers)
ensureReaderClosed(resp)
return err
}
|
go
|
func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) error {
var (
headers map[string][]string
query = url.Values{}
)
if options.EncodedRegistryAuth != "" {
headers = map[string][]string{
"X-Registry-Auth": []string{options.EncodedRegistryAuth},
}
}
query.Set("version", strconv.FormatUint(version.Index, 10))
resp, err := cli.post(ctx, "/services/"+serviceID+"/update", query, service, headers)
ensureReaderClosed(resp)
return err
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"ServiceUpdate",
"(",
"ctx",
"context",
".",
"Context",
",",
"serviceID",
"string",
",",
"version",
"swarm",
".",
"Version",
",",
"service",
"swarm",
".",
"ServiceSpec",
",",
"options",
"types",
".",
"ServiceUpdateOptions",
")",
"error",
"{",
"var",
"(",
"headers",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"\n",
"query",
"=",
"url",
".",
"Values",
"{",
"}",
"\n",
")",
"\n\n",
"if",
"options",
".",
"EncodedRegistryAuth",
"!=",
"\"",
"\"",
"{",
"headers",
"=",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"options",
".",
"EncodedRegistryAuth",
"}",
",",
"}",
"\n",
"}",
"\n\n",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"FormatUint",
"(",
"version",
".",
"Index",
",",
"10",
")",
")",
"\n\n",
"resp",
",",
"err",
":=",
"cli",
".",
"post",
"(",
"ctx",
",",
"\"",
"\"",
"+",
"serviceID",
"+",
"\"",
"\"",
",",
"query",
",",
"service",
",",
"headers",
")",
"\n",
"ensureReaderClosed",
"(",
"resp",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// ServiceUpdate updates a Service.
|
[
"ServiceUpdate",
"updates",
"a",
"Service",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/service_update.go#L13-L30
|
17,938 |
docker/engine-api
|
client/client.go
|
NewEnvClient
|
func NewEnvClient() (*Client, error) {
var client *http.Client
if dockerCertPath := os.Getenv("DOCKER_CERT_PATH"); dockerCertPath != "" {
options := tlsconfig.Options{
CAFile: filepath.Join(dockerCertPath, "ca.pem"),
CertFile: filepath.Join(dockerCertPath, "cert.pem"),
KeyFile: filepath.Join(dockerCertPath, "key.pem"),
InsecureSkipVerify: os.Getenv("DOCKER_TLS_VERIFY") == "",
}
tlsc, err := tlsconfig.Client(options)
if err != nil {
return nil, err
}
client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsc,
},
}
}
host := os.Getenv("DOCKER_HOST")
if host == "" {
host = DefaultDockerHost
}
version := os.Getenv("DOCKER_API_VERSION")
if version == "" {
version = DefaultVersion
}
return NewClient(host, version, client, nil)
}
|
go
|
func NewEnvClient() (*Client, error) {
var client *http.Client
if dockerCertPath := os.Getenv("DOCKER_CERT_PATH"); dockerCertPath != "" {
options := tlsconfig.Options{
CAFile: filepath.Join(dockerCertPath, "ca.pem"),
CertFile: filepath.Join(dockerCertPath, "cert.pem"),
KeyFile: filepath.Join(dockerCertPath, "key.pem"),
InsecureSkipVerify: os.Getenv("DOCKER_TLS_VERIFY") == "",
}
tlsc, err := tlsconfig.Client(options)
if err != nil {
return nil, err
}
client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsc,
},
}
}
host := os.Getenv("DOCKER_HOST")
if host == "" {
host = DefaultDockerHost
}
version := os.Getenv("DOCKER_API_VERSION")
if version == "" {
version = DefaultVersion
}
return NewClient(host, version, client, nil)
}
|
[
"func",
"NewEnvClient",
"(",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"var",
"client",
"*",
"http",
".",
"Client",
"\n",
"if",
"dockerCertPath",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
";",
"dockerCertPath",
"!=",
"\"",
"\"",
"{",
"options",
":=",
"tlsconfig",
".",
"Options",
"{",
"CAFile",
":",
"filepath",
".",
"Join",
"(",
"dockerCertPath",
",",
"\"",
"\"",
")",
",",
"CertFile",
":",
"filepath",
".",
"Join",
"(",
"dockerCertPath",
",",
"\"",
"\"",
")",
",",
"KeyFile",
":",
"filepath",
".",
"Join",
"(",
"dockerCertPath",
",",
"\"",
"\"",
")",
",",
"InsecureSkipVerify",
":",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
",",
"}",
"\n",
"tlsc",
",",
"err",
":=",
"tlsconfig",
".",
"Client",
"(",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"client",
"=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"tlsc",
",",
"}",
",",
"}",
"\n",
"}",
"\n\n",
"host",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"host",
"==",
"\"",
"\"",
"{",
"host",
"=",
"DefaultDockerHost",
"\n",
"}",
"\n\n",
"version",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"version",
"==",
"\"",
"\"",
"{",
"version",
"=",
"DefaultVersion",
"\n",
"}",
"\n\n",
"return",
"NewClient",
"(",
"host",
",",
"version",
",",
"client",
",",
"nil",
")",
"\n",
"}"
] |
// NewEnvClient initializes a new API client based on environment variables.
// Use DOCKER_HOST to set the url to the docker server.
// Use DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest.
// Use DOCKER_CERT_PATH to load the tls certificates from.
// Use DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default.
|
[
"NewEnvClient",
"initializes",
"a",
"new",
"API",
"client",
"based",
"on",
"environment",
"variables",
".",
"Use",
"DOCKER_HOST",
"to",
"set",
"the",
"url",
"to",
"the",
"docker",
"server",
".",
"Use",
"DOCKER_API_VERSION",
"to",
"set",
"the",
"version",
"of",
"the",
"API",
"to",
"reach",
"leave",
"empty",
"for",
"latest",
".",
"Use",
"DOCKER_CERT_PATH",
"to",
"load",
"the",
"tls",
"certificates",
"from",
".",
"Use",
"DOCKER_TLS_VERIFY",
"to",
"enable",
"or",
"disable",
"TLS",
"verification",
"off",
"by",
"default",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/client.go#L42-L74
|
17,939 |
docker/engine-api
|
client/client.go
|
NewClient
|
func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) {
proto, addr, basePath, err := ParseHost(host)
if err != nil {
return nil, err
}
transport, err := transport.NewTransportWithHTTP(proto, addr, client)
if err != nil {
return nil, err
}
return &Client{
host: host,
proto: proto,
addr: addr,
basePath: basePath,
transport: transport,
version: version,
customHTTPHeaders: httpHeaders,
}, nil
}
|
go
|
func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) {
proto, addr, basePath, err := ParseHost(host)
if err != nil {
return nil, err
}
transport, err := transport.NewTransportWithHTTP(proto, addr, client)
if err != nil {
return nil, err
}
return &Client{
host: host,
proto: proto,
addr: addr,
basePath: basePath,
transport: transport,
version: version,
customHTTPHeaders: httpHeaders,
}, nil
}
|
[
"func",
"NewClient",
"(",
"host",
"string",
",",
"version",
"string",
",",
"client",
"*",
"http",
".",
"Client",
",",
"httpHeaders",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"proto",
",",
"addr",
",",
"basePath",
",",
"err",
":=",
"ParseHost",
"(",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"transport",
",",
"err",
":=",
"transport",
".",
"NewTransportWithHTTP",
"(",
"proto",
",",
"addr",
",",
"client",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"Client",
"{",
"host",
":",
"host",
",",
"proto",
":",
"proto",
",",
"addr",
":",
"addr",
",",
"basePath",
":",
"basePath",
",",
"transport",
":",
"transport",
",",
"version",
":",
"version",
",",
"customHTTPHeaders",
":",
"httpHeaders",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewClient initializes a new API client for the given host and API version.
// It uses the given http client as transport.
// It also initializes the custom http headers to add to each request.
//
// It won't send any version information if the version number is empty. It is
// highly recommended that you set a version or your client may break if the
// server is upgraded.
|
[
"NewClient",
"initializes",
"a",
"new",
"API",
"client",
"for",
"the",
"given",
"host",
"and",
"API",
"version",
".",
"It",
"uses",
"the",
"given",
"http",
"client",
"as",
"transport",
".",
"It",
"also",
"initializes",
"the",
"custom",
"http",
"headers",
"to",
"add",
"to",
"each",
"request",
".",
"It",
"won",
"t",
"send",
"any",
"version",
"information",
"if",
"the",
"version",
"number",
"is",
"empty",
".",
"It",
"is",
"highly",
"recommended",
"that",
"you",
"set",
"a",
"version",
"or",
"your",
"client",
"may",
"break",
"if",
"the",
"server",
"is",
"upgraded",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/client.go#L83-L103
|
17,940 |
docker/engine-api
|
client/task_list.go
|
TaskList
|
func (cli *Client) TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) {
query := url.Values{}
if options.Filter.Len() > 0 {
filterJSON, err := filters.ToParam(options.Filter)
if err != nil {
return nil, err
}
query.Set("filters", filterJSON)
}
resp, err := cli.get(ctx, "/tasks", query, nil)
if err != nil {
return nil, err
}
var tasks []swarm.Task
err = json.NewDecoder(resp.body).Decode(&tasks)
ensureReaderClosed(resp)
return tasks, err
}
|
go
|
func (cli *Client) TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) {
query := url.Values{}
if options.Filter.Len() > 0 {
filterJSON, err := filters.ToParam(options.Filter)
if err != nil {
return nil, err
}
query.Set("filters", filterJSON)
}
resp, err := cli.get(ctx, "/tasks", query, nil)
if err != nil {
return nil, err
}
var tasks []swarm.Task
err = json.NewDecoder(resp.body).Decode(&tasks)
ensureReaderClosed(resp)
return tasks, err
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"TaskList",
"(",
"ctx",
"context",
".",
"Context",
",",
"options",
"types",
".",
"TaskListOptions",
")",
"(",
"[",
"]",
"swarm",
".",
"Task",
",",
"error",
")",
"{",
"query",
":=",
"url",
".",
"Values",
"{",
"}",
"\n\n",
"if",
"options",
".",
"Filter",
".",
"Len",
"(",
")",
">",
"0",
"{",
"filterJSON",
",",
"err",
":=",
"filters",
".",
"ToParam",
"(",
"options",
".",
"Filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"filterJSON",
")",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"cli",
".",
"get",
"(",
"ctx",
",",
"\"",
"\"",
",",
"query",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"tasks",
"[",
"]",
"swarm",
".",
"Task",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"body",
")",
".",
"Decode",
"(",
"&",
"tasks",
")",
"\n",
"ensureReaderClosed",
"(",
"resp",
")",
"\n",
"return",
"tasks",
",",
"err",
"\n",
"}"
] |
// TaskList returns the list of tasks.
|
[
"TaskList",
"returns",
"the",
"list",
"of",
"tasks",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/task_list.go#L14-L35
|
17,941 |
docker/engine-api
|
client/network_inspect.go
|
NetworkInspect
|
func (cli *Client) NetworkInspect(ctx context.Context, networkID string) (types.NetworkResource, error) {
networkResource, _, err := cli.NetworkInspectWithRaw(ctx, networkID)
return networkResource, err
}
|
go
|
func (cli *Client) NetworkInspect(ctx context.Context, networkID string) (types.NetworkResource, error) {
networkResource, _, err := cli.NetworkInspectWithRaw(ctx, networkID)
return networkResource, err
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"NetworkInspect",
"(",
"ctx",
"context",
".",
"Context",
",",
"networkID",
"string",
")",
"(",
"types",
".",
"NetworkResource",
",",
"error",
")",
"{",
"networkResource",
",",
"_",
",",
"err",
":=",
"cli",
".",
"NetworkInspectWithRaw",
"(",
"ctx",
",",
"networkID",
")",
"\n",
"return",
"networkResource",
",",
"err",
"\n",
"}"
] |
// NetworkInspect returns the information for a specific network configured in the docker host.
|
[
"NetworkInspect",
"returns",
"the",
"information",
"for",
"a",
"specific",
"network",
"configured",
"in",
"the",
"docker",
"host",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/network_inspect.go#L14-L17
|
17,942 |
docker/engine-api
|
types/filters/parse.go
|
ToParam
|
func ToParam(a Args) (string, error) {
// this way we don't URL encode {}, just empty space
if a.Len() == 0 {
return "", nil
}
buf, err := json.Marshal(a.fields)
if err != nil {
return "", err
}
return string(buf), nil
}
|
go
|
func ToParam(a Args) (string, error) {
// this way we don't URL encode {}, just empty space
if a.Len() == 0 {
return "", nil
}
buf, err := json.Marshal(a.fields)
if err != nil {
return "", err
}
return string(buf), nil
}
|
[
"func",
"ToParam",
"(",
"a",
"Args",
")",
"(",
"string",
",",
"error",
")",
"{",
"// this way we don't URL encode {}, just empty space",
"if",
"a",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n\n",
"buf",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"a",
".",
"fields",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"string",
"(",
"buf",
")",
",",
"nil",
"\n",
"}"
] |
// ToParam packs the Args into a string for easy transport from client to server.
|
[
"ToParam",
"packs",
"the",
"Args",
"into",
"a",
"string",
"for",
"easy",
"transport",
"from",
"client",
"to",
"server",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/filters/parse.go#L60-L71
|
17,943 |
docker/engine-api
|
types/filters/parse.go
|
FromParam
|
func FromParam(p string) (Args, error) {
if len(p) == 0 {
return NewArgs(), nil
}
r := strings.NewReader(p)
d := json.NewDecoder(r)
m := map[string]map[string]bool{}
if err := d.Decode(&m); err != nil {
r.Seek(0, 0)
// Allow parsing old arguments in slice format.
// Because other libraries might be sending them in this format.
deprecated := map[string][]string{}
if deprecatedErr := d.Decode(&deprecated); deprecatedErr == nil {
m = deprecatedArgs(deprecated)
} else {
return NewArgs(), err
}
}
return Args{m}, nil
}
|
go
|
func FromParam(p string) (Args, error) {
if len(p) == 0 {
return NewArgs(), nil
}
r := strings.NewReader(p)
d := json.NewDecoder(r)
m := map[string]map[string]bool{}
if err := d.Decode(&m); err != nil {
r.Seek(0, 0)
// Allow parsing old arguments in slice format.
// Because other libraries might be sending them in this format.
deprecated := map[string][]string{}
if deprecatedErr := d.Decode(&deprecated); deprecatedErr == nil {
m = deprecatedArgs(deprecated)
} else {
return NewArgs(), err
}
}
return Args{m}, nil
}
|
[
"func",
"FromParam",
"(",
"p",
"string",
")",
"(",
"Args",
",",
"error",
")",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"NewArgs",
"(",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"r",
":=",
"strings",
".",
"NewReader",
"(",
"p",
")",
"\n",
"d",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
")",
"\n\n",
"m",
":=",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"Decode",
"(",
"&",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"r",
".",
"Seek",
"(",
"0",
",",
"0",
")",
"\n\n",
"// Allow parsing old arguments in slice format.",
"// Because other libraries might be sending them in this format.",
"deprecated",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"}",
"\n",
"if",
"deprecatedErr",
":=",
"d",
".",
"Decode",
"(",
"&",
"deprecated",
")",
";",
"deprecatedErr",
"==",
"nil",
"{",
"m",
"=",
"deprecatedArgs",
"(",
"deprecated",
")",
"\n",
"}",
"else",
"{",
"return",
"NewArgs",
"(",
")",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"Args",
"{",
"m",
"}",
",",
"nil",
"\n",
"}"
] |
// FromParam unpacks the filter Args.
|
[
"FromParam",
"unpacks",
"the",
"filter",
"Args",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/filters/parse.go#L96-L118
|
17,944 |
docker/engine-api
|
types/filters/parse.go
|
Get
|
func (filters Args) Get(field string) []string {
values := filters.fields[field]
if values == nil {
return make([]string, 0)
}
slice := make([]string, 0, len(values))
for key := range values {
slice = append(slice, key)
}
return slice
}
|
go
|
func (filters Args) Get(field string) []string {
values := filters.fields[field]
if values == nil {
return make([]string, 0)
}
slice := make([]string, 0, len(values))
for key := range values {
slice = append(slice, key)
}
return slice
}
|
[
"func",
"(",
"filters",
"Args",
")",
"Get",
"(",
"field",
"string",
")",
"[",
"]",
"string",
"{",
"values",
":=",
"filters",
".",
"fields",
"[",
"field",
"]",
"\n",
"if",
"values",
"==",
"nil",
"{",
"return",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"}",
"\n",
"slice",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"values",
")",
")",
"\n",
"for",
"key",
":=",
"range",
"values",
"{",
"slice",
"=",
"append",
"(",
"slice",
",",
"key",
")",
"\n",
"}",
"\n",
"return",
"slice",
"\n",
"}"
] |
// Get returns the list of values associates with a field.
// It returns a slice of strings to keep backwards compatibility with old code.
|
[
"Get",
"returns",
"the",
"list",
"of",
"values",
"associates",
"with",
"a",
"field",
".",
"It",
"returns",
"a",
"slice",
"of",
"strings",
"to",
"keep",
"backwards",
"compatibility",
"with",
"old",
"code",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/filters/parse.go#L122-L132
|
17,945 |
docker/engine-api
|
types/filters/parse.go
|
Add
|
func (filters Args) Add(name, value string) {
if _, ok := filters.fields[name]; ok {
filters.fields[name][value] = true
} else {
filters.fields[name] = map[string]bool{value: true}
}
}
|
go
|
func (filters Args) Add(name, value string) {
if _, ok := filters.fields[name]; ok {
filters.fields[name][value] = true
} else {
filters.fields[name] = map[string]bool{value: true}
}
}
|
[
"func",
"(",
"filters",
"Args",
")",
"Add",
"(",
"name",
",",
"value",
"string",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"filters",
".",
"fields",
"[",
"name",
"]",
";",
"ok",
"{",
"filters",
".",
"fields",
"[",
"name",
"]",
"[",
"value",
"]",
"=",
"true",
"\n",
"}",
"else",
"{",
"filters",
".",
"fields",
"[",
"name",
"]",
"=",
"map",
"[",
"string",
"]",
"bool",
"{",
"value",
":",
"true",
"}",
"\n",
"}",
"\n",
"}"
] |
// Add adds a new value to a filter field.
|
[
"Add",
"adds",
"a",
"new",
"value",
"to",
"a",
"filter",
"field",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/filters/parse.go#L135-L141
|
17,946 |
docker/engine-api
|
types/filters/parse.go
|
Del
|
func (filters Args) Del(name, value string) {
if _, ok := filters.fields[name]; ok {
delete(filters.fields[name], value)
}
}
|
go
|
func (filters Args) Del(name, value string) {
if _, ok := filters.fields[name]; ok {
delete(filters.fields[name], value)
}
}
|
[
"func",
"(",
"filters",
"Args",
")",
"Del",
"(",
"name",
",",
"value",
"string",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"filters",
".",
"fields",
"[",
"name",
"]",
";",
"ok",
"{",
"delete",
"(",
"filters",
".",
"fields",
"[",
"name",
"]",
",",
"value",
")",
"\n",
"}",
"\n",
"}"
] |
// Del removes a value from a filter field.
|
[
"Del",
"removes",
"a",
"value",
"from",
"a",
"filter",
"field",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/filters/parse.go#L144-L148
|
17,947 |
docker/engine-api
|
types/filters/parse.go
|
ExactMatch
|
func (filters Args) ExactMatch(field, source string) bool {
fieldValues, ok := filters.fields[field]
//do not filter if there is no filter set or cannot determine filter
if !ok || len(fieldValues) == 0 {
return true
}
// try to match full name value to avoid O(N) regular expression matching
return fieldValues[source]
}
|
go
|
func (filters Args) ExactMatch(field, source string) bool {
fieldValues, ok := filters.fields[field]
//do not filter if there is no filter set or cannot determine filter
if !ok || len(fieldValues) == 0 {
return true
}
// try to match full name value to avoid O(N) regular expression matching
return fieldValues[source]
}
|
[
"func",
"(",
"filters",
"Args",
")",
"ExactMatch",
"(",
"field",
",",
"source",
"string",
")",
"bool",
"{",
"fieldValues",
",",
"ok",
":=",
"filters",
".",
"fields",
"[",
"field",
"]",
"\n",
"//do not filter if there is no filter set or cannot determine filter",
"if",
"!",
"ok",
"||",
"len",
"(",
"fieldValues",
")",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"// try to match full name value to avoid O(N) regular expression matching",
"return",
"fieldValues",
"[",
"source",
"]",
"\n",
"}"
] |
// ExactMatch returns true if the source matches exactly one of the filters.
|
[
"ExactMatch",
"returns",
"true",
"if",
"the",
"source",
"matches",
"exactly",
"one",
"of",
"the",
"filters",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/filters/parse.go#L210-L219
|
17,948 |
docker/engine-api
|
types/filters/parse.go
|
UniqueExactMatch
|
func (filters Args) UniqueExactMatch(field, source string) bool {
fieldValues := filters.fields[field]
//do not filter if there is no filter set or cannot determine filter
if len(fieldValues) == 0 {
return true
}
if len(filters.fields[field]) != 1 {
return false
}
// try to match full name value to avoid O(N) regular expression matching
return fieldValues[source]
}
|
go
|
func (filters Args) UniqueExactMatch(field, source string) bool {
fieldValues := filters.fields[field]
//do not filter if there is no filter set or cannot determine filter
if len(fieldValues) == 0 {
return true
}
if len(filters.fields[field]) != 1 {
return false
}
// try to match full name value to avoid O(N) regular expression matching
return fieldValues[source]
}
|
[
"func",
"(",
"filters",
"Args",
")",
"UniqueExactMatch",
"(",
"field",
",",
"source",
"string",
")",
"bool",
"{",
"fieldValues",
":=",
"filters",
".",
"fields",
"[",
"field",
"]",
"\n",
"//do not filter if there is no filter set or cannot determine filter",
"if",
"len",
"(",
"fieldValues",
")",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"len",
"(",
"filters",
".",
"fields",
"[",
"field",
"]",
")",
"!=",
"1",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// try to match full name value to avoid O(N) regular expression matching",
"return",
"fieldValues",
"[",
"source",
"]",
"\n",
"}"
] |
// UniqueExactMatch returns true if there is only one filter and the source matches exactly this one.
|
[
"UniqueExactMatch",
"returns",
"true",
"if",
"there",
"is",
"only",
"one",
"filter",
"and",
"the",
"source",
"matches",
"exactly",
"this",
"one",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/filters/parse.go#L222-L234
|
17,949 |
docker/engine-api
|
types/filters/parse.go
|
FuzzyMatch
|
func (filters Args) FuzzyMatch(field, source string) bool {
if filters.ExactMatch(field, source) {
return true
}
fieldValues := filters.fields[field]
for prefix := range fieldValues {
if strings.HasPrefix(source, prefix) {
return true
}
}
return false
}
|
go
|
func (filters Args) FuzzyMatch(field, source string) bool {
if filters.ExactMatch(field, source) {
return true
}
fieldValues := filters.fields[field]
for prefix := range fieldValues {
if strings.HasPrefix(source, prefix) {
return true
}
}
return false
}
|
[
"func",
"(",
"filters",
"Args",
")",
"FuzzyMatch",
"(",
"field",
",",
"source",
"string",
")",
"bool",
"{",
"if",
"filters",
".",
"ExactMatch",
"(",
"field",
",",
"source",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"fieldValues",
":=",
"filters",
".",
"fields",
"[",
"field",
"]",
"\n",
"for",
"prefix",
":=",
"range",
"fieldValues",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"source",
",",
"prefix",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// FuzzyMatch returns true if the source matches exactly one of the filters,
// or the source has one of the filters as a prefix.
|
[
"FuzzyMatch",
"returns",
"true",
"if",
"the",
"source",
"matches",
"exactly",
"one",
"of",
"the",
"filters",
"or",
"the",
"source",
"has",
"one",
"of",
"the",
"filters",
"as",
"a",
"prefix",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/filters/parse.go#L238-L250
|
17,950 |
docker/engine-api
|
types/filters/parse.go
|
Include
|
func (filters Args) Include(field string) bool {
_, ok := filters.fields[field]
return ok
}
|
go
|
func (filters Args) Include(field string) bool {
_, ok := filters.fields[field]
return ok
}
|
[
"func",
"(",
"filters",
"Args",
")",
"Include",
"(",
"field",
"string",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"filters",
".",
"fields",
"[",
"field",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] |
// Include returns true if the name of the field to filter is in the filters.
|
[
"Include",
"returns",
"true",
"if",
"the",
"name",
"of",
"the",
"field",
"to",
"filter",
"is",
"in",
"the",
"filters",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/filters/parse.go#L253-L256
|
17,951 |
docker/engine-api
|
types/filters/parse.go
|
Validate
|
func (filters Args) Validate(accepted map[string]bool) error {
for name := range filters.fields {
if !accepted[name] {
return fmt.Errorf("Invalid filter '%s'", name)
}
}
return nil
}
|
go
|
func (filters Args) Validate(accepted map[string]bool) error {
for name := range filters.fields {
if !accepted[name] {
return fmt.Errorf("Invalid filter '%s'", name)
}
}
return nil
}
|
[
"func",
"(",
"filters",
"Args",
")",
"Validate",
"(",
"accepted",
"map",
"[",
"string",
"]",
"bool",
")",
"error",
"{",
"for",
"name",
":=",
"range",
"filters",
".",
"fields",
"{",
"if",
"!",
"accepted",
"[",
"name",
"]",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Validate ensures that all the fields in the filter are valid.
// It returns an error as soon as it finds an invalid field.
|
[
"Validate",
"ensures",
"that",
"all",
"the",
"fields",
"in",
"the",
"filter",
"are",
"valid",
".",
"It",
"returns",
"an",
"error",
"as",
"soon",
"as",
"it",
"finds",
"an",
"invalid",
"field",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/filters/parse.go#L260-L267
|
17,952 |
docker/engine-api
|
client/login.go
|
RegistryLogin
|
func (cli *Client) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) {
resp, err := cli.post(ctx, "/auth", url.Values{}, auth, nil)
if resp.statusCode == http.StatusUnauthorized {
return types.AuthResponse{}, unauthorizedError{err}
}
if err != nil {
return types.AuthResponse{}, err
}
var response types.AuthResponse
err = json.NewDecoder(resp.body).Decode(&response)
ensureReaderClosed(resp)
return response, err
}
|
go
|
func (cli *Client) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) {
resp, err := cli.post(ctx, "/auth", url.Values{}, auth, nil)
if resp.statusCode == http.StatusUnauthorized {
return types.AuthResponse{}, unauthorizedError{err}
}
if err != nil {
return types.AuthResponse{}, err
}
var response types.AuthResponse
err = json.NewDecoder(resp.body).Decode(&response)
ensureReaderClosed(resp)
return response, err
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"RegistryLogin",
"(",
"ctx",
"context",
".",
"Context",
",",
"auth",
"types",
".",
"AuthConfig",
")",
"(",
"types",
".",
"AuthResponse",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"cli",
".",
"post",
"(",
"ctx",
",",
"\"",
"\"",
",",
"url",
".",
"Values",
"{",
"}",
",",
"auth",
",",
"nil",
")",
"\n\n",
"if",
"resp",
".",
"statusCode",
"==",
"http",
".",
"StatusUnauthorized",
"{",
"return",
"types",
".",
"AuthResponse",
"{",
"}",
",",
"unauthorizedError",
"{",
"err",
"}",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"AuthResponse",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"response",
"types",
".",
"AuthResponse",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"body",
")",
".",
"Decode",
"(",
"&",
"response",
")",
"\n",
"ensureReaderClosed",
"(",
"resp",
")",
"\n",
"return",
"response",
",",
"err",
"\n",
"}"
] |
// RegistryLogin authenticates the docker server with a given docker registry.
// It returns UnauthorizerError when the authentication fails.
|
[
"RegistryLogin",
"authenticates",
"the",
"docker",
"server",
"with",
"a",
"given",
"docker",
"registry",
".",
"It",
"returns",
"UnauthorizerError",
"when",
"the",
"authentication",
"fails",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/login.go#L14-L28
|
17,953 |
docker/engine-api
|
types/reference/image_reference.go
|
GetTagFromNamedRef
|
func GetTagFromNamedRef(ref distreference.Named) string {
var tag string
switch x := ref.(type) {
case distreference.Digested:
tag = x.Digest().String()
case distreference.NamedTagged:
tag = x.Tag()
default:
tag = "latest"
}
return tag
}
|
go
|
func GetTagFromNamedRef(ref distreference.Named) string {
var tag string
switch x := ref.(type) {
case distreference.Digested:
tag = x.Digest().String()
case distreference.NamedTagged:
tag = x.Tag()
default:
tag = "latest"
}
return tag
}
|
[
"func",
"GetTagFromNamedRef",
"(",
"ref",
"distreference",
".",
"Named",
")",
"string",
"{",
"var",
"tag",
"string",
"\n",
"switch",
"x",
":=",
"ref",
".",
"(",
"type",
")",
"{",
"case",
"distreference",
".",
"Digested",
":",
"tag",
"=",
"x",
".",
"Digest",
"(",
")",
".",
"String",
"(",
")",
"\n",
"case",
"distreference",
".",
"NamedTagged",
":",
"tag",
"=",
"x",
".",
"Tag",
"(",
")",
"\n",
"default",
":",
"tag",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"tag",
"\n",
"}"
] |
// GetTagFromNamedRef returns a tag from the specified reference.
// This function is necessary as long as the docker "server" api makes the distinction between repository
// and tags.
|
[
"GetTagFromNamedRef",
"returns",
"a",
"tag",
"from",
"the",
"specified",
"reference",
".",
"This",
"function",
"is",
"necessary",
"as",
"long",
"as",
"the",
"docker",
"server",
"api",
"makes",
"the",
"distinction",
"between",
"repository",
"and",
"tags",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/types/reference/image_reference.go#L23-L34
|
17,954 |
docker/engine-api
|
client/container_start.go
|
ContainerStart
|
func (cli *Client) ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error {
query := url.Values{}
if len(options.CheckpointID) != 0 {
query.Set("checkpoint", options.CheckpointID)
}
resp, err := cli.post(ctx, "/containers/"+containerID+"/start", query, nil, nil)
ensureReaderClosed(resp)
return err
}
|
go
|
func (cli *Client) ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error {
query := url.Values{}
if len(options.CheckpointID) != 0 {
query.Set("checkpoint", options.CheckpointID)
}
resp, err := cli.post(ctx, "/containers/"+containerID+"/start", query, nil, nil)
ensureReaderClosed(resp)
return err
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"ContainerStart",
"(",
"ctx",
"context",
".",
"Context",
",",
"containerID",
"string",
",",
"options",
"types",
".",
"ContainerStartOptions",
")",
"error",
"{",
"query",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"if",
"len",
"(",
"options",
".",
"CheckpointID",
")",
"!=",
"0",
"{",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"options",
".",
"CheckpointID",
")",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"cli",
".",
"post",
"(",
"ctx",
",",
"\"",
"\"",
"+",
"containerID",
"+",
"\"",
"\"",
",",
"query",
",",
"nil",
",",
"nil",
")",
"\n",
"ensureReaderClosed",
"(",
"resp",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// ContainerStart sends a request to the docker daemon to start a container.
|
[
"ContainerStart",
"sends",
"a",
"request",
"to",
"the",
"docker",
"daemon",
"to",
"start",
"a",
"container",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/container_start.go#L12-L21
|
17,955 |
docker/engine-api
|
client/service_remove.go
|
ServiceRemove
|
func (cli *Client) ServiceRemove(ctx context.Context, serviceID string) error {
resp, err := cli.delete(ctx, "/services/"+serviceID, nil, nil)
ensureReaderClosed(resp)
return err
}
|
go
|
func (cli *Client) ServiceRemove(ctx context.Context, serviceID string) error {
resp, err := cli.delete(ctx, "/services/"+serviceID, nil, nil)
ensureReaderClosed(resp)
return err
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"ServiceRemove",
"(",
"ctx",
"context",
".",
"Context",
",",
"serviceID",
"string",
")",
"error",
"{",
"resp",
",",
"err",
":=",
"cli",
".",
"delete",
"(",
"ctx",
",",
"\"",
"\"",
"+",
"serviceID",
",",
"nil",
",",
"nil",
")",
"\n",
"ensureReaderClosed",
"(",
"resp",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// ServiceRemove kills and removes a service.
|
[
"ServiceRemove",
"kills",
"and",
"removes",
"a",
"service",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/service_remove.go#L6-L10
|
17,956 |
docker/engine-api
|
client/node_remove.go
|
NodeRemove
|
func (cli *Client) NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error {
query := url.Values{}
if options.Force {
query.Set("force", "1")
}
resp, err := cli.delete(ctx, "/nodes/"+nodeID, query, nil)
ensureReaderClosed(resp)
return err
}
|
go
|
func (cli *Client) NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error {
query := url.Values{}
if options.Force {
query.Set("force", "1")
}
resp, err := cli.delete(ctx, "/nodes/"+nodeID, query, nil)
ensureReaderClosed(resp)
return err
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"NodeRemove",
"(",
"ctx",
"context",
".",
"Context",
",",
"nodeID",
"string",
",",
"options",
"types",
".",
"NodeRemoveOptions",
")",
"error",
"{",
"query",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"if",
"options",
".",
"Force",
"{",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"cli",
".",
"delete",
"(",
"ctx",
",",
"\"",
"\"",
"+",
"nodeID",
",",
"query",
",",
"nil",
")",
"\n",
"ensureReaderClosed",
"(",
"resp",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// NodeRemove removes a Node.
|
[
"NodeRemove",
"removes",
"a",
"Node",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/node_remove.go#L12-L21
|
17,957 |
docker/engine-api
|
client/task_inspect.go
|
TaskInspectWithRaw
|
func (cli *Client) TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) {
serverResp, err := cli.get(ctx, "/tasks/"+taskID, nil, nil)
if err != nil {
if serverResp.statusCode == http.StatusNotFound {
return swarm.Task{}, nil, taskNotFoundError{taskID}
}
return swarm.Task{}, nil, err
}
defer ensureReaderClosed(serverResp)
body, err := ioutil.ReadAll(serverResp.body)
if err != nil {
return swarm.Task{}, nil, err
}
var response swarm.Task
rdr := bytes.NewReader(body)
err = json.NewDecoder(rdr).Decode(&response)
return response, body, err
}
|
go
|
func (cli *Client) TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) {
serverResp, err := cli.get(ctx, "/tasks/"+taskID, nil, nil)
if err != nil {
if serverResp.statusCode == http.StatusNotFound {
return swarm.Task{}, nil, taskNotFoundError{taskID}
}
return swarm.Task{}, nil, err
}
defer ensureReaderClosed(serverResp)
body, err := ioutil.ReadAll(serverResp.body)
if err != nil {
return swarm.Task{}, nil, err
}
var response swarm.Task
rdr := bytes.NewReader(body)
err = json.NewDecoder(rdr).Decode(&response)
return response, body, err
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"TaskInspectWithRaw",
"(",
"ctx",
"context",
".",
"Context",
",",
"taskID",
"string",
")",
"(",
"swarm",
".",
"Task",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"serverResp",
",",
"err",
":=",
"cli",
".",
"get",
"(",
"ctx",
",",
"\"",
"\"",
"+",
"taskID",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"serverResp",
".",
"statusCode",
"==",
"http",
".",
"StatusNotFound",
"{",
"return",
"swarm",
".",
"Task",
"{",
"}",
",",
"nil",
",",
"taskNotFoundError",
"{",
"taskID",
"}",
"\n",
"}",
"\n",
"return",
"swarm",
".",
"Task",
"{",
"}",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"ensureReaderClosed",
"(",
"serverResp",
")",
"\n\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"serverResp",
".",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"swarm",
".",
"Task",
"{",
"}",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"response",
"swarm",
".",
"Task",
"\n",
"rdr",
":=",
"bytes",
".",
"NewReader",
"(",
"body",
")",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"rdr",
")",
".",
"Decode",
"(",
"&",
"response",
")",
"\n",
"return",
"response",
",",
"body",
",",
"err",
"\n",
"}"
] |
// TaskInspectWithRaw returns the task information and its raw representation..
|
[
"TaskInspectWithRaw",
"returns",
"the",
"task",
"information",
"and",
"its",
"raw",
"representation",
".."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/task_inspect.go#L15-L34
|
17,958 |
docker/engine-api
|
client/checkpoint_list.go
|
CheckpointList
|
func (cli *Client) CheckpointList(ctx context.Context, container string) ([]types.Checkpoint, error) {
var checkpoints []types.Checkpoint
resp, err := cli.get(ctx, "/containers/"+container+"/checkpoints", nil, nil)
if err != nil {
return checkpoints, err
}
err = json.NewDecoder(resp.body).Decode(&checkpoints)
ensureReaderClosed(resp)
return checkpoints, err
}
|
go
|
func (cli *Client) CheckpointList(ctx context.Context, container string) ([]types.Checkpoint, error) {
var checkpoints []types.Checkpoint
resp, err := cli.get(ctx, "/containers/"+container+"/checkpoints", nil, nil)
if err != nil {
return checkpoints, err
}
err = json.NewDecoder(resp.body).Decode(&checkpoints)
ensureReaderClosed(resp)
return checkpoints, err
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"CheckpointList",
"(",
"ctx",
"context",
".",
"Context",
",",
"container",
"string",
")",
"(",
"[",
"]",
"types",
".",
"Checkpoint",
",",
"error",
")",
"{",
"var",
"checkpoints",
"[",
"]",
"types",
".",
"Checkpoint",
"\n\n",
"resp",
",",
"err",
":=",
"cli",
".",
"get",
"(",
"ctx",
",",
"\"",
"\"",
"+",
"container",
"+",
"\"",
"\"",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"checkpoints",
",",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"body",
")",
".",
"Decode",
"(",
"&",
"checkpoints",
")",
"\n",
"ensureReaderClosed",
"(",
"resp",
")",
"\n",
"return",
"checkpoints",
",",
"err",
"\n",
"}"
] |
// CheckpointList returns the volumes configured in the docker host.
|
[
"CheckpointList",
"returns",
"the",
"volumes",
"configured",
"in",
"the",
"docker",
"host",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/checkpoint_list.go#L11-L22
|
17,959 |
docker/engine-api
|
client/request.go
|
post
|
func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) {
return cli.sendRequest(ctx, "POST", path, query, obj, headers)
}
|
go
|
func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) {
return cli.sendRequest(ctx, "POST", path, query, obj, headers)
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"post",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"query",
"url",
".",
"Values",
",",
"obj",
"interface",
"{",
"}",
",",
"headers",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"(",
"serverResponse",
",",
"error",
")",
"{",
"return",
"cli",
".",
"sendRequest",
"(",
"ctx",
",",
"\"",
"\"",
",",
"path",
",",
"query",
",",
"obj",
",",
"headers",
")",
"\n",
"}"
] |
// postWithContext sends an http request to the docker API using the method POST with a specific go context.
|
[
"postWithContext",
"sends",
"an",
"http",
"request",
"to",
"the",
"docker",
"API",
"using",
"the",
"method",
"POST",
"with",
"a",
"specific",
"go",
"context",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/request.go#L38-L40
|
17,960 |
docker/engine-api
|
client/events.go
|
Events
|
func (cli *Client) Events(ctx context.Context, options types.EventsOptions) (io.ReadCloser, error) {
query := url.Values{}
ref := time.Now()
if options.Since != "" {
ts, err := timetypes.GetTimestamp(options.Since, ref)
if err != nil {
return nil, err
}
query.Set("since", ts)
}
if options.Until != "" {
ts, err := timetypes.GetTimestamp(options.Until, ref)
if err != nil {
return nil, err
}
query.Set("until", ts)
}
if options.Filters.Len() > 0 {
filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters)
if err != nil {
return nil, err
}
query.Set("filters", filterJSON)
}
serverResponse, err := cli.get(ctx, "/events", query, nil)
if err != nil {
return nil, err
}
return serverResponse.body, nil
}
|
go
|
func (cli *Client) Events(ctx context.Context, options types.EventsOptions) (io.ReadCloser, error) {
query := url.Values{}
ref := time.Now()
if options.Since != "" {
ts, err := timetypes.GetTimestamp(options.Since, ref)
if err != nil {
return nil, err
}
query.Set("since", ts)
}
if options.Until != "" {
ts, err := timetypes.GetTimestamp(options.Until, ref)
if err != nil {
return nil, err
}
query.Set("until", ts)
}
if options.Filters.Len() > 0 {
filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters)
if err != nil {
return nil, err
}
query.Set("filters", filterJSON)
}
serverResponse, err := cli.get(ctx, "/events", query, nil)
if err != nil {
return nil, err
}
return serverResponse.body, nil
}
|
[
"func",
"(",
"cli",
"*",
"Client",
")",
"Events",
"(",
"ctx",
"context",
".",
"Context",
",",
"options",
"types",
".",
"EventsOptions",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"query",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"ref",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"if",
"options",
".",
"Since",
"!=",
"\"",
"\"",
"{",
"ts",
",",
"err",
":=",
"timetypes",
".",
"GetTimestamp",
"(",
"options",
".",
"Since",
",",
"ref",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"ts",
")",
"\n",
"}",
"\n",
"if",
"options",
".",
"Until",
"!=",
"\"",
"\"",
"{",
"ts",
",",
"err",
":=",
"timetypes",
".",
"GetTimestamp",
"(",
"options",
".",
"Until",
",",
"ref",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"ts",
")",
"\n",
"}",
"\n",
"if",
"options",
".",
"Filters",
".",
"Len",
"(",
")",
">",
"0",
"{",
"filterJSON",
",",
"err",
":=",
"filters",
".",
"ToParamWithVersion",
"(",
"cli",
".",
"version",
",",
"options",
".",
"Filters",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"filterJSON",
")",
"\n",
"}",
"\n\n",
"serverResponse",
",",
"err",
":=",
"cli",
".",
"get",
"(",
"ctx",
",",
"\"",
"\"",
",",
"query",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"serverResponse",
".",
"body",
",",
"nil",
"\n",
"}"
] |
// Events returns a stream of events in the daemon in a ReadCloser.
// It's up to the caller to close the stream.
|
[
"Events",
"returns",
"a",
"stream",
"of",
"events",
"in",
"the",
"daemon",
"in",
"a",
"ReadCloser",
".",
"It",
"s",
"up",
"to",
"the",
"caller",
"to",
"close",
"the",
"stream",
"."
] |
4290f40c056686fcaa5c9caf02eac1dde9315adf
|
https://github.com/docker/engine-api/blob/4290f40c056686fcaa5c9caf02eac1dde9315adf/client/events.go#L17-L48
|
17,961 |
revel/cmd
|
revel/version.go
|
UpdateConfig
|
func (v *VersionCommand) UpdateConfig(c *model.CommandConfig, args []string) bool {
if len(args) > 0 {
c.Version.ImportPath = args[0]
}
return true
}
|
go
|
func (v *VersionCommand) UpdateConfig(c *model.CommandConfig, args []string) bool {
if len(args) > 0 {
c.Version.ImportPath = args[0]
}
return true
}
|
[
"func",
"(",
"v",
"*",
"VersionCommand",
")",
"UpdateConfig",
"(",
"c",
"*",
"model",
".",
"CommandConfig",
",",
"args",
"[",
"]",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"args",
")",
">",
"0",
"{",
"c",
".",
"Version",
".",
"ImportPath",
"=",
"args",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// Update the version
|
[
"Update",
"the",
"version"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/version.go#L58-L63
|
17,962 |
revel/cmd
|
revel/version.go
|
RunWith
|
func (v *VersionCommand) RunWith(c *model.CommandConfig) (err error) {
utils.Logger.Info("Requesting version information", "config", c)
v.Command = c
// Update the versions with the local values
v.updateLocalVersions()
needsUpdates := true
versionInfo := ""
for x := 0; x < 2 && needsUpdates; x++ {
needsUpdates = false
versionInfo, needsUpdates = v.doRepoCheck(x==0)
}
fmt.Println(versionInfo)
cmd := exec.Command(c.GoCmd, "version")
cmd.Stdout = os.Stdout
if e := cmd.Start(); e != nil {
fmt.Println("Go command error ", e)
} else {
cmd.Wait()
}
return
}
|
go
|
func (v *VersionCommand) RunWith(c *model.CommandConfig) (err error) {
utils.Logger.Info("Requesting version information", "config", c)
v.Command = c
// Update the versions with the local values
v.updateLocalVersions()
needsUpdates := true
versionInfo := ""
for x := 0; x < 2 && needsUpdates; x++ {
needsUpdates = false
versionInfo, needsUpdates = v.doRepoCheck(x==0)
}
fmt.Println(versionInfo)
cmd := exec.Command(c.GoCmd, "version")
cmd.Stdout = os.Stdout
if e := cmd.Start(); e != nil {
fmt.Println("Go command error ", e)
} else {
cmd.Wait()
}
return
}
|
[
"func",
"(",
"v",
"*",
"VersionCommand",
")",
"RunWith",
"(",
"c",
"*",
"model",
".",
"CommandConfig",
")",
"(",
"err",
"error",
")",
"{",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"c",
")",
"\n",
"v",
".",
"Command",
"=",
"c",
"\n\n",
"// Update the versions with the local values",
"v",
".",
"updateLocalVersions",
"(",
")",
"\n\n",
"needsUpdates",
":=",
"true",
"\n",
"versionInfo",
":=",
"\"",
"\"",
"\n",
"for",
"x",
":=",
"0",
";",
"x",
"<",
"2",
"&&",
"needsUpdates",
";",
"x",
"++",
"{",
"needsUpdates",
"=",
"false",
"\n",
"versionInfo",
",",
"needsUpdates",
"=",
"v",
".",
"doRepoCheck",
"(",
"x",
"==",
"0",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Println",
"(",
"versionInfo",
")",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"c",
".",
"GoCmd",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"os",
".",
"Stdout",
"\n",
"if",
"e",
":=",
"cmd",
".",
"Start",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"e",
")",
"\n",
"}",
"else",
"{",
"cmd",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] |
// Displays the version of go and Revel
|
[
"Displays",
"the",
"version",
"of",
"go",
"and",
"Revel"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/version.go#L66-L90
|
17,963 |
revel/cmd
|
revel/version.go
|
doRepoCheck
|
func (v *VersionCommand) doRepoCheck(updateLibs bool) (versionInfo string, needsUpdate bool) {
var (
title string
localVersion *model.Version
)
for _, repo := range []string{"revel", "cmd", "modules"} {
versonFromRepo, err := v.versionFromRepo(repo, "", "version.go")
if err != nil {
utils.Logger.Info("Failed to get version from repo", "repo", repo, "error", err)
}
switch repo {
case "revel":
title, repo, localVersion = "Revel Framework", "github.com/revel/revel", v.revelVersion
case "cmd":
title, repo, localVersion = "Revel Cmd", "github.com/revel/cmd/revel", v.cmdVersion
case "modules":
title, repo, localVersion = "Revel Modules", "github.com/revel/modules", v.modulesVersion
}
// Only do an update on the first loop, and if specified to update
shouldUpdate := updateLibs && v.Command.Version.Update
if v.Command.Version.Update {
if localVersion == nil || (versonFromRepo != nil && versonFromRepo.Newer(localVersion)) {
needsUpdate = true
if shouldUpdate {
v.doUpdate(title, repo, localVersion, versonFromRepo)
v.updateLocalVersions()
}
}
}
versionInfo = versionInfo + v.outputVersion(title, repo, localVersion, versonFromRepo)
}
return
}
|
go
|
func (v *VersionCommand) doRepoCheck(updateLibs bool) (versionInfo string, needsUpdate bool) {
var (
title string
localVersion *model.Version
)
for _, repo := range []string{"revel", "cmd", "modules"} {
versonFromRepo, err := v.versionFromRepo(repo, "", "version.go")
if err != nil {
utils.Logger.Info("Failed to get version from repo", "repo", repo, "error", err)
}
switch repo {
case "revel":
title, repo, localVersion = "Revel Framework", "github.com/revel/revel", v.revelVersion
case "cmd":
title, repo, localVersion = "Revel Cmd", "github.com/revel/cmd/revel", v.cmdVersion
case "modules":
title, repo, localVersion = "Revel Modules", "github.com/revel/modules", v.modulesVersion
}
// Only do an update on the first loop, and if specified to update
shouldUpdate := updateLibs && v.Command.Version.Update
if v.Command.Version.Update {
if localVersion == nil || (versonFromRepo != nil && versonFromRepo.Newer(localVersion)) {
needsUpdate = true
if shouldUpdate {
v.doUpdate(title, repo, localVersion, versonFromRepo)
v.updateLocalVersions()
}
}
}
versionInfo = versionInfo + v.outputVersion(title, repo, localVersion, versonFromRepo)
}
return
}
|
[
"func",
"(",
"v",
"*",
"VersionCommand",
")",
"doRepoCheck",
"(",
"updateLibs",
"bool",
")",
"(",
"versionInfo",
"string",
",",
"needsUpdate",
"bool",
")",
"{",
"var",
"(",
"title",
"string",
"\n",
"localVersion",
"*",
"model",
".",
"Version",
"\n",
")",
"\n",
"for",
"_",
",",
"repo",
":=",
"range",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"{",
"versonFromRepo",
",",
"err",
":=",
"v",
".",
"versionFromRepo",
"(",
"repo",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"repo",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"switch",
"repo",
"{",
"case",
"\"",
"\"",
":",
"title",
",",
"repo",
",",
"localVersion",
"=",
"\"",
"\"",
",",
"\"",
"\"",
",",
"v",
".",
"revelVersion",
"\n",
"case",
"\"",
"\"",
":",
"title",
",",
"repo",
",",
"localVersion",
"=",
"\"",
"\"",
",",
"\"",
"\"",
",",
"v",
".",
"cmdVersion",
"\n",
"case",
"\"",
"\"",
":",
"title",
",",
"repo",
",",
"localVersion",
"=",
"\"",
"\"",
",",
"\"",
"\"",
",",
"v",
".",
"modulesVersion",
"\n",
"}",
"\n\n",
"// Only do an update on the first loop, and if specified to update",
"shouldUpdate",
":=",
"updateLibs",
"&&",
"v",
".",
"Command",
".",
"Version",
".",
"Update",
"\n",
"if",
"v",
".",
"Command",
".",
"Version",
".",
"Update",
"{",
"if",
"localVersion",
"==",
"nil",
"||",
"(",
"versonFromRepo",
"!=",
"nil",
"&&",
"versonFromRepo",
".",
"Newer",
"(",
"localVersion",
")",
")",
"{",
"needsUpdate",
"=",
"true",
"\n",
"if",
"shouldUpdate",
"{",
"v",
".",
"doUpdate",
"(",
"title",
",",
"repo",
",",
"localVersion",
",",
"versonFromRepo",
")",
"\n",
"v",
".",
"updateLocalVersions",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"versionInfo",
"=",
"versionInfo",
"+",
"v",
".",
"outputVersion",
"(",
"title",
",",
"repo",
",",
"localVersion",
",",
"versonFromRepo",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Checks the Revel repos for the latest version
|
[
"Checks",
"the",
"Revel",
"repos",
"for",
"the",
"latest",
"version"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/version.go#L93-L126
|
17,964 |
revel/cmd
|
revel/version.go
|
doUpdate
|
func (v *VersionCommand) doUpdate(title, repo string, local, remote *model.Version) {
utils.Logger.Info("Updating package", "package", title, "repo",repo)
fmt.Println("Attempting to update package", title)
if err := v.Command.PackageResolver(repo); err != nil {
utils.Logger.Error("Unable to update repo", "repo", repo, "error", err)
} else if repo == "github.com/revel/cmd/revel" {
// One extra step required here to run the install for the command
utils.Logger.Fatal("Revel command tool was updated, you must manually run the following command before continuing\ngo install github.com/revel/cmd/revel")
}
return
}
|
go
|
func (v *VersionCommand) doUpdate(title, repo string, local, remote *model.Version) {
utils.Logger.Info("Updating package", "package", title, "repo",repo)
fmt.Println("Attempting to update package", title)
if err := v.Command.PackageResolver(repo); err != nil {
utils.Logger.Error("Unable to update repo", "repo", repo, "error", err)
} else if repo == "github.com/revel/cmd/revel" {
// One extra step required here to run the install for the command
utils.Logger.Fatal("Revel command tool was updated, you must manually run the following command before continuing\ngo install github.com/revel/cmd/revel")
}
return
}
|
[
"func",
"(",
"v",
"*",
"VersionCommand",
")",
"doUpdate",
"(",
"title",
",",
"repo",
"string",
",",
"local",
",",
"remote",
"*",
"model",
".",
"Version",
")",
"{",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"title",
",",
"\"",
"\"",
",",
"repo",
")",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"title",
")",
"\n",
"if",
"err",
":=",
"v",
".",
"Command",
".",
"PackageResolver",
"(",
"repo",
")",
";",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"repo",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"if",
"repo",
"==",
"\"",
"\"",
"{",
"// One extra step required here to run the install for the command",
"utils",
".",
"Logger",
".",
"Fatal",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Checks for updates if needed
|
[
"Checks",
"for",
"updates",
"if",
"needed"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/version.go#L129-L139
|
17,965 |
revel/cmd
|
revel/version.go
|
outputVersion
|
func (v *VersionCommand) outputVersion(title, repo string, local, remote *model.Version) (output string) {
buffer := &bytes.Buffer{}
remoteVersion := "Unknown"
if remote != nil {
remoteVersion = remote.VersionString()
}
localVersion := "Unknown"
if local != nil {
localVersion = local.VersionString()
}
fmt.Fprintf(buffer, "%s\t:\t%s\t(%s remote master branch)\n", title, localVersion, remoteVersion)
return buffer.String()
}
|
go
|
func (v *VersionCommand) outputVersion(title, repo string, local, remote *model.Version) (output string) {
buffer := &bytes.Buffer{}
remoteVersion := "Unknown"
if remote != nil {
remoteVersion = remote.VersionString()
}
localVersion := "Unknown"
if local != nil {
localVersion = local.VersionString()
}
fmt.Fprintf(buffer, "%s\t:\t%s\t(%s remote master branch)\n", title, localVersion, remoteVersion)
return buffer.String()
}
|
[
"func",
"(",
"v",
"*",
"VersionCommand",
")",
"outputVersion",
"(",
"title",
",",
"repo",
"string",
",",
"local",
",",
"remote",
"*",
"model",
".",
"Version",
")",
"(",
"output",
"string",
")",
"{",
"buffer",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"remoteVersion",
":=",
"\"",
"\"",
"\n",
"if",
"remote",
"!=",
"nil",
"{",
"remoteVersion",
"=",
"remote",
".",
"VersionString",
"(",
")",
"\n",
"}",
"\n",
"localVersion",
":=",
"\"",
"\"",
"\n",
"if",
"local",
"!=",
"nil",
"{",
"localVersion",
"=",
"local",
".",
"VersionString",
"(",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"buffer",
",",
"\"",
"\\t",
"\\t",
"\\t",
"\\n",
"\"",
",",
"title",
",",
"localVersion",
",",
"remoteVersion",
")",
"\n",
"return",
"buffer",
".",
"String",
"(",
")",
"\n",
"}"
] |
// Prints out the local and remote versions, calls update if needed
|
[
"Prints",
"out",
"the",
"local",
"and",
"remote",
"versions",
"calls",
"update",
"if",
"needed"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/version.go#L142-L155
|
17,966 |
revel/cmd
|
revel/version.go
|
versionFromRepo
|
func (v *VersionCommand) versionFromRepo(repoName, branchName, fileName string) (version *model.Version, err error) {
if branchName == "" {
branchName = "master"
}
// Try to download the version of file from the repo, just use an http connection to retrieve the source
// Assuming that the repo is github
fullurl := "https://raw.githubusercontent.com/revel/" + repoName + "/" + branchName + "/" + fileName
resp, err := http.Get(fullurl)
if err != nil {
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
utils.Logger.Info("Got version file", "from", fullurl, "content", string(body))
return v.versionFromBytes(body)
}
|
go
|
func (v *VersionCommand) versionFromRepo(repoName, branchName, fileName string) (version *model.Version, err error) {
if branchName == "" {
branchName = "master"
}
// Try to download the version of file from the repo, just use an http connection to retrieve the source
// Assuming that the repo is github
fullurl := "https://raw.githubusercontent.com/revel/" + repoName + "/" + branchName + "/" + fileName
resp, err := http.Get(fullurl)
if err != nil {
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
utils.Logger.Info("Got version file", "from", fullurl, "content", string(body))
return v.versionFromBytes(body)
}
|
[
"func",
"(",
"v",
"*",
"VersionCommand",
")",
"versionFromRepo",
"(",
"repoName",
",",
"branchName",
",",
"fileName",
"string",
")",
"(",
"version",
"*",
"model",
".",
"Version",
",",
"err",
"error",
")",
"{",
"if",
"branchName",
"==",
"\"",
"\"",
"{",
"branchName",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"// Try to download the version of file from the repo, just use an http connection to retrieve the source",
"// Assuming that the repo is github",
"fullurl",
":=",
"\"",
"\"",
"+",
"repoName",
"+",
"\"",
"\"",
"+",
"branchName",
"+",
"\"",
"\"",
"+",
"fileName",
"\n",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"fullurl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fullurl",
",",
"\"",
"\"",
",",
"string",
"(",
"body",
")",
")",
"\n\n",
"return",
"v",
".",
"versionFromBytes",
"(",
"body",
")",
"\n",
"}"
] |
// Returns the version from the repository
|
[
"Returns",
"the",
"version",
"from",
"the",
"repository"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/version.go#L158-L177
|
17,967 |
revel/cmd
|
revel/version.go
|
updateLocalVersions
|
func (v *VersionCommand) updateLocalVersions() {
v.cmdVersion = &model.Version{}
v.cmdVersion.ParseVersion(cmd.Version)
v.cmdVersion.BuildDate = cmd.BuildDate
v.cmdVersion.MinGoVersion = cmd.MinimumGoVersion
var modulePath, revelPath string
_, revelPath, err := utils.FindSrcPaths(v.Command.ImportPath, model.RevelImportPath, v.Command.PackageResolver)
if err != nil {
utils.Logger.Warn("Unable to extract version information from Revel library", "error,err")
return
}
revelPath = revelPath + model.RevelImportPath
utils.Logger.Info("Fullpath to revel", "dir", revelPath)
v.revelVersion, err = v.versionFromFilepath(revelPath)
if err != nil {
utils.Logger.Warn("Unable to extract version information from Revel", "error,err")
}
_, modulePath, err = utils.FindSrcPaths(v.Command.ImportPath, model.RevelModulesImportPath, v.Command.PackageResolver)
if err != nil {
utils.Logger.Warn("Unable to extract version information from Revel library", "error,err")
return
}
modulePath = modulePath + model.RevelModulesImportPath
v.modulesVersion, err = v.versionFromFilepath(modulePath)
if err != nil {
utils.Logger.Warn("Unable to extract version information from Revel Modules", "error", err)
}
return
}
|
go
|
func (v *VersionCommand) updateLocalVersions() {
v.cmdVersion = &model.Version{}
v.cmdVersion.ParseVersion(cmd.Version)
v.cmdVersion.BuildDate = cmd.BuildDate
v.cmdVersion.MinGoVersion = cmd.MinimumGoVersion
var modulePath, revelPath string
_, revelPath, err := utils.FindSrcPaths(v.Command.ImportPath, model.RevelImportPath, v.Command.PackageResolver)
if err != nil {
utils.Logger.Warn("Unable to extract version information from Revel library", "error,err")
return
}
revelPath = revelPath + model.RevelImportPath
utils.Logger.Info("Fullpath to revel", "dir", revelPath)
v.revelVersion, err = v.versionFromFilepath(revelPath)
if err != nil {
utils.Logger.Warn("Unable to extract version information from Revel", "error,err")
}
_, modulePath, err = utils.FindSrcPaths(v.Command.ImportPath, model.RevelModulesImportPath, v.Command.PackageResolver)
if err != nil {
utils.Logger.Warn("Unable to extract version information from Revel library", "error,err")
return
}
modulePath = modulePath + model.RevelModulesImportPath
v.modulesVersion, err = v.versionFromFilepath(modulePath)
if err != nil {
utils.Logger.Warn("Unable to extract version information from Revel Modules", "error", err)
}
return
}
|
[
"func",
"(",
"v",
"*",
"VersionCommand",
")",
"updateLocalVersions",
"(",
")",
"{",
"v",
".",
"cmdVersion",
"=",
"&",
"model",
".",
"Version",
"{",
"}",
"\n",
"v",
".",
"cmdVersion",
".",
"ParseVersion",
"(",
"cmd",
".",
"Version",
")",
"\n",
"v",
".",
"cmdVersion",
".",
"BuildDate",
"=",
"cmd",
".",
"BuildDate",
"\n",
"v",
".",
"cmdVersion",
".",
"MinGoVersion",
"=",
"cmd",
".",
"MinimumGoVersion",
"\n\n",
"var",
"modulePath",
",",
"revelPath",
"string",
"\n",
"_",
",",
"revelPath",
",",
"err",
":=",
"utils",
".",
"FindSrcPaths",
"(",
"v",
".",
"Command",
".",
"ImportPath",
",",
"model",
".",
"RevelImportPath",
",",
"v",
".",
"Command",
".",
"PackageResolver",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"revelPath",
"=",
"revelPath",
"+",
"model",
".",
"RevelImportPath",
"\n",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"revelPath",
")",
"\n",
"v",
".",
"revelVersion",
",",
"err",
"=",
"v",
".",
"versionFromFilepath",
"(",
"revelPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"_",
",",
"modulePath",
",",
"err",
"=",
"utils",
".",
"FindSrcPaths",
"(",
"v",
".",
"Command",
".",
"ImportPath",
",",
"model",
".",
"RevelModulesImportPath",
",",
"v",
".",
"Command",
".",
"PackageResolver",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"modulePath",
"=",
"modulePath",
"+",
"model",
".",
"RevelModulesImportPath",
"\n",
"v",
".",
"modulesVersion",
",",
"err",
"=",
"v",
".",
"versionFromFilepath",
"(",
"modulePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] |
// Fetch the local version of revel from the file system
|
[
"Fetch",
"the",
"local",
"version",
"of",
"revel",
"from",
"the",
"file",
"system"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/version.go#L231-L262
|
17,968 |
revel/cmd
|
revel/build.go
|
updateBuildConfig
|
func updateBuildConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.BUILD
// If arguments were passed in then there must be two
if len(args) < 2 {
fmt.Fprintf(os.Stderr, "%s\n%s", cmdBuild.UsageLine, cmdBuild.Long)
return false
}
c.Build.ImportPath = args[0]
c.Build.TargetPath = args[1]
if len(args) > 2 {
c.Build.Mode = args[2]
}
return true
}
|
go
|
func updateBuildConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.BUILD
// If arguments were passed in then there must be two
if len(args) < 2 {
fmt.Fprintf(os.Stderr, "%s\n%s", cmdBuild.UsageLine, cmdBuild.Long)
return false
}
c.Build.ImportPath = args[0]
c.Build.TargetPath = args[1]
if len(args) > 2 {
c.Build.Mode = args[2]
}
return true
}
|
[
"func",
"updateBuildConfig",
"(",
"c",
"*",
"model",
".",
"CommandConfig",
",",
"args",
"[",
"]",
"string",
")",
"bool",
"{",
"c",
".",
"Index",
"=",
"model",
".",
"BUILD",
"\n",
"// If arguments were passed in then there must be two",
"if",
"len",
"(",
"args",
")",
"<",
"2",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"cmdBuild",
".",
"UsageLine",
",",
"cmdBuild",
".",
"Long",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"c",
".",
"Build",
".",
"ImportPath",
"=",
"args",
"[",
"0",
"]",
"\n",
"c",
".",
"Build",
".",
"TargetPath",
"=",
"args",
"[",
"1",
"]",
"\n",
"if",
"len",
"(",
"args",
")",
">",
"2",
"{",
"c",
".",
"Build",
".",
"Mode",
"=",
"args",
"[",
"2",
"]",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// The update config updates the configuration command so that it can run
|
[
"The",
"update",
"config",
"updates",
"the",
"configuration",
"command",
"so",
"that",
"it",
"can",
"run"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/build.go#L39-L53
|
17,969 |
revel/cmd
|
revel/build.go
|
buildApp
|
func buildApp(c *model.CommandConfig) (err error) {
appImportPath, destPath, mode := c.ImportPath, c.Build.TargetPath, DefaultRunMode
if len(c.Build.Mode) > 0 {
mode = c.Build.Mode
}
// Convert target to absolute path
c.Build.TargetPath, _ = filepath.Abs(destPath)
c.Build.Mode = mode
c.Build.ImportPath = appImportPath
revel_paths, err := model.NewRevelPaths(mode, appImportPath, "", model.NewWrappedRevelCallback(nil, c.PackageResolver))
if err != nil {
return
}
buildSafetyCheck(destPath)
// Ensure the application can be built, this generates the main file
app, err := harness.Build(c, revel_paths)
if err != nil {
return err
}
// Copy files
// Included are:
// - run scripts
// - binary
// - revel
// - app
packageFolders, err := buildCopyFiles(c, app, revel_paths)
if err != nil {
return
}
err = buildCopyModules(c, revel_paths, packageFolders)
if err != nil {
return
}
err = buildWriteScripts(c, app)
if err != nil {
return
}
return
}
|
go
|
func buildApp(c *model.CommandConfig) (err error) {
appImportPath, destPath, mode := c.ImportPath, c.Build.TargetPath, DefaultRunMode
if len(c.Build.Mode) > 0 {
mode = c.Build.Mode
}
// Convert target to absolute path
c.Build.TargetPath, _ = filepath.Abs(destPath)
c.Build.Mode = mode
c.Build.ImportPath = appImportPath
revel_paths, err := model.NewRevelPaths(mode, appImportPath, "", model.NewWrappedRevelCallback(nil, c.PackageResolver))
if err != nil {
return
}
buildSafetyCheck(destPath)
// Ensure the application can be built, this generates the main file
app, err := harness.Build(c, revel_paths)
if err != nil {
return err
}
// Copy files
// Included are:
// - run scripts
// - binary
// - revel
// - app
packageFolders, err := buildCopyFiles(c, app, revel_paths)
if err != nil {
return
}
err = buildCopyModules(c, revel_paths, packageFolders)
if err != nil {
return
}
err = buildWriteScripts(c, app)
if err != nil {
return
}
return
}
|
[
"func",
"buildApp",
"(",
"c",
"*",
"model",
".",
"CommandConfig",
")",
"(",
"err",
"error",
")",
"{",
"appImportPath",
",",
"destPath",
",",
"mode",
":=",
"c",
".",
"ImportPath",
",",
"c",
".",
"Build",
".",
"TargetPath",
",",
"DefaultRunMode",
"\n",
"if",
"len",
"(",
"c",
".",
"Build",
".",
"Mode",
")",
">",
"0",
"{",
"mode",
"=",
"c",
".",
"Build",
".",
"Mode",
"\n",
"}",
"\n\n",
"// Convert target to absolute path",
"c",
".",
"Build",
".",
"TargetPath",
",",
"_",
"=",
"filepath",
".",
"Abs",
"(",
"destPath",
")",
"\n",
"c",
".",
"Build",
".",
"Mode",
"=",
"mode",
"\n",
"c",
".",
"Build",
".",
"ImportPath",
"=",
"appImportPath",
"\n\n",
"revel_paths",
",",
"err",
":=",
"model",
".",
"NewRevelPaths",
"(",
"mode",
",",
"appImportPath",
",",
"\"",
"\"",
",",
"model",
".",
"NewWrappedRevelCallback",
"(",
"nil",
",",
"c",
".",
"PackageResolver",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"buildSafetyCheck",
"(",
"destPath",
")",
"\n\n",
"// Ensure the application can be built, this generates the main file",
"app",
",",
"err",
":=",
"harness",
".",
"Build",
"(",
"c",
",",
"revel_paths",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Copy files",
"// Included are:",
"// - run scripts",
"// - binary",
"// - revel",
"// - app",
"packageFolders",
",",
"err",
":=",
"buildCopyFiles",
"(",
"c",
",",
"app",
",",
"revel_paths",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"err",
"=",
"buildCopyModules",
"(",
"c",
",",
"revel_paths",
",",
"packageFolders",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"err",
"=",
"buildWriteScripts",
"(",
"c",
",",
"app",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// The main entry point to build application from command line
|
[
"The",
"main",
"entry",
"point",
"to",
"build",
"application",
"from",
"command",
"line"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/build.go#L56-L99
|
17,970 |
revel/cmd
|
revel/build.go
|
buildCopyFiles
|
func buildCopyFiles(c *model.CommandConfig, app *harness.App, revel_paths *model.RevelContainer) (packageFolders []string, err error) {
appImportPath, destPath := c.ImportPath, c.Build.TargetPath
// Revel and the app are in a directory structure mirroring import path
srcPath := filepath.Join(destPath, "src")
destBinaryPath := filepath.Join(destPath, filepath.Base(app.BinaryPath))
tmpRevelPath := filepath.Join(srcPath, filepath.FromSlash(model.RevelImportPath))
if err = utils.CopyFile(destBinaryPath, app.BinaryPath); err != nil {
return
}
utils.MustChmod(destBinaryPath, 0755)
// Copy the templates from the revel
if err = utils.CopyDir(filepath.Join(tmpRevelPath, "conf"), filepath.Join(revel_paths.RevelPath, "conf"), nil); err != nil {
return
}
if err = utils.CopyDir(filepath.Join(tmpRevelPath, "templates"), filepath.Join(revel_paths.RevelPath, "templates"), nil); err != nil {
return
}
// Get the folders to be packaged
packageFolders = strings.Split(revel_paths.Config.StringDefault("package.folders", "conf,public,app/views"), ",")
for i, p := range packageFolders {
// Clean spaces, reformat slash to filesystem
packageFolders[i] = filepath.FromSlash(strings.TrimSpace(p))
}
if c.Build.CopySource {
err = utils.CopyDir(filepath.Join(srcPath, filepath.FromSlash(appImportPath)), revel_paths.BasePath, nil)
if err != nil {
return
}
} else {
for _, folder := range packageFolders {
err = utils.CopyDir(
filepath.Join(srcPath, filepath.FromSlash(appImportPath), folder),
filepath.Join(revel_paths.BasePath, folder),
nil)
if err != nil {
return
}
}
}
return
}
|
go
|
func buildCopyFiles(c *model.CommandConfig, app *harness.App, revel_paths *model.RevelContainer) (packageFolders []string, err error) {
appImportPath, destPath := c.ImportPath, c.Build.TargetPath
// Revel and the app are in a directory structure mirroring import path
srcPath := filepath.Join(destPath, "src")
destBinaryPath := filepath.Join(destPath, filepath.Base(app.BinaryPath))
tmpRevelPath := filepath.Join(srcPath, filepath.FromSlash(model.RevelImportPath))
if err = utils.CopyFile(destBinaryPath, app.BinaryPath); err != nil {
return
}
utils.MustChmod(destBinaryPath, 0755)
// Copy the templates from the revel
if err = utils.CopyDir(filepath.Join(tmpRevelPath, "conf"), filepath.Join(revel_paths.RevelPath, "conf"), nil); err != nil {
return
}
if err = utils.CopyDir(filepath.Join(tmpRevelPath, "templates"), filepath.Join(revel_paths.RevelPath, "templates"), nil); err != nil {
return
}
// Get the folders to be packaged
packageFolders = strings.Split(revel_paths.Config.StringDefault("package.folders", "conf,public,app/views"), ",")
for i, p := range packageFolders {
// Clean spaces, reformat slash to filesystem
packageFolders[i] = filepath.FromSlash(strings.TrimSpace(p))
}
if c.Build.CopySource {
err = utils.CopyDir(filepath.Join(srcPath, filepath.FromSlash(appImportPath)), revel_paths.BasePath, nil)
if err != nil {
return
}
} else {
for _, folder := range packageFolders {
err = utils.CopyDir(
filepath.Join(srcPath, filepath.FromSlash(appImportPath), folder),
filepath.Join(revel_paths.BasePath, folder),
nil)
if err != nil {
return
}
}
}
return
}
|
[
"func",
"buildCopyFiles",
"(",
"c",
"*",
"model",
".",
"CommandConfig",
",",
"app",
"*",
"harness",
".",
"App",
",",
"revel_paths",
"*",
"model",
".",
"RevelContainer",
")",
"(",
"packageFolders",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"appImportPath",
",",
"destPath",
":=",
"c",
".",
"ImportPath",
",",
"c",
".",
"Build",
".",
"TargetPath",
"\n\n",
"// Revel and the app are in a directory structure mirroring import path",
"srcPath",
":=",
"filepath",
".",
"Join",
"(",
"destPath",
",",
"\"",
"\"",
")",
"\n",
"destBinaryPath",
":=",
"filepath",
".",
"Join",
"(",
"destPath",
",",
"filepath",
".",
"Base",
"(",
"app",
".",
"BinaryPath",
")",
")",
"\n",
"tmpRevelPath",
":=",
"filepath",
".",
"Join",
"(",
"srcPath",
",",
"filepath",
".",
"FromSlash",
"(",
"model",
".",
"RevelImportPath",
")",
")",
"\n",
"if",
"err",
"=",
"utils",
".",
"CopyFile",
"(",
"destBinaryPath",
",",
"app",
".",
"BinaryPath",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"utils",
".",
"MustChmod",
"(",
"destBinaryPath",
",",
"0755",
")",
"\n\n",
"// Copy the templates from the revel",
"if",
"err",
"=",
"utils",
".",
"CopyDir",
"(",
"filepath",
".",
"Join",
"(",
"tmpRevelPath",
",",
"\"",
"\"",
")",
",",
"filepath",
".",
"Join",
"(",
"revel_paths",
".",
"RevelPath",
",",
"\"",
"\"",
")",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"err",
"=",
"utils",
".",
"CopyDir",
"(",
"filepath",
".",
"Join",
"(",
"tmpRevelPath",
",",
"\"",
"\"",
")",
",",
"filepath",
".",
"Join",
"(",
"revel_paths",
".",
"RevelPath",
",",
"\"",
"\"",
")",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Get the folders to be packaged",
"packageFolders",
"=",
"strings",
".",
"Split",
"(",
"revel_paths",
".",
"Config",
".",
"StringDefault",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"for",
"i",
",",
"p",
":=",
"range",
"packageFolders",
"{",
"// Clean spaces, reformat slash to filesystem",
"packageFolders",
"[",
"i",
"]",
"=",
"filepath",
".",
"FromSlash",
"(",
"strings",
".",
"TrimSpace",
"(",
"p",
")",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"Build",
".",
"CopySource",
"{",
"err",
"=",
"utils",
".",
"CopyDir",
"(",
"filepath",
".",
"Join",
"(",
"srcPath",
",",
"filepath",
".",
"FromSlash",
"(",
"appImportPath",
")",
")",
",",
"revel_paths",
".",
"BasePath",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"for",
"_",
",",
"folder",
":=",
"range",
"packageFolders",
"{",
"err",
"=",
"utils",
".",
"CopyDir",
"(",
"filepath",
".",
"Join",
"(",
"srcPath",
",",
"filepath",
".",
"FromSlash",
"(",
"appImportPath",
")",
",",
"folder",
")",
",",
"filepath",
".",
"Join",
"(",
"revel_paths",
".",
"BasePath",
",",
"folder",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] |
// Copy the files to the target
|
[
"Copy",
"the",
"files",
"to",
"the",
"target"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/build.go#L102-L147
|
17,971 |
revel/cmd
|
revel/build.go
|
buildCopyModules
|
func buildCopyModules(c *model.CommandConfig, revel_paths *model.RevelContainer, packageFolders []string) (err error) {
destPath := filepath.Join(c.Build.TargetPath, "src")
// Find all the modules used and copy them over.
config := revel_paths.Config.Raw()
modulePaths := make(map[string]string) // import path => filesystem path
// We should only copy over the section of options what the build is targeted for
// We will default to prod
for _, section := range config.Sections() {
// If the runmode is defined we will only import modules defined for that run mode
if c.Build.Mode != "" && c.Build.Mode != section {
continue
}
options, _ := config.SectionOptions(section)
for _, key := range options {
if !strings.HasPrefix(key, "module.") {
continue
}
moduleImportPath, _ := config.String(section, key)
if moduleImportPath == "" {
continue
}
modPkg, err := build.Import(moduleImportPath, revel_paths.RevelPath, build.FindOnly)
if err != nil {
utils.Logger.Fatalf("Failed to load module %s (%s): %s", key[len("module."):], c.ImportPath, err)
}
modulePaths[moduleImportPath] = modPkg.Dir
}
}
// Copy the the paths for each of the modules
for importPath, fsPath := range modulePaths {
utils.Logger.Info("Copy files ", "to", filepath.Join(destPath, importPath), "from", fsPath)
if c.Build.CopySource {
err = utils.CopyDir(filepath.Join(destPath, importPath), fsPath, nil)
if err != nil {
return
}
} else {
for _, folder := range packageFolders {
err = utils.CopyDir(
filepath.Join(destPath, importPath, folder),
filepath.Join(fsPath, folder),
nil)
if err != nil {
return
}
}
}
}
return
}
|
go
|
func buildCopyModules(c *model.CommandConfig, revel_paths *model.RevelContainer, packageFolders []string) (err error) {
destPath := filepath.Join(c.Build.TargetPath, "src")
// Find all the modules used and copy them over.
config := revel_paths.Config.Raw()
modulePaths := make(map[string]string) // import path => filesystem path
// We should only copy over the section of options what the build is targeted for
// We will default to prod
for _, section := range config.Sections() {
// If the runmode is defined we will only import modules defined for that run mode
if c.Build.Mode != "" && c.Build.Mode != section {
continue
}
options, _ := config.SectionOptions(section)
for _, key := range options {
if !strings.HasPrefix(key, "module.") {
continue
}
moduleImportPath, _ := config.String(section, key)
if moduleImportPath == "" {
continue
}
modPkg, err := build.Import(moduleImportPath, revel_paths.RevelPath, build.FindOnly)
if err != nil {
utils.Logger.Fatalf("Failed to load module %s (%s): %s", key[len("module."):], c.ImportPath, err)
}
modulePaths[moduleImportPath] = modPkg.Dir
}
}
// Copy the the paths for each of the modules
for importPath, fsPath := range modulePaths {
utils.Logger.Info("Copy files ", "to", filepath.Join(destPath, importPath), "from", fsPath)
if c.Build.CopySource {
err = utils.CopyDir(filepath.Join(destPath, importPath), fsPath, nil)
if err != nil {
return
}
} else {
for _, folder := range packageFolders {
err = utils.CopyDir(
filepath.Join(destPath, importPath, folder),
filepath.Join(fsPath, folder),
nil)
if err != nil {
return
}
}
}
}
return
}
|
[
"func",
"buildCopyModules",
"(",
"c",
"*",
"model",
".",
"CommandConfig",
",",
"revel_paths",
"*",
"model",
".",
"RevelContainer",
",",
"packageFolders",
"[",
"]",
"string",
")",
"(",
"err",
"error",
")",
"{",
"destPath",
":=",
"filepath",
".",
"Join",
"(",
"c",
".",
"Build",
".",
"TargetPath",
",",
"\"",
"\"",
")",
"\n",
"// Find all the modules used and copy them over.",
"config",
":=",
"revel_paths",
".",
"Config",
".",
"Raw",
"(",
")",
"\n",
"modulePaths",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"// import path => filesystem path",
"\n\n",
"// We should only copy over the section of options what the build is targeted for",
"// We will default to prod",
"for",
"_",
",",
"section",
":=",
"range",
"config",
".",
"Sections",
"(",
")",
"{",
"// If the runmode is defined we will only import modules defined for that run mode",
"if",
"c",
".",
"Build",
".",
"Mode",
"!=",
"\"",
"\"",
"&&",
"c",
".",
"Build",
".",
"Mode",
"!=",
"section",
"{",
"continue",
"\n",
"}",
"\n",
"options",
",",
"_",
":=",
"config",
".",
"SectionOptions",
"(",
"section",
")",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"options",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"moduleImportPath",
",",
"_",
":=",
"config",
".",
"String",
"(",
"section",
",",
"key",
")",
"\n",
"if",
"moduleImportPath",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"modPkg",
",",
"err",
":=",
"build",
".",
"Import",
"(",
"moduleImportPath",
",",
"revel_paths",
".",
"RevelPath",
",",
"build",
".",
"FindOnly",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"key",
"[",
"len",
"(",
"\"",
"\"",
")",
":",
"]",
",",
"c",
".",
"ImportPath",
",",
"err",
")",
"\n",
"}",
"\n",
"modulePaths",
"[",
"moduleImportPath",
"]",
"=",
"modPkg",
".",
"Dir",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Copy the the paths for each of the modules",
"for",
"importPath",
",",
"fsPath",
":=",
"range",
"modulePaths",
"{",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"filepath",
".",
"Join",
"(",
"destPath",
",",
"importPath",
")",
",",
"\"",
"\"",
",",
"fsPath",
")",
"\n",
"if",
"c",
".",
"Build",
".",
"CopySource",
"{",
"err",
"=",
"utils",
".",
"CopyDir",
"(",
"filepath",
".",
"Join",
"(",
"destPath",
",",
"importPath",
")",
",",
"fsPath",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"for",
"_",
",",
"folder",
":=",
"range",
"packageFolders",
"{",
"err",
"=",
"utils",
".",
"CopyDir",
"(",
"filepath",
".",
"Join",
"(",
"destPath",
",",
"importPath",
",",
"folder",
")",
",",
"filepath",
".",
"Join",
"(",
"fsPath",
",",
"folder",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] |
// Based on the section copy over the build modules
|
[
"Based",
"on",
"the",
"section",
"copy",
"over",
"the",
"build",
"modules"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/build.go#L150-L203
|
17,972 |
revel/cmd
|
revel/build.go
|
buildWriteScripts
|
func buildWriteScripts(c *model.CommandConfig, app *harness.App) (err error) {
tmplData := map[string]interface{}{
"BinName": filepath.Base(app.BinaryPath),
"ImportPath": c.Build.ImportPath,
"Mode": c.Build.Mode,
}
err = utils.GenerateTemplate(
filepath.Join(c.Build.TargetPath, "run.sh"),
PACKAGE_RUN_SH,
tmplData,
)
if err != nil {
return
}
utils.MustChmod(filepath.Join(c.Build.TargetPath, "run.sh"), 0755)
err = utils.GenerateTemplate(
filepath.Join(c.Build.TargetPath, "run.bat"),
PACKAGE_RUN_BAT,
tmplData,
)
if err != nil {
return
}
fmt.Println("Your application has been built in:", c.Build.TargetPath)
return
}
|
go
|
func buildWriteScripts(c *model.CommandConfig, app *harness.App) (err error) {
tmplData := map[string]interface{}{
"BinName": filepath.Base(app.BinaryPath),
"ImportPath": c.Build.ImportPath,
"Mode": c.Build.Mode,
}
err = utils.GenerateTemplate(
filepath.Join(c.Build.TargetPath, "run.sh"),
PACKAGE_RUN_SH,
tmplData,
)
if err != nil {
return
}
utils.MustChmod(filepath.Join(c.Build.TargetPath, "run.sh"), 0755)
err = utils.GenerateTemplate(
filepath.Join(c.Build.TargetPath, "run.bat"),
PACKAGE_RUN_BAT,
tmplData,
)
if err != nil {
return
}
fmt.Println("Your application has been built in:", c.Build.TargetPath)
return
}
|
[
"func",
"buildWriteScripts",
"(",
"c",
"*",
"model",
".",
"CommandConfig",
",",
"app",
"*",
"harness",
".",
"App",
")",
"(",
"err",
"error",
")",
"{",
"tmplData",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"filepath",
".",
"Base",
"(",
"app",
".",
"BinaryPath",
")",
",",
"\"",
"\"",
":",
"c",
".",
"Build",
".",
"ImportPath",
",",
"\"",
"\"",
":",
"c",
".",
"Build",
".",
"Mode",
",",
"}",
"\n\n",
"err",
"=",
"utils",
".",
"GenerateTemplate",
"(",
"filepath",
".",
"Join",
"(",
"c",
".",
"Build",
".",
"TargetPath",
",",
"\"",
"\"",
")",
",",
"PACKAGE_RUN_SH",
",",
"tmplData",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"utils",
".",
"MustChmod",
"(",
"filepath",
".",
"Join",
"(",
"c",
".",
"Build",
".",
"TargetPath",
",",
"\"",
"\"",
")",
",",
"0755",
")",
"\n",
"err",
"=",
"utils",
".",
"GenerateTemplate",
"(",
"filepath",
".",
"Join",
"(",
"c",
".",
"Build",
".",
"TargetPath",
",",
"\"",
"\"",
")",
",",
"PACKAGE_RUN_BAT",
",",
"tmplData",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"c",
".",
"Build",
".",
"TargetPath",
")",
"\n\n",
"return",
"\n",
"}"
] |
// Write the run scripts for the build
|
[
"Write",
"the",
"run",
"scripts",
"for",
"the",
"build"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/build.go#L206-L234
|
17,973 |
revel/cmd
|
revel/build.go
|
buildSafetyCheck
|
func buildSafetyCheck(destPath string) error {
// First, verify that it is either already empty or looks like a previous
// build (to avoid clobbering anything)
if utils.Exists(destPath) && !utils.Empty(destPath) && !utils.Exists(filepath.Join(destPath, "run.sh")) {
return utils.NewBuildError("Abort: %s exists and does not look like a build directory.", "path", destPath)
}
if err := os.RemoveAll(destPath); err != nil && !os.IsNotExist(err) {
return utils.NewBuildIfError(err, "Remove all error", "path", destPath)
}
if err := os.MkdirAll(destPath, 0777); err != nil {
return utils.NewBuildIfError(err, "MkDir all error", "path", destPath)
}
return nil
}
|
go
|
func buildSafetyCheck(destPath string) error {
// First, verify that it is either already empty or looks like a previous
// build (to avoid clobbering anything)
if utils.Exists(destPath) && !utils.Empty(destPath) && !utils.Exists(filepath.Join(destPath, "run.sh")) {
return utils.NewBuildError("Abort: %s exists and does not look like a build directory.", "path", destPath)
}
if err := os.RemoveAll(destPath); err != nil && !os.IsNotExist(err) {
return utils.NewBuildIfError(err, "Remove all error", "path", destPath)
}
if err := os.MkdirAll(destPath, 0777); err != nil {
return utils.NewBuildIfError(err, "MkDir all error", "path", destPath)
}
return nil
}
|
[
"func",
"buildSafetyCheck",
"(",
"destPath",
"string",
")",
"error",
"{",
"// First, verify that it is either already empty or looks like a previous",
"// build (to avoid clobbering anything)",
"if",
"utils",
".",
"Exists",
"(",
"destPath",
")",
"&&",
"!",
"utils",
".",
"Empty",
"(",
"destPath",
")",
"&&",
"!",
"utils",
".",
"Exists",
"(",
"filepath",
".",
"Join",
"(",
"destPath",
",",
"\"",
"\"",
")",
")",
"{",
"return",
"utils",
".",
"NewBuildError",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"destPath",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"os",
".",
"RemoveAll",
"(",
"destPath",
")",
";",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"utils",
".",
"NewBuildIfError",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"destPath",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"destPath",
",",
"0777",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"utils",
".",
"NewBuildIfError",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"destPath",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Checks to see if the target folder exists and can be created
|
[
"Checks",
"to",
"see",
"if",
"the",
"target",
"folder",
"exists",
"and",
"can",
"be",
"created"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/build.go#L237-L253
|
17,974 |
revel/cmd
|
model/revel_container.go
|
NewWrappedRevelCallback
|
func NewWrappedRevelCallback(fe func(key Event, value interface{}) (response EventResponse), ie func(pkgName string) error) RevelCallback {
return &WrappedRevelCallback{fe, ie}
}
|
go
|
func NewWrappedRevelCallback(fe func(key Event, value interface{}) (response EventResponse), ie func(pkgName string) error) RevelCallback {
return &WrappedRevelCallback{fe, ie}
}
|
[
"func",
"NewWrappedRevelCallback",
"(",
"fe",
"func",
"(",
"key",
"Event",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"response",
"EventResponse",
")",
",",
"ie",
"func",
"(",
"pkgName",
"string",
")",
"error",
")",
"RevelCallback",
"{",
"return",
"&",
"WrappedRevelCallback",
"{",
"fe",
",",
"ie",
"}",
"\n",
"}"
] |
// Simple Wrapped RevelCallback
|
[
"Simple",
"Wrapped",
"RevelCallback"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/revel_container.go#L78-L80
|
17,975 |
revel/cmd
|
model/revel_container.go
|
FireEvent
|
func (w *WrappedRevelCallback) FireEvent(key Event, value interface{}) (response EventResponse) {
if w.FireEventFunction != nil {
response = w.FireEventFunction(key, value)
}
return
}
|
go
|
func (w *WrappedRevelCallback) FireEvent(key Event, value interface{}) (response EventResponse) {
if w.FireEventFunction != nil {
response = w.FireEventFunction(key, value)
}
return
}
|
[
"func",
"(",
"w",
"*",
"WrappedRevelCallback",
")",
"FireEvent",
"(",
"key",
"Event",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"response",
"EventResponse",
")",
"{",
"if",
"w",
".",
"FireEventFunction",
"!=",
"nil",
"{",
"response",
"=",
"w",
".",
"FireEventFunction",
"(",
"key",
",",
"value",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Function to implement the FireEvent
|
[
"Function",
"to",
"implement",
"the",
"FireEvent"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/revel_container.go#L83-L88
|
17,976 |
revel/cmd
|
model/revel_container.go
|
loadModules
|
func (rp *RevelContainer) loadModules(callback RevelCallback) (err error) {
keys := []string{}
for _, key := range rp.Config.Options("module.") {
keys = append(keys, key)
}
// Reorder module order by key name, a poor mans sort but at least it is consistent
sort.Strings(keys)
for _, key := range keys {
moduleImportPath := rp.Config.StringDefault(key, "")
if moduleImportPath == "" {
continue
}
modulePath, err := rp.ResolveImportPath(moduleImportPath)
if err != nil {
utils.Logger.Info("Missing module ", "module_import_path", moduleImportPath, "error",err)
callback.PackageResolver(moduleImportPath)
modulePath, err = rp.ResolveImportPath(moduleImportPath)
if err != nil {
return fmt.Errorf("Failed to load module. Import of path failed %s:%s %s:%s ", "modulePath", moduleImportPath, "error", err)
}
}
// Drop anything between module.???.<name of module>
name := key[len("module."):]
if index := strings.Index(name, "."); index > -1 {
name = name[index+1:]
}
callback.FireEvent(REVEL_BEFORE_MODULE_LOADED, []interface{}{rp, name, moduleImportPath, modulePath})
rp.addModulePaths(name, moduleImportPath, modulePath)
callback.FireEvent(REVEL_AFTER_MODULE_LOADED, []interface{}{rp, name, moduleImportPath, modulePath})
}
return
}
|
go
|
func (rp *RevelContainer) loadModules(callback RevelCallback) (err error) {
keys := []string{}
for _, key := range rp.Config.Options("module.") {
keys = append(keys, key)
}
// Reorder module order by key name, a poor mans sort but at least it is consistent
sort.Strings(keys)
for _, key := range keys {
moduleImportPath := rp.Config.StringDefault(key, "")
if moduleImportPath == "" {
continue
}
modulePath, err := rp.ResolveImportPath(moduleImportPath)
if err != nil {
utils.Logger.Info("Missing module ", "module_import_path", moduleImportPath, "error",err)
callback.PackageResolver(moduleImportPath)
modulePath, err = rp.ResolveImportPath(moduleImportPath)
if err != nil {
return fmt.Errorf("Failed to load module. Import of path failed %s:%s %s:%s ", "modulePath", moduleImportPath, "error", err)
}
}
// Drop anything between module.???.<name of module>
name := key[len("module."):]
if index := strings.Index(name, "."); index > -1 {
name = name[index+1:]
}
callback.FireEvent(REVEL_BEFORE_MODULE_LOADED, []interface{}{rp, name, moduleImportPath, modulePath})
rp.addModulePaths(name, moduleImportPath, modulePath)
callback.FireEvent(REVEL_AFTER_MODULE_LOADED, []interface{}{rp, name, moduleImportPath, modulePath})
}
return
}
|
[
"func",
"(",
"rp",
"*",
"RevelContainer",
")",
"loadModules",
"(",
"callback",
"RevelCallback",
")",
"(",
"err",
"error",
")",
"{",
"keys",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"rp",
".",
"Config",
".",
"Options",
"(",
"\"",
"\"",
")",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"key",
")",
"\n",
"}",
"\n\n",
"// Reorder module order by key name, a poor mans sort but at least it is consistent",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"moduleImportPath",
":=",
"rp",
".",
"Config",
".",
"StringDefault",
"(",
"key",
",",
"\"",
"\"",
")",
"\n",
"if",
"moduleImportPath",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"modulePath",
",",
"err",
":=",
"rp",
".",
"ResolveImportPath",
"(",
"moduleImportPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"moduleImportPath",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"callback",
".",
"PackageResolver",
"(",
"moduleImportPath",
")",
"\n",
"modulePath",
",",
"err",
"=",
"rp",
".",
"ResolveImportPath",
"(",
"moduleImportPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"moduleImportPath",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Drop anything between module.???.<name of module>",
"name",
":=",
"key",
"[",
"len",
"(",
"\"",
"\"",
")",
":",
"]",
"\n",
"if",
"index",
":=",
"strings",
".",
"Index",
"(",
"name",
",",
"\"",
"\"",
")",
";",
"index",
">",
"-",
"1",
"{",
"name",
"=",
"name",
"[",
"index",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"callback",
".",
"FireEvent",
"(",
"REVEL_BEFORE_MODULE_LOADED",
",",
"[",
"]",
"interface",
"{",
"}",
"{",
"rp",
",",
"name",
",",
"moduleImportPath",
",",
"modulePath",
"}",
")",
"\n",
"rp",
".",
"addModulePaths",
"(",
"name",
",",
"moduleImportPath",
",",
"modulePath",
")",
"\n",
"callback",
".",
"FireEvent",
"(",
"REVEL_AFTER_MODULE_LOADED",
",",
"[",
"]",
"interface",
"{",
"}",
"{",
"rp",
",",
"name",
",",
"moduleImportPath",
",",
"modulePath",
"}",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Loads modules based on the configuration setup.
// This will fire the REVEL_BEFORE_MODULE_LOADED, REVEL_AFTER_MODULE_LOADED
// for each module loaded. The callback will receive the RevelContainer, name, moduleImportPath and modulePath
// It will automatically add in the code paths for the module to the
// container object
|
[
"Loads",
"modules",
"based",
"on",
"the",
"configuration",
"setup",
".",
"This",
"will",
"fire",
"the",
"REVEL_BEFORE_MODULE_LOADED",
"REVEL_AFTER_MODULE_LOADED",
"for",
"each",
"module",
"loaded",
".",
"The",
"callback",
"will",
"receive",
"the",
"RevelContainer",
"name",
"moduleImportPath",
"and",
"modulePath",
"It",
"will",
"automatically",
"add",
"in",
"the",
"code",
"paths",
"for",
"the",
"module",
"to",
"the",
"container",
"object"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/revel_container.go#L214-L247
|
17,977 |
revel/cmd
|
model/revel_container.go
|
addModulePaths
|
func (rp *RevelContainer) addModulePaths(name, importPath, modulePath string) {
if codePath := filepath.Join(modulePath, "app"); utils.DirExists(codePath) {
rp.CodePaths = append(rp.CodePaths, codePath)
rp.ModulePathMap[name] = modulePath
if viewsPath := filepath.Join(modulePath, "app", "views"); utils.DirExists(viewsPath) {
rp.TemplatePaths = append(rp.TemplatePaths, viewsPath)
}
}
// Hack: There is presently no way for the testrunner module to add the
// "test" subdirectory to the CodePaths. So this does it instead.
if importPath == rp.Config.StringDefault("module.testrunner", "github.com/revel/modules/testrunner") {
joinedPath := filepath.Join(rp.BasePath, "tests")
rp.CodePaths = append(rp.CodePaths, joinedPath)
}
if testsPath := filepath.Join(modulePath, "tests"); utils.DirExists(testsPath) {
rp.CodePaths = append(rp.CodePaths, testsPath)
}
}
|
go
|
func (rp *RevelContainer) addModulePaths(name, importPath, modulePath string) {
if codePath := filepath.Join(modulePath, "app"); utils.DirExists(codePath) {
rp.CodePaths = append(rp.CodePaths, codePath)
rp.ModulePathMap[name] = modulePath
if viewsPath := filepath.Join(modulePath, "app", "views"); utils.DirExists(viewsPath) {
rp.TemplatePaths = append(rp.TemplatePaths, viewsPath)
}
}
// Hack: There is presently no way for the testrunner module to add the
// "test" subdirectory to the CodePaths. So this does it instead.
if importPath == rp.Config.StringDefault("module.testrunner", "github.com/revel/modules/testrunner") {
joinedPath := filepath.Join(rp.BasePath, "tests")
rp.CodePaths = append(rp.CodePaths, joinedPath)
}
if testsPath := filepath.Join(modulePath, "tests"); utils.DirExists(testsPath) {
rp.CodePaths = append(rp.CodePaths, testsPath)
}
}
|
[
"func",
"(",
"rp",
"*",
"RevelContainer",
")",
"addModulePaths",
"(",
"name",
",",
"importPath",
",",
"modulePath",
"string",
")",
"{",
"if",
"codePath",
":=",
"filepath",
".",
"Join",
"(",
"modulePath",
",",
"\"",
"\"",
")",
";",
"utils",
".",
"DirExists",
"(",
"codePath",
")",
"{",
"rp",
".",
"CodePaths",
"=",
"append",
"(",
"rp",
".",
"CodePaths",
",",
"codePath",
")",
"\n",
"rp",
".",
"ModulePathMap",
"[",
"name",
"]",
"=",
"modulePath",
"\n",
"if",
"viewsPath",
":=",
"filepath",
".",
"Join",
"(",
"modulePath",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
";",
"utils",
".",
"DirExists",
"(",
"viewsPath",
")",
"{",
"rp",
".",
"TemplatePaths",
"=",
"append",
"(",
"rp",
".",
"TemplatePaths",
",",
"viewsPath",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Hack: There is presently no way for the testrunner module to add the",
"// \"test\" subdirectory to the CodePaths. So this does it instead.",
"if",
"importPath",
"==",
"rp",
".",
"Config",
".",
"StringDefault",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"{",
"joinedPath",
":=",
"filepath",
".",
"Join",
"(",
"rp",
".",
"BasePath",
",",
"\"",
"\"",
")",
"\n",
"rp",
".",
"CodePaths",
"=",
"append",
"(",
"rp",
".",
"CodePaths",
",",
"joinedPath",
")",
"\n",
"}",
"\n",
"if",
"testsPath",
":=",
"filepath",
".",
"Join",
"(",
"modulePath",
",",
"\"",
"\"",
")",
";",
"utils",
".",
"DirExists",
"(",
"testsPath",
")",
"{",
"rp",
".",
"CodePaths",
"=",
"append",
"(",
"rp",
".",
"CodePaths",
",",
"testsPath",
")",
"\n",
"}",
"\n",
"}"
] |
// Adds a module paths to the container object
|
[
"Adds",
"a",
"module",
"paths",
"to",
"the",
"container",
"object"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/revel_container.go#L250-L268
|
17,978 |
revel/cmd
|
harness/build.go
|
genSource
|
func genSource(paths *model.RevelContainer, dir, filename, templateSource string, args map[string]interface{}) error {
return utils.GenerateTemplate(filepath.Join(paths.AppPath, dir, filename), templateSource, args)
}
|
go
|
func genSource(paths *model.RevelContainer, dir, filename, templateSource string, args map[string]interface{}) error {
return utils.GenerateTemplate(filepath.Join(paths.AppPath, dir, filename), templateSource, args)
}
|
[
"func",
"genSource",
"(",
"paths",
"*",
"model",
".",
"RevelContainer",
",",
"dir",
",",
"filename",
",",
"templateSource",
"string",
",",
"args",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"utils",
".",
"GenerateTemplate",
"(",
"filepath",
".",
"Join",
"(",
"paths",
".",
"AppPath",
",",
"dir",
",",
"filename",
")",
",",
"templateSource",
",",
"args",
")",
"\n",
"}"
] |
// genSource renders the given template to produce source code, which it writes
// to the given directory and file.
|
[
"genSource",
"renders",
"the",
"given",
"template",
"to",
"produce",
"source",
"code",
"which",
"it",
"writes",
"to",
"the",
"given",
"directory",
"and",
"file",
"."
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/build.go#L309-L312
|
17,979 |
revel/cmd
|
harness/build.go
|
calcImportAliases
|
func calcImportAliases(src *model.SourceInfo) map[string]string {
aliases := make(map[string]string)
typeArrays := [][]*model.TypeInfo{src.ControllerSpecs(), src.TestSuites()}
for _, specs := range typeArrays {
for _, spec := range specs {
addAlias(aliases, spec.ImportPath, spec.PackageName)
for _, methSpec := range spec.MethodSpecs {
for _, methArg := range methSpec.Args {
if methArg.ImportPath == "" {
continue
}
addAlias(aliases, methArg.ImportPath, methArg.TypeExpr.PkgName)
}
}
}
}
// Add the "InitImportPaths", with alias "_"
for _, importPath := range src.InitImportPaths {
if _, ok := aliases[importPath]; !ok {
aliases[importPath] = "_"
}
}
return aliases
}
|
go
|
func calcImportAliases(src *model.SourceInfo) map[string]string {
aliases := make(map[string]string)
typeArrays := [][]*model.TypeInfo{src.ControllerSpecs(), src.TestSuites()}
for _, specs := range typeArrays {
for _, spec := range specs {
addAlias(aliases, spec.ImportPath, spec.PackageName)
for _, methSpec := range spec.MethodSpecs {
for _, methArg := range methSpec.Args {
if methArg.ImportPath == "" {
continue
}
addAlias(aliases, methArg.ImportPath, methArg.TypeExpr.PkgName)
}
}
}
}
// Add the "InitImportPaths", with alias "_"
for _, importPath := range src.InitImportPaths {
if _, ok := aliases[importPath]; !ok {
aliases[importPath] = "_"
}
}
return aliases
}
|
[
"func",
"calcImportAliases",
"(",
"src",
"*",
"model",
".",
"SourceInfo",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"aliases",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"typeArrays",
":=",
"[",
"]",
"[",
"]",
"*",
"model",
".",
"TypeInfo",
"{",
"src",
".",
"ControllerSpecs",
"(",
")",
",",
"src",
".",
"TestSuites",
"(",
")",
"}",
"\n",
"for",
"_",
",",
"specs",
":=",
"range",
"typeArrays",
"{",
"for",
"_",
",",
"spec",
":=",
"range",
"specs",
"{",
"addAlias",
"(",
"aliases",
",",
"spec",
".",
"ImportPath",
",",
"spec",
".",
"PackageName",
")",
"\n\n",
"for",
"_",
",",
"methSpec",
":=",
"range",
"spec",
".",
"MethodSpecs",
"{",
"for",
"_",
",",
"methArg",
":=",
"range",
"methSpec",
".",
"Args",
"{",
"if",
"methArg",
".",
"ImportPath",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"addAlias",
"(",
"aliases",
",",
"methArg",
".",
"ImportPath",
",",
"methArg",
".",
"TypeExpr",
".",
"PkgName",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Add the \"InitImportPaths\", with alias \"_\"",
"for",
"_",
",",
"importPath",
":=",
"range",
"src",
".",
"InitImportPaths",
"{",
"if",
"_",
",",
"ok",
":=",
"aliases",
"[",
"importPath",
"]",
";",
"!",
"ok",
"{",
"aliases",
"[",
"importPath",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"aliases",
"\n",
"}"
] |
// Looks through all the method args and returns a set of unique import paths
// that cover all the method arg types.
// Additionally, assign package aliases when necessary to resolve ambiguity.
|
[
"Looks",
"through",
"all",
"the",
"method",
"args",
"and",
"returns",
"a",
"set",
"of",
"unique",
"import",
"paths",
"that",
"cover",
"all",
"the",
"method",
"arg",
"types",
".",
"Additionally",
"assign",
"package",
"aliases",
"when",
"necessary",
"to",
"resolve",
"ambiguity",
"."
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/build.go#L317-L344
|
17,980 |
revel/cmd
|
harness/build.go
|
addAlias
|
func addAlias(aliases map[string]string, importPath, pkgName string) {
alias, ok := aliases[importPath]
if ok {
return
}
alias = makePackageAlias(aliases, pkgName)
aliases[importPath] = alias
}
|
go
|
func addAlias(aliases map[string]string, importPath, pkgName string) {
alias, ok := aliases[importPath]
if ok {
return
}
alias = makePackageAlias(aliases, pkgName)
aliases[importPath] = alias
}
|
[
"func",
"addAlias",
"(",
"aliases",
"map",
"[",
"string",
"]",
"string",
",",
"importPath",
",",
"pkgName",
"string",
")",
"{",
"alias",
",",
"ok",
":=",
"aliases",
"[",
"importPath",
"]",
"\n",
"if",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"alias",
"=",
"makePackageAlias",
"(",
"aliases",
",",
"pkgName",
")",
"\n",
"aliases",
"[",
"importPath",
"]",
"=",
"alias",
"\n",
"}"
] |
// Adds an alias to the map of alias names
|
[
"Adds",
"an",
"alias",
"to",
"the",
"map",
"of",
"alias",
"names"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/build.go#L347-L354
|
17,981 |
revel/cmd
|
harness/build.go
|
makePackageAlias
|
func makePackageAlias(aliases map[string]string, pkgName string) string {
i := 0
alias := pkgName
for containsValue(aliases, alias) || alias == "revel" {
alias = fmt.Sprintf("%s%d", pkgName, i)
i++
}
return alias
}
|
go
|
func makePackageAlias(aliases map[string]string, pkgName string) string {
i := 0
alias := pkgName
for containsValue(aliases, alias) || alias == "revel" {
alias = fmt.Sprintf("%s%d", pkgName, i)
i++
}
return alias
}
|
[
"func",
"makePackageAlias",
"(",
"aliases",
"map",
"[",
"string",
"]",
"string",
",",
"pkgName",
"string",
")",
"string",
"{",
"i",
":=",
"0",
"\n",
"alias",
":=",
"pkgName",
"\n",
"for",
"containsValue",
"(",
"aliases",
",",
"alias",
")",
"||",
"alias",
"==",
"\"",
"\"",
"{",
"alias",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"pkgName",
",",
"i",
")",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"return",
"alias",
"\n",
"}"
] |
// Generates a package alias
|
[
"Generates",
"a",
"package",
"alias"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/build.go#L357-L365
|
17,982 |
revel/cmd
|
harness/build.go
|
containsValue
|
func containsValue(m map[string]string, val string) bool {
for _, v := range m {
if v == val {
return true
}
}
return false
}
|
go
|
func containsValue(m map[string]string, val string) bool {
for _, v := range m {
if v == val {
return true
}
}
return false
}
|
[
"func",
"containsValue",
"(",
"m",
"map",
"[",
"string",
"]",
"string",
",",
"val",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"m",
"{",
"if",
"v",
"==",
"val",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Returns true if this value is in the map
|
[
"Returns",
"true",
"if",
"this",
"value",
"is",
"in",
"the",
"map"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/build.go#L368-L375
|
17,983 |
revel/cmd
|
harness/build.go
|
newCompileError
|
func newCompileError(paths *model.RevelContainer, output []byte) *utils.Error {
errorMatch := regexp.MustCompile(`(?m)^([^:#]+):(\d+):(\d+:)? (.*)$`).
FindSubmatch(output)
if errorMatch == nil {
errorMatch = regexp.MustCompile(`(?m)^(.*?):(\d+):\s(.*?)$`).FindSubmatch(output)
if errorMatch == nil {
utils.Logger.Error("Failed to parse build errors", "error", string(output))
return &utils.Error{
SourceType: "Go code",
Title: "Go Compilation Error",
Description: "See console for build error.",
}
}
errorMatch = append(errorMatch, errorMatch[3])
utils.Logger.Error("Build errors", "errors", string(output))
}
findInPaths := func(relFilename string) string {
// Extract the paths from the gopaths, and search for file there first
gopaths := filepath.SplitList(build.Default.GOPATH)
for _, gp := range gopaths {
newPath := filepath.Join(gp,"src", paths.ImportPath, relFilename)
println(newPath)
if utils.Exists(newPath) {
return newPath
}
}
newPath, _ := filepath.Abs(relFilename)
utils.Logger.Warn("Could not find in GO path", "file", relFilename)
return newPath
}
// Read the source for the offending file.
var (
relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go"
absFilename = findInPaths(relFilename)
line, _ = strconv.Atoi(string(errorMatch[2]))
description = string(errorMatch[4])
compileError = &utils.Error{
SourceType: "Go code",
Title: "Go Compilation Error",
Path: relFilename,
Description: description,
Line: line,
}
)
errorLink := paths.Config.StringDefault("error.link", "")
if errorLink != "" {
compileError.SetLink(errorLink)
}
fileStr, err := utils.ReadLines(absFilename)
if err != nil {
compileError.MetaError = absFilename + ": " + err.Error()
utils.Logger.Info("Unable to readlines "+compileError.MetaError, "error", err)
return compileError
}
compileError.SourceLines = fileStr
return compileError
}
|
go
|
func newCompileError(paths *model.RevelContainer, output []byte) *utils.Error {
errorMatch := regexp.MustCompile(`(?m)^([^:#]+):(\d+):(\d+:)? (.*)$`).
FindSubmatch(output)
if errorMatch == nil {
errorMatch = regexp.MustCompile(`(?m)^(.*?):(\d+):\s(.*?)$`).FindSubmatch(output)
if errorMatch == nil {
utils.Logger.Error("Failed to parse build errors", "error", string(output))
return &utils.Error{
SourceType: "Go code",
Title: "Go Compilation Error",
Description: "See console for build error.",
}
}
errorMatch = append(errorMatch, errorMatch[3])
utils.Logger.Error("Build errors", "errors", string(output))
}
findInPaths := func(relFilename string) string {
// Extract the paths from the gopaths, and search for file there first
gopaths := filepath.SplitList(build.Default.GOPATH)
for _, gp := range gopaths {
newPath := filepath.Join(gp,"src", paths.ImportPath, relFilename)
println(newPath)
if utils.Exists(newPath) {
return newPath
}
}
newPath, _ := filepath.Abs(relFilename)
utils.Logger.Warn("Could not find in GO path", "file", relFilename)
return newPath
}
// Read the source for the offending file.
var (
relFilename = string(errorMatch[1]) // e.g. "src/revel/sample/app/controllers/app.go"
absFilename = findInPaths(relFilename)
line, _ = strconv.Atoi(string(errorMatch[2]))
description = string(errorMatch[4])
compileError = &utils.Error{
SourceType: "Go code",
Title: "Go Compilation Error",
Path: relFilename,
Description: description,
Line: line,
}
)
errorLink := paths.Config.StringDefault("error.link", "")
if errorLink != "" {
compileError.SetLink(errorLink)
}
fileStr, err := utils.ReadLines(absFilename)
if err != nil {
compileError.MetaError = absFilename + ": " + err.Error()
utils.Logger.Info("Unable to readlines "+compileError.MetaError, "error", err)
return compileError
}
compileError.SourceLines = fileStr
return compileError
}
|
[
"func",
"newCompileError",
"(",
"paths",
"*",
"model",
".",
"RevelContainer",
",",
"output",
"[",
"]",
"byte",
")",
"*",
"utils",
".",
"Error",
"{",
"errorMatch",
":=",
"regexp",
".",
"MustCompile",
"(",
"`(?m)^([^:#]+):(\\d+):(\\d+:)? (.*)$`",
")",
".",
"FindSubmatch",
"(",
"output",
")",
"\n",
"if",
"errorMatch",
"==",
"nil",
"{",
"errorMatch",
"=",
"regexp",
".",
"MustCompile",
"(",
"`(?m)^(.*?):(\\d+):\\s(.*?)$`",
")",
".",
"FindSubmatch",
"(",
"output",
")",
"\n\n",
"if",
"errorMatch",
"==",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"string",
"(",
"output",
")",
")",
"\n",
"return",
"&",
"utils",
".",
"Error",
"{",
"SourceType",
":",
"\"",
"\"",
",",
"Title",
":",
"\"",
"\"",
",",
"Description",
":",
"\"",
"\"",
",",
"}",
"\n",
"}",
"\n\n",
"errorMatch",
"=",
"append",
"(",
"errorMatch",
",",
"errorMatch",
"[",
"3",
"]",
")",
"\n\n",
"utils",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"string",
"(",
"output",
")",
")",
"\n",
"}",
"\n\n",
"findInPaths",
":=",
"func",
"(",
"relFilename",
"string",
")",
"string",
"{",
"// Extract the paths from the gopaths, and search for file there first",
"gopaths",
":=",
"filepath",
".",
"SplitList",
"(",
"build",
".",
"Default",
".",
"GOPATH",
")",
"\n",
"for",
"_",
",",
"gp",
":=",
"range",
"gopaths",
"{",
"newPath",
":=",
"filepath",
".",
"Join",
"(",
"gp",
",",
"\"",
"\"",
",",
"paths",
".",
"ImportPath",
",",
"relFilename",
")",
"\n",
"println",
"(",
"newPath",
")",
"\n",
"if",
"utils",
".",
"Exists",
"(",
"newPath",
")",
"{",
"return",
"newPath",
"\n",
"}",
"\n",
"}",
"\n",
"newPath",
",",
"_",
":=",
"filepath",
".",
"Abs",
"(",
"relFilename",
")",
"\n",
"utils",
".",
"Logger",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"relFilename",
")",
"\n",
"return",
"newPath",
"\n",
"}",
"\n\n\n",
"// Read the source for the offending file.",
"var",
"(",
"relFilename",
"=",
"string",
"(",
"errorMatch",
"[",
"1",
"]",
")",
"// e.g. \"src/revel/sample/app/controllers/app.go\"",
"\n",
"absFilename",
"=",
"findInPaths",
"(",
"relFilename",
")",
"\n",
"line",
",",
"_",
"=",
"strconv",
".",
"Atoi",
"(",
"string",
"(",
"errorMatch",
"[",
"2",
"]",
")",
")",
"\n",
"description",
"=",
"string",
"(",
"errorMatch",
"[",
"4",
"]",
")",
"\n",
"compileError",
"=",
"&",
"utils",
".",
"Error",
"{",
"SourceType",
":",
"\"",
"\"",
",",
"Title",
":",
"\"",
"\"",
",",
"Path",
":",
"relFilename",
",",
"Description",
":",
"description",
",",
"Line",
":",
"line",
",",
"}",
"\n",
")",
"\n\n",
"errorLink",
":=",
"paths",
".",
"Config",
".",
"StringDefault",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"errorLink",
"!=",
"\"",
"\"",
"{",
"compileError",
".",
"SetLink",
"(",
"errorLink",
")",
"\n",
"}",
"\n\n",
"fileStr",
",",
"err",
":=",
"utils",
".",
"ReadLines",
"(",
"absFilename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"compileError",
".",
"MetaError",
"=",
"absFilename",
"+",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
"\n",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
"+",
"compileError",
".",
"MetaError",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"compileError",
"\n",
"}",
"\n\n",
"compileError",
".",
"SourceLines",
"=",
"fileStr",
"\n",
"return",
"compileError",
"\n",
"}"
] |
// Parse the output of the "go build" command.
// Return a detailed Error.
|
[
"Parse",
"the",
"output",
"of",
"the",
"go",
"build",
"command",
".",
"Return",
"a",
"detailed",
"Error",
"."
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/build.go#L379-L445
|
17,984 |
revel/cmd
|
utils/error.go
|
NewError
|
func NewError(source, title,path,description string) *Error {
return &Error {
SourceType:source,
Title:title,
Path:path,
Description:description,
}
}
|
go
|
func NewError(source, title,path,description string) *Error {
return &Error {
SourceType:source,
Title:title,
Path:path,
Description:description,
}
}
|
[
"func",
"NewError",
"(",
"source",
",",
"title",
",",
"path",
",",
"description",
"string",
")",
"*",
"Error",
"{",
"return",
"&",
"Error",
"{",
"SourceType",
":",
"source",
",",
"Title",
":",
"title",
",",
"Path",
":",
"path",
",",
"Description",
":",
"description",
",",
"}",
"\n",
"}"
] |
// Return a new error object
|
[
"Return",
"a",
"new",
"error",
"object"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/error.go#L27-L34
|
17,985 |
revel/cmd
|
parser/imports.go
|
addImports
|
func addImports(imports map[string]string, decl ast.Decl, srcDir string) {
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
return
}
if genDecl.Tok != token.IMPORT {
return
}
for _, spec := range genDecl.Specs {
importSpec := spec.(*ast.ImportSpec)
var pkgAlias string
if importSpec.Name != nil {
pkgAlias = importSpec.Name.Name
if pkgAlias == "_" {
continue
}
}
quotedPath := importSpec.Path.Value // e.g. "\"sample/app/models\""
fullPath := quotedPath[1 : len(quotedPath)-1] // Remove the quotes
// If the package was not aliased (common case), we have to import it
// to see what the package name is.
// TODO: Can improve performance here a lot:
// 1. Do not import everything over and over again. Keep a cache.
// 2. Exempt the standard library; their directories always match the package name.
// 3. Can use build.FindOnly and then use parser.ParseDir with mode PackageClauseOnly
if pkgAlias == "" {
utils.Logger.Debug("Reading from build", "path", fullPath, "srcPath", srcDir, "gopath", build.Default.GOPATH)
pkg, err := build.Import(fullPath, srcDir, 0)
if err != nil {
// We expect this to happen for apps using reverse routing (since we
// have not yet generated the routes). Don't log that.
if !strings.HasSuffix(fullPath, "/app/routes") {
utils.Logger.Error("Could not find import:", "path", fullPath, "srcPath", srcDir, "error", err)
}
continue
} else {
utils.Logger.Debug("Found package in dir", "dir", pkg.Dir, "name", pkg.ImportPath)
}
pkgAlias = pkg.Name
}
imports[pkgAlias] = fullPath
}
}
|
go
|
func addImports(imports map[string]string, decl ast.Decl, srcDir string) {
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
return
}
if genDecl.Tok != token.IMPORT {
return
}
for _, spec := range genDecl.Specs {
importSpec := spec.(*ast.ImportSpec)
var pkgAlias string
if importSpec.Name != nil {
pkgAlias = importSpec.Name.Name
if pkgAlias == "_" {
continue
}
}
quotedPath := importSpec.Path.Value // e.g. "\"sample/app/models\""
fullPath := quotedPath[1 : len(quotedPath)-1] // Remove the quotes
// If the package was not aliased (common case), we have to import it
// to see what the package name is.
// TODO: Can improve performance here a lot:
// 1. Do not import everything over and over again. Keep a cache.
// 2. Exempt the standard library; their directories always match the package name.
// 3. Can use build.FindOnly and then use parser.ParseDir with mode PackageClauseOnly
if pkgAlias == "" {
utils.Logger.Debug("Reading from build", "path", fullPath, "srcPath", srcDir, "gopath", build.Default.GOPATH)
pkg, err := build.Import(fullPath, srcDir, 0)
if err != nil {
// We expect this to happen for apps using reverse routing (since we
// have not yet generated the routes). Don't log that.
if !strings.HasSuffix(fullPath, "/app/routes") {
utils.Logger.Error("Could not find import:", "path", fullPath, "srcPath", srcDir, "error", err)
}
continue
} else {
utils.Logger.Debug("Found package in dir", "dir", pkg.Dir, "name", pkg.ImportPath)
}
pkgAlias = pkg.Name
}
imports[pkgAlias] = fullPath
}
}
|
[
"func",
"addImports",
"(",
"imports",
"map",
"[",
"string",
"]",
"string",
",",
"decl",
"ast",
".",
"Decl",
",",
"srcDir",
"string",
")",
"{",
"genDecl",
",",
"ok",
":=",
"decl",
".",
"(",
"*",
"ast",
".",
"GenDecl",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"genDecl",
".",
"Tok",
"!=",
"token",
".",
"IMPORT",
"{",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"spec",
":=",
"range",
"genDecl",
".",
"Specs",
"{",
"importSpec",
":=",
"spec",
".",
"(",
"*",
"ast",
".",
"ImportSpec",
")",
"\n",
"var",
"pkgAlias",
"string",
"\n",
"if",
"importSpec",
".",
"Name",
"!=",
"nil",
"{",
"pkgAlias",
"=",
"importSpec",
".",
"Name",
".",
"Name",
"\n",
"if",
"pkgAlias",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"quotedPath",
":=",
"importSpec",
".",
"Path",
".",
"Value",
"// e.g. \"\\\"sample/app/models\\\"\"",
"\n",
"fullPath",
":=",
"quotedPath",
"[",
"1",
":",
"len",
"(",
"quotedPath",
")",
"-",
"1",
"]",
"// Remove the quotes",
"\n\n",
"// If the package was not aliased (common case), we have to import it",
"// to see what the package name is.",
"// TODO: Can improve performance here a lot:",
"// 1. Do not import everything over and over again. Keep a cache.",
"// 2. Exempt the standard library; their directories always match the package name.",
"// 3. Can use build.FindOnly and then use parser.ParseDir with mode PackageClauseOnly",
"if",
"pkgAlias",
"==",
"\"",
"\"",
"{",
"utils",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fullPath",
",",
"\"",
"\"",
",",
"srcDir",
",",
"\"",
"\"",
",",
"build",
".",
"Default",
".",
"GOPATH",
")",
"\n",
"pkg",
",",
"err",
":=",
"build",
".",
"Import",
"(",
"fullPath",
",",
"srcDir",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// We expect this to happen for apps using reverse routing (since we",
"// have not yet generated the routes). Don't log that.",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"fullPath",
",",
"\"",
"\"",
")",
"{",
"utils",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fullPath",
",",
"\"",
"\"",
",",
"srcDir",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"else",
"{",
"utils",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"pkg",
".",
"Dir",
",",
"\"",
"\"",
",",
"pkg",
".",
"ImportPath",
")",
"\n",
"}",
"\n",
"pkgAlias",
"=",
"pkg",
".",
"Name",
"\n",
"}",
"\n\n",
"imports",
"[",
"pkgAlias",
"]",
"=",
"fullPath",
"\n",
"}",
"\n",
"}"
] |
// Add imports to the map from the source dir
|
[
"Add",
"imports",
"to",
"the",
"map",
"from",
"the",
"source",
"dir"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/parser/imports.go#L13-L59
|
17,986 |
revel/cmd
|
parser/imports.go
|
importPathFromPath
|
func importPathFromPath(root, basePath string) string {
vendorTest := filepath.Join(basePath, "vendor")
if len(root) > len(vendorTest) && root[:len(vendorTest)] == vendorTest {
return filepath.ToSlash(root[len(vendorTest)+1:])
}
for _, gopath := range filepath.SplitList(build.Default.GOPATH) {
srcPath := filepath.Join(gopath, "src")
if strings.HasPrefix(root, srcPath) {
return filepath.ToSlash(root[len(srcPath)+1:])
}
}
srcPath := filepath.Join(build.Default.GOROOT, "src", "pkg")
if strings.HasPrefix(root, srcPath) {
utils.Logger.Warn("Code path should be in GOPATH, but is in GOROOT:", "path", root)
return filepath.ToSlash(root[len(srcPath)+1:])
}
utils.Logger.Error("Unexpected! Code path is not in GOPATH:", "path", root)
return ""
}
|
go
|
func importPathFromPath(root, basePath string) string {
vendorTest := filepath.Join(basePath, "vendor")
if len(root) > len(vendorTest) && root[:len(vendorTest)] == vendorTest {
return filepath.ToSlash(root[len(vendorTest)+1:])
}
for _, gopath := range filepath.SplitList(build.Default.GOPATH) {
srcPath := filepath.Join(gopath, "src")
if strings.HasPrefix(root, srcPath) {
return filepath.ToSlash(root[len(srcPath)+1:])
}
}
srcPath := filepath.Join(build.Default.GOROOT, "src", "pkg")
if strings.HasPrefix(root, srcPath) {
utils.Logger.Warn("Code path should be in GOPATH, but is in GOROOT:", "path", root)
return filepath.ToSlash(root[len(srcPath)+1:])
}
utils.Logger.Error("Unexpected! Code path is not in GOPATH:", "path", root)
return ""
}
|
[
"func",
"importPathFromPath",
"(",
"root",
",",
"basePath",
"string",
")",
"string",
"{",
"vendorTest",
":=",
"filepath",
".",
"Join",
"(",
"basePath",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"root",
")",
">",
"len",
"(",
"vendorTest",
")",
"&&",
"root",
"[",
":",
"len",
"(",
"vendorTest",
")",
"]",
"==",
"vendorTest",
"{",
"return",
"filepath",
".",
"ToSlash",
"(",
"root",
"[",
"len",
"(",
"vendorTest",
")",
"+",
"1",
":",
"]",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"gopath",
":=",
"range",
"filepath",
".",
"SplitList",
"(",
"build",
".",
"Default",
".",
"GOPATH",
")",
"{",
"srcPath",
":=",
"filepath",
".",
"Join",
"(",
"gopath",
",",
"\"",
"\"",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"root",
",",
"srcPath",
")",
"{",
"return",
"filepath",
".",
"ToSlash",
"(",
"root",
"[",
"len",
"(",
"srcPath",
")",
"+",
"1",
":",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"srcPath",
":=",
"filepath",
".",
"Join",
"(",
"build",
".",
"Default",
".",
"GOROOT",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"root",
",",
"srcPath",
")",
"{",
"utils",
".",
"Logger",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"root",
")",
"\n",
"return",
"filepath",
".",
"ToSlash",
"(",
"root",
"[",
"len",
"(",
"srcPath",
")",
"+",
"1",
":",
"]",
")",
"\n",
"}",
"\n\n",
"utils",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"root",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// Returns a valid import string from the path
// using the build.Defaul.GOPATH to determine the root
|
[
"Returns",
"a",
"valid",
"import",
"string",
"from",
"the",
"path",
"using",
"the",
"build",
".",
"Defaul",
".",
"GOPATH",
"to",
"determine",
"the",
"root"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/parser/imports.go#L63-L83
|
17,987 |
revel/cmd
|
model/source_info.go
|
ControllerSpecs
|
func (s *SourceInfo) ControllerSpecs() []*TypeInfo {
if s.controllerSpecs == nil {
s.controllerSpecs = s.TypesThatEmbed(RevelImportPath+".Controller", "controllers")
}
return s.controllerSpecs
}
|
go
|
func (s *SourceInfo) ControllerSpecs() []*TypeInfo {
if s.controllerSpecs == nil {
s.controllerSpecs = s.TypesThatEmbed(RevelImportPath+".Controller", "controllers")
}
return s.controllerSpecs
}
|
[
"func",
"(",
"s",
"*",
"SourceInfo",
")",
"ControllerSpecs",
"(",
")",
"[",
"]",
"*",
"TypeInfo",
"{",
"if",
"s",
".",
"controllerSpecs",
"==",
"nil",
"{",
"s",
".",
"controllerSpecs",
"=",
"s",
".",
"TypesThatEmbed",
"(",
"RevelImportPath",
"+",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"s",
".",
"controllerSpecs",
"\n",
"}"
] |
// ControllerSpecs returns the all the controllers that embeds
// `revel.Controller`
|
[
"ControllerSpecs",
"returns",
"the",
"all",
"the",
"controllers",
"that",
"embeds",
"revel",
".",
"Controller"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/source_info.go#L111-L116
|
17,988 |
revel/cmd
|
revel/revel.go
|
ParseArgs
|
func ParseArgs(c *model.CommandConfig, parser *flags.Parser, args []string) (err error) {
var extraArgs []string
if ini := flag.String("ini", "none", ""); *ini != "none" {
if err = flags.NewIniParser(parser).ParseFile(*ini); err != nil {
return
}
} else {
if extraArgs, err = parser.ParseArgs(args); err != nil {
return
} else {
switch parser.Active.Name {
case "new":
c.Index = model.NEW
case "run":
c.Index = model.RUN
case "build":
c.Index = model.BUILD
case "package":
c.Index = model.PACKAGE
case "clean":
c.Index = model.CLEAN
case "test":
c.Index = model.TEST
case "version":
c.Index = model.VERSION
}
}
}
if len(extraArgs) > 0 {
utils.Logger.Info("Found additional arguements, setting them")
if !Commands[c.Index].UpdateConfig(c, extraArgs) {
buffer := &bytes.Buffer{}
parser.WriteHelp(buffer)
err = fmt.Errorf("Invalid command line arguements %v\n%s", extraArgs, buffer.String())
}
}
return
}
|
go
|
func ParseArgs(c *model.CommandConfig, parser *flags.Parser, args []string) (err error) {
var extraArgs []string
if ini := flag.String("ini", "none", ""); *ini != "none" {
if err = flags.NewIniParser(parser).ParseFile(*ini); err != nil {
return
}
} else {
if extraArgs, err = parser.ParseArgs(args); err != nil {
return
} else {
switch parser.Active.Name {
case "new":
c.Index = model.NEW
case "run":
c.Index = model.RUN
case "build":
c.Index = model.BUILD
case "package":
c.Index = model.PACKAGE
case "clean":
c.Index = model.CLEAN
case "test":
c.Index = model.TEST
case "version":
c.Index = model.VERSION
}
}
}
if len(extraArgs) > 0 {
utils.Logger.Info("Found additional arguements, setting them")
if !Commands[c.Index].UpdateConfig(c, extraArgs) {
buffer := &bytes.Buffer{}
parser.WriteHelp(buffer)
err = fmt.Errorf("Invalid command line arguements %v\n%s", extraArgs, buffer.String())
}
}
return
}
|
[
"func",
"ParseArgs",
"(",
"c",
"*",
"model",
".",
"CommandConfig",
",",
"parser",
"*",
"flags",
".",
"Parser",
",",
"args",
"[",
"]",
"string",
")",
"(",
"err",
"error",
")",
"{",
"var",
"extraArgs",
"[",
"]",
"string",
"\n",
"if",
"ini",
":=",
"flag",
".",
"String",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
";",
"*",
"ini",
"!=",
"\"",
"\"",
"{",
"if",
"err",
"=",
"flags",
".",
"NewIniParser",
"(",
"parser",
")",
".",
"ParseFile",
"(",
"*",
"ini",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"extraArgs",
",",
"err",
"=",
"parser",
".",
"ParseArgs",
"(",
"args",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"else",
"{",
"switch",
"parser",
".",
"Active",
".",
"Name",
"{",
"case",
"\"",
"\"",
":",
"c",
".",
"Index",
"=",
"model",
".",
"NEW",
"\n",
"case",
"\"",
"\"",
":",
"c",
".",
"Index",
"=",
"model",
".",
"RUN",
"\n",
"case",
"\"",
"\"",
":",
"c",
".",
"Index",
"=",
"model",
".",
"BUILD",
"\n",
"case",
"\"",
"\"",
":",
"c",
".",
"Index",
"=",
"model",
".",
"PACKAGE",
"\n",
"case",
"\"",
"\"",
":",
"c",
".",
"Index",
"=",
"model",
".",
"CLEAN",
"\n",
"case",
"\"",
"\"",
":",
"c",
".",
"Index",
"=",
"model",
".",
"TEST",
"\n",
"case",
"\"",
"\"",
":",
"c",
".",
"Index",
"=",
"model",
".",
"VERSION",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"extraArgs",
")",
">",
"0",
"{",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"if",
"!",
"Commands",
"[",
"c",
".",
"Index",
"]",
".",
"UpdateConfig",
"(",
"c",
",",
"extraArgs",
")",
"{",
"buffer",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"parser",
".",
"WriteHelp",
"(",
"buffer",
")",
"\n",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"extraArgs",
",",
"buffer",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] |
// Parse the arguments passed into the model.CommandConfig
|
[
"Parse",
"the",
"arguments",
"passed",
"into",
"the",
"model",
".",
"CommandConfig"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/revel.go#L116-L155
|
17,989 |
revel/cmd
|
utils/command.go
|
CmdInit
|
func CmdInit(c *exec.Cmd, basePath string) {
c.Dir = basePath
// Dep does not like paths that are not real, convert all paths in go to real paths
realPath := &bytes.Buffer{}
for _, p := range filepath.SplitList(build.Default.GOPATH) {
rp,_ := filepath.EvalSymlinks(p)
if realPath.Len() > 0 {
realPath.WriteString(string(filepath.ListSeparator))
}
realPath.WriteString(rp)
}
// Go 1.8 fails if we do not include the GOROOT
c.Env = []string{"GOPATH=" + realPath.String(), "GOROOT="+ os.Getenv("GOROOT")}
// Fetch the rest of the env variables
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
if pair[0]=="GOPATH" || pair[0]=="GOROOT" {
continue
}
c.Env = append(c.Env,e)
}
}
|
go
|
func CmdInit(c *exec.Cmd, basePath string) {
c.Dir = basePath
// Dep does not like paths that are not real, convert all paths in go to real paths
realPath := &bytes.Buffer{}
for _, p := range filepath.SplitList(build.Default.GOPATH) {
rp,_ := filepath.EvalSymlinks(p)
if realPath.Len() > 0 {
realPath.WriteString(string(filepath.ListSeparator))
}
realPath.WriteString(rp)
}
// Go 1.8 fails if we do not include the GOROOT
c.Env = []string{"GOPATH=" + realPath.String(), "GOROOT="+ os.Getenv("GOROOT")}
// Fetch the rest of the env variables
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
if pair[0]=="GOPATH" || pair[0]=="GOROOT" {
continue
}
c.Env = append(c.Env,e)
}
}
|
[
"func",
"CmdInit",
"(",
"c",
"*",
"exec",
".",
"Cmd",
",",
"basePath",
"string",
")",
"{",
"c",
".",
"Dir",
"=",
"basePath",
"\n",
"// Dep does not like paths that are not real, convert all paths in go to real paths",
"realPath",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"filepath",
".",
"SplitList",
"(",
"build",
".",
"Default",
".",
"GOPATH",
")",
"{",
"rp",
",",
"_",
":=",
"filepath",
".",
"EvalSymlinks",
"(",
"p",
")",
"\n",
"if",
"realPath",
".",
"Len",
"(",
")",
">",
"0",
"{",
"realPath",
".",
"WriteString",
"(",
"string",
"(",
"filepath",
".",
"ListSeparator",
")",
")",
"\n",
"}",
"\n",
"realPath",
".",
"WriteString",
"(",
"rp",
")",
"\n",
"}",
"\n",
"// Go 1.8 fails if we do not include the GOROOT",
"c",
".",
"Env",
"=",
"[",
"]",
"string",
"{",
"\"",
"\"",
"+",
"realPath",
".",
"String",
"(",
")",
",",
"\"",
"\"",
"+",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"}",
"\n",
"// Fetch the rest of the env variables",
"for",
"_",
",",
"e",
":=",
"range",
"os",
".",
"Environ",
"(",
")",
"{",
"pair",
":=",
"strings",
".",
"Split",
"(",
"e",
",",
"\"",
"\"",
")",
"\n",
"if",
"pair",
"[",
"0",
"]",
"==",
"\"",
"\"",
"||",
"pair",
"[",
"0",
"]",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"c",
".",
"Env",
"=",
"append",
"(",
"c",
".",
"Env",
",",
"e",
")",
"\n",
"}",
"\n",
"}"
] |
// Initialize the command based on the GO environment
|
[
"Initialize",
"the",
"command",
"based",
"on",
"the",
"GO",
"environment"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/command.go#L13-L34
|
17,990 |
revel/cmd
|
revel/package.go
|
packageApp
|
func packageApp(c *model.CommandConfig) (err error) {
// Determine the run mode.
mode := DefaultRunMode
if len(c.Package.Mode) >= 0 {
mode = c.Package.Mode
}
appImportPath := c.ImportPath
revel_paths, err := model.NewRevelPaths(mode, appImportPath, "", model.NewWrappedRevelCallback(nil, c.PackageResolver))
if err != nil {
return
}
// Remove the archive if it already exists.
destFile := filepath.Join(c.AppPath, filepath.Base(revel_paths.BasePath)+".tar.gz")
if c.Package.TargetPath != "" {
if filepath.IsAbs(c.Package.TargetPath) {
destFile = c.Package.TargetPath
} else {
destFile = filepath.Join(c.AppPath, c.Package.TargetPath)
}
}
if err := os.Remove(destFile); err != nil && !os.IsNotExist(err) {
return utils.NewBuildError("Unable to remove target file", "error", err, "file", destFile)
}
// Collect stuff in a temp directory.
tmpDir, err := ioutil.TempDir("", filepath.Base(revel_paths.BasePath))
utils.PanicOnError(err, "Failed to get temp dir")
// Build expects the command the build to contain the proper data
if len(c.Package.Mode) >= 0 {
c.Build.Mode = c.Package.Mode
}
c.Build.TargetPath = tmpDir
c.Build.CopySource = c.Package.CopySource
buildApp(c)
// Create the zip file.
archiveName, err := utils.TarGzDir(destFile, tmpDir)
if err != nil {
return
}
fmt.Println("Your archive is ready:", archiveName)
return
}
|
go
|
func packageApp(c *model.CommandConfig) (err error) {
// Determine the run mode.
mode := DefaultRunMode
if len(c.Package.Mode) >= 0 {
mode = c.Package.Mode
}
appImportPath := c.ImportPath
revel_paths, err := model.NewRevelPaths(mode, appImportPath, "", model.NewWrappedRevelCallback(nil, c.PackageResolver))
if err != nil {
return
}
// Remove the archive if it already exists.
destFile := filepath.Join(c.AppPath, filepath.Base(revel_paths.BasePath)+".tar.gz")
if c.Package.TargetPath != "" {
if filepath.IsAbs(c.Package.TargetPath) {
destFile = c.Package.TargetPath
} else {
destFile = filepath.Join(c.AppPath, c.Package.TargetPath)
}
}
if err := os.Remove(destFile); err != nil && !os.IsNotExist(err) {
return utils.NewBuildError("Unable to remove target file", "error", err, "file", destFile)
}
// Collect stuff in a temp directory.
tmpDir, err := ioutil.TempDir("", filepath.Base(revel_paths.BasePath))
utils.PanicOnError(err, "Failed to get temp dir")
// Build expects the command the build to contain the proper data
if len(c.Package.Mode) >= 0 {
c.Build.Mode = c.Package.Mode
}
c.Build.TargetPath = tmpDir
c.Build.CopySource = c.Package.CopySource
buildApp(c)
// Create the zip file.
archiveName, err := utils.TarGzDir(destFile, tmpDir)
if err != nil {
return
}
fmt.Println("Your archive is ready:", archiveName)
return
}
|
[
"func",
"packageApp",
"(",
"c",
"*",
"model",
".",
"CommandConfig",
")",
"(",
"err",
"error",
")",
"{",
"// Determine the run mode.",
"mode",
":=",
"DefaultRunMode",
"\n",
"if",
"len",
"(",
"c",
".",
"Package",
".",
"Mode",
")",
">=",
"0",
"{",
"mode",
"=",
"c",
".",
"Package",
".",
"Mode",
"\n",
"}",
"\n\n",
"appImportPath",
":=",
"c",
".",
"ImportPath",
"\n",
"revel_paths",
",",
"err",
":=",
"model",
".",
"NewRevelPaths",
"(",
"mode",
",",
"appImportPath",
",",
"\"",
"\"",
",",
"model",
".",
"NewWrappedRevelCallback",
"(",
"nil",
",",
"c",
".",
"PackageResolver",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Remove the archive if it already exists.",
"destFile",
":=",
"filepath",
".",
"Join",
"(",
"c",
".",
"AppPath",
",",
"filepath",
".",
"Base",
"(",
"revel_paths",
".",
"BasePath",
")",
"+",
"\"",
"\"",
")",
"\n",
"if",
"c",
".",
"Package",
".",
"TargetPath",
"!=",
"\"",
"\"",
"{",
"if",
"filepath",
".",
"IsAbs",
"(",
"c",
".",
"Package",
".",
"TargetPath",
")",
"{",
"destFile",
"=",
"c",
".",
"Package",
".",
"TargetPath",
"\n",
"}",
"else",
"{",
"destFile",
"=",
"filepath",
".",
"Join",
"(",
"c",
".",
"AppPath",
",",
"c",
".",
"Package",
".",
"TargetPath",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"Remove",
"(",
"destFile",
")",
";",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"utils",
".",
"NewBuildError",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
",",
"\"",
"\"",
",",
"destFile",
")",
"\n",
"}",
"\n\n",
"// Collect stuff in a temp directory.",
"tmpDir",
",",
"err",
":=",
"ioutil",
".",
"TempDir",
"(",
"\"",
"\"",
",",
"filepath",
".",
"Base",
"(",
"revel_paths",
".",
"BasePath",
")",
")",
"\n",
"utils",
".",
"PanicOnError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n\n",
"// Build expects the command the build to contain the proper data",
"if",
"len",
"(",
"c",
".",
"Package",
".",
"Mode",
")",
">=",
"0",
"{",
"c",
".",
"Build",
".",
"Mode",
"=",
"c",
".",
"Package",
".",
"Mode",
"\n",
"}",
"\n",
"c",
".",
"Build",
".",
"TargetPath",
"=",
"tmpDir",
"\n",
"c",
".",
"Build",
".",
"CopySource",
"=",
"c",
".",
"Package",
".",
"CopySource",
"\n",
"buildApp",
"(",
"c",
")",
"\n\n",
"// Create the zip file.",
"archiveName",
",",
"err",
":=",
"utils",
".",
"TarGzDir",
"(",
"destFile",
",",
"tmpDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"archiveName",
")",
"\n",
"return",
"\n",
"}"
] |
// Called to package the app
|
[
"Called",
"to",
"package",
"the",
"app"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/package.go#L52-L100
|
17,991 |
revel/cmd
|
model/type_expr.go
|
NewTypeExprFromData
|
func NewTypeExprFromData(expr, pkgName string, pkgIndex int, valid bool) TypeExpr {
return TypeExpr{expr, pkgName, pkgIndex, valid}
}
|
go
|
func NewTypeExprFromData(expr, pkgName string, pkgIndex int, valid bool) TypeExpr {
return TypeExpr{expr, pkgName, pkgIndex, valid}
}
|
[
"func",
"NewTypeExprFromData",
"(",
"expr",
",",
"pkgName",
"string",
",",
"pkgIndex",
"int",
",",
"valid",
"bool",
")",
"TypeExpr",
"{",
"return",
"TypeExpr",
"{",
"expr",
",",
"pkgName",
",",
"pkgIndex",
",",
"valid",
"}",
"\n",
"}"
] |
// Returns a new type from the data
|
[
"Returns",
"a",
"new",
"type",
"from",
"the",
"data"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/type_expr.go#L17-L19
|
17,992 |
revel/cmd
|
model/type_expr.go
|
NewTypeExprFromAst
|
func NewTypeExprFromAst(pkgName string, expr ast.Expr) TypeExpr {
error := ""
switch t := expr.(type) {
case *ast.Ident:
if IsBuiltinType(t.Name) {
pkgName = ""
}
return TypeExpr{t.Name, pkgName, 0, true}
case *ast.SelectorExpr:
e := NewTypeExprFromAst(pkgName, t.X)
return NewTypeExprFromData(t.Sel.Name, e.Expr, 0, e.Valid)
case *ast.StarExpr:
e := NewTypeExprFromAst(pkgName, t.X)
return NewTypeExprFromData("*"+e.Expr, e.PkgName, e.pkgIndex+1, e.Valid)
case *ast.ArrayType:
e := NewTypeExprFromAst(pkgName, t.Elt)
return NewTypeExprFromData("[]"+e.Expr, e.PkgName, e.pkgIndex+2, e.Valid)
case *ast.MapType:
if identKey, ok := t.Key.(*ast.Ident); ok && IsBuiltinType(identKey.Name) {
e := NewTypeExprFromAst(pkgName, t.Value)
return NewTypeExprFromData("map["+identKey.Name+"]"+e.Expr, e.PkgName, e.pkgIndex+len("map["+identKey.Name+"]"), e.Valid)
}
error = fmt.Sprintf("Failed to generate name for Map field :%v. Make sure the field name is valid.", t.Key)
case *ast.Ellipsis:
e := NewTypeExprFromAst(pkgName, t.Elt)
return NewTypeExprFromData("[]"+e.Expr, e.PkgName, e.pkgIndex+2, e.Valid)
default:
error = fmt.Sprintf("Failed to generate name for field: %v Package: %v. Make sure the field name is valid.", expr, pkgName)
}
return NewTypeExprFromData(error, "", 0, false)
}
|
go
|
func NewTypeExprFromAst(pkgName string, expr ast.Expr) TypeExpr {
error := ""
switch t := expr.(type) {
case *ast.Ident:
if IsBuiltinType(t.Name) {
pkgName = ""
}
return TypeExpr{t.Name, pkgName, 0, true}
case *ast.SelectorExpr:
e := NewTypeExprFromAst(pkgName, t.X)
return NewTypeExprFromData(t.Sel.Name, e.Expr, 0, e.Valid)
case *ast.StarExpr:
e := NewTypeExprFromAst(pkgName, t.X)
return NewTypeExprFromData("*"+e.Expr, e.PkgName, e.pkgIndex+1, e.Valid)
case *ast.ArrayType:
e := NewTypeExprFromAst(pkgName, t.Elt)
return NewTypeExprFromData("[]"+e.Expr, e.PkgName, e.pkgIndex+2, e.Valid)
case *ast.MapType:
if identKey, ok := t.Key.(*ast.Ident); ok && IsBuiltinType(identKey.Name) {
e := NewTypeExprFromAst(pkgName, t.Value)
return NewTypeExprFromData("map["+identKey.Name+"]"+e.Expr, e.PkgName, e.pkgIndex+len("map["+identKey.Name+"]"), e.Valid)
}
error = fmt.Sprintf("Failed to generate name for Map field :%v. Make sure the field name is valid.", t.Key)
case *ast.Ellipsis:
e := NewTypeExprFromAst(pkgName, t.Elt)
return NewTypeExprFromData("[]"+e.Expr, e.PkgName, e.pkgIndex+2, e.Valid)
default:
error = fmt.Sprintf("Failed to generate name for field: %v Package: %v. Make sure the field name is valid.", expr, pkgName)
}
return NewTypeExprFromData(error, "", 0, false)
}
|
[
"func",
"NewTypeExprFromAst",
"(",
"pkgName",
"string",
",",
"expr",
"ast",
".",
"Expr",
")",
"TypeExpr",
"{",
"error",
":=",
"\"",
"\"",
"\n",
"switch",
"t",
":=",
"expr",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"Ident",
":",
"if",
"IsBuiltinType",
"(",
"t",
".",
"Name",
")",
"{",
"pkgName",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"TypeExpr",
"{",
"t",
".",
"Name",
",",
"pkgName",
",",
"0",
",",
"true",
"}",
"\n",
"case",
"*",
"ast",
".",
"SelectorExpr",
":",
"e",
":=",
"NewTypeExprFromAst",
"(",
"pkgName",
",",
"t",
".",
"X",
")",
"\n",
"return",
"NewTypeExprFromData",
"(",
"t",
".",
"Sel",
".",
"Name",
",",
"e",
".",
"Expr",
",",
"0",
",",
"e",
".",
"Valid",
")",
"\n",
"case",
"*",
"ast",
".",
"StarExpr",
":",
"e",
":=",
"NewTypeExprFromAst",
"(",
"pkgName",
",",
"t",
".",
"X",
")",
"\n",
"return",
"NewTypeExprFromData",
"(",
"\"",
"\"",
"+",
"e",
".",
"Expr",
",",
"e",
".",
"PkgName",
",",
"e",
".",
"pkgIndex",
"+",
"1",
",",
"e",
".",
"Valid",
")",
"\n",
"case",
"*",
"ast",
".",
"ArrayType",
":",
"e",
":=",
"NewTypeExprFromAst",
"(",
"pkgName",
",",
"t",
".",
"Elt",
")",
"\n",
"return",
"NewTypeExprFromData",
"(",
"\"",
"\"",
"+",
"e",
".",
"Expr",
",",
"e",
".",
"PkgName",
",",
"e",
".",
"pkgIndex",
"+",
"2",
",",
"e",
".",
"Valid",
")",
"\n",
"case",
"*",
"ast",
".",
"MapType",
":",
"if",
"identKey",
",",
"ok",
":=",
"t",
".",
"Key",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
";",
"ok",
"&&",
"IsBuiltinType",
"(",
"identKey",
".",
"Name",
")",
"{",
"e",
":=",
"NewTypeExprFromAst",
"(",
"pkgName",
",",
"t",
".",
"Value",
")",
"\n",
"return",
"NewTypeExprFromData",
"(",
"\"",
"\"",
"+",
"identKey",
".",
"Name",
"+",
"\"",
"\"",
"+",
"e",
".",
"Expr",
",",
"e",
".",
"PkgName",
",",
"e",
".",
"pkgIndex",
"+",
"len",
"(",
"\"",
"\"",
"+",
"identKey",
".",
"Name",
"+",
"\"",
"\"",
")",
",",
"e",
".",
"Valid",
")",
"\n",
"}",
"\n",
"error",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Key",
")",
"\n",
"case",
"*",
"ast",
".",
"Ellipsis",
":",
"e",
":=",
"NewTypeExprFromAst",
"(",
"pkgName",
",",
"t",
".",
"Elt",
")",
"\n",
"return",
"NewTypeExprFromData",
"(",
"\"",
"\"",
"+",
"e",
".",
"Expr",
",",
"e",
".",
"PkgName",
",",
"e",
".",
"pkgIndex",
"+",
"2",
",",
"e",
".",
"Valid",
")",
"\n",
"default",
":",
"error",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"expr",
",",
"pkgName",
")",
"\n\n",
"}",
"\n",
"return",
"NewTypeExprFromData",
"(",
"error",
",",
"\"",
"\"",
",",
"0",
",",
"false",
")",
"\n",
"}"
] |
// NewTypeExpr returns the syntactic expression for referencing this type in Go.
|
[
"NewTypeExpr",
"returns",
"the",
"syntactic",
"expression",
"for",
"referencing",
"this",
"type",
"in",
"Go",
"."
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/type_expr.go#L22-L53
|
17,993 |
revel/cmd
|
model/type_expr.go
|
TypeName
|
func (e TypeExpr) TypeName(pkgOverride string) string {
pkgName := FirstNonEmpty(pkgOverride, e.PkgName)
if pkgName == "" {
return e.Expr
}
return e.Expr[:e.pkgIndex] + pkgName + "." + e.Expr[e.pkgIndex:]
}
|
go
|
func (e TypeExpr) TypeName(pkgOverride string) string {
pkgName := FirstNonEmpty(pkgOverride, e.PkgName)
if pkgName == "" {
return e.Expr
}
return e.Expr[:e.pkgIndex] + pkgName + "." + e.Expr[e.pkgIndex:]
}
|
[
"func",
"(",
"e",
"TypeExpr",
")",
"TypeName",
"(",
"pkgOverride",
"string",
")",
"string",
"{",
"pkgName",
":=",
"FirstNonEmpty",
"(",
"pkgOverride",
",",
"e",
".",
"PkgName",
")",
"\n",
"if",
"pkgName",
"==",
"\"",
"\"",
"{",
"return",
"e",
".",
"Expr",
"\n",
"}",
"\n",
"return",
"e",
".",
"Expr",
"[",
":",
"e",
".",
"pkgIndex",
"]",
"+",
"pkgName",
"+",
"\"",
"\"",
"+",
"e",
".",
"Expr",
"[",
"e",
".",
"pkgIndex",
":",
"]",
"\n",
"}"
] |
// TypeName returns the fully-qualified type name for this expression.
// The caller may optionally specify a package name to override the default.
|
[
"TypeName",
"returns",
"the",
"fully",
"-",
"qualified",
"type",
"name",
"for",
"this",
"expression",
".",
"The",
"caller",
"may",
"optionally",
"specify",
"a",
"package",
"name",
"to",
"override",
"the",
"default",
"."
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/type_expr.go#L57-L63
|
17,994 |
revel/cmd
|
model/command_config.go
|
InitGoPaths
|
func (c *CommandConfig) InitGoPaths() {
utils.Logger.Info("InitGoPaths")
// lookup go path
c.GoPath = build.Default.GOPATH
if c.GoPath == "" {
utils.Logger.Fatal("Abort: GOPATH environment variable is not set. " +
"Please refer to http://golang.org/doc/code.html to configure your Go environment.")
}
// check for go executable
var err error
c.GoCmd, err = exec.LookPath("go")
if err != nil {
utils.Logger.Fatal("Go executable not found in PATH.")
}
// revel/revel#1004 choose go path relative to current working directory
// What we want to do is to add the import to the end of the
// gopath, and discover which import exists - If none exist this is an error except in the case
// where we are dealing with new which is a special case where we will attempt to target the working directory first
workingDir, _ := os.Getwd()
goPathList := filepath.SplitList(c.GoPath)
bestpath := ""
for _, path := range goPathList {
if c.Index == NEW {
// If the GOPATH is part of the working dir this is the most likely target
if strings.HasPrefix(workingDir, path) {
bestpath = path
}
} else {
if utils.Exists(filepath.Join(path, "src", c.ImportPath)) {
c.SrcRoot = path
break
}
}
}
utils.Logger.Info("Source root", "path", c.SrcRoot, "cwd", workingDir, "gopath", c.GoPath, "bestpath",bestpath)
if len(c.SrcRoot) == 0 && len(bestpath) > 0 {
c.SrcRoot = bestpath
}
// If source root is empty and this isn't a version then skip it
if len(c.SrcRoot) == 0 {
if c.Index != VERSION {
utils.Logger.Fatal("Abort: could not create a Revel application outside of GOPATH.")
}
return
}
// set go src path
c.SrcRoot = filepath.Join(c.SrcRoot, "src")
c.AppPath = filepath.Join(c.SrcRoot, filepath.FromSlash(c.ImportPath))
utils.Logger.Info("Set application path", "path", c.AppPath)
}
|
go
|
func (c *CommandConfig) InitGoPaths() {
utils.Logger.Info("InitGoPaths")
// lookup go path
c.GoPath = build.Default.GOPATH
if c.GoPath == "" {
utils.Logger.Fatal("Abort: GOPATH environment variable is not set. " +
"Please refer to http://golang.org/doc/code.html to configure your Go environment.")
}
// check for go executable
var err error
c.GoCmd, err = exec.LookPath("go")
if err != nil {
utils.Logger.Fatal("Go executable not found in PATH.")
}
// revel/revel#1004 choose go path relative to current working directory
// What we want to do is to add the import to the end of the
// gopath, and discover which import exists - If none exist this is an error except in the case
// where we are dealing with new which is a special case where we will attempt to target the working directory first
workingDir, _ := os.Getwd()
goPathList := filepath.SplitList(c.GoPath)
bestpath := ""
for _, path := range goPathList {
if c.Index == NEW {
// If the GOPATH is part of the working dir this is the most likely target
if strings.HasPrefix(workingDir, path) {
bestpath = path
}
} else {
if utils.Exists(filepath.Join(path, "src", c.ImportPath)) {
c.SrcRoot = path
break
}
}
}
utils.Logger.Info("Source root", "path", c.SrcRoot, "cwd", workingDir, "gopath", c.GoPath, "bestpath",bestpath)
if len(c.SrcRoot) == 0 && len(bestpath) > 0 {
c.SrcRoot = bestpath
}
// If source root is empty and this isn't a version then skip it
if len(c.SrcRoot) == 0 {
if c.Index != VERSION {
utils.Logger.Fatal("Abort: could not create a Revel application outside of GOPATH.")
}
return
}
// set go src path
c.SrcRoot = filepath.Join(c.SrcRoot, "src")
c.AppPath = filepath.Join(c.SrcRoot, filepath.FromSlash(c.ImportPath))
utils.Logger.Info("Set application path", "path", c.AppPath)
}
|
[
"func",
"(",
"c",
"*",
"CommandConfig",
")",
"InitGoPaths",
"(",
")",
"{",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"// lookup go path",
"c",
".",
"GoPath",
"=",
"build",
".",
"Default",
".",
"GOPATH",
"\n",
"if",
"c",
".",
"GoPath",
"==",
"\"",
"\"",
"{",
"utils",
".",
"Logger",
".",
"Fatal",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// check for go executable",
"var",
"err",
"error",
"\n",
"c",
".",
"GoCmd",
",",
"err",
"=",
"exec",
".",
"LookPath",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// revel/revel#1004 choose go path relative to current working directory",
"// What we want to do is to add the import to the end of the",
"// gopath, and discover which import exists - If none exist this is an error except in the case",
"// where we are dealing with new which is a special case where we will attempt to target the working directory first",
"workingDir",
",",
"_",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"goPathList",
":=",
"filepath",
".",
"SplitList",
"(",
"c",
".",
"GoPath",
")",
"\n",
"bestpath",
":=",
"\"",
"\"",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"goPathList",
"{",
"if",
"c",
".",
"Index",
"==",
"NEW",
"{",
"// If the GOPATH is part of the working dir this is the most likely target",
"if",
"strings",
".",
"HasPrefix",
"(",
"workingDir",
",",
"path",
")",
"{",
"bestpath",
"=",
"path",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"utils",
".",
"Exists",
"(",
"filepath",
".",
"Join",
"(",
"path",
",",
"\"",
"\"",
",",
"c",
".",
"ImportPath",
")",
")",
"{",
"c",
".",
"SrcRoot",
"=",
"path",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"c",
".",
"SrcRoot",
",",
"\"",
"\"",
",",
"workingDir",
",",
"\"",
"\"",
",",
"c",
".",
"GoPath",
",",
"\"",
"\"",
",",
"bestpath",
")",
"\n",
"if",
"len",
"(",
"c",
".",
"SrcRoot",
")",
"==",
"0",
"&&",
"len",
"(",
"bestpath",
")",
">",
"0",
"{",
"c",
".",
"SrcRoot",
"=",
"bestpath",
"\n",
"}",
"\n\n",
"// If source root is empty and this isn't a version then skip it",
"if",
"len",
"(",
"c",
".",
"SrcRoot",
")",
"==",
"0",
"{",
"if",
"c",
".",
"Index",
"!=",
"VERSION",
"{",
"utils",
".",
"Logger",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"// set go src path",
"c",
".",
"SrcRoot",
"=",
"filepath",
".",
"Join",
"(",
"c",
".",
"SrcRoot",
",",
"\"",
"\"",
")",
"\n\n",
"c",
".",
"AppPath",
"=",
"filepath",
".",
"Join",
"(",
"c",
".",
"SrcRoot",
",",
"filepath",
".",
"FromSlash",
"(",
"c",
".",
"ImportPath",
")",
")",
"\n",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"c",
".",
"AppPath",
")",
"\n",
"}"
] |
// lookup and set Go related variables
|
[
"lookup",
"and",
"set",
"Go",
"related",
"variables"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/command_config.go#L240-L296
|
17,995 |
revel/cmd
|
model/command_config.go
|
SetVersions
|
func (c *CommandConfig) SetVersions() (err error) {
c.CommandVersion, _ = ParseVersion(cmd.Version)
_, revelPath, err := utils.FindSrcPaths(c.ImportPath, RevelImportPath, c.PackageResolver)
if err == nil {
utils.Logger.Info("Fullpath to revel", "dir", revelPath)
fset := token.NewFileSet() // positions are relative to fset
versionData, err := ioutil.ReadFile(filepath.Join(revelPath, RevelImportPath, "version.go"))
if err != nil {
utils.Logger.Error("Failed to find Revel version:", "error", err, "path", revelPath)
}
// Parse src but stop after processing the imports.
f, err := parser.ParseFile(fset, "", versionData, parser.ParseComments)
if err != nil {
return utils.NewBuildError("Failed to parse Revel version error:", "error", err)
}
// Print the imports from the file's AST.
for _, s := range f.Decls {
genDecl, ok := s.(*ast.GenDecl)
if !ok {
continue
}
if genDecl.Tok != token.CONST {
continue
}
for _, a := range genDecl.Specs {
spec := a.(*ast.ValueSpec)
r := spec.Values[0].(*ast.BasicLit)
if spec.Names[0].Name == "Version" {
c.FrameworkVersion, err = ParseVersion(strings.Replace(r.Value, `"`, ``, -1))
if err != nil {
utils.Logger.Errorf("Failed to parse version")
} else {
utils.Logger.Info("Parsed revel version", "version", c.FrameworkVersion.String())
}
}
}
}
}
return
}
|
go
|
func (c *CommandConfig) SetVersions() (err error) {
c.CommandVersion, _ = ParseVersion(cmd.Version)
_, revelPath, err := utils.FindSrcPaths(c.ImportPath, RevelImportPath, c.PackageResolver)
if err == nil {
utils.Logger.Info("Fullpath to revel", "dir", revelPath)
fset := token.NewFileSet() // positions are relative to fset
versionData, err := ioutil.ReadFile(filepath.Join(revelPath, RevelImportPath, "version.go"))
if err != nil {
utils.Logger.Error("Failed to find Revel version:", "error", err, "path", revelPath)
}
// Parse src but stop after processing the imports.
f, err := parser.ParseFile(fset, "", versionData, parser.ParseComments)
if err != nil {
return utils.NewBuildError("Failed to parse Revel version error:", "error", err)
}
// Print the imports from the file's AST.
for _, s := range f.Decls {
genDecl, ok := s.(*ast.GenDecl)
if !ok {
continue
}
if genDecl.Tok != token.CONST {
continue
}
for _, a := range genDecl.Specs {
spec := a.(*ast.ValueSpec)
r := spec.Values[0].(*ast.BasicLit)
if spec.Names[0].Name == "Version" {
c.FrameworkVersion, err = ParseVersion(strings.Replace(r.Value, `"`, ``, -1))
if err != nil {
utils.Logger.Errorf("Failed to parse version")
} else {
utils.Logger.Info("Parsed revel version", "version", c.FrameworkVersion.String())
}
}
}
}
}
return
}
|
[
"func",
"(",
"c",
"*",
"CommandConfig",
")",
"SetVersions",
"(",
")",
"(",
"err",
"error",
")",
"{",
"c",
".",
"CommandVersion",
",",
"_",
"=",
"ParseVersion",
"(",
"cmd",
".",
"Version",
")",
"\n",
"_",
",",
"revelPath",
",",
"err",
":=",
"utils",
".",
"FindSrcPaths",
"(",
"c",
".",
"ImportPath",
",",
"RevelImportPath",
",",
"c",
".",
"PackageResolver",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"revelPath",
")",
"\n",
"fset",
":=",
"token",
".",
"NewFileSet",
"(",
")",
"// positions are relative to fset",
"\n\n",
"versionData",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filepath",
".",
"Join",
"(",
"revelPath",
",",
"RevelImportPath",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
",",
"\"",
"\"",
",",
"revelPath",
")",
"\n",
"}",
"\n\n",
"// Parse src but stop after processing the imports.",
"f",
",",
"err",
":=",
"parser",
".",
"ParseFile",
"(",
"fset",
",",
"\"",
"\"",
",",
"versionData",
",",
"parser",
".",
"ParseComments",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"utils",
".",
"NewBuildError",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Print the imports from the file's AST.",
"for",
"_",
",",
"s",
":=",
"range",
"f",
".",
"Decls",
"{",
"genDecl",
",",
"ok",
":=",
"s",
".",
"(",
"*",
"ast",
".",
"GenDecl",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"genDecl",
".",
"Tok",
"!=",
"token",
".",
"CONST",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"genDecl",
".",
"Specs",
"{",
"spec",
":=",
"a",
".",
"(",
"*",
"ast",
".",
"ValueSpec",
")",
"\n",
"r",
":=",
"spec",
".",
"Values",
"[",
"0",
"]",
".",
"(",
"*",
"ast",
".",
"BasicLit",
")",
"\n",
"if",
"spec",
".",
"Names",
"[",
"0",
"]",
".",
"Name",
"==",
"\"",
"\"",
"{",
"c",
".",
"FrameworkVersion",
",",
"err",
"=",
"ParseVersion",
"(",
"strings",
".",
"Replace",
"(",
"r",
".",
"Value",
",",
"`\"`",
",",
"``",
",",
"-",
"1",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"c",
".",
"FrameworkVersion",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Sets the versions on the command config
|
[
"Sets",
"the",
"versions",
"on",
"the",
"command",
"config"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/command_config.go#L299-L341
|
17,996 |
revel/cmd
|
revel/run.go
|
runIsImportPath
|
func runIsImportPath(pathToCheck string) bool {
if _, err := build.Import(pathToCheck, "", build.FindOnly);err==nil {
return true
}
return filepath.IsAbs(pathToCheck)
}
|
go
|
func runIsImportPath(pathToCheck string) bool {
if _, err := build.Import(pathToCheck, "", build.FindOnly);err==nil {
return true
}
return filepath.IsAbs(pathToCheck)
}
|
[
"func",
"runIsImportPath",
"(",
"pathToCheck",
"string",
")",
"bool",
"{",
"if",
"_",
",",
"err",
":=",
"build",
".",
"Import",
"(",
"pathToCheck",
",",
"\"",
"\"",
",",
"build",
".",
"FindOnly",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"filepath",
".",
"IsAbs",
"(",
"pathToCheck",
")",
"\n",
"}"
] |
// Returns true if this is an absolute path or a relative gopath
|
[
"Returns",
"true",
"if",
"this",
"is",
"an",
"absolute",
"path",
"or",
"a",
"relative",
"gopath"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/run.go#L116-L121
|
17,997 |
revel/cmd
|
revel/run.go
|
runApp
|
func runApp(c *model.CommandConfig) (err error) {
if c.Run.Mode == "" {
c.Run.Mode = "dev"
}
revel_path, err := model.NewRevelPaths(c.Run.Mode, c.ImportPath, "", model.NewWrappedRevelCallback(nil, c.PackageResolver))
if err != nil {
return utils.NewBuildIfError(err, "Revel paths")
}
if c.Run.Port > -1 {
revel_path.HTTPPort = c.Run.Port
} else {
c.Run.Port = revel_path.HTTPPort
}
utils.Logger.Infof("Running %s (%s) in %s mode\n", revel_path.AppName, revel_path.ImportPath, revel_path.RunMode)
utils.Logger.Debug("Base path:", "path", revel_path.BasePath)
// If the app is run in "watched" mode, use the harness to run it.
if revel_path.Config.BoolDefault("watch", true) && revel_path.Config.BoolDefault("watch.code", true) {
utils.Logger.Info("Running in watched mode.")
runMode := fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v}`, revel_path.RunMode, c.Verbose)
if c.HistoricMode {
runMode = revel_path.RunMode
}
// **** Never returns.
harness.NewHarness(c, revel_path, runMode, c.Run.NoProxy).Run()
}
// Else, just build and run the app.
utils.Logger.Debug("Running in live build mode.")
app, err := harness.Build(c, revel_path)
if err != nil {
utils.Logger.Errorf("Failed to build app: %s", err)
}
app.Port = revel_path.HTTPPort
runMode := fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v}`, app.Paths.RunMode, c.Verbose)
if c.HistoricMode {
runMode = revel_path.RunMode
}
app.Cmd(runMode).Run()
return
}
|
go
|
func runApp(c *model.CommandConfig) (err error) {
if c.Run.Mode == "" {
c.Run.Mode = "dev"
}
revel_path, err := model.NewRevelPaths(c.Run.Mode, c.ImportPath, "", model.NewWrappedRevelCallback(nil, c.PackageResolver))
if err != nil {
return utils.NewBuildIfError(err, "Revel paths")
}
if c.Run.Port > -1 {
revel_path.HTTPPort = c.Run.Port
} else {
c.Run.Port = revel_path.HTTPPort
}
utils.Logger.Infof("Running %s (%s) in %s mode\n", revel_path.AppName, revel_path.ImportPath, revel_path.RunMode)
utils.Logger.Debug("Base path:", "path", revel_path.BasePath)
// If the app is run in "watched" mode, use the harness to run it.
if revel_path.Config.BoolDefault("watch", true) && revel_path.Config.BoolDefault("watch.code", true) {
utils.Logger.Info("Running in watched mode.")
runMode := fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v}`, revel_path.RunMode, c.Verbose)
if c.HistoricMode {
runMode = revel_path.RunMode
}
// **** Never returns.
harness.NewHarness(c, revel_path, runMode, c.Run.NoProxy).Run()
}
// Else, just build and run the app.
utils.Logger.Debug("Running in live build mode.")
app, err := harness.Build(c, revel_path)
if err != nil {
utils.Logger.Errorf("Failed to build app: %s", err)
}
app.Port = revel_path.HTTPPort
runMode := fmt.Sprintf(`{"mode":"%s", "specialUseFlag":%v}`, app.Paths.RunMode, c.Verbose)
if c.HistoricMode {
runMode = revel_path.RunMode
}
app.Cmd(runMode).Run()
return
}
|
[
"func",
"runApp",
"(",
"c",
"*",
"model",
".",
"CommandConfig",
")",
"(",
"err",
"error",
")",
"{",
"if",
"c",
".",
"Run",
".",
"Mode",
"==",
"\"",
"\"",
"{",
"c",
".",
"Run",
".",
"Mode",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"revel_path",
",",
"err",
":=",
"model",
".",
"NewRevelPaths",
"(",
"c",
".",
"Run",
".",
"Mode",
",",
"c",
".",
"ImportPath",
",",
"\"",
"\"",
",",
"model",
".",
"NewWrappedRevelCallback",
"(",
"nil",
",",
"c",
".",
"PackageResolver",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"utils",
".",
"NewBuildIfError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"Run",
".",
"Port",
">",
"-",
"1",
"{",
"revel_path",
".",
"HTTPPort",
"=",
"c",
".",
"Run",
".",
"Port",
"\n",
"}",
"else",
"{",
"c",
".",
"Run",
".",
"Port",
"=",
"revel_path",
".",
"HTTPPort",
"\n",
"}",
"\n\n",
"utils",
".",
"Logger",
".",
"Infof",
"(",
"\"",
"\\n",
"\"",
",",
"revel_path",
".",
"AppName",
",",
"revel_path",
".",
"ImportPath",
",",
"revel_path",
".",
"RunMode",
")",
"\n",
"utils",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"revel_path",
".",
"BasePath",
")",
"\n\n",
"// If the app is run in \"watched\" mode, use the harness to run it.",
"if",
"revel_path",
".",
"Config",
".",
"BoolDefault",
"(",
"\"",
"\"",
",",
"true",
")",
"&&",
"revel_path",
".",
"Config",
".",
"BoolDefault",
"(",
"\"",
"\"",
",",
"true",
")",
"{",
"utils",
".",
"Logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"runMode",
":=",
"fmt",
".",
"Sprintf",
"(",
"`{\"mode\":\"%s\", \"specialUseFlag\":%v}`",
",",
"revel_path",
".",
"RunMode",
",",
"c",
".",
"Verbose",
")",
"\n",
"if",
"c",
".",
"HistoricMode",
"{",
"runMode",
"=",
"revel_path",
".",
"RunMode",
"\n",
"}",
"\n",
"// **** Never returns.",
"harness",
".",
"NewHarness",
"(",
"c",
",",
"revel_path",
",",
"runMode",
",",
"c",
".",
"Run",
".",
"NoProxy",
")",
".",
"Run",
"(",
")",
"\n",
"}",
"\n\n",
"// Else, just build and run the app.",
"utils",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"app",
",",
"err",
":=",
"harness",
".",
"Build",
"(",
"c",
",",
"revel_path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"utils",
".",
"Logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"app",
".",
"Port",
"=",
"revel_path",
".",
"HTTPPort",
"\n",
"runMode",
":=",
"fmt",
".",
"Sprintf",
"(",
"`{\"mode\":\"%s\", \"specialUseFlag\":%v}`",
",",
"app",
".",
"Paths",
".",
"RunMode",
",",
"c",
".",
"Verbose",
")",
"\n",
"if",
"c",
".",
"HistoricMode",
"{",
"runMode",
"=",
"revel_path",
".",
"RunMode",
"\n",
"}",
"\n",
"app",
".",
"Cmd",
"(",
"runMode",
")",
".",
"Run",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// Called to run the app
|
[
"Called",
"to",
"run",
"the",
"app"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/run.go#L124-L166
|
17,998 |
revel/cmd
|
utils/file.go
|
CopyFile
|
func CopyFile(destFilename, srcFilename string) (err error) {
destFile, err := os.Create(destFilename)
if err != nil {
return NewBuildIfError(err, "Failed to create file", "file", destFilename)
}
srcFile, err := os.Open(srcFilename)
if err != nil {
return NewBuildIfError(err, "Failed to open file", "file", srcFilename)
}
_, err = io.Copy(destFile, srcFile)
if err != nil {
return NewBuildIfError(err, "Failed to copy data", "fromfile", srcFilename, "tofile", destFilename)
}
err = destFile.Close()
if err != nil {
return NewBuildIfError(err, "Failed to close file", "file", destFilename)
}
err = srcFile.Close()
if err != nil {
return NewBuildIfError(err, "Failed to close file", "file", srcFilename)
}
return
}
|
go
|
func CopyFile(destFilename, srcFilename string) (err error) {
destFile, err := os.Create(destFilename)
if err != nil {
return NewBuildIfError(err, "Failed to create file", "file", destFilename)
}
srcFile, err := os.Open(srcFilename)
if err != nil {
return NewBuildIfError(err, "Failed to open file", "file", srcFilename)
}
_, err = io.Copy(destFile, srcFile)
if err != nil {
return NewBuildIfError(err, "Failed to copy data", "fromfile", srcFilename, "tofile", destFilename)
}
err = destFile.Close()
if err != nil {
return NewBuildIfError(err, "Failed to close file", "file", destFilename)
}
err = srcFile.Close()
if err != nil {
return NewBuildIfError(err, "Failed to close file", "file", srcFilename)
}
return
}
|
[
"func",
"CopyFile",
"(",
"destFilename",
",",
"srcFilename",
"string",
")",
"(",
"err",
"error",
")",
"{",
"destFile",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"destFilename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NewBuildIfError",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"destFilename",
")",
"\n",
"}",
"\n\n",
"srcFile",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"srcFilename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NewBuildIfError",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"srcFilename",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"destFile",
",",
"srcFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NewBuildIfError",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"srcFilename",
",",
"\"",
"\"",
",",
"destFilename",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"destFile",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NewBuildIfError",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"destFilename",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"srcFile",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NewBuildIfError",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"srcFilename",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] |
// Copy file returns error
|
[
"Copy",
"file",
"returns",
"error"
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/file.go#L43-L71
|
17,999 |
revel/cmd
|
utils/file.go
|
GenerateTemplate
|
func GenerateTemplate(filename, templateSource string, args map[string]interface{}) (err error) {
tmpl := template.Must(template.New("").Parse(templateSource))
var b bytes.Buffer
if err = tmpl.Execute(&b, args); err != nil {
return NewBuildIfError(err, "ExecuteTemplate: Execute failed")
}
sourceCode := b.String()
filePath := filepath.Dir(filename)
if !DirExists(filePath) {
err = os.MkdirAll(filePath, 0777)
if err != nil && !os.IsExist(err) {
return NewBuildIfError(err, "Failed to make directory", "dir", filePath)
}
}
// Create the file
file, err := os.Create(filename)
if err != nil {
Logger.Fatal("Failed to create file", "error", err)
return
}
defer func() {
_ = file.Close()
}()
if _, err = file.WriteString(sourceCode); err != nil {
Logger.Fatal("Failed to write to file: ", "error", err)
}
return
}
|
go
|
func GenerateTemplate(filename, templateSource string, args map[string]interface{}) (err error) {
tmpl := template.Must(template.New("").Parse(templateSource))
var b bytes.Buffer
if err = tmpl.Execute(&b, args); err != nil {
return NewBuildIfError(err, "ExecuteTemplate: Execute failed")
}
sourceCode := b.String()
filePath := filepath.Dir(filename)
if !DirExists(filePath) {
err = os.MkdirAll(filePath, 0777)
if err != nil && !os.IsExist(err) {
return NewBuildIfError(err, "Failed to make directory", "dir", filePath)
}
}
// Create the file
file, err := os.Create(filename)
if err != nil {
Logger.Fatal("Failed to create file", "error", err)
return
}
defer func() {
_ = file.Close()
}()
if _, err = file.WriteString(sourceCode); err != nil {
Logger.Fatal("Failed to write to file: ", "error", err)
}
return
}
|
[
"func",
"GenerateTemplate",
"(",
"filename",
",",
"templateSource",
"string",
",",
"args",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"tmpl",
":=",
"template",
".",
"Must",
"(",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"templateSource",
")",
")",
"\n\n",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
"=",
"tmpl",
".",
"Execute",
"(",
"&",
"b",
",",
"args",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"NewBuildIfError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"sourceCode",
":=",
"b",
".",
"String",
"(",
")",
"\n",
"filePath",
":=",
"filepath",
".",
"Dir",
"(",
"filename",
")",
"\n",
"if",
"!",
"DirExists",
"(",
"filePath",
")",
"{",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"filePath",
",",
"0777",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsExist",
"(",
"err",
")",
"{",
"return",
"NewBuildIfError",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"filePath",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Create the file",
"file",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"Logger",
".",
"Fatal",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"_",
"=",
"file",
".",
"Close",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"if",
"_",
",",
"err",
"=",
"file",
".",
"WriteString",
"(",
"sourceCode",
")",
";",
"err",
"!=",
"nil",
"{",
"Logger",
".",
"Fatal",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] |
// GenerateTemplate renders the given template to produce source code, which it writes
// to the given file.
|
[
"GenerateTemplate",
"renders",
"the",
"given",
"template",
"to",
"produce",
"source",
"code",
"which",
"it",
"writes",
"to",
"the",
"given",
"file",
"."
] |
149f9f992be9b0957fb1ffeda43c14a123ceb43a
|
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/file.go#L75-L106
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.