_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q11600
ReportRequest
train
func ReportRequest(r *ReportParams) (*http.Request, error) { // Populate some fields automatically if we can if r.RunID == "" { uuid, err := uuid.GenerateUUID() if err != nil { return nil, err } r.RunID = uuid } if r.Arch == "" { r.Arch = runtime.GOARCH } if r.OS == "" { r.OS = runtime.GOOS } if r.Signature == "" { r.Signature = r.signature() } b, err := json.Marshal(r) if err != nil { return nil, err } u := &url.URL{ Scheme: "https", Host: "checkpoint-api.hashicorp.com", Path: fmt.Sprintf("/v1/telemetry/%s", r.Product), } req, err := http.NewRequest("POST", u.String(), bytes.NewReader(b)) if err != nil { return nil, err } req.Header.Set("Accept", "application/json") req.Header.Set("User-Agent", "HashiCorp/go-checkpoint") return req, nil }
go
{ "resource": "" }
q11601
CheckInterval
train
func CheckInterval(p *CheckParams, interval time.Duration, cb func(*CheckResponse, error)) chan struct{} { doneCh := make(chan struct{}) if disabled := os.Getenv("CHECKPOINT_DISABLE"); disabled != "" { return doneCh } go func() { for { select { case <-time.After(randomStagger(interval)): resp, err := Check(p) cb(resp, err) case <-doneCh: return } } }() return doneCh }
go
{ "resource": "" }
q11602
Versions
train
func Versions(p *VersionsParams) (*VersionsResponse, error) { if disabled := os.Getenv("CHECKPOINT_DISABLE"); disabled != "" && !p.Force { return &VersionsResponse{}, nil } // Set a default timeout of 1 sec for the versions request (in milliseconds) timeout := 1000 if _, err := strconv.Atoi(os.Getenv("CHECKPOINT_TIMEOUT")); err == nil { timeout, _ = strconv.Atoi(os.Getenv("CHECKPOINT_TIMEOUT")) } v := url.Values{} v.Set("product", p.Product) u := &url.URL{ Scheme: "https", Host: "checkpoint-api.hashicorp.com", Path: fmt.Sprintf("/v1/versions/%s", p.Service), RawQuery: v.Encode(), } req, err := http.NewRequest("GET", u.String(), nil) if err != nil { return nil, err } req.Header.Set("Accept", "application/json") req.Header.Set("User-Agent", "HashiCorp/go-checkpoint") client := cleanhttp.DefaultClient() // We use a short timeout since checking for new versions is not critical // enough to block on if checkpoint is broken/slow. client.Timeout = time.Duration(timeout) * time.Millisecond resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != 200 { return nil, fmt.Errorf("Unknown status: %d", resp.StatusCode) } result := &VersionsResponse{} if err := json.NewDecoder(resp.Body).Decode(result); err != nil { return nil, err } return result, nil }
go
{ "resource": "" }
q11603
NewConstrain
train
func NewConstrain(operator, version string) *Constraint { constraint := new(Constraint) constraint.SetOperator(operator) constraint.SetVersion(version) return constraint }
go
{ "resource": "" }
q11604
Match
train
func (self *Constraint) Match(version string) bool { return Compare(version, self.version, self.operator) }
go
{ "resource": "" }
q11605
String
train
func (self *Constraint) String() string { return strings.Trim(self.operator+" "+self.version, " ") }
go
{ "resource": "" }
q11606
AddConstraint
train
func (self *ConstraintGroup) AddConstraint(constraint ...*Constraint) { if self.constraints == nil { self.constraints = make([]*Constraint, 0) } self.constraints = append(self.constraints, constraint...) }
go
{ "resource": "" }
q11607
NewWithConfig
train
func NewWithConfig(config *Config) (*Grok, error) { g := &Grok{ config: config, aliases: map[string]string{}, compiledPatterns: map[string]*gRegexp{}, patterns: map[string]*gPattern{}, rawPattern: map[string]string{}, patternsGuard: new(sync.RWMutex), compiledGuard: new(sync.RWMutex), } if !config.SkipDefaultPatterns { g.AddPatternsFromMap(patterns) } if len(config.PatternsDir) > 0 { for _, path := range config.PatternsDir { err := g.AddPatternsFromPath(path) if err != nil { return nil, err } } } if err := g.AddPatternsFromMap(config.Patterns); err != nil { return nil, err } return g, nil }
go
{ "resource": "" }
q11608
addPattern
train
func (g *Grok) addPattern(name, pattern string) error { dnPattern, ti, err := g.denormalizePattern(pattern, g.patterns) if err != nil { return err } g.patterns[name] = &gPattern{expression: dnPattern, typeInfo: ti} return nil }
go
{ "resource": "" }
q11609
AddPattern
train
func (g *Grok) AddPattern(name, pattern string) error { g.patternsGuard.Lock() defer g.patternsGuard.Unlock() g.rawPattern[name] = pattern g.buildPatterns() return nil }
go
{ "resource": "" }
q11610
AddPatternsFromMap
train
func (g *Grok) AddPatternsFromMap(m map[string]string) error { g.patternsGuard.Lock() defer g.patternsGuard.Unlock() for name, pattern := range m { g.rawPattern[name] = pattern } return g.buildPatterns() }
go
{ "resource": "" }
q11611
addPatternsFromMap
train
func (g *Grok) addPatternsFromMap(m map[string]string) error { patternDeps := graph{} for k, v := range m { keys := []string{} for _, key := range canonical.FindAllStringSubmatch(v, -1) { names := strings.Split(key[1], ":") syntax := names[0] if g.patterns[syntax] == nil { if _, ok := m[syntax]; !ok { return fmt.Errorf("no pattern found for %%{%s}", syntax) } } keys = append(keys, syntax) } patternDeps[k] = keys } order, _ := sortGraph(patternDeps) for _, key := range reverseList(order) { g.addPattern(key, m[key]) } return nil }
go
{ "resource": "" }
q11612
AddPatternsFromPath
train
func (g *Grok) AddPatternsFromPath(path string) error { if fi, err := os.Stat(path); err == nil { if fi.IsDir() { path = path + "/*" } } else { return fmt.Errorf("invalid path : %s", path) } // only one error can be raised, when pattern is malformed // pattern is hard-coded "/*" so we ignore err files, _ := filepath.Glob(path) var filePatterns = map[string]string{} for _, fileName := range files { file, err := os.Open(fileName) if err != nil { return err } scanner := bufio.NewScanner(bufio.NewReader(file)) for scanner.Scan() { l := scanner.Text() if len(l) > 0 && l[0] != '#' { names := strings.SplitN(l, " ", 2) filePatterns[names[0]] = names[1] } } file.Close() } return g.AddPatternsFromMap(filePatterns) }
go
{ "resource": "" }
q11613
Match
train
func (g *Grok) Match(pattern, text string) (bool, error) { gr, err := g.compile(pattern) if err != nil { return false, err } if ok := gr.regexp.MatchString(text); !ok { return false, nil } return true, nil }
go
{ "resource": "" }
q11614
compiledParse
train
func (g *Grok) compiledParse(gr *gRegexp, text string) (map[string]string, error) { captures := make(map[string]string) if match := gr.regexp.FindStringSubmatch(text); len(match) > 0 { for i, name := range gr.regexp.SubexpNames() { if name != "" { if g.config.RemoveEmptyValues && match[i] == "" { continue } name = g.nameToAlias(name) captures[name] = match[i] } } } return captures, nil }
go
{ "resource": "" }
q11615
Parse
train
func (g *Grok) Parse(pattern, text string) (map[string]string, error) { gr, err := g.compile(pattern) if err != nil { return nil, err } return g.compiledParse(gr, text) }
go
{ "resource": "" }
q11616
ParseToMultiMap
train
func (g *Grok) ParseToMultiMap(pattern, text string) (map[string][]string, error) { gr, err := g.compile(pattern) if err != nil { return nil, err } captures := make(map[string][]string) if match := gr.regexp.FindStringSubmatch(text); len(match) > 0 { for i, name := range gr.regexp.SubexpNames() { if name != "" { if g.config.RemoveEmptyValues == true && match[i] == "" { continue } name = g.nameToAlias(name) captures[name] = append(captures[name], match[i]) } } } return captures, nil }
go
{ "resource": "" }
q11617
ParseStream
train
func (g *Grok) ParseStream(reader *bufio.Reader, pattern string, process func(map[string]string) error) error { gr, err := g.compile(pattern) if err != nil { return err } for { line, err := reader.ReadString('\n') if err == io.EOF { return nil } if err != nil { return err } values, err := g.compiledParse(gr, line) if err != nil { return err } if err = process(values); err != nil { return err } } }
go
{ "resource": "" }
q11618
Bytes
train
func (c CidStruct) Bytes() []byte { switch c.version { case 0: return []byte(c.hash) case 1: // two 8 bytes (max) numbers plus hash buf := make([]byte, 2*binary.MaxVarintLen64+len(c.hash)) n := binary.PutUvarint(buf, c.version) n += binary.PutUvarint(buf[n:], c.codec) cn := copy(buf[n:], c.hash) if cn != len(c.hash) { panic("copy hash length is inconsistent") } return buf[:n+len(c.hash)] default: panic("not possible to reach this point") } }
go
{ "resource": "" }
q11619
Has
train
func (s *Set) Has(c Cid) bool { _, ok := s.set[c] return ok }
go
{ "resource": "" }
q11620
Keys
train
func (s *Set) Keys() []Cid { out := make([]Cid, 0, len(s.set)) for k := range s.set { out = append(out, k) } return out }
go
{ "resource": "" }
q11621
Visit
train
func (s *Set) Visit(c Cid) bool { if !s.Has(c) { s.Add(c) return true } return false }
go
{ "resource": "" }
q11622
ForEach
train
func (s *Set) ForEach(f func(c Cid) error) error { for c := range s.set { err := f(c) if err != nil { return err } } return nil }
go
{ "resource": "" }
q11623
NewCidV0
train
func NewCidV0(mhash mh.Multihash) Cid { // Need to make sure hash is valid for CidV0 otherwise we will // incorrectly detect it as CidV1 in the Version() method dec, err := mh.Decode(mhash) if err != nil { panic(err) } if dec.Code != mh.SHA2_256 || dec.Length != 32 { panic("invalid hash for cidv0") } return Cid{string(mhash)} }
go
{ "resource": "" }
q11624
NewCidV1
train
func NewCidV1(codecType uint64, mhash mh.Multihash) Cid { hashlen := len(mhash) // two 8 bytes (max) numbers plus hash buf := make([]byte, 2*binary.MaxVarintLen64+hashlen) n := binary.PutUvarint(buf, 1) n += binary.PutUvarint(buf[n:], codecType) cn := copy(buf[n:], mhash) if cn != hashlen { panic("copy hash length is inconsistent") } return Cid{string(buf[:n+hashlen])} }
go
{ "resource": "" }
q11625
ExtractEncoding
train
func ExtractEncoding(v string) (mbase.Encoding, error) { if len(v) < 2 { return -1, ErrCidTooShort } if len(v) == 46 && v[:2] == "Qm" { return mbase.Base58BTC, nil } encoding := mbase.Encoding(v[0]) // check encoding is valid _, err := mbase.NewEncoder(encoding) if err != nil { return -1, err } return encoding, nil }
go
{ "resource": "" }
q11626
Version
train
func (c Cid) Version() uint64 { if len(c.str) == 34 && c.str[0] == 18 && c.str[1] == 32 { return 0 } return 1 }
go
{ "resource": "" }
q11627
Type
train
func (c Cid) Type() uint64 { if c.Version() == 0 { return DagProtobuf } _, n := uvarint(c.str) codec, _ := uvarint(c.str[n:]) return codec }
go
{ "resource": "" }
q11628
StringOfBase
train
func (c Cid) StringOfBase(base mbase.Encoding) (string, error) { switch c.Version() { case 0: if base != mbase.Base58BTC { return "", ErrInvalidEncoding } return c.Hash().B58String(), nil case 1: return mbase.Encode(base, c.Bytes()) default: panic("not possible to reach this point") } }
go
{ "resource": "" }
q11629
Encode
train
func (c Cid) Encode(base mbase.Encoder) string { switch c.Version() { case 0: return c.Hash().B58String() case 1: return base.Encode(c.Bytes()) default: panic("not possible to reach this point") } }
go
{ "resource": "" }
q11630
Hash
train
func (c Cid) Hash() mh.Multihash { bytes := c.Bytes() if c.Version() == 0 { return mh.Multihash(bytes) } // skip version length _, n1 := binary.Uvarint(bytes) // skip codec length _, n2 := binary.Uvarint(bytes[n1:]) return mh.Multihash(bytes[n1+n2:]) }
go
{ "resource": "" }
q11631
UnmarshalJSON
train
func (c *Cid) UnmarshalJSON(b []byte) error { if len(b) < 2 { return fmt.Errorf("invalid cid json blob") } obj := struct { CidTarget string `json:"/"` }{} objptr := &obj err := json.Unmarshal(b, &objptr) if err != nil { return err } if objptr == nil { *c = Cid{} return nil } if obj.CidTarget == "" { return fmt.Errorf("cid was incorrectly formatted") } out, err := Decode(obj.CidTarget) if err != nil { return err } *c = out return nil }
go
{ "resource": "" }
q11632
PrefixFromBytes
train
func PrefixFromBytes(buf []byte) (Prefix, error) { r := bytes.NewReader(buf) vers, err := binary.ReadUvarint(r) if err != nil { return Prefix{}, err } codec, err := binary.ReadUvarint(r) if err != nil { return Prefix{}, err } mhtype, err := binary.ReadUvarint(r) if err != nil { return Prefix{}, err } mhlen, err := binary.ReadUvarint(r) if err != nil { return Prefix{}, err } return Prefix{ Version: vers, Codec: codec, MhType: mhtype, MhLength: int(mhlen), }, nil }
go
{ "resource": "" }
q11633
Tag
train
func (p Paginator) Tag(opts Options) (*Tag, error) { // return an empty div if there is only 1 page if p.TotalPages <= 1 { return New("div", Options{}), nil } path, class, wing := extractBaseOptions(opts) opts["class"] = strings.Join([]string{class, "pagination"}, " ") t := New("ul", opts) barLength := wing*2 + 1 center := wing + 1 loopStart := 1 loopEnd := p.TotalPages li, err := p.addPrev(opts, path) if err != nil { return t, errors.WithStack(err) } t.Append(li) if p.TotalPages > barLength { loopEnd = barLength - 2 // range 1 ~ center if p.Page > center { /// range center loopStart = p.Page - wing + 2 loopEnd = loopStart + barLength - 5 li, err := pageLI("1", 1, path, p) if err != nil { return t, errors.WithStack(err) } t.Append(li) t.Append(pageLIDummy()) } if p.Page > (p.TotalPages - wing - 1) { loopEnd = p.TotalPages loopStart = p.TotalPages - barLength + 3 } } for i := loopStart; i <= loopEnd; i++ { li, err := pageLI(strconv.Itoa(i), i, path, p) if err != nil { return t, errors.WithStack(err) } t.Append(li) } if p.TotalPages > loopEnd { t.Append(pageLIDummy()) label := strconv.Itoa(p.TotalPages) li, err := pageLI(label, p.TotalPages, path, p) if err != nil { return t, errors.WithStack(err) } t.Append(li) } li, err = p.addNext(opts, path) if err != nil { return t, errors.WithStack(err) } t.Append(li) return t, nil }
go
{ "resource": "" }
q11634
Pagination
train
func Pagination(pagination interface{}, opts Options) (*Tag, error) { if p, ok := pagination.(Paginator); ok { return p.Tag(opts) } p := Paginator{ Page: 1, PerPage: 20, } return p.TagFromPagination(pagination, opts) }
go
{ "resource": "" }
q11635
SetAuthenticityToken
train
func (f *Form) SetAuthenticityToken(s string) { f.Prepend(tags.New("input", tags.Options{ "value": s, "type": "hidden", "name": "authenticity_token", })) }
go
{ "resource": "" }
q11636
Label
train
func (f Form) Label(value string, opts tags.Options) *tags.Tag { opts["body"] = value return tags.New("label", opts) }
go
{ "resource": "" }
q11637
New
train
func New(opts tags.Options) *Form { if opts["method"] == nil { opts["method"] = "POST" } if opts["multipart"] != nil { opts["enctype"] = "multipart/form-data" delete(opts, "multipart") } form := &Form{ Tag: tags.New("form", opts), } m := strings.ToUpper(form.Options["method"].(string)) if m != "POST" && m != "GET" { form.Options["method"] = "POST" form.Prepend(tags.New("input", tags.Options{ "value": m, "type": "hidden", "name": "_method", })) } return form }
go
{ "resource": "" }
q11638
CheckboxTag
train
func (f Form) CheckboxTag(opts tags.Options) *tags.Tag { opts["type"] = "checkbox" value := opts["value"] delete(opts, "value") checked := opts["checked"] delete(opts, "checked") if checked == nil { checked = "true" } opts["value"] = checked unchecked := opts["unchecked"] delete(opts, "unchecked") hl := opts["hide_label"] delete(opts, "hide_label") if opts["tag_only"] == true { delete(opts, "label") ct := f.InputTag(opts) ct.Checked = template.HTMLEscaper(value) == template.HTMLEscaper(checked) return ct } tag := tags.New("label", tags.Options{}) ct := f.InputTag(opts) ct.Checked = template.HTMLEscaper(value) == template.HTMLEscaper(checked) tag.Append(ct) if opts["name"] != nil && unchecked != nil { tag.Append(tags.New("input", tags.Options{ "type": "hidden", "name": opts["name"], "value": unchecked, })) } if opts["label"] != nil && hl == nil { label := fmt.Sprint(opts["label"]) delete(opts, "label") tag.Append(" " + label) } return tag }
go
{ "resource": "" }
q11639
RadioButton
train
func (f Form) RadioButton(opts tags.Options) *tags.Tag { return f.RadioButtonTag(opts) }
go
{ "resource": "" }
q11640
RadioButtonTag
train
func (f Form) RadioButtonTag(opts tags.Options) *tags.Tag { opts["type"] = "radio" var label string if opts["label"] != nil { label = fmt.Sprint(opts["label"]) delete(opts, "label") } var ID string if opts["id"] != nil { ID = fmt.Sprint(opts["id"]) } value := opts["value"] checked := opts["checked"] delete(opts, "checked") if opts["tag_only"] == true { ct := f.InputTag(opts) ct.Checked = template.HTMLEscaper(value) == template.HTMLEscaper(checked) return ct } ct := f.InputTag(opts) ct.Checked = template.HTMLEscaper(value) == template.HTMLEscaper(checked) labelOptions := tags.Options{ "body": strings.Join([]string{ct.String(), label}, " "), } // If the ID is provided, give it to the label's for attribute if ID != "" { labelOptions["for"] = ID } tag := tags.New("label", labelOptions) return tag }
go
{ "resource": "" }
q11641
CheckboxTag
train
func (f Form) CheckboxTag(opts tags.Options) *tags.Tag { return divWrapper(opts, func(o tags.Options) tags.Body { return f.Form.CheckboxTag(o) }) }
go
{ "resource": "" }
q11642
TextArea
train
func (f Form) TextArea(opts tags.Options) *tags.Tag { return f.TextAreaTag(opts) }
go
{ "resource": "" }
q11643
HiddenTag
train
func (f Form) HiddenTag(opts tags.Options) *tags.Tag { return f.Form.HiddenTag(opts) }
go
{ "resource": "" }
q11644
TextAreaTag
train
func (f Form) TextAreaTag(opts tags.Options) *tags.Tag { if opts["value"] != nil { opts["body"] = opts["value"] delete(opts, "value") } delete(opts, "tag_only") return tags.New("textarea", opts) }
go
{ "resource": "" }
q11645
InputTag
train
func (f Form) InputTag(opts tags.Options) *tags.Tag { if opts["type"] == "hidden" { return f.HiddenTag(opts) } if opts["type"] == nil { opts["type"] = "text" } if opts["type"] == "file" { f.Options["enctype"] = "multipart/form-data" } delete(opts, "tag_only") return tags.New("input", opts) }
go
{ "resource": "" }
q11646
HiddenTag
train
func (f Form) HiddenTag(opts tags.Options) *tags.Tag { opts["type"] = "hidden" return tags.New("input", opts) }
go
{ "resource": "" }
q11647
NewFormFor
train
func NewFormFor(model interface{}, opts tags.Options) *FormFor { rv := reflect.ValueOf(model) if rv.Kind() == reflect.Ptr { rv = rv.Elem() } name := rv.Type().Name() dashedName := flect.Dasherize(name) if opts["id"] == nil { opts["id"] = fmt.Sprintf("%s-form", dashedName) } errors := loadErrors(opts) delete(opts, "errors") return &FormFor{ Form: New(opts), Model: model, name: name, dashedName: dashedName, reflection: rv, Errors: errors, } }
go
{ "resource": "" }
q11648
InputTag
train
func (f FormFor) InputTag(field string, opts tags.Options) *tags.Tag { f.buildOptions(field, opts) f.addFormatTag(field, opts) return f.Form.InputTag(opts) }
go
{ "resource": "" }
q11649
HiddenTag
train
func (f FormFor) HiddenTag(field string, opts tags.Options) *tags.Tag { f.buildOptions(field, opts) return f.Form.HiddenTag(opts) }
go
{ "resource": "" }
q11650
RadioButton
train
func (f FormFor) RadioButton(field string, opts tags.Options) *tags.Tag { return f.RadioButtonTag(field, opts) }
go
{ "resource": "" }
q11651
TextArea
train
func (f FormFor) TextArea(field string, opts tags.Options) *tags.Tag { return f.TextAreaTag(field, opts) }
go
{ "resource": "" }
q11652
SubmitTag
train
func (f FormFor) SubmitTag(value string, opts tags.Options) *tags.Tag { return f.Form.SubmitTag(value, opts) }
go
{ "resource": "" }
q11653
New
train
func New(name string, opts Options) *Tag { tag := &Tag{ Name: name, Options: opts, } if tag.Options["body"] != nil { tag.Body = []Body{tag.Options["body"]} delete(tag.Options, "body") } if tag.Options["before_tag"] != nil { tag.BeforeTag = []BeforeTag{tag.Options["before_tag"]} delete(tag.Options, "before_tag") } if tag.Options["after_tag"] != nil { tag.AfterTag = []AfterTag{tag.Options["after_tag"]} delete(tag.Options, "after_tag") } if tag.Options["value"] != nil { val := tag.Options["value"] switch val.(type) { case time.Time: format := tag.Options["format"] if format == nil || format.(string) == "" { format = "2006-01-02" } delete(tag.Options, "format") tag.Options["value"] = val.(time.Time).Format(format.(string)) default: r := reflect.ValueOf(val) if r.IsValid() == false { tag.Options["value"] = "" } i := r.Interface() if dv, ok := i.(driver.Valuer); ok { value, _ := dv.Value() if value == nil { tag.Options["value"] = "" } tag.Options["value"] = fmt.Sprintf("%v", value) } } } if tag.Options["selected"] != nil { tag.Selected = template.HTMLEscaper(opts["value"]) == template.HTMLEscaper(opts["selected"]) delete(tag.Options, "selected") } return tag }
go
{ "resource": "" }
q11654
CheckboxTag
train
func (f FormFor) CheckboxTag(field string, opts tags.Options) *tags.Tag { label := field if opts["label"] != nil { label = fmt.Sprint(opts["label"]) } hl := opts["hide_label"] delete(opts, "label") fieldKey := validators.GenerateKey(field) if err := f.Errors.Get(fieldKey); err != nil { opts["errors"] = err } return divWrapper(opts, func(o tags.Options) tags.Body { if o["class"] != nil { cls := strings.Split(o["class"].(string), " ") ncls := make([]string, 0, len(cls)) for _, c := range cls { if c != "form-control" { ncls = append(ncls, c) } } o["class"] = strings.Join(ncls, " ") } if label != "" { o["label"] = label } if hl != nil { o["hide_label"] = hl } return f.FormFor.CheckboxTag(field, o) }) }
go
{ "resource": "" }
q11655
NewFormFor
train
func NewFormFor(model interface{}, opts tags.Options) *FormFor { return &FormFor{form.NewFormFor(model, opts)} }
go
{ "resource": "" }
q11656
JavascriptTag
train
func JavascriptTag(opts Options) *Tag { if opts["src"] != nil { delete(opts, "body") } return New("script", opts) }
go
{ "resource": "" }
q11657
GetMergeBase
train
func (repo *Repository) GetMergeBase(base, head string) (string, error) { stdout, err := NewCommand("merge-base", base, head).RunInDir(repo.Path) if err != nil { if strings.Contains(err.Error(), "exit status 1") { return "", ErrNoMergeBase{} } return "", err } return strings.TrimSpace(stdout), nil }
go
{ "resource": "" }
q11658
GetPullRequestInfo
train
func (repo *Repository) GetPullRequestInfo(basePath, baseBranch, headBranch string) (_ *PullRequestInfo, err error) { var remoteBranch string // We don't need a temporary remote for same repository. if repo.Path != basePath { // Add a temporary remote tmpRemote := strconv.FormatInt(time.Now().UnixNano(), 10) if err = repo.AddRemote(tmpRemote, basePath, true); err != nil { return nil, fmt.Errorf("AddRemote: %v", err) } defer repo.RemoveRemote(tmpRemote) remoteBranch = "remotes/" + tmpRemote + "/" + baseBranch } else { remoteBranch = baseBranch } prInfo := new(PullRequestInfo) prInfo.MergeBase, err = repo.GetMergeBase(remoteBranch, headBranch) if err != nil { return nil, err } logs, err := NewCommand("log", prInfo.MergeBase+"..."+headBranch, _PRETTY_LOG_FORMAT).RunInDirBytes(repo.Path) if err != nil { return nil, err } prInfo.Commits, err = repo.parsePrettyFormatLogToList(logs) if err != nil { return nil, fmt.Errorf("parsePrettyFormatLogToList: %v", err) } // Count number of changed files. stdout, err := NewCommand("diff", "--name-only", remoteBranch+"..."+headBranch).RunInDir(repo.Path) if err != nil { return nil, err } prInfo.NumFiles = len(strings.Split(stdout, "\n")) - 1 return prInfo, nil }
go
{ "resource": "" }
q11659
GetPatch
train
func (repo *Repository) GetPatch(base, head string) ([]byte, error) { return NewCommand("diff", "-p", "--binary", base, head).RunInDirBytes(repo.Path) }
go
{ "resource": "" }
q11660
IsValidHookName
train
func IsValidHookName(name string) bool { for _, hn := range HookNames { if hn == name { return true } } return false }
go
{ "resource": "" }
q11661
GetHook
train
func GetHook(repoPath, name string) (*Hook, error) { if !IsValidHookName(name) { return nil, ErrNotValidHook } h := &Hook{ name: name, path: path.Join(repoPath, HookDir, name), } if isFile(h.path) { data, err := ioutil.ReadFile(h.path) if err != nil { return nil, err } h.IsActive = true h.Content = string(data) return h, nil } // Check sample file samplePath := path.Join(repoPath, HookSampleDir, h.name) + ".sample" if isFile(samplePath) { data, err := ioutil.ReadFile(samplePath) if err != nil { return nil, err } h.Sample = string(data) } return h, nil }
go
{ "resource": "" }
q11662
Update
train
func (h *Hook) Update() error { if len(strings.TrimSpace(h.Content)) == 0 { if isExist(h.path) { return os.Remove(h.path) } return nil } os.MkdirAll(path.Dir(h.path), os.ModePerm) return ioutil.WriteFile(h.path, []byte(strings.Replace(h.Content, "\r", "", -1)), os.ModePerm) }
go
{ "resource": "" }
q11663
ListHooks
train
func ListHooks(repoPath string) (_ []*Hook, err error) { if !isDir(path.Join(repoPath, "hooks")) { return nil, errors.New("hooks path does not exist") } hooks := make([]*Hook, len(HookNames)) for i, name := range HookNames { hooks[i], err = GetHook(repoPath, name) if err != nil { return nil, err } } return hooks, nil }
go
{ "resource": "" }
q11664
RefURL
train
func (sf *SubModuleFile) RefURL(urlPrefix string, parentPath string) string { if sf.refURL == "" { return "" } url := strings.TrimSuffix(sf.refURL, ".git") // git://xxx/user/repo if strings.HasPrefix(url, "git://") { return "http://" + strings.TrimPrefix(url, "git://") } // http[s]://xxx/user/repo if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") { return url } // Relative url prefix check (according to git submodule documentation) if strings.HasPrefix(url, "./") || strings.HasPrefix(url, "../") { // ...construct and return correct submodule url here... idx := strings.Index(parentPath, "/src/") if idx == -1 { return url } return strings.TrimSuffix(urlPrefix, "/") + parentPath[:idx] + "/" + url } // sysuser@xxx:user/repo i := strings.Index(url, "@") j := strings.LastIndex(url, ":") // Only process when i < j because git+ssh://git@git.forwardbias.in/npploader.git if i > -1 && j > -1 && i < j { // fix problem with reverse proxy works only with local server if strings.Contains(urlPrefix, url[i+1:j]) { return urlPrefix + url[j+1:] } else { return "http://" + url[i+1:j] + "/" + url[j+1:] } } return url }
go
{ "resource": "" }
q11665
BinVersion
train
func BinVersion() (string, error) { if len(gitVersion) > 0 { return gitVersion, nil } stdout, err := NewCommand("version").Run() if err != nil { return "", err } fields := strings.Fields(stdout) if len(fields) < 3 { return "", fmt.Errorf("not enough output: %s", stdout) } // Handle special case on Windows. i := strings.Index(fields[2], "windows") if i >= 1 { gitVersion = fields[2][:i-1] return gitVersion, nil } gitVersion = fields[2] return gitVersion, nil }
go
{ "resource": "" }
q11666
Fsck
train
func Fsck(repoPath string, timeout time.Duration, args ...string) error { // Make sure timeout makes sense. if timeout <= 0 { timeout = -1 } _, err := NewCommand("fsck").AddArguments(args...).RunInDirTimeout(timeout, repoPath) return err }
go
{ "resource": "" }
q11667
GetTree
train
func (repo *Repository) GetTree(idStr string) (*Tree, error) { id, err := NewIDFromString(idStr) if err != nil { return nil, err } return repo.getTree(id) }
go
{ "resource": "" }
q11668
AddEnvs
train
func (c *Command) AddEnvs(envs ...string) *Command { c.envs = append(c.envs, envs...) return c }
go
{ "resource": "" }
q11669
RunInDirTimeoutPipeline
train
func (c *Command) RunInDirTimeoutPipeline(timeout time.Duration, dir string, stdout, stderr io.Writer) error { if timeout == -1 { timeout = DEFAULT_TIMEOUT } if len(dir) == 0 { log(c.String()) } else { log("%s: %v", dir, c) } cmd := exec.Command(c.name, c.args...) if c.envs != nil { cmd.Env = append(os.Environ(), c.envs...) } cmd.Dir = dir cmd.Stdout = stdout cmd.Stderr = stderr if err := cmd.Start(); err != nil { return err } done := make(chan error) go func() { done <- cmd.Wait() }() var err error select { case <-time.After(timeout): if cmd.Process != nil && cmd.ProcessState != nil && !cmd.ProcessState.Exited() { if err := cmd.Process.Kill(); err != nil { return fmt.Errorf("fail to kill process: %v", err) } } <-done return ErrExecTimeout{timeout} case err = <-done: } return err }
go
{ "resource": "" }
q11670
RunInDirPipeline
train
func (c *Command) RunInDirPipeline(dir string, stdout, stderr io.Writer) error { return c.RunInDirTimeoutPipeline(-1, dir, stdout, stderr) }
go
{ "resource": "" }
q11671
IsReferenceExist
train
func IsReferenceExist(repoPath, name string) bool { _, err := NewCommand("show-ref", "--verify", name).RunInDir(repoPath) return err == nil }
go
{ "resource": "" }
q11672
GetHEADBranch
train
func (repo *Repository) GetHEADBranch() (*Branch, error) { stdout, err := NewCommand("symbolic-ref", "HEAD").RunInDir(repo.Path) if err != nil { return nil, err } stdout = strings.TrimSpace(stdout) if !strings.HasPrefix(stdout, BRANCH_PREFIX) { return nil, fmt.Errorf("invalid HEAD branch: %v", stdout) } return &Branch{ Name: stdout[len(BRANCH_PREFIX):], Path: stdout, }, nil }
go
{ "resource": "" }
q11673
SetDefaultBranch
train
func (repo *Repository) SetDefaultBranch(name string) error { if version.Compare(gitVersion, "1.7.10", "<") { return ErrUnsupportedVersion{"1.7.10"} } _, err := NewCommand("symbolic-ref", "HEAD", BRANCH_PREFIX+name).RunInDir(repo.Path) return err }
go
{ "resource": "" }
q11674
GetBranches
train
func (repo *Repository) GetBranches() ([]string, error) { stdout, err := NewCommand("show-ref", "--heads").RunInDir(repo.Path) if err != nil { return nil, err } infos := strings.Split(stdout, "\n") branches := make([]string, len(infos)-1) for i, info := range infos[:len(infos)-1] { fields := strings.Fields(info) if len(fields) != 2 { continue // NOTE: I should believe git will not give me wrong string. } branches[i] = strings.TrimPrefix(fields[1], BRANCH_PREFIX) } return branches, nil }
go
{ "resource": "" }
q11675
DeleteBranch
train
func DeleteBranch(repoPath, name string, opts DeleteBranchOptions) error { cmd := NewCommand("branch") if opts.Force { cmd.AddArguments("-D") } else { cmd.AddArguments("-d") } cmd.AddArguments(name) _, err := cmd.RunInDir(repoPath) return err }
go
{ "resource": "" }
q11676
DeleteBranch
train
func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) error { return DeleteBranch(repo.Path, name, opts) }
go
{ "resource": "" }
q11677
AddRemote
train
func (repo *Repository) AddRemote(name, url string, fetch bool) error { cmd := NewCommand("remote", "add") if fetch { cmd.AddArguments("-f") } cmd.AddArguments(name, url) _, err := cmd.RunInDir(repo.Path) return err }
go
{ "resource": "" }
q11678
RemoveRemote
train
func (repo *Repository) RemoveRemote(name string) error { _, err := NewCommand("remote", "remove", name).RunInDir(repo.Path) return err }
go
{ "resource": "" }
q11679
Data
train
func (b *Blob) Data() (io.Reader, error) { stdout := new(bytes.Buffer) stderr := new(bytes.Buffer) // Preallocate memory to save ~50% memory usage on big files. stdout.Grow(int(b.Size() + 2048)) if err := b.DataPipeline(stdout, stderr); err != nil { return nil, concatenateError(err, stderr.String()) } return stdout, nil }
go
{ "resource": "" }
q11680
MustIDFromString
train
func MustIDFromString(s string) sha1 { b, _ := hex.DecodeString(s) return MustID(b) }
go
{ "resource": "" }
q11681
NewIDFromString
train
func NewIDFromString(s string) (sha1, error) { var id sha1 s = strings.TrimSpace(s) if len(s) != 40 { return id, fmt.Errorf("Length must be 40: %s", s) } b, err := hex.DecodeString(s) if err != nil { return id, err } return NewID(b) }
go
{ "resource": "" }
q11682
GetDiffRange
train
func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxLineCharacteres, maxFiles int) (*Diff, error) { repo, err := OpenRepository(repoPath) if err != nil { return nil, err } commit, err := repo.GetCommit(afterCommitID) if err != nil { return nil, err } cmd := NewCommand() if len(beforeCommitID) == 0 { // First commit of repository if commit.ParentCount() == 0 { cmd.AddArguments("show", "--full-index", afterCommitID) } else { c, _ := commit.Parent(0) cmd.AddArguments("diff", "--full-index", "-M", c.ID.String(), afterCommitID) } } else { cmd.AddArguments("diff", "--full-index", "-M", beforeCommitID, afterCommitID) } stdout, w := io.Pipe() done := make(chan error) var diff *Diff go func() { diff = ParsePatch(done, maxLines, maxLineCharacteres, maxFiles, stdout) }() stderr := new(bytes.Buffer) err = cmd.RunInDirTimeoutPipeline(2*time.Minute, repoPath, w, stderr) w.Close() // Close writer to exit parsing goroutine if err != nil { return nil, concatenateError(err, stderr.String()) } return diff, <-done }
go
{ "resource": "" }
q11683
GetRawDiff
train
func GetRawDiff(repoPath, commitID string, diffType RawDiffType, writer io.Writer) error { repo, err := OpenRepository(repoPath) if err != nil { return fmt.Errorf("OpenRepository: %v", err) } commit, err := repo.GetCommit(commitID) if err != nil { return err } cmd := NewCommand() switch diffType { case RAW_DIFF_NORMAL: if commit.ParentCount() == 0 { cmd.AddArguments("show", commitID) } else { c, _ := commit.Parent(0) cmd.AddArguments("diff", "-M", c.ID.String(), commitID) } case RAW_DIFF_PATCH: if commit.ParentCount() == 0 { cmd.AddArguments("format-patch", "--no-signature", "--stdout", "--root", commitID) } else { c, _ := commit.Parent(0) query := fmt.Sprintf("%s...%s", commitID, c.ID.String()) cmd.AddArguments("format-patch", "--no-signature", "--stdout", query) } default: return fmt.Errorf("invalid diffType: %s", diffType) } stderr := new(bytes.Buffer) if err = cmd.RunInDirPipeline(repoPath, writer, stderr); err != nil { return concatenateError(err, stderr.String()) } return nil }
go
{ "resource": "" }
q11684
GetDiffCommit
train
func GetDiffCommit(repoPath, commitID string, maxLines, maxLineCharacteres, maxFiles int) (*Diff, error) { return GetDiffRange(repoPath, "", commitID, maxLines, maxLineCharacteres, maxFiles) }
go
{ "resource": "" }
q11685
GetCommitByPath
train
func (c *Commit) GetCommitByPath(relpath string) (*Commit, error) { return c.repo.getCommitByPathWithID(c.ID, relpath) }
go
{ "resource": "" }
q11686
AddChanges
train
func AddChanges(repoPath string, all bool, files ...string) error { cmd := NewCommand("add") if all { cmd.AddArguments("--all") } _, err := cmd.AddArguments(files...).RunInDir(repoPath) return err }
go
{ "resource": "" }
q11687
CommitChanges
train
func CommitChanges(repoPath string, opts CommitChangesOptions) error { cmd := NewCommand() if opts.Committer != nil { cmd.AddEnvs("GIT_COMMITTER_NAME="+opts.Committer.Name, "GIT_COMMITTER_EMAIL="+opts.Committer.Email) } cmd.AddArguments("commit") if opts.Author == nil { opts.Author = opts.Committer } if opts.Author != nil { cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email)) } cmd.AddArguments("-m", opts.Message) _, err := cmd.RunInDir(repoPath) // No stderr but exit status 1 means nothing to commit. if err != nil && err.Error() == "exit status 1" { return nil } return err }
go
{ "resource": "" }
q11688
GetCommitFileStatus
train
func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error) { stdout, w := io.Pipe() done := make(chan struct{}) fileStatus := NewCommitFileStatus() go func() { scanner := bufio.NewScanner(stdout) for scanner.Scan() { fields := strings.Fields(scanner.Text()) if len(fields) < 2 { continue } switch fields[0][0] { case 'A': fileStatus.Added = append(fileStatus.Added, fields[1]) case 'D': fileStatus.Removed = append(fileStatus.Removed, fields[1]) case 'M': fileStatus.Modified = append(fileStatus.Modified, fields[1]) } } done <- struct{}{} }() stderr := new(bytes.Buffer) err := NewCommand("show", "--name-status", "--pretty=format:''", commitID).RunInDirPipeline(repoPath, w, stderr) w.Close() // Close writer to exit parsing goroutine if err != nil { return nil, concatenateError(err, stderr.String()) } <-done return fileStatus, nil }
go
{ "resource": "" }
q11689
FileStatus
train
func (c *Commit) FileStatus() (*CommitFileStatus, error) { return GetCommitFileStatus(c.repo.Path, c.ID.String()) }
go
{ "resource": "" }
q11690
GetBranchCommitID
train
func (repo *Repository) GetBranchCommitID(name string) (string, error) { return repo.getRefCommitID(BRANCH_PREFIX + name) }
go
{ "resource": "" }
q11691
GetTagCommitID
train
func (repo *Repository) GetTagCommitID(name string) (string, error) { return repo.getRefCommitID(TAG_PREFIX + name) }
go
{ "resource": "" }
q11692
GetRemoteBranchCommitID
train
func (repo *Repository) GetRemoteBranchCommitID(name string) (string, error) { return repo.getRefCommitID(REMOTE_PREFIX + name) }
go
{ "resource": "" }
q11693
GetCommit
train
func (repo *Repository) GetCommit(commitID string) (*Commit, error) { var err error commitID, err = GetFullCommitID(repo.Path, commitID) if err != nil { return nil, err } id, err := NewIDFromString(commitID) if err != nil { return nil, err } return repo.getCommit(id) }
go
{ "resource": "" }
q11694
GetBranchCommit
train
func (repo *Repository) GetBranchCommit(name string) (*Commit, error) { commitID, err := repo.GetBranchCommitID(name) if err != nil { return nil, err } return repo.GetCommit(commitID) }
go
{ "resource": "" }
q11695
GetTagCommit
train
func (repo *Repository) GetTagCommit(name string) (*Commit, error) { commitID, err := repo.GetTagCommitID(name) if err != nil { return nil, err } return repo.GetCommit(commitID) }
go
{ "resource": "" }
q11696
GetRemoteBranchCommit
train
func (repo *Repository) GetRemoteBranchCommit(name string) (*Commit, error) { commitID, err := repo.GetRemoteBranchCommitID(name) if err != nil { return nil, err } return repo.GetCommit(commitID) }
go
{ "resource": "" }
q11697
GetCommitByPath
train
func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { stdout, err := NewCommand("log", "-1", _PRETTY_LOG_FORMAT, "--", relpath).RunInDirBytes(repo.Path) if err != nil { return nil, err } commits, err := repo.parsePrettyFormatLogToList(stdout) if err != nil { return nil, err } return commits.Front().Value.(*Commit), nil }
go
{ "resource": "" }
q11698
CommitsBetween
train
func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) { if version.Compare(gitVersion, "1.8.0", ">=") { stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path) if err != nil { return nil, err } return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) } // Fallback to stupid solution, which iterates all commits of the repository // if before is not an ancestor of last. l := list.New() if last == nil || last.ParentCount() == 0 { return l, nil } var err error cur := last for { if cur.ID.Equal(before.ID) { break } l.PushBack(cur) if cur.ParentCount() == 0 { break } cur, err = cur.Parent(0) if err != nil { return nil, err } } return l, nil }
go
{ "resource": "" }
q11699
commitsBefore
train
func (repo *Repository) commitsBefore(l *list.List, parent *list.Element, id sha1, current, limit int) error { // Reach the limit if limit > 0 && current > limit { return nil } commit, err := repo.getCommit(id) if err != nil { return fmt.Errorf("getCommit: %v", err) } var e *list.Element if parent == nil { e = l.PushBack(commit) } else { var in = parent for { if in == nil { break } else if in.Value.(*Commit).ID.Equal(commit.ID) { return nil } else if in.Next() == nil { break } if in.Value.(*Commit).Committer.When.Equal(commit.Committer.When) { break } if in.Value.(*Commit).Committer.When.After(commit.Committer.When) && in.Next().Value.(*Commit).Committer.When.Before(commit.Committer.When) { break } in = in.Next() } e = l.InsertAfter(commit, in) } pr := parent if commit.ParentCount() > 1 { pr = e } for i := 0; i < commit.ParentCount(); i++ { id, err := commit.ParentID(i) if err != nil { return err } err = repo.commitsBefore(l, pr, id, current+1, limit) if err != nil { return err } } return nil }
go
{ "resource": "" }