_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q17900 | NewManager | train | func NewManager(logger Logger) *Manager {
return &Manager{
root: logger,
loggers: make(map[string]Node),
loggerMaker: defaultLoggerMaker,
}
} | go | {
"resource": ""
} |
q17901 | SetLoggerMaker | train | func (self *Manager) SetLoggerMaker(maker LoggerMaker) {
self.lock.Lock()
defer self.lock.Unlock()
self.loggerMaker = maker
} | go | {
"resource": ""
} |
q17902 | fixupParents | train | 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 | {
"resource": ""
} |
q17903 | fixupChildren | train | 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 | {
"resource": ""
} |
q17904 | NewLogRecord | train | 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 | {
"resource": ""
} |
q17905 | String | train | 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 | {
"resource": ""
} |
q17906 | GetMessage | train | 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 | {
"resource": ""
} |
q17907 | NewStreamHandler | train | func NewStreamHandler(
name string, level LogLevelType, stream Stream) *StreamHandler {
object := &StreamHandler{
BaseHandler: NewBaseHandler(name, level),
stream: stream,
}
Closer.AddHandler(object)
return object
} | go | {
"resource": ""
} |
q17908 | Emit2 | train | 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 | {
"resource": ""
} |
q17909 | NewNullHandler | train | func NewNullHandler() *NullHandler {
object := &NullHandler{
BaseHandler: NewBaseHandler("", LevelNotset),
}
Closer.AddHandler(object)
return object
} | go | {
"resource": ""
} |
q17910 | initFormatRegexp | train | 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 | {
"resource": ""
} |
q17911 | NewStandardFormatter | train | 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 | {
"resource": ""
} |
q17912 | FormatAll | train | func (self *StandardFormatter) FormatAll(record *LogRecord) string {
return fmt.Sprintf(self.strFormat, self.getFormatArgsFunc(record)...)
} | go | {
"resource": ""
} |
q17913 | Format | train | 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 | {
"resource": ""
} |
q17914 | NewFSock | train | 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 | {
"resource": ""
} |
q17915 | Connected | train | func (self *FSock) Connected() (ok bool) {
self.fsMutex.RLock()
ok = (self.conn != nil)
self.fsMutex.RUnlock()
return
} | go | {
"resource": ""
} |
q17916 | auth | train | 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 | {
"resource": ""
} |
q17917 | SendCmd | train | func (self *FSock) SendCmd(cmdStr string) (string, error) {
return self.sendCmd(cmdStr + "\n")
} | go | {
"resource": ""
} |
q17918 | SendApiCmd | train | func (self *FSock) SendApiCmd(cmdStr string) (string, error) {
return self.sendCmd("api " + cmdStr + "\n")
} | go | {
"resource": ""
} |
q17919 | SendBgapiCmd | train | 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 | {
"resource": ""
} |
q17920 | ReadEvents | train | 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 | {
"resource": ""
} |
q17921 | readHeaders | train | 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 | {
"resource": ""
} |
q17922 | readBody | train | 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 | {
"resource": ""
} |
q17923 | readEvents | train | 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 | {
"resource": ""
} |
q17924 | eventsPlain | train | 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 | {
"resource": ""
} |
q17925 | dispatchEvent | train | 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 | {
"resource": ""
} |
q17926 | doBackgroudJob | train | 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 | {
"resource": ""
} |
q17927 | NewFSockPool | train | 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 | {
"resource": ""
} |
q17928 | FSEventStrToMap | train | 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 | {
"resource": ""
} |
q17929 | MapChanData | train | 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 | {
"resource": ""
} |
q17930 | genUUID | train | 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 | {
"resource": ""
} |
q17931 | headerVal | train | 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 | {
"resource": ""
} |
q17932 | urlDecode | train | func urlDecode(hdrVal string) string {
if valUnescaped, errUnescaping := url.QueryUnescape(hdrVal); errUnescaping == nil {
hdrVal = valUnescaped
}
return hdrVal
} | go | {
"resource": ""
} |
q17933 | isSliceMember | train | func isSliceMember(ss []string, s string) bool {
sort.Strings(ss)
i := sort.SearchStrings(ss, s)
return (i < len(ss) && ss[i] == s)
} | go | {
"resource": ""
} |
q17934 | NewQueue | train | 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 | {
"resource": ""
} |
q17935 | Len | train | func (q *Queue) Len() (_, _ int) {
return q.count, len(q.buffer)
} | go | {
"resource": ""
} |
q17936 | PluginInspectWithRaw | train | 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 | {
"resource": ""
} |
q17937 | ServiceUpdate | train | 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 | {
"resource": ""
} |
q17938 | NewEnvClient | train | 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 | {
"resource": ""
} |
q17939 | NewClient | train | 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 | {
"resource": ""
} |
q17940 | TaskList | train | 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 | {
"resource": ""
} |
q17941 | NetworkInspect | train | func (cli *Client) NetworkInspect(ctx context.Context, networkID string) (types.NetworkResource, error) {
networkResource, _, err := cli.NetworkInspectWithRaw(ctx, networkID)
return networkResource, err
} | go | {
"resource": ""
} |
q17942 | ToParam | train | 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 | {
"resource": ""
} |
q17943 | FromParam | train | 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 | {
"resource": ""
} |
q17944 | Get | train | 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 | {
"resource": ""
} |
q17945 | Add | train | 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 | {
"resource": ""
} |
q17946 | Del | train | func (filters Args) Del(name, value string) {
if _, ok := filters.fields[name]; ok {
delete(filters.fields[name], value)
}
} | go | {
"resource": ""
} |
q17947 | ExactMatch | train | 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 | {
"resource": ""
} |
q17948 | UniqueExactMatch | train | 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 | {
"resource": ""
} |
q17949 | FuzzyMatch | train | 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 | {
"resource": ""
} |
q17950 | Include | train | func (filters Args) Include(field string) bool {
_, ok := filters.fields[field]
return ok
} | go | {
"resource": ""
} |
q17951 | Validate | train | 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 | {
"resource": ""
} |
q17952 | RegistryLogin | train | 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 | {
"resource": ""
} |
q17953 | GetTagFromNamedRef | train | 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 | {
"resource": ""
} |
q17954 | ContainerStart | train | 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 | {
"resource": ""
} |
q17955 | ServiceRemove | train | func (cli *Client) ServiceRemove(ctx context.Context, serviceID string) error {
resp, err := cli.delete(ctx, "/services/"+serviceID, nil, nil)
ensureReaderClosed(resp)
return err
} | go | {
"resource": ""
} |
q17956 | NodeRemove | train | 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 | {
"resource": ""
} |
q17957 | TaskInspectWithRaw | train | 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 | {
"resource": ""
} |
q17958 | CheckpointList | train | 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 | {
"resource": ""
} |
q17959 | post | train | 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 | {
"resource": ""
} |
q17960 | Events | train | 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 | {
"resource": ""
} |
q17961 | UpdateConfig | train | func (v *VersionCommand) UpdateConfig(c *model.CommandConfig, args []string) bool {
if len(args) > 0 {
c.Version.ImportPath = args[0]
}
return true
} | go | {
"resource": ""
} |
q17962 | RunWith | train | 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 | {
"resource": ""
} |
q17963 | doRepoCheck | train | 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 | {
"resource": ""
} |
q17964 | doUpdate | train | 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 | {
"resource": ""
} |
q17965 | outputVersion | train | 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 | {
"resource": ""
} |
q17966 | versionFromRepo | train | 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 | {
"resource": ""
} |
q17967 | updateLocalVersions | train | 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 | {
"resource": ""
} |
q17968 | updateBuildConfig | train | 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 | {
"resource": ""
} |
q17969 | buildApp | train | 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 | {
"resource": ""
} |
q17970 | buildCopyFiles | train | 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 | {
"resource": ""
} |
q17971 | buildCopyModules | train | 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 | {
"resource": ""
} |
q17972 | buildWriteScripts | train | 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 | {
"resource": ""
} |
q17973 | buildSafetyCheck | train | 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 | {
"resource": ""
} |
q17974 | NewWrappedRevelCallback | train | func NewWrappedRevelCallback(fe func(key Event, value interface{}) (response EventResponse), ie func(pkgName string) error) RevelCallback {
return &WrappedRevelCallback{fe, ie}
} | go | {
"resource": ""
} |
q17975 | FireEvent | train | func (w *WrappedRevelCallback) FireEvent(key Event, value interface{}) (response EventResponse) {
if w.FireEventFunction != nil {
response = w.FireEventFunction(key, value)
}
return
} | go | {
"resource": ""
} |
q17976 | loadModules | train | 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 | {
"resource": ""
} |
q17977 | addModulePaths | train | 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 | {
"resource": ""
} |
q17978 | genSource | train | 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 | {
"resource": ""
} |
q17979 | calcImportAliases | train | 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 | {
"resource": ""
} |
q17980 | addAlias | train | func addAlias(aliases map[string]string, importPath, pkgName string) {
alias, ok := aliases[importPath]
if ok {
return
}
alias = makePackageAlias(aliases, pkgName)
aliases[importPath] = alias
} | go | {
"resource": ""
} |
q17981 | makePackageAlias | train | 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 | {
"resource": ""
} |
q17982 | containsValue | train | func containsValue(m map[string]string, val string) bool {
for _, v := range m {
if v == val {
return true
}
}
return false
} | go | {
"resource": ""
} |
q17983 | newCompileError | train | 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 | {
"resource": ""
} |
q17984 | NewError | train | func NewError(source, title,path,description string) *Error {
return &Error {
SourceType:source,
Title:title,
Path:path,
Description:description,
}
} | go | {
"resource": ""
} |
q17985 | addImports | train | 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 | {
"resource": ""
} |
q17986 | importPathFromPath | train | 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 | {
"resource": ""
} |
q17987 | ControllerSpecs | train | func (s *SourceInfo) ControllerSpecs() []*TypeInfo {
if s.controllerSpecs == nil {
s.controllerSpecs = s.TypesThatEmbed(RevelImportPath+".Controller", "controllers")
}
return s.controllerSpecs
} | go | {
"resource": ""
} |
q17988 | ParseArgs | train | 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 | {
"resource": ""
} |
q17989 | CmdInit | train | 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 | {
"resource": ""
} |
q17990 | packageApp | train | 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 | {
"resource": ""
} |
q17991 | NewTypeExprFromData | train | func NewTypeExprFromData(expr, pkgName string, pkgIndex int, valid bool) TypeExpr {
return TypeExpr{expr, pkgName, pkgIndex, valid}
} | go | {
"resource": ""
} |
q17992 | NewTypeExprFromAst | train | 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 | {
"resource": ""
} |
q17993 | TypeName | train | 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 | {
"resource": ""
} |
q17994 | InitGoPaths | train | 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 | {
"resource": ""
} |
q17995 | SetVersions | train | 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 | {
"resource": ""
} |
q17996 | runIsImportPath | train | func runIsImportPath(pathToCheck string) bool {
if _, err := build.Import(pathToCheck, "", build.FindOnly);err==nil {
return true
}
return filepath.IsAbs(pathToCheck)
} | go | {
"resource": ""
} |
q17997 | runApp | train | 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 | {
"resource": ""
} |
q17998 | CopyFile | train | 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 | {
"resource": ""
} |
q17999 | GenerateTemplate | train | 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 | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.