_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3
values | text stringlengths 52 85.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q172000 | childOf | validation | func (l *line) childOf(parent element) (bool, error) {
var ok bool
var err error
switch {
case l.isEmpty():
ok = true
case parent.ContainPlainText():
switch {
case parent.Base().ln.indent < l.indent:
ok = true
}
default:
switch {
case l.indent == parent.Base().ln.indent+1:
ok = true
case l.in... | go | {
"resource": ""
} |
q172001 | newLine | validation | func newLine(no int, str string, opts *Options, f *File) *line {
return &line{
no: no,
str: str,
indent: indent(str),
tokens: strings.Split(strings.TrimLeft(str, space), space),
opts: opts,
file: f,
}
} | go | {
"resource": ""
} |
q172002 | indent | validation | func indent(str string) int {
var i int
for _, b := range str {
if b != unicodeSpace {
break
}
i++
}
return i / 2
} | go | {
"resource": ""
} |
q172003 | InitializeOptions | validation | func InitializeOptions(opts *Options) *Options {
if opts == nil {
opts = &Options{}
}
if opts.Extension == "" {
opts.Extension = defaultExtension
}
if opts.DelimLeft == "" {
opts.DelimLeft = defaultDelimLeft
}
if opts.DelimRight == "" {
opts.DelimRight = defaultDelimRight
}
if opts.AttributeNameCla... | go | {
"resource": ""
} |
q172004 | AddNoCloseTagName | validation | func (opts *Options) AddNoCloseTagName(name string) {
opts.NoCloseTagNames = append(opts.NoCloseTagNames, name)
} | go | {
"resource": ""
} |
q172005 | DeleteNoCloseTagName | validation | func (opts *Options) DeleteNoCloseTagName(name string) {
var newset []string
for _, n := range opts.NoCloseTagNames {
if n != name {
newset = append(newset, n)
}
}
opts.NoCloseTagNames = newset
} | go | {
"resource": ""
} |
q172006 | Asset | validation | func Asset(name string) ([]byte, error) {
if f, ok := _bindata[name]; ok {
return f()
}
return nil, fmt.Errorf("Asset %s not found", name)
} | go | {
"resource": ""
} |
q172007 | newAction | validation | func newAction(ln *line, rslt *result, src *source, parent element, opts *Options) *action {
return &action{
elementBase: newElementBase(ln, rslt, src, parent, opts),
}
} | go | {
"resource": ""
} |
q172008 | AddRelayTransport | validation | func AddRelayTransport(ctx context.Context, h host.Host, upgrader *tptu.Upgrader, opts ...RelayOpt) error {
n, ok := h.Network().(tpt.Network)
if !ok {
return fmt.Errorf("%v is not a transport network", h.Network())
}
r, err := NewRelay(ctx, h, upgrader, opts...)
if err != nil {
return err
}
// There's no ... | go | {
"resource": ""
} |
q172009 | NewRelay | validation | func NewRelay(ctx context.Context, h host.Host, upgrader *tptu.Upgrader, opts ...RelayOpt) (*Relay, error) {
r := &Relay{
upgrader: upgrader,
host: h,
ctx: ctx,
self: h.ID(),
incoming: make(chan *Conn),
relays: make(map[peer.ID]struct{}),
liveHops: make(map[peer.ID]map[peer.ID]int),
}
f... | go | {
"resource": ""
} |
q172010 | ParseJSONBody | validation | func ParseJSONBody(r io.Reader) (interface{}, error) {
var v interface{}
if err := json.NewDecoder(r).Decode(&v); err != nil {
return nil, err
}
return v, nil
} | go | {
"resource": ""
} |
q172011 | New | validation | func New(t T, URL string) *Runner {
r := &Runner{
t: t,
rootURL: URL,
vars: make(map[string]*parse.Value),
DoRequest: http.DefaultTransport.RoundTrip,
Log: func(s string) {
fmt.Println(s)
},
Verbose: func(args ...interface{}) {
if !testing.Verbose() {
return
}
fmt.Println(a... | go | {
"resource": ""
} |
q172012 | RunGroup | validation | func (r *Runner) RunGroup(groups ...*parse.Group) {
for _, group := range groups {
r.runGroup(group)
}
} | go | {
"resource": ""
} |
q172013 | ParseFile | validation | func ParseFile(files ...string) ([]*Group, error) {
var groups []*Group
for _, file := range files {
if err := func(file string) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
gs, err := Parse(file, f)
if err != nil {
return err
}
groups = append(groups,... | go | {
"resource": ""
} |
q172014 | ParseLine | validation | func ParseLine(n int, unsafeText []byte) (*Line, error) {
linetype := LineTypePlain
// trim off comments
var comment []byte
text := make([]byte, len(unsafeText))
copy(text, unsafeText)
if bytes.Contains(text, commentPrefix) {
segs := bytes.Split(text, commentPrefix)
text = segs[0]
comment = segs[1]
}
var ... | go | {
"resource": ""
} |
q172015 | Capture | validation | func (l *Line) Capture() string {
if len(l.Comment) == 0 {
return ""
}
matches := placeholderRegexp.FindSubmatch(l.Comment)
if len(matches) < 2 {
return ""
}
return string(matches[1])
} | go | {
"resource": ""
} |
q172016 | Bytes | validation | func (l Lines) Bytes() []byte {
var lines [][]byte
for _, line := range l {
lines = append(lines, line.Bytes)
}
return bytes.Join(lines, []byte("\n"))
} | go | {
"resource": ""
} |
q172017 | Equal | validation | func (v Value) Equal(val interface{}) bool {
var str string
var ok bool
if str, ok = v.Data.(string); !ok {
return v.Data == val
}
if isRegex(str) {
// looks like regexp to me
regex := regexp.MustCompile(str[1 : len(str)-1])
// turn the value into a string
valStr := fmt.Sprintf("%v", val)
if regex.Matc... | go | {
"resource": ""
} |
q172018 | Type | validation | func (v Value) Type() string {
var str string
var ok bool
if str, ok = v.Data.(string); !ok {
return fmt.Sprintf("%T", v.Data)
}
if isRegex(str) {
return "regex"
}
return "string"
} | go | {
"resource": ""
} |
q172019 | NewServer | validation | func NewServer() http.Handler {
r := mux.NewRouter()
r.Path("/hello").Methods("GET").HandlerFunc(handleHello)
return r
} | go | {
"resource": ""
} |
q172020 | PrettyPrintAsJSON | validation | func PrettyPrintAsJSON(input interface{}, indent ...string) error {
var indentStr string
if len(indent) == 0 {
indentStr = " "
} else {
indentStr = strings.Join(indent, "")
}
data, err := json.MarshalIndent(input, "", indentStr)
if err != nil {
return err
}
_, err = fmt.Println(string(data))
return err
... | go | {
"resource": ""
} |
q172021 | StringMarshalJSON | validation | func StringMarshalJSON(data interface{}, indent string) string {
buffer, err := json.MarshalIndent(data, "", indent)
if err != nil {
return ""
}
return string(buffer)
} | go | {
"resource": ""
} |
q172022 | StringMD5Hex | validation | func StringMD5Hex(data string) string {
hash := md5.New()
hash.Write([]byte(data))
return fmt.Sprintf("%x", hash.Sum(nil))
} | go | {
"resource": ""
} |
q172023 | StringSHA1Base64 | validation | func StringSHA1Base64(data string) string {
hash := sha1.Sum([]byte(data))
return base64.StdEncoding.EncodeToString(hash[:])
} | go | {
"resource": ""
} |
q172024 | StringJoinFormat | validation | func StringJoinFormat(format string, values interface{}, sep string) string {
v := reflect.ValueOf(values)
if v.Kind() != reflect.Slice {
panic("values is not a slice")
}
var buffer bytes.Buffer
for i := 0; i < v.Len(); i++ {
if i > 0 {
buffer.WriteString(sep)
}
buffer.WriteString(fmt.Sprintf(format, v.... | go | {
"resource": ""
} |
q172025 | StringJoin | validation | func StringJoin(values interface{}, sep string) string {
v := reflect.ValueOf(values)
if v.Kind() != reflect.Slice {
panic("values is not a slice")
}
var buffer bytes.Buffer
for i := 0; i < v.Len(); i++ {
if i > 0 {
buffer.WriteString(sep)
}
buffer.WriteString(fmt.Sprint(v.Index(i).Interface()))
}
ret... | go | {
"resource": ""
} |
q172026 | Less | validation | func (s StringGroupedNumberPostfixSorter) Less(i, j int) bool {
bi, ni := StringSplitNumberPostfix(s[i])
bj, nj := StringSplitNumberPostfix(s[j])
if bi == bj {
if len(ni) == len(nj) {
inti, _ := strconv.Atoi(ni)
intj, _ := strconv.Atoi(nj)
return inti < intj
} else {
return len(ni) < len(nj)
}
}
... | go | {
"resource": ""
} |
q172027 | Swap | validation | func (s StringGroupedNumberPostfixSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
} | go | {
"resource": ""
} |
q172028 | StringMap | validation | func StringMap(f func(string) string, data []string) []string {
size := len(data)
result := make([]string, size, size)
for i := 0; i < size; i++ {
result[i] = f(data[i])
}
return result
} | go | {
"resource": ""
} |
q172029 | StringFilter | validation | func StringFilter(f func(string) bool, data []string) []string {
result := make([]string, 0, 0)
for _, element := range data {
if f(element) {
result = append(result, element)
}
}
return result
} | go | {
"resource": ""
} |
q172030 | StringFindBetween | validation | func StringFindBetween(s, start, stop string) (between, remainder string, found bool) {
begin := strings.Index(s, start)
if begin == -1 {
return "", s, false
}
between = s[begin+len(start):]
end := strings.Index(between, stop)
if end == -1 {
return "", s, false
}
return between[:end], s[begin+len(start)+end... | go | {
"resource": ""
} |
q172031 | StringFind | validation | func StringFind(s, token string) (remainder string, found bool) {
i := strings.Index(s, token)
if i == -1 {
return s, false
}
return s[i+len(token):], true
} | go | {
"resource": ""
} |
q172032 | EncryptAES | validation | func EncryptAES(key []byte, plaintext []byte) []byte {
block := AES.GetCypher(key)
defer AES.ReturnCypher(key, block)
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[... | go | {
"resource": ""
} |
q172033 | DecryptAES | validation | func DecryptAES(key []byte, ciphertext []byte) []byte {
block := AES.GetCypher(key)
defer AES.ReturnCypher(key, block)
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
if len(ciphertext) < aes.BlockSize {
panic("ciphertext too short")
}
i... | go | {
"resource": ""
} |
q172034 | PanicIfErr | validation | func PanicIfErr(args ...interface{}) {
for _, v := range args {
if err, _ := v.(error); err != nil {
panic(fmt.Errorf("Panicking because of error: %s\nAt:\n%s\n", err, StackTrace(2)))
}
}
} | go | {
"resource": ""
} |
q172035 | AsError | validation | func AsError(r interface{}) error {
if r == nil {
return nil
}
if err, ok := r.(error); ok {
return err
}
return fmt.Errorf("%v", r)
} | go | {
"resource": ""
} |
q172036 | FirstError | validation | func FirstError(errs ...error) error {
for _, err := range errs {
if err != nil {
return err
}
}
return nil
} | go | {
"resource": ""
} |
q172037 | LastError | validation | func LastError(errs ...error) error {
for i := len(errs) - 1; i >= 0; i-- {
err := errs[i]
if err != nil {
return err
}
}
return nil
} | go | {
"resource": ""
} |
q172038 | AsErrorList | validation | func AsErrorList(err error) ErrorList {
if list, ok := err.(ErrorList); ok {
return list
}
return ErrorList{err}
} | go | {
"resource": ""
} |
q172039 | Error | validation | func (list ErrorList) Error() string {
if len(list) == 0 {
return "Empty ErrorList"
}
var b strings.Builder
for _, err := range list {
fmt.Fprintln(&b, err)
}
return b.String()
} | go | {
"resource": ""
} |
q172040 | Last | validation | func (list ErrorList) Last() error {
if len(list) == 0 {
return nil
}
return list[len(list)-1]
} | go | {
"resource": ""
} |
q172041 | Collect | validation | func (list *ErrorList) Collect(args ...interface{}) {
for _, a := range args {
if err, _ := a.(error); err != nil {
*list = append(*list, err)
}
}
} | go | {
"resource": ""
} |
q172042 | HTTPCompressHandlerFunc | validation | func HTTPCompressHandlerFunc(handlerFunc http.HandlerFunc) http.HandlerFunc {
return func(response http.ResponseWriter, request *http.Request) {
NewHTTPCompressHandlerFromFunc(handlerFunc).ServeHTTP(response, request)
}
} | go | {
"resource": ""
} |
q172043 | HTTPPostJSON | validation | func HTTPPostJSON(url string, data interface{}) error {
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
response, err := http.Post(url, "application/json", bytes.NewBuffer(b))
if err == nil && (response.StatusCode < 200 || response.StatusCode > 299) {
err = errors.New(response.Status)... | go | {
"resource": ""
} |
q172044 | HTTPDelete | validation | func HTTPDelete(url string) (statusCode int, statusText string, err error) {
request, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return 0, "", err
}
response, err := http.DefaultClient.Do(request)
if err != nil {
return 0, "", err
}
return response.StatusCode, response.Status, nil
} | go | {
"resource": ""
} |
q172045 | HTTPUnmarshalRequestBodyJSON | validation | func HTTPUnmarshalRequestBodyJSON(request *http.Request, result interface{}) error {
defer request.Body.Close()
body, err := ioutil.ReadAll(request.Body)
if err != nil {
return err
}
return json.Unmarshal(body, result)
} | go | {
"resource": ""
} |
q172046 | GetWriter | validation | func (pool *DeflatePool) GetWriter(dst io.Writer) (writer *flate.Writer) {
if w := pool.pool.Get(); w != nil {
writer = w.(*flate.Writer)
writer.Reset(dst)
} else {
writer, _ = flate.NewWriter(dst, flate.BestCompression)
}
return writer
} | go | {
"resource": ""
} |
q172047 | ReturnWriter | validation | func (pool *DeflatePool) ReturnWriter(writer *flate.Writer) {
writer.Close()
pool.pool.Put(writer)
} | go | {
"resource": ""
} |
q172048 | GetWriter | validation | func (pool *GzipPool) GetWriter(dst io.Writer) (writer *gzip.Writer) {
if w := pool.pool.Get(); w != nil {
writer = w.(*gzip.Writer)
writer.Reset(dst)
} else {
writer, _ = gzip.NewWriterLevel(dst, gzip.BestCompression)
}
return writer
} | go | {
"resource": ""
} |
q172049 | ReturnWriter | validation | func (pool *GzipPool) ReturnWriter(writer *gzip.Writer) {
writer.Close()
pool.pool.Put(writer)
} | go | {
"resource": ""
} |
q172050 | FileGetLines | validation | func FileGetLines(filenameOrURL string, timeout ...time.Duration) (lines []string, err error) {
data, err := FileGetBytes(filenameOrURL, timeout...)
if err != nil {
return nil, err
}
lastR := -1
lastN := -1
for i, c := range data {
if c == '\r' {
l := string(data[lastN+1 : i])
lines = appe... | go | {
"resource": ""
} |
q172051 | FileGetLastLine | validation | func FileGetLastLine(filenameOrURL string, timeout ...time.Duration) (line string, err error) {
if strings.Index(filenameOrURL, "file://") == 0 {
return FileGetLastLine(filenameOrURL[len("file://"):])
}
var data []byte
if strings.Contains(filenameOrURL, "://") {
data, err = FileGetBytes(filenameOrURL,... | go | {
"resource": ""
} |
q172052 | FileSize | validation | func FileSize(filename string) int64 {
info, err := os.Stat(filename)
if err != nil {
return 0
}
return info.Size()
} | go | {
"resource": ""
} |
q172053 | BytesHead | validation | func BytesHead(data []byte, numLines int) (lines []string, rest []byte) {
if numLines <= 0 {
panic("numLines must be greater than zero")
}
lines = make([]string, 0, numLines)
begin := 0
for i := range data {
if data[i] == '\n' {
end := i
if i > 0 && data[i-1] == '\r' {
end--
}
lines... | go | {
"resource": ""
} |
q172054 | BytesMap | validation | func BytesMap(f func(byte) byte, data []byte) []byte {
size := len(data)
result := make([]byte, size, size)
for i := 0; i < size; i++ {
result[i] = f(data[i])
}
return result
} | go | {
"resource": ""
} |
q172055 | BytesFilter | validation | func BytesFilter(f func(byte) bool, data []byte) []byte {
result := make([]byte, 0, 0)
for _, element := range data {
if f(element) {
result = append(result, element)
}
}
return result
} | go | {
"resource": ""
} |
q172056 | ReflectSetStructFieldString | validation | func ReflectSetStructFieldString(structPtr interface{}, name, value string) error {
v := reflect.ValueOf(structPtr)
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
return fmt.Errorf("structPtr must be pointer to a struct, but is %T", structPtr)
}
v = v.Elem()
if f := v.FieldByName(name); f.IsV... | go | {
"resource": ""
} |
q172057 | ReadBinary | validation | func ReadBinary(r io.Reader, order binary.ByteOrder, data interface{}) (n int, err error) {
countingReader := CountingReader{Reader: r}
err = binary.Read(&countingReader, order, data)
return countingReader.BytesRead, err
} | go | {
"resource": ""
} |
q172058 | WriteFull | validation | func WriteFull(data []byte, writer io.Writer) (n int, err error) {
dataSize := len(data)
for n = 0; n < dataSize; {
m, err := writer.Write(data[n:])
n += m
if err != nil {
return n, err
}
}
return dataSize, nil
} | go | {
"resource": ""
} |
q172059 | ReadLine | validation | func ReadLine(reader io.Reader) (line string, err error) {
buffer := bytes.NewBuffer(make([]byte, 0, 4096))
p := make([]byte, 1)
for {
var n int
n, err = reader.Read(p)
if err != nil || p[0] == '\n' {
break
}
if n > 0 {
buffer.WriteByte(p[0])
}
}
data := buffer.Bytes()
if len(data) > 0 && data[l... | go | {
"resource": ""
} |
q172060 | WaitForStdin | validation | func WaitForStdin(println ...interface{}) byte {
if len(println) > 0 {
fmt.Println(println...)
}
buffer := make([]byte, 1)
os.Stdin.Read(buffer)
return buffer[0]
} | go | {
"resource": ""
} |
q172061 | GetenvDefault | validation | func GetenvDefault(key, defaultValue string) string {
ret := os.Getenv(key)
if ret == "" {
return defaultValue
}
return ret
} | go | {
"resource": ""
} |
q172062 | NetIP | validation | func NetIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, addr := range addrs {
ip := addr.String()
if ip != "127.0.0.1" {
return ip
}
}
return ""
} | go | {
"resource": ""
} |
q172063 | RealNetIP | validation | func RealNetIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err)
return ""
}
// get real local IP
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return... | go | {
"resource": ""
} |
q172064 | Load | validation | func Load(conf interface{}, configPaths ...string) error {
return loadWithFunc(conf, configPaths, nil, yaml.Unmarshal)
} | go | {
"resource": ""
} |
q172065 | LoadJSON | validation | func LoadJSON(conf interface{}, configPaths ...string) error {
return loadWithFunc(conf, configPaths, nil, json.Unmarshal)
} | go | {
"resource": ""
} |
q172066 | LoadTOML | validation | func LoadTOML(conf interface{}, configPaths ...string) error {
return loadWithFunc(conf, configPaths, nil, toml.Unmarshal)
} | go | {
"resource": ""
} |
q172067 | LoadBytes | validation | func LoadBytes(conf interface{}, src []byte) error {
return loadConfigBytes(conf, src, nil, yaml.Unmarshal)
} | go | {
"resource": ""
} |
q172068 | LoadJSONBytes | validation | func LoadJSONBytes(conf interface{}, src []byte) error {
return loadConfigBytes(conf, src, nil, json.Unmarshal)
} | go | {
"resource": ""
} |
q172069 | LoadTOMLBytes | validation | func LoadTOMLBytes(conf interface{}, src []byte) error {
return loadConfigBytes(conf, src, nil, toml.Unmarshal)
} | go | {
"resource": ""
} |
q172070 | LoadWithEnvJSON | validation | func LoadWithEnvJSON(conf interface{}, configPaths ...string) error {
return loadWithFunc(conf, configPaths, envReplacer, json.Unmarshal)
} | go | {
"resource": ""
} |
q172071 | LoadWithEnvTOML | validation | func LoadWithEnvTOML(conf interface{}, configPaths ...string) error {
return loadWithFunc(conf, configPaths, envReplacer, toml.Unmarshal)
} | go | {
"resource": ""
} |
q172072 | LoadWithEnvBytes | validation | func LoadWithEnvBytes(conf interface{}, src []byte) error {
return loadConfigBytes(conf, src, envReplacer, yaml.Unmarshal)
} | go | {
"resource": ""
} |
q172073 | LoadWithEnvJSONBytes | validation | func LoadWithEnvJSONBytes(conf interface{}, src []byte) error {
return loadConfigBytes(conf, src, envReplacer, json.Unmarshal)
} | go | {
"resource": ""
} |
q172074 | LoadWithEnvTOMLBytes | validation | func LoadWithEnvTOMLBytes(conf interface{}, src []byte) error {
return loadConfigBytes(conf, src, envReplacer, toml.Unmarshal)
} | go | {
"resource": ""
} |
q172075 | Crop | validation | func Crop(img image.Image, c Config) (image.Image, error) {
maxBounds := c.maxBounds(img.Bounds())
size := c.computeSize(maxBounds, image.Point{c.Width, c.Height})
cr := c.computedCropArea(img.Bounds(), size)
cr = img.Bounds().Intersect(cr)
if c.Options&Copy == Copy {
return cropWithCopy(img, cr)
}
if dImg, o... | go | {
"resource": ""
} |
q172076 | computeSize | validation | func (c Config) computeSize(bounds image.Rectangle, ratio image.Point) (p image.Point) {
if c.Options&Ratio == Ratio {
// Ratio option is on, so we take the biggest size available that fit the given ratio.
if float64(ratio.X)/float64(bounds.Dx()) > float64(ratio.Y)/float64(bounds.Dy()) {
p = image.Point{bounds.... | go | {
"resource": ""
} |
q172077 | computedCropArea | validation | func (c Config) computedCropArea(bounds image.Rectangle, size image.Point) (r image.Rectangle) {
min := bounds.Min
switch c.Mode {
case Centered:
rMin := c.centeredMin(bounds)
r = image.Rect(rMin.X-size.X/2, rMin.Y-size.Y/2, rMin.X-size.X/2+size.X, rMin.Y-size.Y/2+size.Y)
default: // TopLeft
rMin := image.Poi... | go | {
"resource": ""
} |
q172078 | NewThen | validation | func NewThen(command string, args ...string) Then {
return &gitCmd{command: command, args: args}
} | go | {
"resource": ""
} |
q172079 | NewLongThen | validation | func NewLongThen(command string, args ...string) Then {
return &gitCmd{command: command, args: args, background: true, haltChan: make(chan struct{})}
} | go | {
"resource": ""
} |
q172080 | Command | validation | func (g *gitCmd) Command() string {
return g.command + " " + strings.Join(g.args, " ")
} | go | {
"resource": ""
} |
q172081 | Exec | validation | func (g *gitCmd) Exec(dir string) error {
g.Lock()
g.dir = dir
g.Unlock()
if g.background {
return g.execBackground(dir)
}
return g.exec(dir)
} | go | {
"resource": ""
} |
q172082 | haltProcess | validation | func (g *gitCmd) haltProcess() {
g.RLock()
monitoring := g.monitoring
g.RUnlock()
if monitoring {
g.haltChan <- struct{}{}
}
} | go | {
"resource": ""
} |
q172083 | runCmd | validation | func runCmd(command string, args []string, dir string) error {
cmd := gos.Command(command, args...)
cmd.Stdout(os.Stderr)
cmd.Stderr(os.Stderr)
cmd.Dir(dir)
if err := cmd.Start(); err != nil {
return err
}
return cmd.Wait()
} | go | {
"resource": ""
} |
q172084 | runCmdOutput | validation | func runCmdOutput(command string, args []string, dir string) (string, error) {
cmd := gos.Command(command, args...)
cmd.Dir(dir)
var err error
if output, err := cmd.Output(); err == nil {
return string(bytes.TrimSpace(output)), nil
}
return "", err
} | go | {
"resource": ""
} |
q172085 | Init | validation | func Init() error {
// prevent concurrent call
initMutex.Lock()
defer initMutex.Unlock()
// if validation has been done before and binary located in
// PATH, return.
if gitBinary != "" {
return nil
}
// locate git binary in path
var err error
if gitBinary, err = gos.LookPath("git"); err != nil {
return ... | go | {
"resource": ""
} |
q172086 | writeScriptFile | validation | func writeScriptFile(content []byte) (file gitos.File, err error) {
if file, err = gos.TempFile("", "caddy"); err != nil {
return nil, err
}
if _, err = file.Write(content); err != nil {
return nil, err
}
if err = file.Chmod(os.FileMode(0755)); err != nil {
return nil, err
}
return file, file.Close()
} | go | {
"resource": ""
} |
q172087 | gitWrapperScript | validation | func gitWrapperScript() []byte {
scriptTemplate := `#!/usr/bin/env {shell}
# The MIT License (MIT)
# Copyright (c) 2013 Alvin Abad
if [ $# -eq 0 ]; then
echo "Git wrapper script that can specify an ssh-key file
Usage:
git.sh -i ssh-key-file git-command
"
exit 1
fi
# remove temporary file on exit
tra... | go | {
"resource": ""
} |
q172088 | bashScript | validation | func bashScript(gitSSHPath string, repo *Repo, params []string) []byte {
scriptTemplate := `#!/usr/bin/env {shell}
mkdir -p ~/.ssh;
touch ~/.ssh/known_hosts;
ssh-keyscan -t rsa,dsa {repo_host} 2>&1 | sort -u - ~/.ssh/known_hosts > ~/.ssh/tmp_hosts;
cat ~/.ssh/tmp_hosts | while read line
do
grep -q "$line" ~/.ssh/kn... | go | {
"resource": ""
} |
q172089 | handleToken | validation | func (g GitlabHook) handleToken(r *http.Request, body []byte, secret string) error {
token := r.Header.Get("X-Gitlab-Token")
if token != "" {
if secret == "" {
Logger().Print("Unable to verify request. Secret not set in caddyfile!\n")
} else {
if token != secret {
return errors.New("Unable to verify req... | go | {
"resource": ""
} |
q172090 | Handle | validation | func (g GenericHook) Handle(w http.ResponseWriter, r *http.Request, repo *Repo) (int, error) {
if r.Method != "POST" {
return http.StatusMethodNotAllowed, errors.New("the request had an invalid method")
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return http.StatusRequestTimeout, errors.New("could no... | go | {
"resource": ""
} |
q172091 | handleSignature | validation | func (g GithubHook) handleSignature(r *http.Request, body []byte, secret string) error {
signature := r.Header.Get("X-Hub-Signature")
if signature != "" {
if secret == "" {
Logger().Print("Unable to verify request signature. Secret not set in caddyfile!\n")
} else {
mac := hmac.New(sha1.New, []byte(secret))... | go | {
"resource": ""
} |
q172092 | setup | validation | func setup(c *caddy.Controller) error {
git, err := parse(c)
if err != nil {
return err
}
// repos configured with webhooks
var hookRepos []*Repo
// functions to execute at startup
var startupFuncs []func() error
// loop through all repos and and start monitoring
for i := range git {
repo := git.Repo(i)... | go | {
"resource": ""
} |
q172093 | parseURL | validation | func parseURL(repoURL string, private bool) (*url.URL, error) {
// scheme
urlParts := strings.Split(repoURL, "://")
switch {
case strings.HasPrefix(repoURL, "https://"):
case strings.HasPrefix(repoURL, "http://"):
case strings.HasPrefix(repoURL, "ssh://"):
case len(urlParts) > 1:
return nil, fmt.Errorf("Invali... | go | {
"resource": ""
} |
q172094 | Start | validation | func Start(repo *Repo) {
if repo.Interval <= 0 {
// ignore, don't setup periodic pull.
Logger().Println("interval too small, periodic pull not enabled.")
return
}
service := &repoService{
repo,
gos.NewTicker(repo.Interval),
make(chan struct{}),
}
go func(s *repoService) {
for {
select {
case <-... | go | {
"resource": ""
} |
q172095 | add | validation | func (s *services) add(r *repoService) {
s.Lock()
defer s.Unlock()
s.services = append(s.services, r)
} | go | {
"resource": ""
} |
q172096 | Repo | validation | func (g Git) Repo(i int) *Repo {
if i < len(g) {
return g[i]
}
return nil
} | go | {
"resource": ""
} |
q172097 | String | validation | func (r RepoURL) String() string {
u, err := url.Parse(string(r))
if err != nil {
return string(r)
}
if u.User != nil {
u.User = url.User(u.User.Username())
}
return u.String()
} | go | {
"resource": ""
} |
q172098 | Val | validation | func (r RepoURL) Val() string {
if strings.HasPrefix(string(r), "ssh://") {
return strings.TrimPrefix(string(r), "ssh://")
}
return string(r)
} | go | {
"resource": ""
} |
q172099 | Pull | validation | func (r *Repo) Pull() error {
r.Lock()
defer r.Unlock()
// prevent a pull if the last one was less than 5 seconds ago
if gos.TimeSince(r.lastPull) < 5*time.Second {
return nil
}
// keep last commit hash for comparison later
lastCommit := r.lastCommit
var err error
// Attempt to pull at most numRetries tim... | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.