repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
mholt/archiver
tar.go
hasTarHeader
func hasTarHeader(buf []byte) bool { if len(buf) < tarBlockSize { return false } b := buf[148:156] b = bytes.Trim(b, " \x00") // clean up all spaces and null bytes if len(b) == 0 { return false // unknown format } hdrSum, err := strconv.ParseUint(string(b), 8, 64) if err != nil { return false } // According to the go official archive/tar, Sun tar uses signed byte // values so this calcs both signed and unsigned var usum uint64 var sum int64 for i, c := range buf { if 148 <= i && i < 156 { c = ' ' // checksum field itself is counted as branks } usum += uint64(uint8(c)) sum += int64(int8(c)) } if hdrSum != usum && int64(hdrSum) != sum { return false // invalid checksum } return true }
go
func hasTarHeader(buf []byte) bool { if len(buf) < tarBlockSize { return false } b := buf[148:156] b = bytes.Trim(b, " \x00") // clean up all spaces and null bytes if len(b) == 0 { return false // unknown format } hdrSum, err := strconv.ParseUint(string(b), 8, 64) if err != nil { return false } // According to the go official archive/tar, Sun tar uses signed byte // values so this calcs both signed and unsigned var usum uint64 var sum int64 for i, c := range buf { if 148 <= i && i < 156 { c = ' ' // checksum field itself is counted as branks } usum += uint64(uint8(c)) sum += int64(int8(c)) } if hdrSum != usum && int64(hdrSum) != sum { return false // invalid checksum } return true }
[ "func", "hasTarHeader", "(", "buf", "[", "]", "byte", ")", "bool", "{", "if", "len", "(", "buf", ")", "<", "tarBlockSize", "{", "return", "false", "\n", "}", "\n\n", "b", ":=", "buf", "[", "148", ":", "156", "]", "\n", "b", "=", "bytes", ".", "Trim", "(", "b", ",", "\"", "\\x00", "\"", ")", "// clean up all spaces and null bytes", "\n", "if", "len", "(", "b", ")", "==", "0", "{", "return", "false", "// unknown format", "\n", "}", "\n", "hdrSum", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "string", "(", "b", ")", ",", "8", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "// According to the go official archive/tar, Sun tar uses signed byte", "// values so this calcs both signed and unsigned", "var", "usum", "uint64", "\n", "var", "sum", "int64", "\n", "for", "i", ",", "c", ":=", "range", "buf", "{", "if", "148", "<=", "i", "&&", "i", "<", "156", "{", "c", "=", "' '", "// checksum field itself is counted as branks", "\n", "}", "\n", "usum", "+=", "uint64", "(", "uint8", "(", "c", ")", ")", "\n", "sum", "+=", "int64", "(", "int8", "(", "c", ")", ")", "\n", "}", "\n\n", "if", "hdrSum", "!=", "usum", "&&", "int64", "(", "hdrSum", ")", "!=", "sum", "{", "return", "false", "// invalid checksum", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// hasTarHeader checks passed bytes has a valid tar header or not. buf must // contain at least 512 bytes and if not, it always returns false.
[ "hasTarHeader", "checks", "passed", "bytes", "has", "a", "valid", "tar", "header", "or", "not", ".", "buf", "must", "contain", "at", "least", "512", "bytes", "and", "if", "not", "it", "always", "returns", "false", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tar.go#L558-L590
train
mholt/archiver
tarlz4.go
Archive
func (tlz4 *TarLz4) Archive(sources []string, destination string) error { err := tlz4.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tlz4.wrapWriter() return tlz4.Tar.Archive(sources, destination) }
go
func (tlz4 *TarLz4) Archive(sources []string, destination string) error { err := tlz4.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tlz4.wrapWriter() return tlz4.Tar.Archive(sources, destination) }
[ "func", "(", "tlz4", "*", "TarLz4", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "tlz4", ".", "CheckExt", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "tlz4", ".", "wrapWriter", "(", ")", "\n", "return", "tlz4", ".", "Tar", ".", "Archive", "(", "sources", ",", "destination", ")", "\n", "}" ]
// Archive creates a compressed tar file at destination // containing the files listed in sources. The destination // must end with ".tar.lz4" or ".tlz4". File paths can be // those of regular files or directories; directories will // be recursively added.
[ "Archive", "creates", "a", "compressed", "tar", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "lz4", "or", ".", "tlz4", ".", "File", "paths", "can", "be", "those", "of", "regular", "files", "or", "directories", ";", "directories", "will", "be", "recursively", "added", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarlz4.go#L38-L45
train
mholt/archiver
tarlz4.go
Create
func (tlz4 *TarLz4) Create(out io.Writer) error { tlz4.wrapWriter() return tlz4.Tar.Create(out) }
go
func (tlz4 *TarLz4) Create(out io.Writer) error { tlz4.wrapWriter() return tlz4.Tar.Create(out) }
[ "func", "(", "tlz4", "*", "TarLz4", ")", "Create", "(", "out", "io", ".", "Writer", ")", "error", "{", "tlz4", ".", "wrapWriter", "(", ")", "\n", "return", "tlz4", ".", "Tar", ".", "Create", "(", "out", ")", "\n", "}" ]
// Create opens tlz4 for writing a compressed // tar archive to out.
[ "Create", "opens", "tlz4", "for", "writing", "a", "compressed", "tar", "archive", "to", "out", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarlz4.go#L63-L66
train
mholt/archiver
tarsz.go
Archive
func (tsz *TarSz) Archive(sources []string, destination string) error { err := tsz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tsz.wrapWriter() return tsz.Tar.Archive(sources, destination) }
go
func (tsz *TarSz) Archive(sources []string, destination string) error { err := tsz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tsz.wrapWriter() return tsz.Tar.Archive(sources, destination) }
[ "func", "(", "tsz", "*", "TarSz", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "tsz", ".", "CheckExt", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "tsz", ".", "wrapWriter", "(", ")", "\n", "return", "tsz", ".", "Tar", ".", "Archive", "(", "sources", ",", "destination", ")", "\n", "}" ]
// Archive creates a compressed tar file at destination // containing the files listed in sources. The destination // must end with ".tar.sz" or ".tsz". File paths can be // those of regular files or directories; directories will // be recursively added.
[ "Archive", "creates", "a", "compressed", "tar", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "sz", "or", ".", "tsz", ".", "File", "paths", "can", "be", "those", "of", "regular", "files", "or", "directories", ";", "directories", "will", "be", "recursively", "added", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarsz.go#L32-L39
train
mholt/archiver
tarsz.go
Create
func (tsz *TarSz) Create(out io.Writer) error { tsz.wrapWriter() return tsz.Tar.Create(out) }
go
func (tsz *TarSz) Create(out io.Writer) error { tsz.wrapWriter() return tsz.Tar.Create(out) }
[ "func", "(", "tsz", "*", "TarSz", ")", "Create", "(", "out", "io", ".", "Writer", ")", "error", "{", "tsz", ".", "wrapWriter", "(", ")", "\n", "return", "tsz", ".", "Tar", ".", "Create", "(", "out", ")", "\n", "}" ]
// Create opens tsz for writing a compressed // tar archive to out.
[ "Create", "opens", "tsz", "for", "writing", "a", "compressed", "tar", "archive", "to", "out", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarsz.go#L57-L60
train
mholt/archiver
targz.go
Archive
func (tgz *TarGz) Archive(sources []string, destination string) error { err := tgz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tgz.wrapWriter() return tgz.Tar.Archive(sources, destination) }
go
func (tgz *TarGz) Archive(sources []string, destination string) error { err := tgz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tgz.wrapWriter() return tgz.Tar.Archive(sources, destination) }
[ "func", "(", "tgz", "*", "TarGz", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "tgz", ".", "CheckExt", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "tgz", ".", "wrapWriter", "(", ")", "\n", "return", "tgz", ".", "Tar", ".", "Archive", "(", "sources", ",", "destination", ")", "\n", "}" ]
// Archive creates a compressed tar file at destination // containing the files listed in sources. The destination // must end with ".tar.gz" or ".tgz". File paths can be // those of regular files or directories; directories will // be recursively added.
[ "Archive", "creates", "a", "compressed", "tar", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "gz", "or", ".", "tgz", ".", "File", "paths", "can", "be", "those", "of", "regular", "files", "or", "directories", ";", "directories", "will", "be", "recursively", "added", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/targz.go#L34-L41
train
mholt/archiver
tarbz2.go
Archive
func (tbz2 *TarBz2) Archive(sources []string, destination string) error { err := tbz2.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tbz2.wrapWriter() return tbz2.Tar.Archive(sources, destination) }
go
func (tbz2 *TarBz2) Archive(sources []string, destination string) error { err := tbz2.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tbz2.wrapWriter() return tbz2.Tar.Archive(sources, destination) }
[ "func", "(", "tbz2", "*", "TarBz2", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "tbz2", ".", "CheckExt", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "tbz2", ".", "wrapWriter", "(", ")", "\n", "return", "tbz2", ".", "Tar", ".", "Archive", "(", "sources", ",", "destination", ")", "\n", "}" ]
// Archive creates a compressed tar file at destination // containing the files listed in sources. The destination // must end with ".tar.bz2" or ".tbz2". File paths can be // those of regular files or directories; directories will // be recursively added.
[ "Archive", "creates", "a", "compressed", "tar", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "bz2", "or", ".", "tbz2", ".", "File", "paths", "can", "be", "those", "of", "regular", "files", "or", "directories", ";", "directories", "will", "be", "recursively", "added", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarbz2.go#L34-L41
train
mholt/archiver
tarbz2.go
Create
func (tbz2 *TarBz2) Create(out io.Writer) error { tbz2.wrapWriter() return tbz2.Tar.Create(out) }
go
func (tbz2 *TarBz2) Create(out io.Writer) error { tbz2.wrapWriter() return tbz2.Tar.Create(out) }
[ "func", "(", "tbz2", "*", "TarBz2", ")", "Create", "(", "out", "io", ".", "Writer", ")", "error", "{", "tbz2", ".", "wrapWriter", "(", ")", "\n", "return", "tbz2", ".", "Tar", ".", "Create", "(", "out", ")", "\n", "}" ]
// Create opens tbz2 for writing a compressed // tar archive to out.
[ "Create", "opens", "tbz2", "for", "writing", "a", "compressed", "tar", "archive", "to", "out", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarbz2.go#L59-L62
train
mholt/archiver
zip.go
Unarchive
func (z *Zip) Unarchive(source, destination string) error { if !fileExists(destination) && z.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } file, err := os.Open(source) if err != nil { return fmt.Errorf("opening source file: %v", err) } defer file.Close() fileInfo, err := file.Stat() if err != nil { return fmt.Errorf("statting source file: %v", err) } err = z.Open(file, fileInfo.Size()) if err != nil { return fmt.Errorf("opening zip archive for reading: %v", err) } defer z.Close() // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if z.ImplicitTopLevelFolder { files := make([]string, len(z.zr.File)) for i := range z.zr.File { files[i] = z.zr.File[i].Name } if multipleTopLevels(files) { destination = filepath.Join(destination, folderNameFromFileName(source)) } } for { err := z.extractNext(destination) if err == io.EOF { break } if err != nil { if z.ContinueOnError { log.Printf("[ERROR] Reading file in zip archive: %v", err) continue } return fmt.Errorf("reading file in zip archive: %v", err) } } return nil }
go
func (z *Zip) Unarchive(source, destination string) error { if !fileExists(destination) && z.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } file, err := os.Open(source) if err != nil { return fmt.Errorf("opening source file: %v", err) } defer file.Close() fileInfo, err := file.Stat() if err != nil { return fmt.Errorf("statting source file: %v", err) } err = z.Open(file, fileInfo.Size()) if err != nil { return fmt.Errorf("opening zip archive for reading: %v", err) } defer z.Close() // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if z.ImplicitTopLevelFolder { files := make([]string, len(z.zr.File)) for i := range z.zr.File { files[i] = z.zr.File[i].Name } if multipleTopLevels(files) { destination = filepath.Join(destination, folderNameFromFileName(source)) } } for { err := z.extractNext(destination) if err == io.EOF { break } if err != nil { if z.ContinueOnError { log.Printf("[ERROR] Reading file in zip archive: %v", err) continue } return fmt.Errorf("reading file in zip archive: %v", err) } } return nil }
[ "func", "(", "z", "*", "Zip", ")", "Unarchive", "(", "source", ",", "destination", "string", ")", "error", "{", "if", "!", "fileExists", "(", "destination", ")", "&&", "z", ".", "MkdirAll", "{", "err", ":=", "mkdir", "(", "destination", ",", "0755", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n\n", "fileInfo", ",", "err", ":=", "file", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "z", ".", "Open", "(", "file", ",", "fileInfo", ".", "Size", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "z", ".", "Close", "(", ")", "\n\n", "// if the files in the archive do not all share a common", "// root, then make sure we extract to a single subfolder", "// rather than potentially littering the destination...", "if", "z", ".", "ImplicitTopLevelFolder", "{", "files", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "z", ".", "zr", ".", "File", ")", ")", "\n", "for", "i", ":=", "range", "z", ".", "zr", ".", "File", "{", "files", "[", "i", "]", "=", "z", ".", "zr", ".", "File", "[", "i", "]", ".", "Name", "\n", "}", "\n", "if", "multipleTopLevels", "(", "files", ")", "{", "destination", "=", "filepath", ".", "Join", "(", "destination", ",", "folderNameFromFileName", "(", "source", ")", ")", "\n", "}", "\n", "}", "\n\n", "for", "{", "err", ":=", "z", ".", "extractNext", "(", "destination", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "if", "z", ".", "ContinueOnError", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Unarchive unpacks the .zip file at source to destination. // Destination will be treated as a folder name.
[ "Unarchive", "unpacks", "the", ".", "zip", "file", "at", "source", "to", "destination", ".", "Destination", "will", "be", "treated", "as", "a", "folder", "name", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L124-L177
train
mholt/archiver
zip.go
Create
func (z *Zip) Create(out io.Writer) error { if z.zw != nil { return fmt.Errorf("zip archive is already created for writing") } z.zw = zip.NewWriter(out) if z.CompressionLevel != flate.DefaultCompression { z.zw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { return flate.NewWriter(out, z.CompressionLevel) }) } return nil }
go
func (z *Zip) Create(out io.Writer) error { if z.zw != nil { return fmt.Errorf("zip archive is already created for writing") } z.zw = zip.NewWriter(out) if z.CompressionLevel != flate.DefaultCompression { z.zw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { return flate.NewWriter(out, z.CompressionLevel) }) } return nil }
[ "func", "(", "z", "*", "Zip", ")", "Create", "(", "out", "io", ".", "Writer", ")", "error", "{", "if", "z", ".", "zw", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "z", ".", "zw", "=", "zip", ".", "NewWriter", "(", "out", ")", "\n", "if", "z", ".", "CompressionLevel", "!=", "flate", ".", "DefaultCompression", "{", "z", ".", "zw", ".", "RegisterCompressor", "(", "zip", ".", "Deflate", ",", "func", "(", "out", "io", ".", "Writer", ")", "(", "io", ".", "WriteCloser", ",", "error", ")", "{", "return", "flate", ".", "NewWriter", "(", "out", ",", "z", ".", "CompressionLevel", ")", "\n", "}", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Create opens z for writing a ZIP archive to out.
[ "Create", "opens", "z", "for", "writing", "a", "ZIP", "archive", "to", "out", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L285-L296
train
mholt/archiver
zip.go
Write
func (z *Zip) Write(f File) error { if z.zw == nil { return fmt.Errorf("zip archive was not created for writing first") } if f.FileInfo == nil { return fmt.Errorf("no file info") } if f.FileInfo.Name() == "" { return fmt.Errorf("missing file name") } header, err := zip.FileInfoHeader(f) if err != nil { return fmt.Errorf("%s: getting header: %v", f.Name(), err) } if f.IsDir() { header.Name += "/" // required - strangely no mention of this in zip spec? but is in godoc... header.Method = zip.Store } else { ext := strings.ToLower(path.Ext(header.Name)) if _, ok := compressedFormats[ext]; ok && z.SelectiveCompression { header.Method = zip.Store } else { header.Method = zip.Deflate } } writer, err := z.zw.CreateHeader(header) if err != nil { return fmt.Errorf("%s: making header: %v", f.Name(), err) } return z.writeFile(f, writer) }
go
func (z *Zip) Write(f File) error { if z.zw == nil { return fmt.Errorf("zip archive was not created for writing first") } if f.FileInfo == nil { return fmt.Errorf("no file info") } if f.FileInfo.Name() == "" { return fmt.Errorf("missing file name") } header, err := zip.FileInfoHeader(f) if err != nil { return fmt.Errorf("%s: getting header: %v", f.Name(), err) } if f.IsDir() { header.Name += "/" // required - strangely no mention of this in zip spec? but is in godoc... header.Method = zip.Store } else { ext := strings.ToLower(path.Ext(header.Name)) if _, ok := compressedFormats[ext]; ok && z.SelectiveCompression { header.Method = zip.Store } else { header.Method = zip.Deflate } } writer, err := z.zw.CreateHeader(header) if err != nil { return fmt.Errorf("%s: making header: %v", f.Name(), err) } return z.writeFile(f, writer) }
[ "func", "(", "z", "*", "Zip", ")", "Write", "(", "f", "File", ")", "error", "{", "if", "z", ".", "zw", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "f", ".", "FileInfo", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "f", ".", "FileInfo", ".", "Name", "(", ")", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "header", ",", "err", ":=", "zip", ".", "FileInfoHeader", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "if", "f", ".", "IsDir", "(", ")", "{", "header", ".", "Name", "+=", "\"", "\"", "// required - strangely no mention of this in zip spec? but is in godoc...", "\n", "header", ".", "Method", "=", "zip", ".", "Store", "\n", "}", "else", "{", "ext", ":=", "strings", ".", "ToLower", "(", "path", ".", "Ext", "(", "header", ".", "Name", ")", ")", "\n", "if", "_", ",", "ok", ":=", "compressedFormats", "[", "ext", "]", ";", "ok", "&&", "z", ".", "SelectiveCompression", "{", "header", ".", "Method", "=", "zip", ".", "Store", "\n", "}", "else", "{", "header", ".", "Method", "=", "zip", ".", "Deflate", "\n", "}", "\n", "}", "\n\n", "writer", ",", "err", ":=", "z", ".", "zw", ".", "CreateHeader", "(", "header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "z", ".", "writeFile", "(", "f", ",", "writer", ")", "\n", "}" ]
// Write writes f to z, which must have been opened for writing first.
[ "Write", "writes", "f", "to", "z", "which", "must", "have", "been", "opened", "for", "writing", "first", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L299-L333
train
mholt/archiver
zip.go
Open
func (z *Zip) Open(in io.Reader, size int64) error { inRdrAt, ok := in.(io.ReaderAt) if !ok { return fmt.Errorf("reader must be io.ReaderAt") } if z.zr != nil { return fmt.Errorf("zip archive is already open for reading") } var err error z.zr, err = zip.NewReader(inRdrAt, size) if err != nil { return fmt.Errorf("creating reader: %v", err) } z.ridx = 0 return nil }
go
func (z *Zip) Open(in io.Reader, size int64) error { inRdrAt, ok := in.(io.ReaderAt) if !ok { return fmt.Errorf("reader must be io.ReaderAt") } if z.zr != nil { return fmt.Errorf("zip archive is already open for reading") } var err error z.zr, err = zip.NewReader(inRdrAt, size) if err != nil { return fmt.Errorf("creating reader: %v", err) } z.ridx = 0 return nil }
[ "func", "(", "z", "*", "Zip", ")", "Open", "(", "in", "io", ".", "Reader", ",", "size", "int64", ")", "error", "{", "inRdrAt", ",", "ok", ":=", "in", ".", "(", "io", ".", "ReaderAt", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "z", ".", "zr", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "err", "error", "\n", "z", ".", "zr", ",", "err", "=", "zip", ".", "NewReader", "(", "inRdrAt", ",", "size", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "z", ".", "ridx", "=", "0", "\n", "return", "nil", "\n", "}" ]
// Open opens z for reading an archive from in, // which is expected to have the given size and // which must be an io.ReaderAt.
[ "Open", "opens", "z", "for", "reading", "an", "archive", "from", "in", "which", "is", "expected", "to", "have", "the", "given", "size", "and", "which", "must", "be", "an", "io", ".", "ReaderAt", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L366-L381
train
mholt/archiver
zip.go
Read
func (z *Zip) Read() (File, error) { if z.zr == nil { return File{}, fmt.Errorf("zip archive is not open") } if z.ridx >= len(z.zr.File) { return File{}, io.EOF } // access the file and increment counter so that // if there is an error processing this file, the // caller can still iterate to the next file zf := z.zr.File[z.ridx] z.ridx++ file := File{ FileInfo: zf.FileInfo(), Header: zf.FileHeader, } rc, err := zf.Open() if err != nil { return file, fmt.Errorf("%s: open compressed file: %v", zf.Name, err) } file.ReadCloser = rc return file, nil }
go
func (z *Zip) Read() (File, error) { if z.zr == nil { return File{}, fmt.Errorf("zip archive is not open") } if z.ridx >= len(z.zr.File) { return File{}, io.EOF } // access the file and increment counter so that // if there is an error processing this file, the // caller can still iterate to the next file zf := z.zr.File[z.ridx] z.ridx++ file := File{ FileInfo: zf.FileInfo(), Header: zf.FileHeader, } rc, err := zf.Open() if err != nil { return file, fmt.Errorf("%s: open compressed file: %v", zf.Name, err) } file.ReadCloser = rc return file, nil }
[ "func", "(", "z", "*", "Zip", ")", "Read", "(", ")", "(", "File", ",", "error", ")", "{", "if", "z", ".", "zr", "==", "nil", "{", "return", "File", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "z", ".", "ridx", ">=", "len", "(", "z", ".", "zr", ".", "File", ")", "{", "return", "File", "{", "}", ",", "io", ".", "EOF", "\n", "}", "\n\n", "// access the file and increment counter so that", "// if there is an error processing this file, the", "// caller can still iterate to the next file", "zf", ":=", "z", ".", "zr", ".", "File", "[", "z", ".", "ridx", "]", "\n", "z", ".", "ridx", "++", "\n\n", "file", ":=", "File", "{", "FileInfo", ":", "zf", ".", "FileInfo", "(", ")", ",", "Header", ":", "zf", ".", "FileHeader", ",", "}", "\n\n", "rc", ",", "err", ":=", "zf", ".", "Open", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "file", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "zf", ".", "Name", ",", "err", ")", "\n", "}", "\n", "file", ".", "ReadCloser", "=", "rc", "\n\n", "return", "file", ",", "nil", "\n", "}" ]
// Read reads the next file from z, which must have // already been opened for reading. If there are no // more files, the error is io.EOF. The File must // be closed when finished reading from it.
[ "Read", "reads", "the", "next", "file", "from", "z", "which", "must", "have", "already", "been", "opened", "for", "reading", ".", "If", "there", "are", "no", "more", "files", "the", "error", "is", "io", ".", "EOF", ".", "The", "File", "must", "be", "closed", "when", "finished", "reading", "from", "it", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L387-L413
train
mholt/archiver
zip.go
Extract
func (z *Zip) Extract(source, target, destination string) error { // target refers to a path inside the archive, which should be clean also target = path.Clean(target) // if the target ends up being a directory, then // we will continue walking and extracting files // until we are no longer within that directory var targetDirPath string return z.Walk(source, func(f File) error { zfh, ok := f.Header.(zip.FileHeader) if !ok { return fmt.Errorf("expected header to be zip.FileHeader but was %T", f.Header) } // importantly, cleaning the path strips tailing slash, // which must be appended to folders within the archive name := path.Clean(zfh.Name) if f.IsDir() && target == name { targetDirPath = path.Dir(name) } if within(target, zfh.Name) { // either this is the exact file we want, or is // in the directory we want to extract // build the filename we will extract to end, err := filepath.Rel(targetDirPath, zfh.Name) if err != nil { return fmt.Errorf("relativizing paths: %v", err) } joined := filepath.Join(destination, end) err = z.extractFile(f, joined) if err != nil { return fmt.Errorf("extracting file %s: %v", zfh.Name, err) } // if our target was not a directory, stop walk if targetDirPath == "" { return ErrStopWalk } } else if targetDirPath != "" { // finished walking the entire directory return ErrStopWalk } return nil }) }
go
func (z *Zip) Extract(source, target, destination string) error { // target refers to a path inside the archive, which should be clean also target = path.Clean(target) // if the target ends up being a directory, then // we will continue walking and extracting files // until we are no longer within that directory var targetDirPath string return z.Walk(source, func(f File) error { zfh, ok := f.Header.(zip.FileHeader) if !ok { return fmt.Errorf("expected header to be zip.FileHeader but was %T", f.Header) } // importantly, cleaning the path strips tailing slash, // which must be appended to folders within the archive name := path.Clean(zfh.Name) if f.IsDir() && target == name { targetDirPath = path.Dir(name) } if within(target, zfh.Name) { // either this is the exact file we want, or is // in the directory we want to extract // build the filename we will extract to end, err := filepath.Rel(targetDirPath, zfh.Name) if err != nil { return fmt.Errorf("relativizing paths: %v", err) } joined := filepath.Join(destination, end) err = z.extractFile(f, joined) if err != nil { return fmt.Errorf("extracting file %s: %v", zfh.Name, err) } // if our target was not a directory, stop walk if targetDirPath == "" { return ErrStopWalk } } else if targetDirPath != "" { // finished walking the entire directory return ErrStopWalk } return nil }) }
[ "func", "(", "z", "*", "Zip", ")", "Extract", "(", "source", ",", "target", ",", "destination", "string", ")", "error", "{", "// target refers to a path inside the archive, which should be clean also", "target", "=", "path", ".", "Clean", "(", "target", ")", "\n\n", "// if the target ends up being a directory, then", "// we will continue walking and extracting files", "// until we are no longer within that directory", "var", "targetDirPath", "string", "\n\n", "return", "z", ".", "Walk", "(", "source", ",", "func", "(", "f", "File", ")", "error", "{", "zfh", ",", "ok", ":=", "f", ".", "Header", ".", "(", "zip", ".", "FileHeader", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Header", ")", "\n", "}", "\n\n", "// importantly, cleaning the path strips tailing slash,", "// which must be appended to folders within the archive", "name", ":=", "path", ".", "Clean", "(", "zfh", ".", "Name", ")", "\n", "if", "f", ".", "IsDir", "(", ")", "&&", "target", "==", "name", "{", "targetDirPath", "=", "path", ".", "Dir", "(", "name", ")", "\n", "}", "\n\n", "if", "within", "(", "target", ",", "zfh", ".", "Name", ")", "{", "// either this is the exact file we want, or is", "// in the directory we want to extract", "// build the filename we will extract to", "end", ",", "err", ":=", "filepath", ".", "Rel", "(", "targetDirPath", ",", "zfh", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "joined", ":=", "filepath", ".", "Join", "(", "destination", ",", "end", ")", "\n\n", "err", "=", "z", ".", "extractFile", "(", "f", ",", "joined", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "zfh", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "// if our target was not a directory, stop walk", "if", "targetDirPath", "==", "\"", "\"", "{", "return", "ErrStopWalk", "\n", "}", "\n", "}", "else", "if", "targetDirPath", "!=", "\"", "\"", "{", "// finished walking the entire directory", "return", "ErrStopWalk", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// Extract extracts a single file from the zip archive. // If the target is a directory, the entire folder will // be extracted into destination.
[ "Extract", "extracts", "a", "single", "file", "from", "the", "zip", "archive", ".", "If", "the", "target", "is", "a", "directory", "the", "entire", "folder", "will", "be", "extracted", "into", "destination", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L471-L520
train
mholt/archiver
zip.go
NewZip
func NewZip() *Zip { return &Zip{ CompressionLevel: flate.DefaultCompression, MkdirAll: true, SelectiveCompression: true, } }
go
func NewZip() *Zip { return &Zip{ CompressionLevel: flate.DefaultCompression, MkdirAll: true, SelectiveCompression: true, } }
[ "func", "NewZip", "(", ")", "*", "Zip", "{", "return", "&", "Zip", "{", "CompressionLevel", ":", "flate", ".", "DefaultCompression", ",", "MkdirAll", ":", "true", ",", "SelectiveCompression", ":", "true", ",", "}", "\n", "}" ]
// NewZip returns a new, default instance ready to be customized and used.
[ "NewZip", "returns", "a", "new", "default", "instance", "ready", "to", "be", "customized", "and", "used", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L545-L551
train
mholt/archiver
archiver.go
Archive
func Archive(sources []string, destination string) error { aIface, err := ByExtension(destination) if err != nil { return err } a, ok := aIface.(Archiver) if !ok { return fmt.Errorf("format specified by destination filename is not an archive format: %s (%T)", destination, aIface) } return a.Archive(sources, destination) }
go
func Archive(sources []string, destination string) error { aIface, err := ByExtension(destination) if err != nil { return err } a, ok := aIface.(Archiver) if !ok { return fmt.Errorf("format specified by destination filename is not an archive format: %s (%T)", destination, aIface) } return a.Archive(sources, destination) }
[ "func", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "aIface", ",", "err", ":=", "ByExtension", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "a", ",", "ok", ":=", "aIface", ".", "(", "Archiver", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "destination", ",", "aIface", ")", "\n", "}", "\n", "return", "a", ".", "Archive", "(", "sources", ",", "destination", ")", "\n", "}" ]
// Archive creates an archive of the source files to a new file at destination. // The archive format is chosen implicitly by file extension.
[ "Archive", "creates", "an", "archive", "of", "the", "source", "files", "to", "a", "new", "file", "at", "destination", ".", "The", "archive", "format", "is", "chosen", "implicitly", "by", "file", "extension", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L186-L196
train
mholt/archiver
archiver.go
Unarchive
func Unarchive(source, destination string) error { uaIface, err := ByExtension(source) if err != nil { return err } u, ok := uaIface.(Unarchiver) if !ok { return fmt.Errorf("format specified by source filename is not an archive format: %s (%T)", source, uaIface) } return u.Unarchive(source, destination) }
go
func Unarchive(source, destination string) error { uaIface, err := ByExtension(source) if err != nil { return err } u, ok := uaIface.(Unarchiver) if !ok { return fmt.Errorf("format specified by source filename is not an archive format: %s (%T)", source, uaIface) } return u.Unarchive(source, destination) }
[ "func", "Unarchive", "(", "source", ",", "destination", "string", ")", "error", "{", "uaIface", ",", "err", ":=", "ByExtension", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "u", ",", "ok", ":=", "uaIface", ".", "(", "Unarchiver", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "source", ",", "uaIface", ")", "\n", "}", "\n", "return", "u", ".", "Unarchive", "(", "source", ",", "destination", ")", "\n", "}" ]
// Unarchive unarchives the given archive file into the destination folder. // The archive format is selected implicitly.
[ "Unarchive", "unarchives", "the", "given", "archive", "file", "into", "the", "destination", "folder", ".", "The", "archive", "format", "is", "selected", "implicitly", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L200-L210
train
mholt/archiver
archiver.go
Walk
func Walk(archive string, walkFn WalkFunc) error { wIface, err := ByExtension(archive) if err != nil { return err } w, ok := wIface.(Walker) if !ok { return fmt.Errorf("format specified by archive filename is not a walker format: %s (%T)", archive, wIface) } return w.Walk(archive, walkFn) }
go
func Walk(archive string, walkFn WalkFunc) error { wIface, err := ByExtension(archive) if err != nil { return err } w, ok := wIface.(Walker) if !ok { return fmt.Errorf("format specified by archive filename is not a walker format: %s (%T)", archive, wIface) } return w.Walk(archive, walkFn) }
[ "func", "Walk", "(", "archive", "string", ",", "walkFn", "WalkFunc", ")", "error", "{", "wIface", ",", "err", ":=", "ByExtension", "(", "archive", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "w", ",", "ok", ":=", "wIface", ".", "(", "Walker", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "archive", ",", "wIface", ")", "\n", "}", "\n", "return", "w", ".", "Walk", "(", "archive", ",", "walkFn", ")", "\n", "}" ]
// Walk calls walkFn for each file within the given archive file. // The archive format is chosen implicitly.
[ "Walk", "calls", "walkFn", "for", "each", "file", "within", "the", "given", "archive", "file", ".", "The", "archive", "format", "is", "chosen", "implicitly", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L214-L224
train
mholt/archiver
archiver.go
Extract
func Extract(source, target, destination string) error { eIface, err := ByExtension(source) if err != nil { return err } e, ok := eIface.(Extractor) if !ok { return fmt.Errorf("format specified by source filename is not an extractor format: %s (%T)", source, eIface) } return e.Extract(source, target, destination) }
go
func Extract(source, target, destination string) error { eIface, err := ByExtension(source) if err != nil { return err } e, ok := eIface.(Extractor) if !ok { return fmt.Errorf("format specified by source filename is not an extractor format: %s (%T)", source, eIface) } return e.Extract(source, target, destination) }
[ "func", "Extract", "(", "source", ",", "target", ",", "destination", "string", ")", "error", "{", "eIface", ",", "err", ":=", "ByExtension", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "e", ",", "ok", ":=", "eIface", ".", "(", "Extractor", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "source", ",", "eIface", ")", "\n", "}", "\n", "return", "e", ".", "Extract", "(", "source", ",", "target", ",", "destination", ")", "\n", "}" ]
// Extract extracts a single file from the given source archive. If the target // is a directory, the entire folder will be extracted into destination. The // archive format is chosen implicitly.
[ "Extract", "extracts", "a", "single", "file", "from", "the", "given", "source", "archive", ".", "If", "the", "target", "is", "a", "directory", "the", "entire", "folder", "will", "be", "extracted", "into", "destination", ".", "The", "archive", "format", "is", "chosen", "implicitly", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L229-L239
train
mholt/archiver
archiver.go
CompressFile
func CompressFile(source, destination string) error { cIface, err := ByExtension(destination) if err != nil { return err } c, ok := cIface.(Compressor) if !ok { return fmt.Errorf("format specified by destination filename is not a recognized compression algorithm: %s", destination) } return FileCompressor{Compressor: c}.CompressFile(source, destination) }
go
func CompressFile(source, destination string) error { cIface, err := ByExtension(destination) if err != nil { return err } c, ok := cIface.(Compressor) if !ok { return fmt.Errorf("format specified by destination filename is not a recognized compression algorithm: %s", destination) } return FileCompressor{Compressor: c}.CompressFile(source, destination) }
[ "func", "CompressFile", "(", "source", ",", "destination", "string", ")", "error", "{", "cIface", ",", "err", ":=", "ByExtension", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ",", "ok", ":=", "cIface", ".", "(", "Compressor", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "destination", ")", "\n", "}", "\n", "return", "FileCompressor", "{", "Compressor", ":", "c", "}", ".", "CompressFile", "(", "source", ",", "destination", ")", "\n", "}" ]
// CompressFile is a convenience function to simply compress a file. // The compression algorithm is selected implicitly based on the // destination's extension.
[ "CompressFile", "is", "a", "convenience", "function", "to", "simply", "compress", "a", "file", ".", "The", "compression", "algorithm", "is", "selected", "implicitly", "based", "on", "the", "destination", "s", "extension", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L244-L254
train
mholt/archiver
archiver.go
DecompressFile
func DecompressFile(source, destination string) error { cIface, err := ByExtension(source) if err != nil { return err } c, ok := cIface.(Decompressor) if !ok { return fmt.Errorf("format specified by source filename is not a recognized compression algorithm: %s", source) } return FileCompressor{Decompressor: c}.DecompressFile(source, destination) }
go
func DecompressFile(source, destination string) error { cIface, err := ByExtension(source) if err != nil { return err } c, ok := cIface.(Decompressor) if !ok { return fmt.Errorf("format specified by source filename is not a recognized compression algorithm: %s", source) } return FileCompressor{Decompressor: c}.DecompressFile(source, destination) }
[ "func", "DecompressFile", "(", "source", ",", "destination", "string", ")", "error", "{", "cIface", ",", "err", ":=", "ByExtension", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ",", "ok", ":=", "cIface", ".", "(", "Decompressor", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "source", ")", "\n", "}", "\n", "return", "FileCompressor", "{", "Decompressor", ":", "c", "}", ".", "DecompressFile", "(", "source", ",", "destination", ")", "\n", "}" ]
// DecompressFile is a convenience function to simply compress a file. // The compression algorithm is selected implicitly based on the // source's extension.
[ "DecompressFile", "is", "a", "convenience", "function", "to", "simply", "compress", "a", "file", ".", "The", "compression", "algorithm", "is", "selected", "implicitly", "based", "on", "the", "source", "s", "extension", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L259-L269
train
mholt/archiver
archiver.go
within
func within(parent, sub string) bool { rel, err := filepath.Rel(parent, sub) if err != nil { return false } return !strings.Contains(rel, "..") }
go
func within(parent, sub string) bool { rel, err := filepath.Rel(parent, sub) if err != nil { return false } return !strings.Contains(rel, "..") }
[ "func", "within", "(", "parent", ",", "sub", "string", ")", "bool", "{", "rel", ",", "err", ":=", "filepath", ".", "Rel", "(", "parent", ",", "sub", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "!", "strings", ".", "Contains", "(", "rel", ",", "\"", "\"", ")", "\n", "}" ]
// within returns true if sub is within or equal to parent.
[ "within", "returns", "true", "if", "sub", "is", "within", "or", "equal", "to", "parent", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L355-L361
train
mholt/archiver
archiver.go
multipleTopLevels
func multipleTopLevels(paths []string) bool { if len(paths) < 2 { return false } var lastTop string for _, p := range paths { p = strings.TrimPrefix(strings.Replace(p, `\`, "/", -1), "/") for { next := path.Dir(p) if next == "." { break } p = next } if lastTop == "" { lastTop = p } if p != lastTop { return true } } return false }
go
func multipleTopLevels(paths []string) bool { if len(paths) < 2 { return false } var lastTop string for _, p := range paths { p = strings.TrimPrefix(strings.Replace(p, `\`, "/", -1), "/") for { next := path.Dir(p) if next == "." { break } p = next } if lastTop == "" { lastTop = p } if p != lastTop { return true } } return false }
[ "func", "multipleTopLevels", "(", "paths", "[", "]", "string", ")", "bool", "{", "if", "len", "(", "paths", ")", "<", "2", "{", "return", "false", "\n", "}", "\n", "var", "lastTop", "string", "\n", "for", "_", ",", "p", ":=", "range", "paths", "{", "p", "=", "strings", ".", "TrimPrefix", "(", "strings", ".", "Replace", "(", "p", ",", "`\\`", ",", "\"", "\"", ",", "-", "1", ")", ",", "\"", "\"", ")", "\n", "for", "{", "next", ":=", "path", ".", "Dir", "(", "p", ")", "\n", "if", "next", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "p", "=", "next", "\n", "}", "\n", "if", "lastTop", "==", "\"", "\"", "{", "lastTop", "=", "p", "\n", "}", "\n", "if", "p", "!=", "lastTop", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// multipleTopLevels returns true if the paths do not // share a common top-level folder.
[ "multipleTopLevels", "returns", "true", "if", "the", "paths", "do", "not", "share", "a", "common", "top", "-", "level", "folder", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L365-L387
train
mholt/archiver
archiver.go
folderNameFromFileName
func folderNameFromFileName(filename string) string { base := filepath.Base(filename) firstDot := strings.Index(base, ".") if firstDot > -1 { return base[:firstDot] } return base }
go
func folderNameFromFileName(filename string) string { base := filepath.Base(filename) firstDot := strings.Index(base, ".") if firstDot > -1 { return base[:firstDot] } return base }
[ "func", "folderNameFromFileName", "(", "filename", "string", ")", "string", "{", "base", ":=", "filepath", ".", "Base", "(", "filename", ")", "\n", "firstDot", ":=", "strings", ".", "Index", "(", "base", ",", "\"", "\"", ")", "\n", "if", "firstDot", ">", "-", "1", "{", "return", "base", "[", ":", "firstDot", "]", "\n", "}", "\n", "return", "base", "\n", "}" ]
// folderNameFromFileName returns a name for a folder // that is suitable based on the filename, which will // be stripped of its extensions.
[ "folderNameFromFileName", "returns", "a", "name", "for", "a", "folder", "that", "is", "suitable", "based", "on", "the", "filename", "which", "will", "be", "stripped", "of", "its", "extensions", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L392-L399
train
mholt/archiver
archiver.go
makeNameInArchive
func makeNameInArchive(sourceInfo os.FileInfo, source, baseDir, fpath string) (string, error) { name := filepath.Base(fpath) // start with the file or dir name if sourceInfo.IsDir() { // preserve internal directory structure; that's the path components // between the source directory's leaf and this file's leaf dir, err := filepath.Rel(filepath.Dir(source), filepath.Dir(fpath)) if err != nil { return "", err } // prepend the internal directory structure to the leaf name, // and convert path separators to forward slashes as per spec name = path.Join(filepath.ToSlash(dir), name) } return path.Join(baseDir, name), nil // prepend the base directory }
go
func makeNameInArchive(sourceInfo os.FileInfo, source, baseDir, fpath string) (string, error) { name := filepath.Base(fpath) // start with the file or dir name if sourceInfo.IsDir() { // preserve internal directory structure; that's the path components // between the source directory's leaf and this file's leaf dir, err := filepath.Rel(filepath.Dir(source), filepath.Dir(fpath)) if err != nil { return "", err } // prepend the internal directory structure to the leaf name, // and convert path separators to forward slashes as per spec name = path.Join(filepath.ToSlash(dir), name) } return path.Join(baseDir, name), nil // prepend the base directory }
[ "func", "makeNameInArchive", "(", "sourceInfo", "os", ".", "FileInfo", ",", "source", ",", "baseDir", ",", "fpath", "string", ")", "(", "string", ",", "error", ")", "{", "name", ":=", "filepath", ".", "Base", "(", "fpath", ")", "// start with the file or dir name", "\n", "if", "sourceInfo", ".", "IsDir", "(", ")", "{", "// preserve internal directory structure; that's the path components", "// between the source directory's leaf and this file's leaf", "dir", ",", "err", ":=", "filepath", ".", "Rel", "(", "filepath", ".", "Dir", "(", "source", ")", ",", "filepath", ".", "Dir", "(", "fpath", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "// prepend the internal directory structure to the leaf name,", "// and convert path separators to forward slashes as per spec", "name", "=", "path", ".", "Join", "(", "filepath", ".", "ToSlash", "(", "dir", ")", ",", "name", ")", "\n", "}", "\n", "return", "path", ".", "Join", "(", "baseDir", ",", "name", ")", ",", "nil", "// prepend the base directory", "\n", "}" ]
// makeNameInArchive returns the filename for the file given by fpath to be used within // the archive. sourceInfo is the FileInfo obtained by calling os.Stat on source, and baseDir // is an optional base directory that becomes the root of the archive. fpath should be the // unaltered file path of the file given to a filepath.WalkFunc.
[ "makeNameInArchive", "returns", "the", "filename", "for", "the", "file", "given", "by", "fpath", "to", "be", "used", "within", "the", "archive", ".", "sourceInfo", "is", "the", "FileInfo", "obtained", "by", "calling", "os", ".", "Stat", "on", "source", "and", "baseDir", "is", "an", "optional", "base", "directory", "that", "becomes", "the", "root", "of", "the", "archive", ".", "fpath", "should", "be", "the", "unaltered", "file", "path", "of", "the", "file", "given", "to", "a", "filepath", ".", "WalkFunc", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L405-L419
train
mholt/archiver
archiver.go
NameInArchive
func NameInArchive(sourceInfo os.FileInfo, source, fpath string) (string, error) { return makeNameInArchive(sourceInfo, source, "", fpath) }
go
func NameInArchive(sourceInfo os.FileInfo, source, fpath string) (string, error) { return makeNameInArchive(sourceInfo, source, "", fpath) }
[ "func", "NameInArchive", "(", "sourceInfo", "os", ".", "FileInfo", ",", "source", ",", "fpath", "string", ")", "(", "string", ",", "error", ")", "{", "return", "makeNameInArchive", "(", "sourceInfo", ",", "source", ",", "\"", "\"", ",", "fpath", ")", "\n", "}" ]
// NameInArchive returns a name for the file at fpath suitable for // the inside of an archive. The source and its associated sourceInfo // is the path where walking a directory started, and if no directory // was walked, source may == fpath. The returned name is essentially // the components of the path between source and fpath, preserving // the internal directory structure.
[ "NameInArchive", "returns", "a", "name", "for", "the", "file", "at", "fpath", "suitable", "for", "the", "inside", "of", "an", "archive", ".", "The", "source", "and", "its", "associated", "sourceInfo", "is", "the", "path", "where", "walking", "a", "directory", "started", "and", "if", "no", "directory", "was", "walked", "source", "may", "==", "fpath", ".", "The", "returned", "name", "is", "essentially", "the", "components", "of", "the", "path", "between", "source", "and", "fpath", "preserving", "the", "internal", "directory", "structure", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L427-L429
train
mholt/archiver
archiver.go
ByExtension
func ByExtension(filename string) (interface{}, error) { var ec interface{} for _, c := range extCheckers { if err := c.CheckExt(filename); err == nil { ec = c break } } switch ec.(type) { case *Rar: return NewRar(), nil case *Tar: return NewTar(), nil case *TarBz2: return NewTarBz2(), nil case *TarGz: return NewTarGz(), nil case *TarLz4: return NewTarLz4(), nil case *TarSz: return NewTarSz(), nil case *TarXz: return NewTarXz(), nil case *Zip: return NewZip(), nil case *Gz: return NewGz(), nil case *Bz2: return NewBz2(), nil case *Lz4: return NewLz4(), nil case *Snappy: return NewSnappy(), nil case *Xz: return NewXz(), nil } return nil, fmt.Errorf("format unrecognized by filename: %s", filename) }
go
func ByExtension(filename string) (interface{}, error) { var ec interface{} for _, c := range extCheckers { if err := c.CheckExt(filename); err == nil { ec = c break } } switch ec.(type) { case *Rar: return NewRar(), nil case *Tar: return NewTar(), nil case *TarBz2: return NewTarBz2(), nil case *TarGz: return NewTarGz(), nil case *TarLz4: return NewTarLz4(), nil case *TarSz: return NewTarSz(), nil case *TarXz: return NewTarXz(), nil case *Zip: return NewZip(), nil case *Gz: return NewGz(), nil case *Bz2: return NewBz2(), nil case *Lz4: return NewLz4(), nil case *Snappy: return NewSnappy(), nil case *Xz: return NewXz(), nil } return nil, fmt.Errorf("format unrecognized by filename: %s", filename) }
[ "func", "ByExtension", "(", "filename", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "ec", "interface", "{", "}", "\n", "for", "_", ",", "c", ":=", "range", "extCheckers", "{", "if", "err", ":=", "c", ".", "CheckExt", "(", "filename", ")", ";", "err", "==", "nil", "{", "ec", "=", "c", "\n", "break", "\n", "}", "\n", "}", "\n", "switch", "ec", ".", "(", "type", ")", "{", "case", "*", "Rar", ":", "return", "NewRar", "(", ")", ",", "nil", "\n", "case", "*", "Tar", ":", "return", "NewTar", "(", ")", ",", "nil", "\n", "case", "*", "TarBz2", ":", "return", "NewTarBz2", "(", ")", ",", "nil", "\n", "case", "*", "TarGz", ":", "return", "NewTarGz", "(", ")", ",", "nil", "\n", "case", "*", "TarLz4", ":", "return", "NewTarLz4", "(", ")", ",", "nil", "\n", "case", "*", "TarSz", ":", "return", "NewTarSz", "(", ")", ",", "nil", "\n", "case", "*", "TarXz", ":", "return", "NewTarXz", "(", ")", ",", "nil", "\n", "case", "*", "Zip", ":", "return", "NewZip", "(", ")", ",", "nil", "\n", "case", "*", "Gz", ":", "return", "NewGz", "(", ")", ",", "nil", "\n", "case", "*", "Bz2", ":", "return", "NewBz2", "(", ")", ",", "nil", "\n", "case", "*", "Lz4", ":", "return", "NewLz4", "(", ")", ",", "nil", "\n", "case", "*", "Snappy", ":", "return", "NewSnappy", "(", ")", ",", "nil", "\n", "case", "*", "Xz", ":", "return", "NewXz", "(", ")", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filename", ")", "\n", "}" ]
// ByExtension returns an archiver and unarchiver, or compressor // and decompressor, based on the extension of the filename.
[ "ByExtension", "returns", "an", "archiver", "and", "unarchiver", "or", "compressor", "and", "decompressor", "based", "on", "the", "extension", "of", "the", "filename", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L433-L470
train
mholt/archiver
archiver.go
ByHeader
func ByHeader(input io.ReadSeeker) (Unarchiver, error) { var matcher Matcher for _, m := range matchers { ok, err := m.Match(input) if err != nil { return nil, fmt.Errorf("matching on format %s: %v", m, err) } if ok { matcher = m break } } switch matcher.(type) { case *Zip: return NewZip(), nil case *Tar: return NewTar(), nil case *Rar: return NewRar(), nil } return nil, ErrFormatNotRecognized }
go
func ByHeader(input io.ReadSeeker) (Unarchiver, error) { var matcher Matcher for _, m := range matchers { ok, err := m.Match(input) if err != nil { return nil, fmt.Errorf("matching on format %s: %v", m, err) } if ok { matcher = m break } } switch matcher.(type) { case *Zip: return NewZip(), nil case *Tar: return NewTar(), nil case *Rar: return NewRar(), nil } return nil, ErrFormatNotRecognized }
[ "func", "ByHeader", "(", "input", "io", ".", "ReadSeeker", ")", "(", "Unarchiver", ",", "error", ")", "{", "var", "matcher", "Matcher", "\n", "for", "_", ",", "m", ":=", "range", "matchers", "{", "ok", ",", "err", ":=", "m", ".", "Match", "(", "input", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "m", ",", "err", ")", "\n", "}", "\n", "if", "ok", "{", "matcher", "=", "m", "\n", "break", "\n", "}", "\n", "}", "\n", "switch", "matcher", ".", "(", "type", ")", "{", "case", "*", "Zip", ":", "return", "NewZip", "(", ")", ",", "nil", "\n", "case", "*", "Tar", ":", "return", "NewTar", "(", ")", ",", "nil", "\n", "case", "*", "Rar", ":", "return", "NewRar", "(", ")", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "ErrFormatNotRecognized", "\n", "}" ]
// ByHeader returns the unarchiver value that matches the input's // file header. It does not affect the current read position. // If the file's header is not a recognized archive format, then // ErrFormatNotRecognized will be returned.
[ "ByHeader", "returns", "the", "unarchiver", "value", "that", "matches", "the", "input", "s", "file", "header", ".", "It", "does", "not", "affect", "the", "current", "read", "position", ".", "If", "the", "file", "s", "header", "is", "not", "a", "recognized", "archive", "format", "then", "ErrFormatNotRecognized", "will", "be", "returned", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L476-L497
train
mholt/archiver
filecompressor.go
CompressFile
func (fc FileCompressor) CompressFile(source, destination string) error { if err := fc.CheckExt(destination); err != nil { return err } if fc.Compressor == nil { return fmt.Errorf("no compressor specified") } if !fc.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file exists: %s", destination) } in, err := os.Open(source) if err != nil { return err } defer in.Close() out, err := os.Create(destination) if err != nil { return err } defer out.Close() return fc.Compress(in, out) }
go
func (fc FileCompressor) CompressFile(source, destination string) error { if err := fc.CheckExt(destination); err != nil { return err } if fc.Compressor == nil { return fmt.Errorf("no compressor specified") } if !fc.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file exists: %s", destination) } in, err := os.Open(source) if err != nil { return err } defer in.Close() out, err := os.Create(destination) if err != nil { return err } defer out.Close() return fc.Compress(in, out) }
[ "func", "(", "fc", "FileCompressor", ")", "CompressFile", "(", "source", ",", "destination", "string", ")", "error", "{", "if", "err", ":=", "fc", ".", "CheckExt", "(", "destination", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "fc", ".", "Compressor", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "fc", ".", "OverwriteExisting", "&&", "fileExists", "(", "destination", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "destination", ")", "\n", "}", "\n\n", "in", ",", "err", ":=", "os", ".", "Open", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "in", ".", "Close", "(", ")", "\n\n", "out", ",", "err", ":=", "os", ".", "Create", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "out", ".", "Close", "(", ")", "\n\n", "return", "fc", ".", "Compress", "(", "in", ",", "out", ")", "\n", "}" ]
// CompressFile reads the source file and compresses it to destination. // The destination must have a matching extension.
[ "CompressFile", "reads", "the", "source", "file", "and", "compresses", "it", "to", "destination", ".", "The", "destination", "must", "have", "a", "matching", "extension", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/filecompressor.go#L19-L43
train
mholt/archiver
filecompressor.go
DecompressFile
func (fc FileCompressor) DecompressFile(source, destination string) error { if fc.Decompressor == nil { return fmt.Errorf("no decompressor specified") } if !fc.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file exists: %s", destination) } in, err := os.Open(source) if err != nil { return err } defer in.Close() out, err := os.Create(destination) if err != nil { return err } defer out.Close() return fc.Decompress(in, out) }
go
func (fc FileCompressor) DecompressFile(source, destination string) error { if fc.Decompressor == nil { return fmt.Errorf("no decompressor specified") } if !fc.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file exists: %s", destination) } in, err := os.Open(source) if err != nil { return err } defer in.Close() out, err := os.Create(destination) if err != nil { return err } defer out.Close() return fc.Decompress(in, out) }
[ "func", "(", "fc", "FileCompressor", ")", "DecompressFile", "(", "source", ",", "destination", "string", ")", "error", "{", "if", "fc", ".", "Decompressor", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "fc", ".", "OverwriteExisting", "&&", "fileExists", "(", "destination", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "destination", ")", "\n", "}", "\n\n", "in", ",", "err", ":=", "os", ".", "Open", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "in", ".", "Close", "(", ")", "\n\n", "out", ",", "err", ":=", "os", ".", "Create", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "out", ".", "Close", "(", ")", "\n\n", "return", "fc", ".", "Decompress", "(", "in", ",", "out", ")", "\n", "}" ]
// DecompressFile reads the source file and decompresses it to destination.
[ "DecompressFile", "reads", "the", "source", "file", "and", "decompresses", "it", "to", "destination", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/filecompressor.go#L46-L67
train
GeertJohan/go.rice
config.go
FindBox
func (c *Config) FindBox(boxName string) (*Box, error) { return findBox(boxName, c.LocateOrder) }
go
func (c *Config) FindBox(boxName string) (*Box, error) { return findBox(boxName, c.LocateOrder) }
[ "func", "(", "c", "*", "Config", ")", "FindBox", "(", "boxName", "string", ")", "(", "*", "Box", ",", "error", ")", "{", "return", "findBox", "(", "boxName", ",", "c", ".", "LocateOrder", ")", "\n", "}" ]
// FindBox searches for boxes using the LocateOrder of the config.
[ "FindBox", "searches", "for", "boxes", "using", "the", "LocateOrder", "of", "the", "config", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/config.go#L26-L28
train
GeertJohan/go.rice
config.go
MustFindBox
func (c *Config) MustFindBox(boxName string) *Box { box, err := findBox(boxName, c.LocateOrder) if err != nil { panic(err) } return box }
go
func (c *Config) MustFindBox(boxName string) *Box { box, err := findBox(boxName, c.LocateOrder) if err != nil { panic(err) } return box }
[ "func", "(", "c", "*", "Config", ")", "MustFindBox", "(", "boxName", "string", ")", "*", "Box", "{", "box", ",", "err", ":=", "findBox", "(", "boxName", ",", "c", ".", "LocateOrder", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "box", "\n", "}" ]
// MustFindBox searches for boxes using the LocateOrder of the config, like // FindBox does. It does not return an error, instead it panics when an error // occurs.
[ "MustFindBox", "searches", "for", "boxes", "using", "the", "LocateOrder", "of", "the", "config", "like", "FindBox", "does", ".", "It", "does", "not", "return", "an", "error", "instead", "it", "panics", "when", "an", "error", "occurs", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/config.go#L33-L39
train
GeertJohan/go.rice
embedded/embedded.go
Link
func (e *EmbeddedBox) Link() { for _, ed := range e.Dirs { ed.ChildDirs = make([]*EmbeddedDir, 0) ed.ChildFiles = make([]*EmbeddedFile, 0) } for path, ed := range e.Dirs { // skip for root, it'll create a recursion if path == "" { continue } parentDirpath, _ := filepath.Split(path) if strings.HasSuffix(parentDirpath, "/") { parentDirpath = parentDirpath[:len(parentDirpath)-1] } parentDir := e.Dirs[parentDirpath] if parentDir == nil { panic("parentDir `" + parentDirpath + "` is missing in embedded box") } parentDir.ChildDirs = append(parentDir.ChildDirs, ed) } for path, ef := range e.Files { dirpath, _ := filepath.Split(path) if strings.HasSuffix(dirpath, "/") { dirpath = dirpath[:len(dirpath)-1] } dir := e.Dirs[dirpath] if dir == nil { panic("dir `" + dirpath + "` is missing in embedded box") } dir.ChildFiles = append(dir.ChildFiles, ef) } }
go
func (e *EmbeddedBox) Link() { for _, ed := range e.Dirs { ed.ChildDirs = make([]*EmbeddedDir, 0) ed.ChildFiles = make([]*EmbeddedFile, 0) } for path, ed := range e.Dirs { // skip for root, it'll create a recursion if path == "" { continue } parentDirpath, _ := filepath.Split(path) if strings.HasSuffix(parentDirpath, "/") { parentDirpath = parentDirpath[:len(parentDirpath)-1] } parentDir := e.Dirs[parentDirpath] if parentDir == nil { panic("parentDir `" + parentDirpath + "` is missing in embedded box") } parentDir.ChildDirs = append(parentDir.ChildDirs, ed) } for path, ef := range e.Files { dirpath, _ := filepath.Split(path) if strings.HasSuffix(dirpath, "/") { dirpath = dirpath[:len(dirpath)-1] } dir := e.Dirs[dirpath] if dir == nil { panic("dir `" + dirpath + "` is missing in embedded box") } dir.ChildFiles = append(dir.ChildFiles, ef) } }
[ "func", "(", "e", "*", "EmbeddedBox", ")", "Link", "(", ")", "{", "for", "_", ",", "ed", ":=", "range", "e", ".", "Dirs", "{", "ed", ".", "ChildDirs", "=", "make", "(", "[", "]", "*", "EmbeddedDir", ",", "0", ")", "\n", "ed", ".", "ChildFiles", "=", "make", "(", "[", "]", "*", "EmbeddedFile", ",", "0", ")", "\n", "}", "\n", "for", "path", ",", "ed", ":=", "range", "e", ".", "Dirs", "{", "// skip for root, it'll create a recursion", "if", "path", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "parentDirpath", ",", "_", ":=", "filepath", ".", "Split", "(", "path", ")", "\n", "if", "strings", ".", "HasSuffix", "(", "parentDirpath", ",", "\"", "\"", ")", "{", "parentDirpath", "=", "parentDirpath", "[", ":", "len", "(", "parentDirpath", ")", "-", "1", "]", "\n", "}", "\n", "parentDir", ":=", "e", ".", "Dirs", "[", "parentDirpath", "]", "\n", "if", "parentDir", "==", "nil", "{", "panic", "(", "\"", "\"", "+", "parentDirpath", "+", "\"", "\"", ")", "\n", "}", "\n", "parentDir", ".", "ChildDirs", "=", "append", "(", "parentDir", ".", "ChildDirs", ",", "ed", ")", "\n", "}", "\n", "for", "path", ",", "ef", ":=", "range", "e", ".", "Files", "{", "dirpath", ",", "_", ":=", "filepath", ".", "Split", "(", "path", ")", "\n", "if", "strings", ".", "HasSuffix", "(", "dirpath", ",", "\"", "\"", ")", "{", "dirpath", "=", "dirpath", "[", ":", "len", "(", "dirpath", ")", "-", "1", "]", "\n", "}", "\n", "dir", ":=", "e", ".", "Dirs", "[", "dirpath", "]", "\n", "if", "dir", "==", "nil", "{", "panic", "(", "\"", "\"", "+", "dirpath", "+", "\"", "\"", ")", "\n", "}", "\n", "dir", ".", "ChildFiles", "=", "append", "(", "dir", ".", "ChildFiles", ",", "ef", ")", "\n", "}", "\n", "}" ]
// Link creates the ChildDirs and ChildFiles links in all EmbeddedDir's
[ "Link", "creates", "the", "ChildDirs", "and", "ChildFiles", "links", "in", "all", "EmbeddedDir", "s" ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/embedded/embedded.go#L26-L57
train
GeertJohan/go.rice
embedded/embedded.go
RegisterEmbeddedBox
func RegisterEmbeddedBox(name string, box *EmbeddedBox) { if _, exists := EmbeddedBoxes[name]; exists { panic(fmt.Sprintf("EmbeddedBox with name `%s` exists already", name)) } EmbeddedBoxes[name] = box }
go
func RegisterEmbeddedBox(name string, box *EmbeddedBox) { if _, exists := EmbeddedBoxes[name]; exists { panic(fmt.Sprintf("EmbeddedBox with name `%s` exists already", name)) } EmbeddedBoxes[name] = box }
[ "func", "RegisterEmbeddedBox", "(", "name", "string", ",", "box", "*", "EmbeddedBox", ")", "{", "if", "_", ",", "exists", ":=", "EmbeddedBoxes", "[", "name", "]", ";", "exists", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n", "EmbeddedBoxes", "[", "name", "]", "=", "box", "\n", "}" ]
// RegisterEmbeddedBox registers an EmbeddedBox
[ "RegisterEmbeddedBox", "registers", "an", "EmbeddedBox" ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/embedded/embedded.go#L78-L83
train
GeertJohan/go.rice
box.go
MustFindBox
func MustFindBox(name string) *Box { box, err := findBox(name, defaultLocateOrder) if err != nil { panic(err) } return box }
go
func MustFindBox(name string) *Box { box, err := findBox(name, defaultLocateOrder) if err != nil { panic(err) } return box }
[ "func", "MustFindBox", "(", "name", "string", ")", "*", "Box", "{", "box", ",", "err", ":=", "findBox", "(", "name", ",", "defaultLocateOrder", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "box", "\n", "}" ]
// MustFindBox returns a Box instance for given name, like FindBox does. // It does not return an error, instead it panics when an error occurs.
[ "MustFindBox", "returns", "a", "Box", "instance", "for", "given", "name", "like", "FindBox", "does", ".", "It", "does", "not", "return", "an", "error", "instead", "it", "panics", "when", "an", "error", "occurs", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/box.go#L107-L113
train
GeertJohan/go.rice
box.go
String
func (b *Box) String(name string) (string, error) { // check if box is embedded, optimized fast path if b.IsEmbedded() { // find file in embed ef := b.embed.Files[name] if ef == nil { return "", os.ErrNotExist } // return as string return ef.Content, nil } bts, err := b.Bytes(name) if err != nil { return "", err } return string(bts), nil }
go
func (b *Box) String(name string) (string, error) { // check if box is embedded, optimized fast path if b.IsEmbedded() { // find file in embed ef := b.embed.Files[name] if ef == nil { return "", os.ErrNotExist } // return as string return ef.Content, nil } bts, err := b.Bytes(name) if err != nil { return "", err } return string(bts), nil }
[ "func", "(", "b", "*", "Box", ")", "String", "(", "name", "string", ")", "(", "string", ",", "error", ")", "{", "// check if box is embedded, optimized fast path", "if", "b", ".", "IsEmbedded", "(", ")", "{", "// find file in embed", "ef", ":=", "b", ".", "embed", ".", "Files", "[", "name", "]", "\n", "if", "ef", "==", "nil", "{", "return", "\"", "\"", ",", "os", ".", "ErrNotExist", "\n", "}", "\n", "// return as string", "return", "ef", ".", "Content", ",", "nil", "\n", "}", "\n\n", "bts", ",", "err", ":=", "b", ".", "Bytes", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "bts", ")", ",", "nil", "\n", "}" ]
// String returns the content of the file with given name as string.
[ "String", "returns", "the", "content", "of", "the", "file", "with", "given", "name", "as", "string", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/box.go#L305-L322
train
GeertJohan/go.rice
box.go
MustString
func (b *Box) MustString(name string) string { str, err := b.String(name) if err != nil { panic(err) } return str }
go
func (b *Box) MustString(name string) string { str, err := b.String(name) if err != nil { panic(err) } return str }
[ "func", "(", "b", "*", "Box", ")", "MustString", "(", "name", "string", ")", "string", "{", "str", ",", "err", ":=", "b", ".", "String", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "str", "\n", "}" ]
// MustString returns the content of the file with given name as string. // panic's on error.
[ "MustString", "returns", "the", "content", "of", "the", "file", "with", "given", "name", "as", "string", ".", "panic", "s", "on", "error", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/box.go#L326-L332
train
GeertJohan/go.rice
virtual.go
newVirtualFile
func newVirtualFile(ef *embedded.EmbeddedFile) *virtualFile { vf := &virtualFile{ EmbeddedFile: ef, offset: 0, closed: false, } return vf }
go
func newVirtualFile(ef *embedded.EmbeddedFile) *virtualFile { vf := &virtualFile{ EmbeddedFile: ef, offset: 0, closed: false, } return vf }
[ "func", "newVirtualFile", "(", "ef", "*", "embedded", ".", "EmbeddedFile", ")", "*", "virtualFile", "{", "vf", ":=", "&", "virtualFile", "{", "EmbeddedFile", ":", "ef", ",", "offset", ":", "0", ",", "closed", ":", "false", ",", "}", "\n", "return", "vf", "\n", "}" ]
// create a new virtualFile for given EmbeddedFile
[ "create", "a", "new", "virtualFile", "for", "given", "EmbeddedFile" ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/virtual.go#L25-L32
train
GeertJohan/go.rice
virtual.go
newVirtualDir
func newVirtualDir(ed *embedded.EmbeddedDir) *virtualDir { vd := &virtualDir{ EmbeddedDir: ed, offset: 0, closed: false, } return vd }
go
func newVirtualDir(ed *embedded.EmbeddedDir) *virtualDir { vd := &virtualDir{ EmbeddedDir: ed, offset: 0, closed: false, } return vd }
[ "func", "newVirtualDir", "(", "ed", "*", "embedded", ".", "EmbeddedDir", ")", "*", "virtualDir", "{", "vd", ":=", "&", "virtualDir", "{", "EmbeddedDir", ":", "ed", ",", "offset", ":", "0", ",", "closed", ":", "false", ",", "}", "\n", "return", "vd", "\n", "}" ]
// create a new virtualDir for given EmbeddedDir
[ "create", "a", "new", "virtualDir", "for", "given", "EmbeddedDir" ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/virtual.go#L150-L157
train
GeertJohan/go.rice
rice/util.go
generated
func generated(filename string) bool { return filepath.Base(filename) == boxFilename || strings.HasSuffix(filename, "."+boxFilename) || strings.HasSuffix(filename, sysoBoxSuffix) }
go
func generated(filename string) bool { return filepath.Base(filename) == boxFilename || strings.HasSuffix(filename, "."+boxFilename) || strings.HasSuffix(filename, sysoBoxSuffix) }
[ "func", "generated", "(", "filename", "string", ")", "bool", "{", "return", "filepath", ".", "Base", "(", "filename", ")", "==", "boxFilename", "||", "strings", ".", "HasSuffix", "(", "filename", ",", "\"", "\"", "+", "boxFilename", ")", "||", "strings", ".", "HasSuffix", "(", "filename", ",", "sysoBoxSuffix", ")", "\n", "}" ]
// generated tests if a filename was generated by rice
[ "generated", "tests", "if", "a", "filename", "was", "generated", "by", "rice" ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/rice/util.go#L11-L15
train
GeertJohan/go.rice
rice/util.go
randomString
func randomString(length int) string { rand.Seed(time.Now().UnixNano()) k := make([]rune, length) for i := 0; i < length; i++ { c := rand.Intn(35) if c < 10 { c += 48 // numbers (0-9) (0+48 == 48 == '0', 9+48 == 57 == '9') } else { c += 87 // lower case alphabets (a-z) (10+87 == 97 == 'a', 35+87 == 122 = 'z') } k[i] = rune(c) } return string(k) }
go
func randomString(length int) string { rand.Seed(time.Now().UnixNano()) k := make([]rune, length) for i := 0; i < length; i++ { c := rand.Intn(35) if c < 10 { c += 48 // numbers (0-9) (0+48 == 48 == '0', 9+48 == 57 == '9') } else { c += 87 // lower case alphabets (a-z) (10+87 == 97 == 'a', 35+87 == 122 = 'z') } k[i] = rune(c) } return string(k) }
[ "func", "randomString", "(", "length", "int", ")", "string", "{", "rand", ".", "Seed", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "k", ":=", "make", "(", "[", "]", "rune", ",", "length", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "length", ";", "i", "++", "{", "c", ":=", "rand", ".", "Intn", "(", "35", ")", "\n", "if", "c", "<", "10", "{", "c", "+=", "48", "// numbers (0-9) (0+48 == 48 == '0', 9+48 == 57 == '9')", "\n", "}", "else", "{", "c", "+=", "87", "// lower case alphabets (a-z) (10+87 == 97 == 'a', 35+87 == 122 = 'z')", "\n", "}", "\n", "k", "[", "i", "]", "=", "rune", "(", "c", ")", "\n", "}", "\n", "return", "string", "(", "k", ")", "\n", "}" ]
// randomString generates a pseudo-random alpha-numeric string with given length.
[ "randomString", "generates", "a", "pseudo", "-", "random", "alpha", "-", "numeric", "string", "with", "given", "length", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/rice/util.go#L18-L31
train
bwmarrin/discordgo
ratelimit.go
NewRatelimiter
func NewRatelimiter() *RateLimiter { return &RateLimiter{ buckets: make(map[string]*Bucket), global: new(int64), customRateLimits: []*customRateLimit{ &customRateLimit{ suffix: "//reactions//", requests: 1, reset: 200 * time.Millisecond, }, }, } }
go
func NewRatelimiter() *RateLimiter { return &RateLimiter{ buckets: make(map[string]*Bucket), global: new(int64), customRateLimits: []*customRateLimit{ &customRateLimit{ suffix: "//reactions//", requests: 1, reset: 200 * time.Millisecond, }, }, } }
[ "func", "NewRatelimiter", "(", ")", "*", "RateLimiter", "{", "return", "&", "RateLimiter", "{", "buckets", ":", "make", "(", "map", "[", "string", "]", "*", "Bucket", ")", ",", "global", ":", "new", "(", "int64", ")", ",", "customRateLimits", ":", "[", "]", "*", "customRateLimit", "{", "&", "customRateLimit", "{", "suffix", ":", "\"", "\"", ",", "requests", ":", "1", ",", "reset", ":", "200", "*", "time", ".", "Millisecond", ",", "}", ",", "}", ",", "}", "\n", "}" ]
// NewRatelimiter returns a new RateLimiter
[ "NewRatelimiter", "returns", "a", "new", "RateLimiter" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L29-L42
train
bwmarrin/discordgo
ratelimit.go
GetBucket
func (r *RateLimiter) GetBucket(key string) *Bucket { r.Lock() defer r.Unlock() if bucket, ok := r.buckets[key]; ok { return bucket } b := &Bucket{ Remaining: 1, Key: key, global: r.global, } // Check if there is a custom ratelimit set for this bucket ID. for _, rl := range r.customRateLimits { if strings.HasSuffix(b.Key, rl.suffix) { b.customRateLimit = rl break } } r.buckets[key] = b return b }
go
func (r *RateLimiter) GetBucket(key string) *Bucket { r.Lock() defer r.Unlock() if bucket, ok := r.buckets[key]; ok { return bucket } b := &Bucket{ Remaining: 1, Key: key, global: r.global, } // Check if there is a custom ratelimit set for this bucket ID. for _, rl := range r.customRateLimits { if strings.HasSuffix(b.Key, rl.suffix) { b.customRateLimit = rl break } } r.buckets[key] = b return b }
[ "func", "(", "r", "*", "RateLimiter", ")", "GetBucket", "(", "key", "string", ")", "*", "Bucket", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n\n", "if", "bucket", ",", "ok", ":=", "r", ".", "buckets", "[", "key", "]", ";", "ok", "{", "return", "bucket", "\n", "}", "\n\n", "b", ":=", "&", "Bucket", "{", "Remaining", ":", "1", ",", "Key", ":", "key", ",", "global", ":", "r", ".", "global", ",", "}", "\n\n", "// Check if there is a custom ratelimit set for this bucket ID.", "for", "_", ",", "rl", ":=", "range", "r", ".", "customRateLimits", "{", "if", "strings", ".", "HasSuffix", "(", "b", ".", "Key", ",", "rl", ".", "suffix", ")", "{", "b", ".", "customRateLimit", "=", "rl", "\n", "break", "\n", "}", "\n", "}", "\n\n", "r", ".", "buckets", "[", "key", "]", "=", "b", "\n", "return", "b", "\n", "}" ]
// GetBucket retrieves or creates a bucket
[ "GetBucket", "retrieves", "or", "creates", "a", "bucket" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L45-L69
train
bwmarrin/discordgo
ratelimit.go
GetWaitTime
func (r *RateLimiter) GetWaitTime(b *Bucket, minRemaining int) time.Duration { // If we ran out of calls and the reset time is still ahead of us // then we need to take it easy and relax a little if b.Remaining < minRemaining && b.reset.After(time.Now()) { return b.reset.Sub(time.Now()) } // Check for global ratelimits sleepTo := time.Unix(0, atomic.LoadInt64(r.global)) if now := time.Now(); now.Before(sleepTo) { return sleepTo.Sub(now) } return 0 }
go
func (r *RateLimiter) GetWaitTime(b *Bucket, minRemaining int) time.Duration { // If we ran out of calls and the reset time is still ahead of us // then we need to take it easy and relax a little if b.Remaining < minRemaining && b.reset.After(time.Now()) { return b.reset.Sub(time.Now()) } // Check for global ratelimits sleepTo := time.Unix(0, atomic.LoadInt64(r.global)) if now := time.Now(); now.Before(sleepTo) { return sleepTo.Sub(now) } return 0 }
[ "func", "(", "r", "*", "RateLimiter", ")", "GetWaitTime", "(", "b", "*", "Bucket", ",", "minRemaining", "int", ")", "time", ".", "Duration", "{", "// If we ran out of calls and the reset time is still ahead of us", "// then we need to take it easy and relax a little", "if", "b", ".", "Remaining", "<", "minRemaining", "&&", "b", ".", "reset", ".", "After", "(", "time", ".", "Now", "(", ")", ")", "{", "return", "b", ".", "reset", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "}", "\n\n", "// Check for global ratelimits", "sleepTo", ":=", "time", ".", "Unix", "(", "0", ",", "atomic", ".", "LoadInt64", "(", "r", ".", "global", ")", ")", "\n", "if", "now", ":=", "time", ".", "Now", "(", ")", ";", "now", ".", "Before", "(", "sleepTo", ")", "{", "return", "sleepTo", ".", "Sub", "(", "now", ")", "\n", "}", "\n\n", "return", "0", "\n", "}" ]
// GetWaitTime returns the duration you should wait for a Bucket
[ "GetWaitTime", "returns", "the", "duration", "you", "should", "wait", "for", "a", "Bucket" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L72-L86
train
bwmarrin/discordgo
ratelimit.go
LockBucket
func (r *RateLimiter) LockBucket(bucketID string) *Bucket { return r.LockBucketObject(r.GetBucket(bucketID)) }
go
func (r *RateLimiter) LockBucket(bucketID string) *Bucket { return r.LockBucketObject(r.GetBucket(bucketID)) }
[ "func", "(", "r", "*", "RateLimiter", ")", "LockBucket", "(", "bucketID", "string", ")", "*", "Bucket", "{", "return", "r", ".", "LockBucketObject", "(", "r", ".", "GetBucket", "(", "bucketID", ")", ")", "\n", "}" ]
// LockBucket Locks until a request can be made
[ "LockBucket", "Locks", "until", "a", "request", "can", "be", "made" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L89-L91
train
bwmarrin/discordgo
ratelimit.go
LockBucketObject
func (r *RateLimiter) LockBucketObject(b *Bucket) *Bucket { b.Lock() if wait := r.GetWaitTime(b, 1); wait > 0 { time.Sleep(wait) } b.Remaining-- return b }
go
func (r *RateLimiter) LockBucketObject(b *Bucket) *Bucket { b.Lock() if wait := r.GetWaitTime(b, 1); wait > 0 { time.Sleep(wait) } b.Remaining-- return b }
[ "func", "(", "r", "*", "RateLimiter", ")", "LockBucketObject", "(", "b", "*", "Bucket", ")", "*", "Bucket", "{", "b", ".", "Lock", "(", ")", "\n\n", "if", "wait", ":=", "r", ".", "GetWaitTime", "(", "b", ",", "1", ")", ";", "wait", ">", "0", "{", "time", ".", "Sleep", "(", "wait", ")", "\n", "}", "\n\n", "b", ".", "Remaining", "--", "\n", "return", "b", "\n", "}" ]
// LockBucketObject Locks an already resolved bucket until a request can be made
[ "LockBucketObject", "Locks", "an", "already", "resolved", "bucket", "until", "a", "request", "can", "be", "made" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L94-L103
train
bwmarrin/discordgo
ratelimit.go
Release
func (b *Bucket) Release(headers http.Header) error { defer b.Unlock() // Check if the bucket uses a custom ratelimiter if rl := b.customRateLimit; rl != nil { if time.Now().Sub(b.lastReset) >= rl.reset { b.Remaining = rl.requests - 1 b.lastReset = time.Now() } if b.Remaining < 1 { b.reset = time.Now().Add(rl.reset) } return nil } if headers == nil { return nil } remaining := headers.Get("X-RateLimit-Remaining") reset := headers.Get("X-RateLimit-Reset") global := headers.Get("X-RateLimit-Global") retryAfter := headers.Get("Retry-After") // Update global and per bucket reset time if the proper headers are available // If global is set, then it will block all buckets until after Retry-After // If Retry-After without global is provided it will use that for the new reset // time since it's more accurate than X-RateLimit-Reset. // If Retry-After after is not proided, it will update the reset time from X-RateLimit-Reset if retryAfter != "" { parsedAfter, err := strconv.ParseInt(retryAfter, 10, 64) if err != nil { return err } resetAt := time.Now().Add(time.Duration(parsedAfter) * time.Millisecond) // Lock either this single bucket or all buckets if global != "" { atomic.StoreInt64(b.global, resetAt.UnixNano()) } else { b.reset = resetAt } } else if reset != "" { // Calculate the reset time by using the date header returned from discord discordTime, err := http.ParseTime(headers.Get("Date")) if err != nil { return err } unix, err := strconv.ParseInt(reset, 10, 64) if err != nil { return err } // Calculate the time until reset and add it to the current local time // some extra time is added because without it i still encountered 429's. // The added amount is the lowest amount that gave no 429's // in 1k requests delta := time.Unix(unix, 0).Sub(discordTime) + time.Millisecond*250 b.reset = time.Now().Add(delta) } // Udpate remaining if header is present if remaining != "" { parsedRemaining, err := strconv.ParseInt(remaining, 10, 32) if err != nil { return err } b.Remaining = int(parsedRemaining) } return nil }
go
func (b *Bucket) Release(headers http.Header) error { defer b.Unlock() // Check if the bucket uses a custom ratelimiter if rl := b.customRateLimit; rl != nil { if time.Now().Sub(b.lastReset) >= rl.reset { b.Remaining = rl.requests - 1 b.lastReset = time.Now() } if b.Remaining < 1 { b.reset = time.Now().Add(rl.reset) } return nil } if headers == nil { return nil } remaining := headers.Get("X-RateLimit-Remaining") reset := headers.Get("X-RateLimit-Reset") global := headers.Get("X-RateLimit-Global") retryAfter := headers.Get("Retry-After") // Update global and per bucket reset time if the proper headers are available // If global is set, then it will block all buckets until after Retry-After // If Retry-After without global is provided it will use that for the new reset // time since it's more accurate than X-RateLimit-Reset. // If Retry-After after is not proided, it will update the reset time from X-RateLimit-Reset if retryAfter != "" { parsedAfter, err := strconv.ParseInt(retryAfter, 10, 64) if err != nil { return err } resetAt := time.Now().Add(time.Duration(parsedAfter) * time.Millisecond) // Lock either this single bucket or all buckets if global != "" { atomic.StoreInt64(b.global, resetAt.UnixNano()) } else { b.reset = resetAt } } else if reset != "" { // Calculate the reset time by using the date header returned from discord discordTime, err := http.ParseTime(headers.Get("Date")) if err != nil { return err } unix, err := strconv.ParseInt(reset, 10, 64) if err != nil { return err } // Calculate the time until reset and add it to the current local time // some extra time is added because without it i still encountered 429's. // The added amount is the lowest amount that gave no 429's // in 1k requests delta := time.Unix(unix, 0).Sub(discordTime) + time.Millisecond*250 b.reset = time.Now().Add(delta) } // Udpate remaining if header is present if remaining != "" { parsedRemaining, err := strconv.ParseInt(remaining, 10, 32) if err != nil { return err } b.Remaining = int(parsedRemaining) } return nil }
[ "func", "(", "b", "*", "Bucket", ")", "Release", "(", "headers", "http", ".", "Header", ")", "error", "{", "defer", "b", ".", "Unlock", "(", ")", "\n\n", "// Check if the bucket uses a custom ratelimiter", "if", "rl", ":=", "b", ".", "customRateLimit", ";", "rl", "!=", "nil", "{", "if", "time", ".", "Now", "(", ")", ".", "Sub", "(", "b", ".", "lastReset", ")", ">=", "rl", ".", "reset", "{", "b", ".", "Remaining", "=", "rl", ".", "requests", "-", "1", "\n", "b", ".", "lastReset", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n", "if", "b", ".", "Remaining", "<", "1", "{", "b", ".", "reset", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "rl", ".", "reset", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "if", "headers", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "remaining", ":=", "headers", ".", "Get", "(", "\"", "\"", ")", "\n", "reset", ":=", "headers", ".", "Get", "(", "\"", "\"", ")", "\n", "global", ":=", "headers", ".", "Get", "(", "\"", "\"", ")", "\n", "retryAfter", ":=", "headers", ".", "Get", "(", "\"", "\"", ")", "\n\n", "// Update global and per bucket reset time if the proper headers are available", "// If global is set, then it will block all buckets until after Retry-After", "// If Retry-After without global is provided it will use that for the new reset", "// time since it's more accurate than X-RateLimit-Reset.", "// If Retry-After after is not proided, it will update the reset time from X-RateLimit-Reset", "if", "retryAfter", "!=", "\"", "\"", "{", "parsedAfter", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "retryAfter", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "resetAt", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Duration", "(", "parsedAfter", ")", "*", "time", ".", "Millisecond", ")", "\n\n", "// Lock either this single bucket or all buckets", "if", "global", "!=", "\"", "\"", "{", "atomic", ".", "StoreInt64", "(", "b", ".", "global", ",", "resetAt", ".", "UnixNano", "(", ")", ")", "\n", "}", "else", "{", "b", ".", "reset", "=", "resetAt", "\n", "}", "\n", "}", "else", "if", "reset", "!=", "\"", "\"", "{", "// Calculate the reset time by using the date header returned from discord", "discordTime", ",", "err", ":=", "http", ".", "ParseTime", "(", "headers", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "unix", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "reset", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Calculate the time until reset and add it to the current local time", "// some extra time is added because without it i still encountered 429's.", "// The added amount is the lowest amount that gave no 429's", "// in 1k requests", "delta", ":=", "time", ".", "Unix", "(", "unix", ",", "0", ")", ".", "Sub", "(", "discordTime", ")", "+", "time", ".", "Millisecond", "*", "250", "\n", "b", ".", "reset", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "delta", ")", "\n", "}", "\n\n", "// Udpate remaining if header is present", "if", "remaining", "!=", "\"", "\"", "{", "parsedRemaining", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "remaining", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "b", ".", "Remaining", "=", "int", "(", "parsedRemaining", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Release unlocks the bucket and reads the headers to update the buckets ratelimit info // and locks up the whole thing in case if there's a global ratelimit.
[ "Release", "unlocks", "the", "bucket", "and", "reads", "the", "headers", "to", "update", "the", "buckets", "ratelimit", "info", "and", "locks", "up", "the", "whole", "thing", "in", "case", "if", "there", "s", "a", "global", "ratelimit", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L121-L194
train
bwmarrin/discordgo
state.go
NewState
func NewState() *State { return &State{ Ready: Ready{ PrivateChannels: []*Channel{}, Guilds: []*Guild{}, }, TrackChannels: true, TrackEmojis: true, TrackMembers: true, TrackRoles: true, TrackVoice: true, TrackPresences: true, guildMap: make(map[string]*Guild), channelMap: make(map[string]*Channel), memberMap: make(map[string]map[string]*Member), } }
go
func NewState() *State { return &State{ Ready: Ready{ PrivateChannels: []*Channel{}, Guilds: []*Guild{}, }, TrackChannels: true, TrackEmojis: true, TrackMembers: true, TrackRoles: true, TrackVoice: true, TrackPresences: true, guildMap: make(map[string]*Guild), channelMap: make(map[string]*Channel), memberMap: make(map[string]map[string]*Member), } }
[ "func", "NewState", "(", ")", "*", "State", "{", "return", "&", "State", "{", "Ready", ":", "Ready", "{", "PrivateChannels", ":", "[", "]", "*", "Channel", "{", "}", ",", "Guilds", ":", "[", "]", "*", "Guild", "{", "}", ",", "}", ",", "TrackChannels", ":", "true", ",", "TrackEmojis", ":", "true", ",", "TrackMembers", ":", "true", ",", "TrackRoles", ":", "true", ",", "TrackVoice", ":", "true", ",", "TrackPresences", ":", "true", ",", "guildMap", ":", "make", "(", "map", "[", "string", "]", "*", "Guild", ")", ",", "channelMap", ":", "make", "(", "map", "[", "string", "]", "*", "Channel", ")", ",", "memberMap", ":", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "*", "Member", ")", ",", "}", "\n", "}" ]
// NewState creates an empty state.
[ "NewState", "creates", "an", "empty", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L50-L66
train
bwmarrin/discordgo
state.go
GuildAdd
func (s *State) GuildAdd(guild *Guild) error { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // Update the channels to point to the right guild, adding them to the channelMap as we go for _, c := range guild.Channels { s.channelMap[c.ID] = c } // If this guild contains a new member slice, we must regenerate the member map so the pointers stay valid if guild.Members != nil { s.createMemberMap(guild) } else if _, ok := s.memberMap[guild.ID]; !ok { // Even if we have no new member slice, we still initialize the member map for this guild if it doesn't exist s.memberMap[guild.ID] = make(map[string]*Member) } if g, ok := s.guildMap[guild.ID]; ok { // We are about to replace `g` in the state with `guild`, but first we need to // make sure we preserve any fields that the `guild` doesn't contain from `g`. if guild.MemberCount == 0 { guild.MemberCount = g.MemberCount } if guild.Roles == nil { guild.Roles = g.Roles } if guild.Emojis == nil { guild.Emojis = g.Emojis } if guild.Members == nil { guild.Members = g.Members } if guild.Presences == nil { guild.Presences = g.Presences } if guild.Channels == nil { guild.Channels = g.Channels } if guild.VoiceStates == nil { guild.VoiceStates = g.VoiceStates } *g = *guild return nil } s.Guilds = append(s.Guilds, guild) s.guildMap[guild.ID] = guild return nil }
go
func (s *State) GuildAdd(guild *Guild) error { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // Update the channels to point to the right guild, adding them to the channelMap as we go for _, c := range guild.Channels { s.channelMap[c.ID] = c } // If this guild contains a new member slice, we must regenerate the member map so the pointers stay valid if guild.Members != nil { s.createMemberMap(guild) } else if _, ok := s.memberMap[guild.ID]; !ok { // Even if we have no new member slice, we still initialize the member map for this guild if it doesn't exist s.memberMap[guild.ID] = make(map[string]*Member) } if g, ok := s.guildMap[guild.ID]; ok { // We are about to replace `g` in the state with `guild`, but first we need to // make sure we preserve any fields that the `guild` doesn't contain from `g`. if guild.MemberCount == 0 { guild.MemberCount = g.MemberCount } if guild.Roles == nil { guild.Roles = g.Roles } if guild.Emojis == nil { guild.Emojis = g.Emojis } if guild.Members == nil { guild.Members = g.Members } if guild.Presences == nil { guild.Presences = g.Presences } if guild.Channels == nil { guild.Channels = g.Channels } if guild.VoiceStates == nil { guild.VoiceStates = g.VoiceStates } *g = *guild return nil } s.Guilds = append(s.Guilds, guild) s.guildMap[guild.ID] = guild return nil }
[ "func", "(", "s", "*", "State", ")", "GuildAdd", "(", "guild", "*", "Guild", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "// Update the channels to point to the right guild, adding them to the channelMap as we go", "for", "_", ",", "c", ":=", "range", "guild", ".", "Channels", "{", "s", ".", "channelMap", "[", "c", ".", "ID", "]", "=", "c", "\n", "}", "\n\n", "// If this guild contains a new member slice, we must regenerate the member map so the pointers stay valid", "if", "guild", ".", "Members", "!=", "nil", "{", "s", ".", "createMemberMap", "(", "guild", ")", "\n", "}", "else", "if", "_", ",", "ok", ":=", "s", ".", "memberMap", "[", "guild", ".", "ID", "]", ";", "!", "ok", "{", "// Even if we have no new member slice, we still initialize the member map for this guild if it doesn't exist", "s", ".", "memberMap", "[", "guild", ".", "ID", "]", "=", "make", "(", "map", "[", "string", "]", "*", "Member", ")", "\n", "}", "\n\n", "if", "g", ",", "ok", ":=", "s", ".", "guildMap", "[", "guild", ".", "ID", "]", ";", "ok", "{", "// We are about to replace `g` in the state with `guild`, but first we need to", "// make sure we preserve any fields that the `guild` doesn't contain from `g`.", "if", "guild", ".", "MemberCount", "==", "0", "{", "guild", ".", "MemberCount", "=", "g", ".", "MemberCount", "\n", "}", "\n", "if", "guild", ".", "Roles", "==", "nil", "{", "guild", ".", "Roles", "=", "g", ".", "Roles", "\n", "}", "\n", "if", "guild", ".", "Emojis", "==", "nil", "{", "guild", ".", "Emojis", "=", "g", ".", "Emojis", "\n", "}", "\n", "if", "guild", ".", "Members", "==", "nil", "{", "guild", ".", "Members", "=", "g", ".", "Members", "\n", "}", "\n", "if", "guild", ".", "Presences", "==", "nil", "{", "guild", ".", "Presences", "=", "g", ".", "Presences", "\n", "}", "\n", "if", "guild", ".", "Channels", "==", "nil", "{", "guild", ".", "Channels", "=", "g", ".", "Channels", "\n", "}", "\n", "if", "guild", ".", "VoiceStates", "==", "nil", "{", "guild", ".", "VoiceStates", "=", "g", ".", "VoiceStates", "\n", "}", "\n", "*", "g", "=", "*", "guild", "\n", "return", "nil", "\n", "}", "\n\n", "s", ".", "Guilds", "=", "append", "(", "s", ".", "Guilds", ",", "guild", ")", "\n", "s", ".", "guildMap", "[", "guild", ".", "ID", "]", "=", "guild", "\n\n", "return", "nil", "\n", "}" ]
// GuildAdd adds a guild to the current world state, or // updates it if it already exists.
[ "GuildAdd", "adds", "a", "guild", "to", "the", "current", "world", "state", "or", "updates", "it", "if", "it", "already", "exists", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L78-L131
train
bwmarrin/discordgo
state.go
GuildRemove
func (s *State) GuildRemove(guild *Guild) error { if s == nil { return ErrNilState } _, err := s.Guild(guild.ID) if err != nil { return err } s.Lock() defer s.Unlock() delete(s.guildMap, guild.ID) for i, g := range s.Guilds { if g.ID == guild.ID { s.Guilds = append(s.Guilds[:i], s.Guilds[i+1:]...) return nil } } return nil }
go
func (s *State) GuildRemove(guild *Guild) error { if s == nil { return ErrNilState } _, err := s.Guild(guild.ID) if err != nil { return err } s.Lock() defer s.Unlock() delete(s.guildMap, guild.ID) for i, g := range s.Guilds { if g.ID == guild.ID { s.Guilds = append(s.Guilds[:i], s.Guilds[i+1:]...) return nil } } return nil }
[ "func", "(", "s", "*", "State", ")", "GuildRemove", "(", "guild", "*", "Guild", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "_", ",", "err", ":=", "s", ".", "Guild", "(", "guild", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "s", ".", "guildMap", ",", "guild", ".", "ID", ")", "\n\n", "for", "i", ",", "g", ":=", "range", "s", ".", "Guilds", "{", "if", "g", ".", "ID", "==", "guild", ".", "ID", "{", "s", ".", "Guilds", "=", "append", "(", "s", ".", "Guilds", "[", ":", "i", "]", ",", "s", ".", "Guilds", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// GuildRemove removes a guild from current world state.
[ "GuildRemove", "removes", "a", "guild", "from", "current", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L134-L157
train
bwmarrin/discordgo
state.go
Guild
func (s *State) Guild(guildID string) (*Guild, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() if g, ok := s.guildMap[guildID]; ok { return g, nil } return nil, ErrStateNotFound }
go
func (s *State) Guild(guildID string) (*Guild, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() if g, ok := s.guildMap[guildID]; ok { return g, nil } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Guild", "(", "guildID", "string", ")", "(", "*", "Guild", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n\n", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "if", "g", ",", "ok", ":=", "s", ".", "guildMap", "[", "guildID", "]", ";", "ok", "{", "return", "g", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "ErrStateNotFound", "\n", "}" ]
// Guild gets a guild by ID. // Useful for querying if @me is in a guild: // _, err := discordgo.Session.State.Guild(guildID) // isInGuild := err == nil
[ "Guild", "gets", "a", "guild", "by", "ID", ".", "Useful", "for", "querying", "if" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L163-L176
train
bwmarrin/discordgo
state.go
PresenceAdd
func (s *State) PresenceAdd(guildID string, presence *Presence) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, p := range guild.Presences { if p.User.ID == presence.User.ID { //guild.Presences[i] = presence //Update status guild.Presences[i].Game = presence.Game guild.Presences[i].Roles = presence.Roles if presence.Status != "" { guild.Presences[i].Status = presence.Status } if presence.Nick != "" { guild.Presences[i].Nick = presence.Nick } //Update the optionally sent user information //ID Is a mandatory field so you should not need to check if it is empty guild.Presences[i].User.ID = presence.User.ID if presence.User.Avatar != "" { guild.Presences[i].User.Avatar = presence.User.Avatar } if presence.User.Discriminator != "" { guild.Presences[i].User.Discriminator = presence.User.Discriminator } if presence.User.Email != "" { guild.Presences[i].User.Email = presence.User.Email } if presence.User.Token != "" { guild.Presences[i].User.Token = presence.User.Token } if presence.User.Username != "" { guild.Presences[i].User.Username = presence.User.Username } return nil } } guild.Presences = append(guild.Presences, presence) return nil }
go
func (s *State) PresenceAdd(guildID string, presence *Presence) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, p := range guild.Presences { if p.User.ID == presence.User.ID { //guild.Presences[i] = presence //Update status guild.Presences[i].Game = presence.Game guild.Presences[i].Roles = presence.Roles if presence.Status != "" { guild.Presences[i].Status = presence.Status } if presence.Nick != "" { guild.Presences[i].Nick = presence.Nick } //Update the optionally sent user information //ID Is a mandatory field so you should not need to check if it is empty guild.Presences[i].User.ID = presence.User.ID if presence.User.Avatar != "" { guild.Presences[i].User.Avatar = presence.User.Avatar } if presence.User.Discriminator != "" { guild.Presences[i].User.Discriminator = presence.User.Discriminator } if presence.User.Email != "" { guild.Presences[i].User.Email = presence.User.Email } if presence.User.Token != "" { guild.Presences[i].User.Token = presence.User.Token } if presence.User.Username != "" { guild.Presences[i].User.Username = presence.User.Username } return nil } } guild.Presences = append(guild.Presences, presence) return nil }
[ "func", "(", "s", "*", "State", ")", "PresenceAdd", "(", "guildID", "string", ",", "presence", "*", "Presence", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "guildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "for", "i", ",", "p", ":=", "range", "guild", ".", "Presences", "{", "if", "p", ".", "User", ".", "ID", "==", "presence", ".", "User", ".", "ID", "{", "//guild.Presences[i] = presence", "//Update status", "guild", ".", "Presences", "[", "i", "]", ".", "Game", "=", "presence", ".", "Game", "\n", "guild", ".", "Presences", "[", "i", "]", ".", "Roles", "=", "presence", ".", "Roles", "\n", "if", "presence", ".", "Status", "!=", "\"", "\"", "{", "guild", ".", "Presences", "[", "i", "]", ".", "Status", "=", "presence", ".", "Status", "\n", "}", "\n", "if", "presence", ".", "Nick", "!=", "\"", "\"", "{", "guild", ".", "Presences", "[", "i", "]", ".", "Nick", "=", "presence", ".", "Nick", "\n", "}", "\n\n", "//Update the optionally sent user information", "//ID Is a mandatory field so you should not need to check if it is empty", "guild", ".", "Presences", "[", "i", "]", ".", "User", ".", "ID", "=", "presence", ".", "User", ".", "ID", "\n\n", "if", "presence", ".", "User", ".", "Avatar", "!=", "\"", "\"", "{", "guild", ".", "Presences", "[", "i", "]", ".", "User", ".", "Avatar", "=", "presence", ".", "User", ".", "Avatar", "\n", "}", "\n", "if", "presence", ".", "User", ".", "Discriminator", "!=", "\"", "\"", "{", "guild", ".", "Presences", "[", "i", "]", ".", "User", ".", "Discriminator", "=", "presence", ".", "User", ".", "Discriminator", "\n", "}", "\n", "if", "presence", ".", "User", ".", "Email", "!=", "\"", "\"", "{", "guild", ".", "Presences", "[", "i", "]", ".", "User", ".", "Email", "=", "presence", ".", "User", ".", "Email", "\n", "}", "\n", "if", "presence", ".", "User", ".", "Token", "!=", "\"", "\"", "{", "guild", ".", "Presences", "[", "i", "]", ".", "User", ".", "Token", "=", "presence", ".", "User", ".", "Token", "\n", "}", "\n", "if", "presence", ".", "User", ".", "Username", "!=", "\"", "\"", "{", "guild", ".", "Presences", "[", "i", "]", ".", "User", ".", "Username", "=", "presence", ".", "User", ".", "Username", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "guild", ".", "Presences", "=", "append", "(", "guild", ".", "Presences", ",", "presence", ")", "\n", "return", "nil", "\n", "}" ]
// PresenceAdd adds a presence to the current world state, or // updates it if it already exists.
[ "PresenceAdd", "adds", "a", "presence", "to", "the", "current", "world", "state", "or", "updates", "it", "if", "it", "already", "exists", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L180-L233
train
bwmarrin/discordgo
state.go
PresenceRemove
func (s *State) PresenceRemove(guildID string, presence *Presence) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, p := range guild.Presences { if p.User.ID == presence.User.ID { guild.Presences = append(guild.Presences[:i], guild.Presences[i+1:]...) return nil } } return ErrStateNotFound }
go
func (s *State) PresenceRemove(guildID string, presence *Presence) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, p := range guild.Presences { if p.User.ID == presence.User.ID { guild.Presences = append(guild.Presences[:i], guild.Presences[i+1:]...) return nil } } return ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "PresenceRemove", "(", "guildID", "string", ",", "presence", "*", "Presence", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "guildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "for", "i", ",", "p", ":=", "range", "guild", ".", "Presences", "{", "if", "p", ".", "User", ".", "ID", "==", "presence", ".", "User", ".", "ID", "{", "guild", ".", "Presences", "=", "append", "(", "guild", ".", "Presences", "[", ":", "i", "]", ",", "guild", ".", "Presences", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "ErrStateNotFound", "\n", "}" ]
// PresenceRemove removes a presence from the current world state.
[ "PresenceRemove", "removes", "a", "presence", "from", "the", "current", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L236-L257
train
bwmarrin/discordgo
state.go
Presence
func (s *State) Presence(guildID, userID string) (*Presence, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } for _, p := range guild.Presences { if p.User.ID == userID { return p, nil } } return nil, ErrStateNotFound }
go
func (s *State) Presence(guildID, userID string) (*Presence, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } for _, p := range guild.Presences { if p.User.ID == userID { return p, nil } } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Presence", "(", "guildID", ",", "userID", "string", ")", "(", "*", "Presence", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "guildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "p", ":=", "range", "guild", ".", "Presences", "{", "if", "p", ".", "User", ".", "ID", "==", "userID", "{", "return", "p", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "ErrStateNotFound", "\n", "}" ]
// Presence gets a presence by ID from a guild.
[ "Presence", "gets", "a", "presence", "by", "ID", "from", "a", "guild", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L260-L277
train
bwmarrin/discordgo
state.go
MemberRemove
func (s *State) MemberRemove(member *Member) error { if s == nil { return ErrNilState } guild, err := s.Guild(member.GuildID) if err != nil { return err } s.Lock() defer s.Unlock() members, ok := s.memberMap[member.GuildID] if !ok { return ErrStateNotFound } _, ok = members[member.User.ID] if !ok { return ErrStateNotFound } delete(members, member.User.ID) for i, m := range guild.Members { if m.User.ID == member.User.ID { guild.Members = append(guild.Members[:i], guild.Members[i+1:]...) return nil } } return ErrStateNotFound }
go
func (s *State) MemberRemove(member *Member) error { if s == nil { return ErrNilState } guild, err := s.Guild(member.GuildID) if err != nil { return err } s.Lock() defer s.Unlock() members, ok := s.memberMap[member.GuildID] if !ok { return ErrStateNotFound } _, ok = members[member.User.ID] if !ok { return ErrStateNotFound } delete(members, member.User.ID) for i, m := range guild.Members { if m.User.ID == member.User.ID { guild.Members = append(guild.Members[:i], guild.Members[i+1:]...) return nil } } return ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "MemberRemove", "(", "member", "*", "Member", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "member", ".", "GuildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "members", ",", "ok", ":=", "s", ".", "memberMap", "[", "member", ".", "GuildID", "]", "\n", "if", "!", "ok", "{", "return", "ErrStateNotFound", "\n", "}", "\n\n", "_", ",", "ok", "=", "members", "[", "member", ".", "User", ".", "ID", "]", "\n", "if", "!", "ok", "{", "return", "ErrStateNotFound", "\n", "}", "\n", "delete", "(", "members", ",", "member", ".", "User", ".", "ID", ")", "\n\n", "for", "i", ",", "m", ":=", "range", "guild", ".", "Members", "{", "if", "m", ".", "User", ".", "ID", "==", "member", ".", "User", ".", "ID", "{", "guild", ".", "Members", "=", "append", "(", "guild", ".", "Members", "[", ":", "i", "]", ",", "guild", ".", "Members", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "ErrStateNotFound", "\n", "}" ]
// MemberRemove removes a member from current world state.
[ "MemberRemove", "removes", "a", "member", "from", "current", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L318-L350
train
bwmarrin/discordgo
state.go
Member
func (s *State) Member(guildID, userID string) (*Member, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() members, ok := s.memberMap[guildID] if !ok { return nil, ErrStateNotFound } m, ok := members[userID] if ok { return m, nil } return nil, ErrStateNotFound }
go
func (s *State) Member(guildID, userID string) (*Member, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() members, ok := s.memberMap[guildID] if !ok { return nil, ErrStateNotFound } m, ok := members[userID] if ok { return m, nil } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Member", "(", "guildID", ",", "userID", "string", ")", "(", "*", "Member", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n\n", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "members", ",", "ok", ":=", "s", ".", "memberMap", "[", "guildID", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "ErrStateNotFound", "\n", "}", "\n\n", "m", ",", "ok", ":=", "members", "[", "userID", "]", "\n", "if", "ok", "{", "return", "m", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "ErrStateNotFound", "\n", "}" ]
// Member gets a member by ID from a guild.
[ "Member", "gets", "a", "member", "by", "ID", "from", "a", "guild", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L353-L372
train
bwmarrin/discordgo
state.go
RoleAdd
func (s *State) RoleAdd(guildID string, role *Role) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, r := range guild.Roles { if r.ID == role.ID { guild.Roles[i] = role return nil } } guild.Roles = append(guild.Roles, role) return nil }
go
func (s *State) RoleAdd(guildID string, role *Role) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, r := range guild.Roles { if r.ID == role.ID { guild.Roles[i] = role return nil } } guild.Roles = append(guild.Roles, role) return nil }
[ "func", "(", "s", "*", "State", ")", "RoleAdd", "(", "guildID", "string", ",", "role", "*", "Role", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "guildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "for", "i", ",", "r", ":=", "range", "guild", ".", "Roles", "{", "if", "r", ".", "ID", "==", "role", ".", "ID", "{", "guild", ".", "Roles", "[", "i", "]", "=", "role", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "guild", ".", "Roles", "=", "append", "(", "guild", ".", "Roles", ",", "role", ")", "\n", "return", "nil", "\n", "}" ]
// RoleAdd adds a role to the current world state, or // updates it if it already exists.
[ "RoleAdd", "adds", "a", "role", "to", "the", "current", "world", "state", "or", "updates", "it", "if", "it", "already", "exists", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L376-L398
train
bwmarrin/discordgo
state.go
RoleRemove
func (s *State) RoleRemove(guildID, roleID string) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, r := range guild.Roles { if r.ID == roleID { guild.Roles = append(guild.Roles[:i], guild.Roles[i+1:]...) return nil } } return ErrStateNotFound }
go
func (s *State) RoleRemove(guildID, roleID string) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, r := range guild.Roles { if r.ID == roleID { guild.Roles = append(guild.Roles[:i], guild.Roles[i+1:]...) return nil } } return ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "RoleRemove", "(", "guildID", ",", "roleID", "string", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "guildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "for", "i", ",", "r", ":=", "range", "guild", ".", "Roles", "{", "if", "r", ".", "ID", "==", "roleID", "{", "guild", ".", "Roles", "=", "append", "(", "guild", ".", "Roles", "[", ":", "i", "]", ",", "guild", ".", "Roles", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "ErrStateNotFound", "\n", "}" ]
// RoleRemove removes a role from current world state by ID.
[ "RoleRemove", "removes", "a", "role", "from", "current", "world", "state", "by", "ID", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L401-L422
train
bwmarrin/discordgo
state.go
Role
func (s *State) Role(guildID, roleID string) (*Role, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, r := range guild.Roles { if r.ID == roleID { return r, nil } } return nil, ErrStateNotFound }
go
func (s *State) Role(guildID, roleID string) (*Role, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, r := range guild.Roles { if r.ID == roleID { return r, nil } } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Role", "(", "guildID", ",", "roleID", "string", ")", "(", "*", "Role", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "guildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "for", "_", ",", "r", ":=", "range", "guild", ".", "Roles", "{", "if", "r", ".", "ID", "==", "roleID", "{", "return", "r", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "ErrStateNotFound", "\n", "}" ]
// Role gets a role by ID from a guild.
[ "Role", "gets", "a", "role", "by", "ID", "from", "a", "guild", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L425-L445
train
bwmarrin/discordgo
state.go
ChannelAdd
func (s *State) ChannelAdd(channel *Channel) error { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // If the channel exists, replace it if c, ok := s.channelMap[channel.ID]; ok { if channel.Messages == nil { channel.Messages = c.Messages } if channel.PermissionOverwrites == nil { channel.PermissionOverwrites = c.PermissionOverwrites } *c = *channel return nil } if channel.Type == ChannelTypeDM || channel.Type == ChannelTypeGroupDM { s.PrivateChannels = append(s.PrivateChannels, channel) } else { guild, ok := s.guildMap[channel.GuildID] if !ok { return ErrStateNotFound } guild.Channels = append(guild.Channels, channel) } s.channelMap[channel.ID] = channel return nil }
go
func (s *State) ChannelAdd(channel *Channel) error { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // If the channel exists, replace it if c, ok := s.channelMap[channel.ID]; ok { if channel.Messages == nil { channel.Messages = c.Messages } if channel.PermissionOverwrites == nil { channel.PermissionOverwrites = c.PermissionOverwrites } *c = *channel return nil } if channel.Type == ChannelTypeDM || channel.Type == ChannelTypeGroupDM { s.PrivateChannels = append(s.PrivateChannels, channel) } else { guild, ok := s.guildMap[channel.GuildID] if !ok { return ErrStateNotFound } guild.Channels = append(guild.Channels, channel) } s.channelMap[channel.ID] = channel return nil }
[ "func", "(", "s", "*", "State", ")", "ChannelAdd", "(", "channel", "*", "Channel", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "// If the channel exists, replace it", "if", "c", ",", "ok", ":=", "s", ".", "channelMap", "[", "channel", ".", "ID", "]", ";", "ok", "{", "if", "channel", ".", "Messages", "==", "nil", "{", "channel", ".", "Messages", "=", "c", ".", "Messages", "\n", "}", "\n", "if", "channel", ".", "PermissionOverwrites", "==", "nil", "{", "channel", ".", "PermissionOverwrites", "=", "c", ".", "PermissionOverwrites", "\n", "}", "\n\n", "*", "c", "=", "*", "channel", "\n", "return", "nil", "\n", "}", "\n\n", "if", "channel", ".", "Type", "==", "ChannelTypeDM", "||", "channel", ".", "Type", "==", "ChannelTypeGroupDM", "{", "s", ".", "PrivateChannels", "=", "append", "(", "s", ".", "PrivateChannels", ",", "channel", ")", "\n", "}", "else", "{", "guild", ",", "ok", ":=", "s", ".", "guildMap", "[", "channel", ".", "GuildID", "]", "\n", "if", "!", "ok", "{", "return", "ErrStateNotFound", "\n", "}", "\n\n", "guild", ".", "Channels", "=", "append", "(", "guild", ".", "Channels", ",", "channel", ")", "\n", "}", "\n\n", "s", ".", "channelMap", "[", "channel", ".", "ID", "]", "=", "channel", "\n\n", "return", "nil", "\n", "}" ]
// ChannelAdd adds a channel to the current world state, or // updates it if it already exists. // Channels may exist either as PrivateChannels or inside // a guild.
[ "ChannelAdd", "adds", "a", "channel", "to", "the", "current", "world", "state", "or", "updates", "it", "if", "it", "already", "exists", ".", "Channels", "may", "exist", "either", "as", "PrivateChannels", "or", "inside", "a", "guild", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L451-L486
train
bwmarrin/discordgo
state.go
ChannelRemove
func (s *State) ChannelRemove(channel *Channel) error { if s == nil { return ErrNilState } _, err := s.Channel(channel.ID) if err != nil { return err } if channel.Type == ChannelTypeDM || channel.Type == ChannelTypeGroupDM { s.Lock() defer s.Unlock() for i, c := range s.PrivateChannels { if c.ID == channel.ID { s.PrivateChannels = append(s.PrivateChannels[:i], s.PrivateChannels[i+1:]...) break } } } else { guild, err := s.Guild(channel.GuildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, c := range guild.Channels { if c.ID == channel.ID { guild.Channels = append(guild.Channels[:i], guild.Channels[i+1:]...) break } } } delete(s.channelMap, channel.ID) return nil }
go
func (s *State) ChannelRemove(channel *Channel) error { if s == nil { return ErrNilState } _, err := s.Channel(channel.ID) if err != nil { return err } if channel.Type == ChannelTypeDM || channel.Type == ChannelTypeGroupDM { s.Lock() defer s.Unlock() for i, c := range s.PrivateChannels { if c.ID == channel.ID { s.PrivateChannels = append(s.PrivateChannels[:i], s.PrivateChannels[i+1:]...) break } } } else { guild, err := s.Guild(channel.GuildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, c := range guild.Channels { if c.ID == channel.ID { guild.Channels = append(guild.Channels[:i], guild.Channels[i+1:]...) break } } } delete(s.channelMap, channel.ID) return nil }
[ "func", "(", "s", "*", "State", ")", "ChannelRemove", "(", "channel", "*", "Channel", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "_", ",", "err", ":=", "s", ".", "Channel", "(", "channel", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "channel", ".", "Type", "==", "ChannelTypeDM", "||", "channel", ".", "Type", "==", "ChannelTypeGroupDM", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "for", "i", ",", "c", ":=", "range", "s", ".", "PrivateChannels", "{", "if", "c", ".", "ID", "==", "channel", ".", "ID", "{", "s", ".", "PrivateChannels", "=", "append", "(", "s", ".", "PrivateChannels", "[", ":", "i", "]", ",", "s", ".", "PrivateChannels", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "else", "{", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "channel", ".", "GuildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "for", "i", ",", "c", ":=", "range", "guild", ".", "Channels", "{", "if", "c", ".", "ID", "==", "channel", ".", "ID", "{", "guild", ".", "Channels", "=", "append", "(", "guild", ".", "Channels", "[", ":", "i", "]", ",", "guild", ".", "Channels", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "delete", "(", "s", ".", "channelMap", ",", "channel", ".", "ID", ")", "\n\n", "return", "nil", "\n", "}" ]
// ChannelRemove removes a channel from current world state.
[ "ChannelRemove", "removes", "a", "channel", "from", "current", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L489-L529
train
bwmarrin/discordgo
state.go
Channel
func (s *State) Channel(channelID string) (*Channel, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() if c, ok := s.channelMap[channelID]; ok { return c, nil } return nil, ErrStateNotFound }
go
func (s *State) Channel(channelID string) (*Channel, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() if c, ok := s.channelMap[channelID]; ok { return c, nil } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Channel", "(", "channelID", "string", ")", "(", "*", "Channel", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n\n", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "if", "c", ",", "ok", ":=", "s", ".", "channelMap", "[", "channelID", "]", ";", "ok", "{", "return", "c", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "ErrStateNotFound", "\n", "}" ]
// Channel gets a channel by ID, it will look in all guilds and private channels.
[ "Channel", "gets", "a", "channel", "by", "ID", "it", "will", "look", "in", "all", "guilds", "and", "private", "channels", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L544-L557
train
bwmarrin/discordgo
state.go
Emoji
func (s *State) Emoji(guildID, emojiID string) (*Emoji, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, e := range guild.Emojis { if e.ID == emojiID { return e, nil } } return nil, ErrStateNotFound }
go
func (s *State) Emoji(guildID, emojiID string) (*Emoji, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, e := range guild.Emojis { if e.ID == emojiID { return e, nil } } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Emoji", "(", "guildID", ",", "emojiID", "string", ")", "(", "*", "Emoji", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "guildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "for", "_", ",", "e", ":=", "range", "guild", ".", "Emojis", "{", "if", "e", ".", "ID", "==", "emojiID", "{", "return", "e", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "ErrStateNotFound", "\n", "}" ]
// Emoji returns an emoji for a guild and emoji id.
[ "Emoji", "returns", "an", "emoji", "for", "a", "guild", "and", "emoji", "id", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L560-L580
train
bwmarrin/discordgo
state.go
EmojiAdd
func (s *State) EmojiAdd(guildID string, emoji *Emoji) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, e := range guild.Emojis { if e.ID == emoji.ID { guild.Emojis[i] = emoji return nil } } guild.Emojis = append(guild.Emojis, emoji) return nil }
go
func (s *State) EmojiAdd(guildID string, emoji *Emoji) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, e := range guild.Emojis { if e.ID == emoji.ID { guild.Emojis[i] = emoji return nil } } guild.Emojis = append(guild.Emojis, emoji) return nil }
[ "func", "(", "s", "*", "State", ")", "EmojiAdd", "(", "guildID", "string", ",", "emoji", "*", "Emoji", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "guildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "for", "i", ",", "e", ":=", "range", "guild", ".", "Emojis", "{", "if", "e", ".", "ID", "==", "emoji", ".", "ID", "{", "guild", ".", "Emojis", "[", "i", "]", "=", "emoji", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "guild", ".", "Emojis", "=", "append", "(", "guild", ".", "Emojis", ",", "emoji", ")", "\n", "return", "nil", "\n", "}" ]
// EmojiAdd adds an emoji to the current world state.
[ "EmojiAdd", "adds", "an", "emoji", "to", "the", "current", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L583-L605
train
bwmarrin/discordgo
state.go
EmojisAdd
func (s *State) EmojisAdd(guildID string, emojis []*Emoji) error { for _, e := range emojis { if err := s.EmojiAdd(guildID, e); err != nil { return err } } return nil }
go
func (s *State) EmojisAdd(guildID string, emojis []*Emoji) error { for _, e := range emojis { if err := s.EmojiAdd(guildID, e); err != nil { return err } } return nil }
[ "func", "(", "s", "*", "State", ")", "EmojisAdd", "(", "guildID", "string", ",", "emojis", "[", "]", "*", "Emoji", ")", "error", "{", "for", "_", ",", "e", ":=", "range", "emojis", "{", "if", "err", ":=", "s", ".", "EmojiAdd", "(", "guildID", ",", "e", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// EmojisAdd adds multiple emojis to the world state.
[ "EmojisAdd", "adds", "multiple", "emojis", "to", "the", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L608-L615
train
bwmarrin/discordgo
state.go
MessageAdd
func (s *State) MessageAdd(message *Message) error { if s == nil { return ErrNilState } c, err := s.Channel(message.ChannelID) if err != nil { return err } s.Lock() defer s.Unlock() // If the message exists, merge in the new message contents. for _, m := range c.Messages { if m.ID == message.ID { if message.Content != "" { m.Content = message.Content } if message.EditedTimestamp != "" { m.EditedTimestamp = message.EditedTimestamp } if message.Mentions != nil { m.Mentions = message.Mentions } if message.Embeds != nil { m.Embeds = message.Embeds } if message.Attachments != nil { m.Attachments = message.Attachments } if message.Timestamp != "" { m.Timestamp = message.Timestamp } if message.Author != nil { m.Author = message.Author } return nil } } c.Messages = append(c.Messages, message) if len(c.Messages) > s.MaxMessageCount { c.Messages = c.Messages[len(c.Messages)-s.MaxMessageCount:] } return nil }
go
func (s *State) MessageAdd(message *Message) error { if s == nil { return ErrNilState } c, err := s.Channel(message.ChannelID) if err != nil { return err } s.Lock() defer s.Unlock() // If the message exists, merge in the new message contents. for _, m := range c.Messages { if m.ID == message.ID { if message.Content != "" { m.Content = message.Content } if message.EditedTimestamp != "" { m.EditedTimestamp = message.EditedTimestamp } if message.Mentions != nil { m.Mentions = message.Mentions } if message.Embeds != nil { m.Embeds = message.Embeds } if message.Attachments != nil { m.Attachments = message.Attachments } if message.Timestamp != "" { m.Timestamp = message.Timestamp } if message.Author != nil { m.Author = message.Author } return nil } } c.Messages = append(c.Messages, message) if len(c.Messages) > s.MaxMessageCount { c.Messages = c.Messages[len(c.Messages)-s.MaxMessageCount:] } return nil }
[ "func", "(", "s", "*", "State", ")", "MessageAdd", "(", "message", "*", "Message", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "c", ",", "err", ":=", "s", ".", "Channel", "(", "message", ".", "ChannelID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "// If the message exists, merge in the new message contents.", "for", "_", ",", "m", ":=", "range", "c", ".", "Messages", "{", "if", "m", ".", "ID", "==", "message", ".", "ID", "{", "if", "message", ".", "Content", "!=", "\"", "\"", "{", "m", ".", "Content", "=", "message", ".", "Content", "\n", "}", "\n", "if", "message", ".", "EditedTimestamp", "!=", "\"", "\"", "{", "m", ".", "EditedTimestamp", "=", "message", ".", "EditedTimestamp", "\n", "}", "\n", "if", "message", ".", "Mentions", "!=", "nil", "{", "m", ".", "Mentions", "=", "message", ".", "Mentions", "\n", "}", "\n", "if", "message", ".", "Embeds", "!=", "nil", "{", "m", ".", "Embeds", "=", "message", ".", "Embeds", "\n", "}", "\n", "if", "message", ".", "Attachments", "!=", "nil", "{", "m", ".", "Attachments", "=", "message", ".", "Attachments", "\n", "}", "\n", "if", "message", ".", "Timestamp", "!=", "\"", "\"", "{", "m", ".", "Timestamp", "=", "message", ".", "Timestamp", "\n", "}", "\n", "if", "message", ".", "Author", "!=", "nil", "{", "m", ".", "Author", "=", "message", ".", "Author", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "c", ".", "Messages", "=", "append", "(", "c", ".", "Messages", ",", "message", ")", "\n\n", "if", "len", "(", "c", ".", "Messages", ")", ">", "s", ".", "MaxMessageCount", "{", "c", ".", "Messages", "=", "c", ".", "Messages", "[", "len", "(", "c", ".", "Messages", ")", "-", "s", ".", "MaxMessageCount", ":", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MessageAdd adds a message to the current world state, or updates it if it exists. // If the channel cannot be found, the message is discarded. // Messages are kept in state up to s.MaxMessageCount per channel.
[ "MessageAdd", "adds", "a", "message", "to", "the", "current", "world", "state", "or", "updates", "it", "if", "it", "exists", ".", "If", "the", "channel", "cannot", "be", "found", "the", "message", "is", "discarded", ".", "Messages", "are", "kept", "in", "state", "up", "to", "s", ".", "MaxMessageCount", "per", "channel", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L620-L668
train
bwmarrin/discordgo
state.go
MessageRemove
func (s *State) MessageRemove(message *Message) error { if s == nil { return ErrNilState } return s.messageRemoveByID(message.ChannelID, message.ID) }
go
func (s *State) MessageRemove(message *Message) error { if s == nil { return ErrNilState } return s.messageRemoveByID(message.ChannelID, message.ID) }
[ "func", "(", "s", "*", "State", ")", "MessageRemove", "(", "message", "*", "Message", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "return", "s", ".", "messageRemoveByID", "(", "message", ".", "ChannelID", ",", "message", ".", "ID", ")", "\n", "}" ]
// MessageRemove removes a message from the world state.
[ "MessageRemove", "removes", "a", "message", "from", "the", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L671-L677
train
bwmarrin/discordgo
state.go
messageRemoveByID
func (s *State) messageRemoveByID(channelID, messageID string) error { c, err := s.Channel(channelID) if err != nil { return err } s.Lock() defer s.Unlock() for i, m := range c.Messages { if m.ID == messageID { c.Messages = append(c.Messages[:i], c.Messages[i+1:]...) return nil } } return ErrStateNotFound }
go
func (s *State) messageRemoveByID(channelID, messageID string) error { c, err := s.Channel(channelID) if err != nil { return err } s.Lock() defer s.Unlock() for i, m := range c.Messages { if m.ID == messageID { c.Messages = append(c.Messages[:i], c.Messages[i+1:]...) return nil } } return ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "messageRemoveByID", "(", "channelID", ",", "messageID", "string", ")", "error", "{", "c", ",", "err", ":=", "s", ".", "Channel", "(", "channelID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "for", "i", ",", "m", ":=", "range", "c", ".", "Messages", "{", "if", "m", ".", "ID", "==", "messageID", "{", "c", ".", "Messages", "=", "append", "(", "c", ".", "Messages", "[", ":", "i", "]", ",", "c", ".", "Messages", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "ErrStateNotFound", "\n", "}" ]
// messageRemoveByID removes a message by channelID and messageID from the world state.
[ "messageRemoveByID", "removes", "a", "message", "by", "channelID", "and", "messageID", "from", "the", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L680-L697
train
bwmarrin/discordgo
state.go
Message
func (s *State) Message(channelID, messageID string) (*Message, error) { if s == nil { return nil, ErrNilState } c, err := s.Channel(channelID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, m := range c.Messages { if m.ID == messageID { return m, nil } } return nil, ErrStateNotFound }
go
func (s *State) Message(channelID, messageID string) (*Message, error) { if s == nil { return nil, ErrNilState } c, err := s.Channel(channelID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, m := range c.Messages { if m.ID == messageID { return m, nil } } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Message", "(", "channelID", ",", "messageID", "string", ")", "(", "*", "Message", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n\n", "c", ",", "err", ":=", "s", ".", "Channel", "(", "channelID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "for", "_", ",", "m", ":=", "range", "c", ".", "Messages", "{", "if", "m", ".", "ID", "==", "messageID", "{", "return", "m", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "ErrStateNotFound", "\n", "}" ]
// Message gets a message by channel and message ID.
[ "Message", "gets", "a", "message", "by", "channel", "and", "message", "ID", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L731-L751
train
bwmarrin/discordgo
state.go
onReady
func (s *State) onReady(se *Session, r *Ready) (err error) { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // We must track at least the current user for Voice, even // if state is disabled, store the bare essentials. if !se.StateEnabled { ready := Ready{ Version: r.Version, SessionID: r.SessionID, User: r.User, } s.Ready = ready return nil } s.Ready = *r for _, g := range s.Guilds { s.guildMap[g.ID] = g s.createMemberMap(g) for _, c := range g.Channels { s.channelMap[c.ID] = c } } for _, c := range s.PrivateChannels { s.channelMap[c.ID] = c } return nil }
go
func (s *State) onReady(se *Session, r *Ready) (err error) { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // We must track at least the current user for Voice, even // if state is disabled, store the bare essentials. if !se.StateEnabled { ready := Ready{ Version: r.Version, SessionID: r.SessionID, User: r.User, } s.Ready = ready return nil } s.Ready = *r for _, g := range s.Guilds { s.guildMap[g.ID] = g s.createMemberMap(g) for _, c := range g.Channels { s.channelMap[c.ID] = c } } for _, c := range s.PrivateChannels { s.channelMap[c.ID] = c } return nil }
[ "func", "(", "s", "*", "State", ")", "onReady", "(", "se", "*", "Session", ",", "r", "*", "Ready", ")", "(", "err", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "// We must track at least the current user for Voice, even", "// if state is disabled, store the bare essentials.", "if", "!", "se", ".", "StateEnabled", "{", "ready", ":=", "Ready", "{", "Version", ":", "r", ".", "Version", ",", "SessionID", ":", "r", ".", "SessionID", ",", "User", ":", "r", ".", "User", ",", "}", "\n\n", "s", ".", "Ready", "=", "ready", "\n\n", "return", "nil", "\n", "}", "\n\n", "s", ".", "Ready", "=", "*", "r", "\n\n", "for", "_", ",", "g", ":=", "range", "s", ".", "Guilds", "{", "s", ".", "guildMap", "[", "g", ".", "ID", "]", "=", "g", "\n", "s", ".", "createMemberMap", "(", "g", ")", "\n\n", "for", "_", ",", "c", ":=", "range", "g", ".", "Channels", "{", "s", ".", "channelMap", "[", "c", ".", "ID", "]", "=", "c", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "c", ":=", "range", "s", ".", "PrivateChannels", "{", "s", ".", "channelMap", "[", "c", ".", "ID", "]", "=", "c", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// OnReady takes a Ready event and updates all internal state.
[ "OnReady", "takes", "a", "Ready", "event", "and", "updates", "all", "internal", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L754-L792
train
bwmarrin/discordgo
state.go
UserColor
func (s *State) UserColor(userID, channelID string) int { if s == nil { return 0 } channel, err := s.Channel(channelID) if err != nil { return 0 } guild, err := s.Guild(channel.GuildID) if err != nil { return 0 } member, err := s.Member(guild.ID, userID) if err != nil { return 0 } roles := Roles(guild.Roles) sort.Sort(roles) for _, role := range roles { for _, roleID := range member.Roles { if role.ID == roleID { if role.Color != 0 { return role.Color } } } } return 0 }
go
func (s *State) UserColor(userID, channelID string) int { if s == nil { return 0 } channel, err := s.Channel(channelID) if err != nil { return 0 } guild, err := s.Guild(channel.GuildID) if err != nil { return 0 } member, err := s.Member(guild.ID, userID) if err != nil { return 0 } roles := Roles(guild.Roles) sort.Sort(roles) for _, role := range roles { for _, roleID := range member.Roles { if role.ID == roleID { if role.Color != 0 { return role.Color } } } } return 0 }
[ "func", "(", "s", "*", "State", ")", "UserColor", "(", "userID", ",", "channelID", "string", ")", "int", "{", "if", "s", "==", "nil", "{", "return", "0", "\n", "}", "\n\n", "channel", ",", "err", ":=", "s", ".", "Channel", "(", "channelID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "channel", ".", "GuildID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n\n", "member", ",", "err", ":=", "s", ".", "Member", "(", "guild", ".", "ID", ",", "userID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n\n", "roles", ":=", "Roles", "(", "guild", ".", "Roles", ")", "\n", "sort", ".", "Sort", "(", "roles", ")", "\n\n", "for", "_", ",", "role", ":=", "range", "roles", "{", "for", "_", ",", "roleID", ":=", "range", "member", ".", "Roles", "{", "if", "role", ".", "ID", "==", "roleID", "{", "if", "role", ".", "Color", "!=", "0", "{", "return", "role", ".", "Color", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "0", "\n", "}" ]
// UserColor returns the color of a user in a channel. // While colors are defined at a Guild level, determining for a channel is more useful in message handlers. // 0 is returned in cases of error, which is the color of @everyone. // userID : The ID of the user to calculate the color for. // channelID : The ID of the channel to calculate the color for.
[ "UserColor", "returns", "the", "color", "of", "a", "user", "in", "a", "channel", ".", "While", "colors", "are", "defined", "at", "a", "Guild", "level", "determining", "for", "a", "channel", "is", "more", "useful", "in", "message", "handlers", ".", "0", "is", "returned", "in", "cases", "of", "error", "which", "is", "the", "color", "of" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L981-L1015
train
bwmarrin/discordgo
voice.go
ChangeChannel
func (v *VoiceConnection) ChangeChannel(channelID string, mute, deaf bool) (err error) { v.log(LogInformational, "called") data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, &channelID, mute, deaf}} v.wsMutex.Lock() err = v.session.wsConn.WriteJSON(data) v.wsMutex.Unlock() if err != nil { return } v.ChannelID = channelID v.deaf = deaf v.mute = mute v.speaking = false return }
go
func (v *VoiceConnection) ChangeChannel(channelID string, mute, deaf bool) (err error) { v.log(LogInformational, "called") data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, &channelID, mute, deaf}} v.wsMutex.Lock() err = v.session.wsConn.WriteJSON(data) v.wsMutex.Unlock() if err != nil { return } v.ChannelID = channelID v.deaf = deaf v.mute = mute v.speaking = false return }
[ "func", "(", "v", "*", "VoiceConnection", ")", "ChangeChannel", "(", "channelID", "string", ",", "mute", ",", "deaf", "bool", ")", "(", "err", "error", ")", "{", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ")", "\n\n", "data", ":=", "voiceChannelJoinOp", "{", "4", ",", "voiceChannelJoinData", "{", "&", "v", ".", "GuildID", ",", "&", "channelID", ",", "mute", ",", "deaf", "}", "}", "\n", "v", ".", "wsMutex", ".", "Lock", "(", ")", "\n", "err", "=", "v", ".", "session", ".", "wsConn", ".", "WriteJSON", "(", "data", ")", "\n", "v", ".", "wsMutex", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "v", ".", "ChannelID", "=", "channelID", "\n", "v", ".", "deaf", "=", "deaf", "\n", "v", ".", "mute", "=", "mute", "\n", "v", ".", "speaking", "=", "false", "\n\n", "return", "\n", "}" ]
// ChangeChannel sends Discord a request to change channels within a Guild // !!! NOTE !!! This function may be removed in favour of just using ChannelVoiceJoin
[ "ChangeChannel", "sends", "Discord", "a", "request", "to", "change", "channels", "within", "a", "Guild", "!!!", "NOTE", "!!!", "This", "function", "may", "be", "removed", "in", "favour", "of", "just", "using", "ChannelVoiceJoin" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L118-L135
train
bwmarrin/discordgo
voice.go
Disconnect
func (v *VoiceConnection) Disconnect() (err error) { // Send a OP4 with a nil channel to disconnect if v.sessionID != "" { data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}} v.session.wsMutex.Lock() err = v.session.wsConn.WriteJSON(data) v.session.wsMutex.Unlock() v.sessionID = "" } // Close websocket and udp connections v.Close() v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID) v.session.Lock() delete(v.session.VoiceConnections, v.GuildID) v.session.Unlock() return }
go
func (v *VoiceConnection) Disconnect() (err error) { // Send a OP4 with a nil channel to disconnect if v.sessionID != "" { data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}} v.session.wsMutex.Lock() err = v.session.wsConn.WriteJSON(data) v.session.wsMutex.Unlock() v.sessionID = "" } // Close websocket and udp connections v.Close() v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID) v.session.Lock() delete(v.session.VoiceConnections, v.GuildID) v.session.Unlock() return }
[ "func", "(", "v", "*", "VoiceConnection", ")", "Disconnect", "(", ")", "(", "err", "error", ")", "{", "// Send a OP4 with a nil channel to disconnect", "if", "v", ".", "sessionID", "!=", "\"", "\"", "{", "data", ":=", "voiceChannelJoinOp", "{", "4", ",", "voiceChannelJoinData", "{", "&", "v", ".", "GuildID", ",", "nil", ",", "true", ",", "true", "}", "}", "\n", "v", ".", "session", ".", "wsMutex", ".", "Lock", "(", ")", "\n", "err", "=", "v", ".", "session", ".", "wsConn", ".", "WriteJSON", "(", "data", ")", "\n", "v", ".", "session", ".", "wsMutex", ".", "Unlock", "(", ")", "\n", "v", ".", "sessionID", "=", "\"", "\"", "\n", "}", "\n\n", "// Close websocket and udp connections", "v", ".", "Close", "(", ")", "\n\n", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ",", "v", ".", "GuildID", ")", "\n\n", "v", ".", "session", ".", "Lock", "(", ")", "\n", "delete", "(", "v", ".", "session", ".", "VoiceConnections", ",", "v", ".", "GuildID", ")", "\n", "v", ".", "session", ".", "Unlock", "(", ")", "\n\n", "return", "\n", "}" ]
// Disconnect disconnects from this voice channel and closes the websocket // and udp connections to Discord.
[ "Disconnect", "disconnects", "from", "this", "voice", "channel", "and", "closes", "the", "websocket", "and", "udp", "connections", "to", "Discord", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L139-L160
train
bwmarrin/discordgo
voice.go
Close
func (v *VoiceConnection) Close() { v.log(LogInformational, "called") v.Lock() defer v.Unlock() v.Ready = false v.speaking = false if v.close != nil { v.log(LogInformational, "closing v.close") close(v.close) v.close = nil } if v.udpConn != nil { v.log(LogInformational, "closing udp") err := v.udpConn.Close() if err != nil { v.log(LogError, "error closing udp connection, %s", err) } v.udpConn = nil } if v.wsConn != nil { v.log(LogInformational, "sending close frame") // To cleanly close a connection, a client should send a close // frame and wait for the server to close the connection. v.wsMutex.Lock() err := v.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) v.wsMutex.Unlock() if err != nil { v.log(LogError, "error closing websocket, %s", err) } // TODO: Wait for Discord to actually close the connection. time.Sleep(1 * time.Second) v.log(LogInformational, "closing websocket") err = v.wsConn.Close() if err != nil { v.log(LogError, "error closing websocket, %s", err) } v.wsConn = nil } }
go
func (v *VoiceConnection) Close() { v.log(LogInformational, "called") v.Lock() defer v.Unlock() v.Ready = false v.speaking = false if v.close != nil { v.log(LogInformational, "closing v.close") close(v.close) v.close = nil } if v.udpConn != nil { v.log(LogInformational, "closing udp") err := v.udpConn.Close() if err != nil { v.log(LogError, "error closing udp connection, %s", err) } v.udpConn = nil } if v.wsConn != nil { v.log(LogInformational, "sending close frame") // To cleanly close a connection, a client should send a close // frame and wait for the server to close the connection. v.wsMutex.Lock() err := v.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) v.wsMutex.Unlock() if err != nil { v.log(LogError, "error closing websocket, %s", err) } // TODO: Wait for Discord to actually close the connection. time.Sleep(1 * time.Second) v.log(LogInformational, "closing websocket") err = v.wsConn.Close() if err != nil { v.log(LogError, "error closing websocket, %s", err) } v.wsConn = nil } }
[ "func", "(", "v", "*", "VoiceConnection", ")", "Close", "(", ")", "{", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ")", "\n\n", "v", ".", "Lock", "(", ")", "\n", "defer", "v", ".", "Unlock", "(", ")", "\n\n", "v", ".", "Ready", "=", "false", "\n", "v", ".", "speaking", "=", "false", "\n\n", "if", "v", ".", "close", "!=", "nil", "{", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ")", "\n", "close", "(", "v", ".", "close", ")", "\n", "v", ".", "close", "=", "nil", "\n", "}", "\n\n", "if", "v", ".", "udpConn", "!=", "nil", "{", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ")", "\n", "err", ":=", "v", ".", "udpConn", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogError", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "v", ".", "udpConn", "=", "nil", "\n", "}", "\n\n", "if", "v", ".", "wsConn", "!=", "nil", "{", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ")", "\n\n", "// To cleanly close a connection, a client should send a close", "// frame and wait for the server to close the connection.", "v", ".", "wsMutex", ".", "Lock", "(", ")", "\n", "err", ":=", "v", ".", "wsConn", ".", "WriteMessage", "(", "websocket", ".", "CloseMessage", ",", "websocket", ".", "FormatCloseMessage", "(", "websocket", ".", "CloseNormalClosure", ",", "\"", "\"", ")", ")", "\n", "v", ".", "wsMutex", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogError", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// TODO: Wait for Discord to actually close the connection.", "time", ".", "Sleep", "(", "1", "*", "time", ".", "Second", ")", "\n\n", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ")", "\n", "err", "=", "v", ".", "wsConn", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogError", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "v", ".", "wsConn", "=", "nil", "\n", "}", "\n", "}" ]
// Close closes the voice ws and udp connections
[ "Close", "closes", "the", "voice", "ws", "and", "udp", "connections" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L163-L211
train
bwmarrin/discordgo
voice.go
AddHandler
func (v *VoiceConnection) AddHandler(h VoiceSpeakingUpdateHandler) { v.Lock() defer v.Unlock() v.voiceSpeakingUpdateHandlers = append(v.voiceSpeakingUpdateHandlers, h) }
go
func (v *VoiceConnection) AddHandler(h VoiceSpeakingUpdateHandler) { v.Lock() defer v.Unlock() v.voiceSpeakingUpdateHandlers = append(v.voiceSpeakingUpdateHandlers, h) }
[ "func", "(", "v", "*", "VoiceConnection", ")", "AddHandler", "(", "h", "VoiceSpeakingUpdateHandler", ")", "{", "v", ".", "Lock", "(", ")", "\n", "defer", "v", ".", "Unlock", "(", ")", "\n\n", "v", ".", "voiceSpeakingUpdateHandlers", "=", "append", "(", "v", ".", "voiceSpeakingUpdateHandlers", ",", "h", ")", "\n", "}" ]
// AddHandler adds a Handler for VoiceSpeakingUpdate events.
[ "AddHandler", "adds", "a", "Handler", "for", "VoiceSpeakingUpdate", "events", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L214-L219
train
bwmarrin/discordgo
voice.go
waitUntilConnected
func (v *VoiceConnection) waitUntilConnected() error { v.log(LogInformational, "called") i := 0 for { v.RLock() ready := v.Ready v.RUnlock() if ready { return nil } if i > 10 { return fmt.Errorf("timeout waiting for voice") } time.Sleep(1 * time.Second) i++ } }
go
func (v *VoiceConnection) waitUntilConnected() error { v.log(LogInformational, "called") i := 0 for { v.RLock() ready := v.Ready v.RUnlock() if ready { return nil } if i > 10 { return fmt.Errorf("timeout waiting for voice") } time.Sleep(1 * time.Second) i++ } }
[ "func", "(", "v", "*", "VoiceConnection", ")", "waitUntilConnected", "(", ")", "error", "{", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ")", "\n\n", "i", ":=", "0", "\n", "for", "{", "v", ".", "RLock", "(", ")", "\n", "ready", ":=", "v", ".", "Ready", "\n", "v", ".", "RUnlock", "(", ")", "\n", "if", "ready", "{", "return", "nil", "\n", "}", "\n\n", "if", "i", ">", "10", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "time", ".", "Sleep", "(", "1", "*", "time", ".", "Second", ")", "\n", "i", "++", "\n", "}", "\n", "}" ]
// WaitUntilConnected waits for the Voice Connection to // become ready, if it does not become ready it returns an err
[ "WaitUntilConnected", "waits", "for", "the", "Voice", "Connection", "to", "become", "ready", "if", "it", "does", "not", "become", "ready", "it", "returns", "an", "err" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L250-L270
train
bwmarrin/discordgo
voice.go
open
func (v *VoiceConnection) open() (err error) { v.log(LogInformational, "called") v.Lock() defer v.Unlock() // Don't open a websocket if one is already open if v.wsConn != nil { v.log(LogWarning, "refusing to overwrite non-nil websocket") return } // TODO temp? loop to wait for the SessionID i := 0 for { if v.sessionID != "" { break } if i > 20 { // only loop for up to 1 second total return fmt.Errorf("did not receive voice Session ID in time") } time.Sleep(50 * time.Millisecond) i++ } // Connect to VoiceConnection Websocket vg := "wss://" + strings.TrimSuffix(v.endpoint, ":80") v.log(LogInformational, "connecting to voice endpoint %s", vg) v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil) if err != nil { v.log(LogWarning, "error connecting to voice endpoint %s, %s", vg, err) v.log(LogDebug, "voice struct: %#v\n", v) return } type voiceHandshakeData struct { ServerID string `json:"server_id"` UserID string `json:"user_id"` SessionID string `json:"session_id"` Token string `json:"token"` } type voiceHandshakeOp struct { Op int `json:"op"` // Always 0 Data voiceHandshakeData `json:"d"` } data := voiceHandshakeOp{0, voiceHandshakeData{v.GuildID, v.UserID, v.sessionID, v.token}} err = v.wsConn.WriteJSON(data) if err != nil { v.log(LogWarning, "error sending init packet, %s", err) return } v.close = make(chan struct{}) go v.wsListen(v.wsConn, v.close) // add loop/check for Ready bool here? // then return false if not ready? // but then wsListen will also err. return }
go
func (v *VoiceConnection) open() (err error) { v.log(LogInformational, "called") v.Lock() defer v.Unlock() // Don't open a websocket if one is already open if v.wsConn != nil { v.log(LogWarning, "refusing to overwrite non-nil websocket") return } // TODO temp? loop to wait for the SessionID i := 0 for { if v.sessionID != "" { break } if i > 20 { // only loop for up to 1 second total return fmt.Errorf("did not receive voice Session ID in time") } time.Sleep(50 * time.Millisecond) i++ } // Connect to VoiceConnection Websocket vg := "wss://" + strings.TrimSuffix(v.endpoint, ":80") v.log(LogInformational, "connecting to voice endpoint %s", vg) v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil) if err != nil { v.log(LogWarning, "error connecting to voice endpoint %s, %s", vg, err) v.log(LogDebug, "voice struct: %#v\n", v) return } type voiceHandshakeData struct { ServerID string `json:"server_id"` UserID string `json:"user_id"` SessionID string `json:"session_id"` Token string `json:"token"` } type voiceHandshakeOp struct { Op int `json:"op"` // Always 0 Data voiceHandshakeData `json:"d"` } data := voiceHandshakeOp{0, voiceHandshakeData{v.GuildID, v.UserID, v.sessionID, v.token}} err = v.wsConn.WriteJSON(data) if err != nil { v.log(LogWarning, "error sending init packet, %s", err) return } v.close = make(chan struct{}) go v.wsListen(v.wsConn, v.close) // add loop/check for Ready bool here? // then return false if not ready? // but then wsListen will also err. return }
[ "func", "(", "v", "*", "VoiceConnection", ")", "open", "(", ")", "(", "err", "error", ")", "{", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ")", "\n\n", "v", ".", "Lock", "(", ")", "\n", "defer", "v", ".", "Unlock", "(", ")", "\n\n", "// Don't open a websocket if one is already open", "if", "v", ".", "wsConn", "!=", "nil", "{", "v", ".", "log", "(", "LogWarning", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "// TODO temp? loop to wait for the SessionID", "i", ":=", "0", "\n", "for", "{", "if", "v", ".", "sessionID", "!=", "\"", "\"", "{", "break", "\n", "}", "\n", "if", "i", ">", "20", "{", "// only loop for up to 1 second total", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "time", ".", "Sleep", "(", "50", "*", "time", ".", "Millisecond", ")", "\n", "i", "++", "\n", "}", "\n\n", "// Connect to VoiceConnection Websocket", "vg", ":=", "\"", "\"", "+", "strings", ".", "TrimSuffix", "(", "v", ".", "endpoint", ",", "\"", "\"", ")", "\n", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ",", "vg", ")", "\n", "v", ".", "wsConn", ",", "_", ",", "err", "=", "websocket", ".", "DefaultDialer", ".", "Dial", "(", "vg", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogWarning", ",", "\"", "\"", ",", "vg", ",", "err", ")", "\n", "v", ".", "log", "(", "LogDebug", ",", "\"", "\\n", "\"", ",", "v", ")", "\n", "return", "\n", "}", "\n\n", "type", "voiceHandshakeData", "struct", "{", "ServerID", "string", "`json:\"server_id\"`", "\n", "UserID", "string", "`json:\"user_id\"`", "\n", "SessionID", "string", "`json:\"session_id\"`", "\n", "Token", "string", "`json:\"token\"`", "\n", "}", "\n", "type", "voiceHandshakeOp", "struct", "{", "Op", "int", "`json:\"op\"`", "// Always 0", "\n", "Data", "voiceHandshakeData", "`json:\"d\"`", "\n", "}", "\n", "data", ":=", "voiceHandshakeOp", "{", "0", ",", "voiceHandshakeData", "{", "v", ".", "GuildID", ",", "v", ".", "UserID", ",", "v", ".", "sessionID", ",", "v", ".", "token", "}", "}", "\n\n", "err", "=", "v", ".", "wsConn", ".", "WriteJSON", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogWarning", ",", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "v", ".", "close", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "v", ".", "wsListen", "(", "v", ".", "wsConn", ",", "v", ".", "close", ")", "\n\n", "// add loop/check for Ready bool here?", "// then return false if not ready?", "// but then wsListen will also err.", "return", "\n", "}" ]
// Open opens a voice connection. This should be called // after VoiceChannelJoin is used and the data VOICE websocket events // are captured.
[ "Open", "opens", "a", "voice", "connection", ".", "This", "should", "be", "called", "after", "VoiceChannelJoin", "is", "used", "and", "the", "data", "VOICE", "websocket", "events", "are", "captured", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L275-L337
train
bwmarrin/discordgo
voice.go
wsListen
func (v *VoiceConnection) wsListen(wsConn *websocket.Conn, close <-chan struct{}) { v.log(LogInformational, "called") for { _, message, err := v.wsConn.ReadMessage() if err != nil { // Detect if we have been closed manually. If a Close() has already // happened, the websocket we are listening on will be different to the // current session. v.RLock() sameConnection := v.wsConn == wsConn v.RUnlock() if sameConnection { v.log(LogError, "voice endpoint %s websocket closed unexpectantly, %s", v.endpoint, err) // Start reconnect goroutine then exit. go v.reconnect() } return } // Pass received message to voice event handler select { case <-close: return default: go v.onEvent(message) } } }
go
func (v *VoiceConnection) wsListen(wsConn *websocket.Conn, close <-chan struct{}) { v.log(LogInformational, "called") for { _, message, err := v.wsConn.ReadMessage() if err != nil { // Detect if we have been closed manually. If a Close() has already // happened, the websocket we are listening on will be different to the // current session. v.RLock() sameConnection := v.wsConn == wsConn v.RUnlock() if sameConnection { v.log(LogError, "voice endpoint %s websocket closed unexpectantly, %s", v.endpoint, err) // Start reconnect goroutine then exit. go v.reconnect() } return } // Pass received message to voice event handler select { case <-close: return default: go v.onEvent(message) } } }
[ "func", "(", "v", "*", "VoiceConnection", ")", "wsListen", "(", "wsConn", "*", "websocket", ".", "Conn", ",", "close", "<-", "chan", "struct", "{", "}", ")", "{", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ")", "\n\n", "for", "{", "_", ",", "message", ",", "err", ":=", "v", ".", "wsConn", ".", "ReadMessage", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// Detect if we have been closed manually. If a Close() has already", "// happened, the websocket we are listening on will be different to the", "// current session.", "v", ".", "RLock", "(", ")", "\n", "sameConnection", ":=", "v", ".", "wsConn", "==", "wsConn", "\n", "v", ".", "RUnlock", "(", ")", "\n", "if", "sameConnection", "{", "v", ".", "log", "(", "LogError", ",", "\"", "\"", ",", "v", ".", "endpoint", ",", "err", ")", "\n\n", "// Start reconnect goroutine then exit.", "go", "v", ".", "reconnect", "(", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "// Pass received message to voice event handler", "select", "{", "case", "<-", "close", ":", "return", "\n", "default", ":", "go", "v", ".", "onEvent", "(", "message", ")", "\n", "}", "\n", "}", "\n", "}" ]
// wsListen listens on the voice websocket for messages and passes them // to the voice event handler. This is automatically called by the Open func
[ "wsListen", "listens", "on", "the", "voice", "websocket", "for", "messages", "and", "passes", "them", "to", "the", "voice", "event", "handler", ".", "This", "is", "automatically", "called", "by", "the", "Open", "func" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L341-L372
train
bwmarrin/discordgo
voice.go
udpOpen
func (v *VoiceConnection) udpOpen() (err error) { v.Lock() defer v.Unlock() if v.wsConn == nil { return fmt.Errorf("nil voice websocket") } if v.udpConn != nil { return fmt.Errorf("udp connection already open") } if v.close == nil { return fmt.Errorf("nil close channel") } if v.endpoint == "" { return fmt.Errorf("empty endpoint") } host := strings.TrimSuffix(v.endpoint, ":80") + ":" + strconv.Itoa(v.op2.Port) addr, err := net.ResolveUDPAddr("udp", host) if err != nil { v.log(LogWarning, "error resolving udp host %s, %s", host, err) return } v.log(LogInformational, "connecting to udp addr %s", addr.String()) v.udpConn, err = net.DialUDP("udp", nil, addr) if err != nil { v.log(LogWarning, "error connecting to udp addr %s, %s", addr.String(), err) return } // Create a 70 byte array and put the SSRC code from the Op 2 VoiceConnection event // into it. Then send that over the UDP connection to Discord sb := make([]byte, 70) binary.BigEndian.PutUint32(sb, v.op2.SSRC) _, err = v.udpConn.Write(sb) if err != nil { v.log(LogWarning, "udp write error to %s, %s", addr.String(), err) return } // Create a 70 byte array and listen for the initial handshake response // from Discord. Once we get it parse the IP and PORT information out // of the response. This should be our public IP and PORT as Discord // saw us. rb := make([]byte, 70) rlen, _, err := v.udpConn.ReadFromUDP(rb) if err != nil { v.log(LogWarning, "udp read error, %s, %s", addr.String(), err) return } if rlen < 70 { v.log(LogWarning, "received udp packet too small") return fmt.Errorf("received udp packet too small") } // Loop over position 4 through 20 to grab the IP address // Should never be beyond position 20. var ip string for i := 4; i < 20; i++ { if rb[i] == 0 { break } ip += string(rb[i]) } // Grab port from position 68 and 69 port := binary.LittleEndian.Uint16(rb[68:70]) // Take the data from above and send it back to Discord to finalize // the UDP connection handshake. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "xsalsa20_poly1305"}}} v.wsMutex.Lock() err = v.wsConn.WriteJSON(data) v.wsMutex.Unlock() if err != nil { v.log(LogWarning, "udp write error, %#v, %s", data, err) return } // start udpKeepAlive go v.udpKeepAlive(v.udpConn, v.close, 5*time.Second) // TODO: find a way to check that it fired off okay return }
go
func (v *VoiceConnection) udpOpen() (err error) { v.Lock() defer v.Unlock() if v.wsConn == nil { return fmt.Errorf("nil voice websocket") } if v.udpConn != nil { return fmt.Errorf("udp connection already open") } if v.close == nil { return fmt.Errorf("nil close channel") } if v.endpoint == "" { return fmt.Errorf("empty endpoint") } host := strings.TrimSuffix(v.endpoint, ":80") + ":" + strconv.Itoa(v.op2.Port) addr, err := net.ResolveUDPAddr("udp", host) if err != nil { v.log(LogWarning, "error resolving udp host %s, %s", host, err) return } v.log(LogInformational, "connecting to udp addr %s", addr.String()) v.udpConn, err = net.DialUDP("udp", nil, addr) if err != nil { v.log(LogWarning, "error connecting to udp addr %s, %s", addr.String(), err) return } // Create a 70 byte array and put the SSRC code from the Op 2 VoiceConnection event // into it. Then send that over the UDP connection to Discord sb := make([]byte, 70) binary.BigEndian.PutUint32(sb, v.op2.SSRC) _, err = v.udpConn.Write(sb) if err != nil { v.log(LogWarning, "udp write error to %s, %s", addr.String(), err) return } // Create a 70 byte array and listen for the initial handshake response // from Discord. Once we get it parse the IP and PORT information out // of the response. This should be our public IP and PORT as Discord // saw us. rb := make([]byte, 70) rlen, _, err := v.udpConn.ReadFromUDP(rb) if err != nil { v.log(LogWarning, "udp read error, %s, %s", addr.String(), err) return } if rlen < 70 { v.log(LogWarning, "received udp packet too small") return fmt.Errorf("received udp packet too small") } // Loop over position 4 through 20 to grab the IP address // Should never be beyond position 20. var ip string for i := 4; i < 20; i++ { if rb[i] == 0 { break } ip += string(rb[i]) } // Grab port from position 68 and 69 port := binary.LittleEndian.Uint16(rb[68:70]) // Take the data from above and send it back to Discord to finalize // the UDP connection handshake. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "xsalsa20_poly1305"}}} v.wsMutex.Lock() err = v.wsConn.WriteJSON(data) v.wsMutex.Unlock() if err != nil { v.log(LogWarning, "udp write error, %#v, %s", data, err) return } // start udpKeepAlive go v.udpKeepAlive(v.udpConn, v.close, 5*time.Second) // TODO: find a way to check that it fired off okay return }
[ "func", "(", "v", "*", "VoiceConnection", ")", "udpOpen", "(", ")", "(", "err", "error", ")", "{", "v", ".", "Lock", "(", ")", "\n", "defer", "v", ".", "Unlock", "(", ")", "\n\n", "if", "v", ".", "wsConn", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "v", ".", "udpConn", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "v", ".", "close", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "v", ".", "endpoint", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "host", ":=", "strings", ".", "TrimSuffix", "(", "v", ".", "endpoint", ",", "\"", "\"", ")", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "v", ".", "op2", ".", "Port", ")", "\n", "addr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "host", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogWarning", ",", "\"", "\"", ",", "host", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "v", ".", "log", "(", "LogInformational", ",", "\"", "\"", ",", "addr", ".", "String", "(", ")", ")", "\n", "v", ".", "udpConn", ",", "err", "=", "net", ".", "DialUDP", "(", "\"", "\"", ",", "nil", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogWarning", ",", "\"", "\"", ",", "addr", ".", "String", "(", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// Create a 70 byte array and put the SSRC code from the Op 2 VoiceConnection event", "// into it. Then send that over the UDP connection to Discord", "sb", ":=", "make", "(", "[", "]", "byte", ",", "70", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "sb", ",", "v", ".", "op2", ".", "SSRC", ")", "\n", "_", ",", "err", "=", "v", ".", "udpConn", ".", "Write", "(", "sb", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogWarning", ",", "\"", "\"", ",", "addr", ".", "String", "(", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// Create a 70 byte array and listen for the initial handshake response", "// from Discord. Once we get it parse the IP and PORT information out", "// of the response. This should be our public IP and PORT as Discord", "// saw us.", "rb", ":=", "make", "(", "[", "]", "byte", ",", "70", ")", "\n", "rlen", ",", "_", ",", "err", ":=", "v", ".", "udpConn", ".", "ReadFromUDP", "(", "rb", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogWarning", ",", "\"", "\"", ",", "addr", ".", "String", "(", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "rlen", "<", "70", "{", "v", ".", "log", "(", "LogWarning", ",", "\"", "\"", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Loop over position 4 through 20 to grab the IP address", "// Should never be beyond position 20.", "var", "ip", "string", "\n", "for", "i", ":=", "4", ";", "i", "<", "20", ";", "i", "++", "{", "if", "rb", "[", "i", "]", "==", "0", "{", "break", "\n", "}", "\n", "ip", "+=", "string", "(", "rb", "[", "i", "]", ")", "\n", "}", "\n\n", "// Grab port from position 68 and 69", "port", ":=", "binary", ".", "LittleEndian", ".", "Uint16", "(", "rb", "[", "68", ":", "70", "]", ")", "\n\n", "// Take the data from above and send it back to Discord to finalize", "// the UDP connection handshake.", "data", ":=", "voiceUDPOp", "{", "1", ",", "voiceUDPD", "{", "\"", "\"", ",", "voiceUDPData", "{", "ip", ",", "port", ",", "\"", "\"", "}", "}", "}", "\n\n", "v", ".", "wsMutex", ".", "Lock", "(", ")", "\n", "err", "=", "v", ".", "wsConn", ".", "WriteJSON", "(", "data", ")", "\n", "v", ".", "wsMutex", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogWarning", ",", "\"", "\"", ",", "data", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// start udpKeepAlive", "go", "v", ".", "udpKeepAlive", "(", "v", ".", "udpConn", ",", "v", ".", "close", ",", "5", "*", "time", ".", "Second", ")", "\n", "// TODO: find a way to check that it fired off okay", "return", "\n", "}" ]
// udpOpen opens a UDP connection to the voice server and completes the // initial required handshake. This connection is left open in the session // and can be used to send or receive audio. This should only be called // from voice.wsEvent OP2
[ "udpOpen", "opens", "a", "UDP", "connection", "to", "the", "voice", "server", "and", "completes", "the", "initial", "required", "handshake", ".", "This", "connection", "is", "left", "open", "in", "the", "session", "and", "can", "be", "used", "to", "send", "or", "receive", "audio", ".", "This", "should", "only", "be", "called", "from", "voice", ".", "wsEvent", "OP2" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L524-L615
train
bwmarrin/discordgo
voice.go
udpKeepAlive
func (v *VoiceConnection) udpKeepAlive(udpConn *net.UDPConn, close <-chan struct{}, i time.Duration) { if udpConn == nil || close == nil { return } var err error var sequence uint64 packet := make([]byte, 8) ticker := time.NewTicker(i) defer ticker.Stop() for { binary.LittleEndian.PutUint64(packet, sequence) sequence++ _, err = udpConn.Write(packet) if err != nil { v.log(LogError, "write error, %s", err) return } select { case <-ticker.C: // continue loop and send keepalive case <-close: return } } }
go
func (v *VoiceConnection) udpKeepAlive(udpConn *net.UDPConn, close <-chan struct{}, i time.Duration) { if udpConn == nil || close == nil { return } var err error var sequence uint64 packet := make([]byte, 8) ticker := time.NewTicker(i) defer ticker.Stop() for { binary.LittleEndian.PutUint64(packet, sequence) sequence++ _, err = udpConn.Write(packet) if err != nil { v.log(LogError, "write error, %s", err) return } select { case <-ticker.C: // continue loop and send keepalive case <-close: return } } }
[ "func", "(", "v", "*", "VoiceConnection", ")", "udpKeepAlive", "(", "udpConn", "*", "net", ".", "UDPConn", ",", "close", "<-", "chan", "struct", "{", "}", ",", "i", "time", ".", "Duration", ")", "{", "if", "udpConn", "==", "nil", "||", "close", "==", "nil", "{", "return", "\n", "}", "\n\n", "var", "err", "error", "\n", "var", "sequence", "uint64", "\n\n", "packet", ":=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n\n", "ticker", ":=", "time", ".", "NewTicker", "(", "i", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "for", "{", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "packet", ",", "sequence", ")", "\n", "sequence", "++", "\n\n", "_", ",", "err", "=", "udpConn", ".", "Write", "(", "packet", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogError", ",", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "select", "{", "case", "<-", "ticker", ".", "C", ":", "// continue loop and send keepalive", "case", "<-", "close", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// udpKeepAlive sends a udp packet to keep the udp connection open // This is still a bit of a "proof of concept"
[ "udpKeepAlive", "sends", "a", "udp", "packet", "to", "keep", "the", "udp", "connection", "open", "This", "is", "still", "a", "bit", "of", "a", "proof", "of", "concept" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L619-L650
train
bwmarrin/discordgo
voice.go
opusSender
func (v *VoiceConnection) opusSender(udpConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) { if udpConn == nil || close == nil { return } // VoiceConnection is now ready to receive audio packets // TODO: this needs reviewed as I think there must be a better way. v.Lock() v.Ready = true v.Unlock() defer func() { v.Lock() v.Ready = false v.Unlock() }() var sequence uint16 var timestamp uint32 var recvbuf []byte var ok bool udpHeader := make([]byte, 12) var nonce [24]byte // build the parts that don't change in the udpHeader udpHeader[0] = 0x80 udpHeader[1] = 0x78 binary.BigEndian.PutUint32(udpHeader[8:], v.op2.SSRC) // start a send loop that loops until buf chan is closed ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000))) defer ticker.Stop() for { // Get data from chan. If chan is closed, return. select { case <-close: return case recvbuf, ok = <-opus: if !ok { return } // else, continue loop } v.RLock() speaking := v.speaking v.RUnlock() if !speaking { err := v.Speaking(true) if err != nil { v.log(LogError, "error sending speaking packet, %s", err) } } // Add sequence and timestamp to udpPacket binary.BigEndian.PutUint16(udpHeader[2:], sequence) binary.BigEndian.PutUint32(udpHeader[4:], timestamp) // encrypt the opus data copy(nonce[:], udpHeader) v.RLock() sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey) v.RUnlock() // block here until we're exactly at the right time :) // Then send rtp audio packet to Discord over UDP select { case <-close: return case <-ticker.C: // continue } _, err := udpConn.Write(sendbuf) if err != nil { v.log(LogError, "udp write error, %s", err) v.log(LogDebug, "voice struct: %#v\n", v) return } if (sequence) == 0xFFFF { sequence = 0 } else { sequence++ } if (timestamp + uint32(size)) >= 0xFFFFFFFF { timestamp = 0 } else { timestamp += uint32(size) } } }
go
func (v *VoiceConnection) opusSender(udpConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) { if udpConn == nil || close == nil { return } // VoiceConnection is now ready to receive audio packets // TODO: this needs reviewed as I think there must be a better way. v.Lock() v.Ready = true v.Unlock() defer func() { v.Lock() v.Ready = false v.Unlock() }() var sequence uint16 var timestamp uint32 var recvbuf []byte var ok bool udpHeader := make([]byte, 12) var nonce [24]byte // build the parts that don't change in the udpHeader udpHeader[0] = 0x80 udpHeader[1] = 0x78 binary.BigEndian.PutUint32(udpHeader[8:], v.op2.SSRC) // start a send loop that loops until buf chan is closed ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000))) defer ticker.Stop() for { // Get data from chan. If chan is closed, return. select { case <-close: return case recvbuf, ok = <-opus: if !ok { return } // else, continue loop } v.RLock() speaking := v.speaking v.RUnlock() if !speaking { err := v.Speaking(true) if err != nil { v.log(LogError, "error sending speaking packet, %s", err) } } // Add sequence and timestamp to udpPacket binary.BigEndian.PutUint16(udpHeader[2:], sequence) binary.BigEndian.PutUint32(udpHeader[4:], timestamp) // encrypt the opus data copy(nonce[:], udpHeader) v.RLock() sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey) v.RUnlock() // block here until we're exactly at the right time :) // Then send rtp audio packet to Discord over UDP select { case <-close: return case <-ticker.C: // continue } _, err := udpConn.Write(sendbuf) if err != nil { v.log(LogError, "udp write error, %s", err) v.log(LogDebug, "voice struct: %#v\n", v) return } if (sequence) == 0xFFFF { sequence = 0 } else { sequence++ } if (timestamp + uint32(size)) >= 0xFFFFFFFF { timestamp = 0 } else { timestamp += uint32(size) } } }
[ "func", "(", "v", "*", "VoiceConnection", ")", "opusSender", "(", "udpConn", "*", "net", ".", "UDPConn", ",", "close", "<-", "chan", "struct", "{", "}", ",", "opus", "<-", "chan", "[", "]", "byte", ",", "rate", ",", "size", "int", ")", "{", "if", "udpConn", "==", "nil", "||", "close", "==", "nil", "{", "return", "\n", "}", "\n\n", "// VoiceConnection is now ready to receive audio packets", "// TODO: this needs reviewed as I think there must be a better way.", "v", ".", "Lock", "(", ")", "\n", "v", ".", "Ready", "=", "true", "\n", "v", ".", "Unlock", "(", ")", "\n", "defer", "func", "(", ")", "{", "v", ".", "Lock", "(", ")", "\n", "v", ".", "Ready", "=", "false", "\n", "v", ".", "Unlock", "(", ")", "\n", "}", "(", ")", "\n\n", "var", "sequence", "uint16", "\n", "var", "timestamp", "uint32", "\n", "var", "recvbuf", "[", "]", "byte", "\n", "var", "ok", "bool", "\n", "udpHeader", ":=", "make", "(", "[", "]", "byte", ",", "12", ")", "\n", "var", "nonce", "[", "24", "]", "byte", "\n\n", "// build the parts that don't change in the udpHeader", "udpHeader", "[", "0", "]", "=", "0x80", "\n", "udpHeader", "[", "1", "]", "=", "0x78", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "udpHeader", "[", "8", ":", "]", ",", "v", ".", "op2", ".", "SSRC", ")", "\n\n", "// start a send loop that loops until buf chan is closed", "ticker", ":=", "time", ".", "NewTicker", "(", "time", ".", "Millisecond", "*", "time", ".", "Duration", "(", "size", "/", "(", "rate", "/", "1000", ")", ")", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "for", "{", "// Get data from chan. If chan is closed, return.", "select", "{", "case", "<-", "close", ":", "return", "\n", "case", "recvbuf", ",", "ok", "=", "<-", "opus", ":", "if", "!", "ok", "{", "return", "\n", "}", "\n", "// else, continue loop", "}", "\n\n", "v", ".", "RLock", "(", ")", "\n", "speaking", ":=", "v", ".", "speaking", "\n", "v", ".", "RUnlock", "(", ")", "\n", "if", "!", "speaking", "{", "err", ":=", "v", ".", "Speaking", "(", "true", ")", "\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogError", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Add sequence and timestamp to udpPacket", "binary", ".", "BigEndian", ".", "PutUint16", "(", "udpHeader", "[", "2", ":", "]", ",", "sequence", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "udpHeader", "[", "4", ":", "]", ",", "timestamp", ")", "\n\n", "// encrypt the opus data", "copy", "(", "nonce", "[", ":", "]", ",", "udpHeader", ")", "\n", "v", ".", "RLock", "(", ")", "\n", "sendbuf", ":=", "secretbox", ".", "Seal", "(", "udpHeader", ",", "recvbuf", ",", "&", "nonce", ",", "&", "v", ".", "op4", ".", "SecretKey", ")", "\n", "v", ".", "RUnlock", "(", ")", "\n\n", "// block here until we're exactly at the right time :)", "// Then send rtp audio packet to Discord over UDP", "select", "{", "case", "<-", "close", ":", "return", "\n", "case", "<-", "ticker", ".", "C", ":", "// continue", "}", "\n", "_", ",", "err", ":=", "udpConn", ".", "Write", "(", "sendbuf", ")", "\n\n", "if", "err", "!=", "nil", "{", "v", ".", "log", "(", "LogError", ",", "\"", "\"", ",", "err", ")", "\n", "v", ".", "log", "(", "LogDebug", ",", "\"", "\\n", "\"", ",", "v", ")", "\n", "return", "\n", "}", "\n\n", "if", "(", "sequence", ")", "==", "0xFFFF", "{", "sequence", "=", "0", "\n", "}", "else", "{", "sequence", "++", "\n", "}", "\n\n", "if", "(", "timestamp", "+", "uint32", "(", "size", ")", ")", ">=", "0xFFFFFFFF", "{", "timestamp", "=", "0", "\n", "}", "else", "{", "timestamp", "+=", "uint32", "(", "size", ")", "\n", "}", "\n", "}", "\n", "}" ]
// opusSender will listen on the given channel and send any // pre-encoded opus audio to Discord. Supposedly.
[ "opusSender", "will", "listen", "on", "the", "given", "channel", "and", "send", "any", "pre", "-", "encoded", "opus", "audio", "to", "Discord", ".", "Supposedly", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L654-L747
train
bwmarrin/discordgo
structs.go
MessageFormat
func (e *Emoji) MessageFormat() string { if e.ID != "" && e.Name != "" { if e.Animated { return "<a:" + e.APIName() + ">" } return "<:" + e.APIName() + ">" } return e.APIName() }
go
func (e *Emoji) MessageFormat() string { if e.ID != "" && e.Name != "" { if e.Animated { return "<a:" + e.APIName() + ">" } return "<:" + e.APIName() + ">" } return e.APIName() }
[ "func", "(", "e", "*", "Emoji", ")", "MessageFormat", "(", ")", "string", "{", "if", "e", ".", "ID", "!=", "\"", "\"", "&&", "e", ".", "Name", "!=", "\"", "\"", "{", "if", "e", ".", "Animated", "{", "return", "\"", "\"", "+", "e", ".", "APIName", "(", ")", "+", "\"", "\"", "\n", "}", "\n\n", "return", "\"", "\"", "+", "e", ".", "APIName", "(", ")", "+", "\"", "\"", "\n", "}", "\n\n", "return", "e", ".", "APIName", "(", ")", "\n", "}" ]
// MessageFormat returns a correctly formatted Emoji for use in Message content and embeds
[ "MessageFormat", "returns", "a", "correctly", "formatted", "Emoji", "for", "use", "in", "Message", "content", "and", "embeds" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/structs.go#L289-L299
train
bwmarrin/discordgo
structs.go
APIName
func (e *Emoji) APIName() string { if e.ID != "" && e.Name != "" { return e.Name + ":" + e.ID } if e.Name != "" { return e.Name } return e.ID }
go
func (e *Emoji) APIName() string { if e.ID != "" && e.Name != "" { return e.Name + ":" + e.ID } if e.Name != "" { return e.Name } return e.ID }
[ "func", "(", "e", "*", "Emoji", ")", "APIName", "(", ")", "string", "{", "if", "e", ".", "ID", "!=", "\"", "\"", "&&", "e", ".", "Name", "!=", "\"", "\"", "{", "return", "e", ".", "Name", "+", "\"", "\"", "+", "e", ".", "ID", "\n", "}", "\n", "if", "e", ".", "Name", "!=", "\"", "\"", "{", "return", "e", ".", "Name", "\n", "}", "\n", "return", "e", ".", "ID", "\n", "}" ]
// APIName returns an correctly formatted API name for use in the MessageReactions endpoints.
[ "APIName", "returns", "an", "correctly", "formatted", "API", "name", "for", "use", "in", "the", "MessageReactions", "endpoints", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/structs.go#L302-L310
train
bwmarrin/discordgo
structs.go
UnmarshalJSON
func (t *TimeStamps) UnmarshalJSON(b []byte) error { temp := struct { End float64 `json:"end,omitempty"` Start float64 `json:"start,omitempty"` }{} err := json.Unmarshal(b, &temp) if err != nil { return err } t.EndTimestamp = int64(temp.End) t.StartTimestamp = int64(temp.Start) return nil }
go
func (t *TimeStamps) UnmarshalJSON(b []byte) error { temp := struct { End float64 `json:"end,omitempty"` Start float64 `json:"start,omitempty"` }{} err := json.Unmarshal(b, &temp) if err != nil { return err } t.EndTimestamp = int64(temp.End) t.StartTimestamp = int64(temp.Start) return nil }
[ "func", "(", "t", "*", "TimeStamps", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "temp", ":=", "struct", "{", "End", "float64", "`json:\"end,omitempty\"`", "\n", "Start", "float64", "`json:\"start,omitempty\"`", "\n", "}", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "temp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t", ".", "EndTimestamp", "=", "int64", "(", "temp", ".", "End", ")", "\n", "t", ".", "StartTimestamp", "=", "int64", "(", "temp", ".", "Start", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON unmarshals JSON into TimeStamps struct
[ "UnmarshalJSON", "unmarshals", "JSON", "into", "TimeStamps", "struct" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/structs.go#L575-L587
train
bwmarrin/discordgo
restapi.go
Request
func (s *Session) Request(method, urlStr string, data interface{}) (response []byte, err error) { return s.RequestWithBucketID(method, urlStr, data, strings.SplitN(urlStr, "?", 2)[0]) }
go
func (s *Session) Request(method, urlStr string, data interface{}) (response []byte, err error) { return s.RequestWithBucketID(method, urlStr, data, strings.SplitN(urlStr, "?", 2)[0]) }
[ "func", "(", "s", "*", "Session", ")", "Request", "(", "method", ",", "urlStr", "string", ",", "data", "interface", "{", "}", ")", "(", "response", "[", "]", "byte", ",", "err", "error", ")", "{", "return", "s", ".", "RequestWithBucketID", "(", "method", ",", "urlStr", ",", "data", ",", "strings", ".", "SplitN", "(", "urlStr", ",", "\"", "\"", ",", "2", ")", "[", "0", "]", ")", "\n", "}" ]
// Request is the same as RequestWithBucketID but the bucket id is the same as the urlStr
[ "Request", "is", "the", "same", "as", "RequestWithBucketID", "but", "the", "bucket", "id", "is", "the", "same", "as", "the", "urlStr" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L45-L47
train
bwmarrin/discordgo
restapi.go
RequestWithLockedBucket
func (s *Session) RequestWithLockedBucket(method, urlStr, contentType string, b []byte, bucket *Bucket, sequence int) (response []byte, err error) { if s.Debug { log.Printf("API REQUEST %8s :: %s\n", method, urlStr) log.Printf("API REQUEST PAYLOAD :: [%s]\n", string(b)) } req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b)) if err != nil { bucket.Release(nil) return } // Not used on initial login.. // TODO: Verify if a login, otherwise complain about no-token if s.Token != "" { req.Header.Set("authorization", s.Token) } req.Header.Set("Content-Type", contentType) // TODO: Make a configurable static variable. req.Header.Set("User-Agent", "DiscordBot (https://github.com/bwmarrin/discordgo, v"+VERSION+")") if s.Debug { for k, v := range req.Header { log.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v) } } resp, err := s.Client.Do(req) if err != nil { bucket.Release(nil) return } defer func() { err2 := resp.Body.Close() if err2 != nil { log.Println("error closing resp body") } }() err = bucket.Release(resp.Header) if err != nil { return } response, err = ioutil.ReadAll(resp.Body) if err != nil { return } if s.Debug { log.Printf("API RESPONSE STATUS :: %s\n", resp.Status) for k, v := range resp.Header { log.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v) } log.Printf("API RESPONSE BODY :: [%s]\n\n\n", response) } switch resp.StatusCode { case http.StatusOK: case http.StatusCreated: case http.StatusNoContent: case http.StatusBadGateway: // Retry sending request if possible if sequence < s.MaxRestRetries { s.log(LogInformational, "%s Failed (%s), Retrying...", urlStr, resp.Status) response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence+1) } else { err = fmt.Errorf("Exceeded Max retries HTTP %s, %s", resp.Status, response) } case 429: // TOO MANY REQUESTS - Rate limiting rl := TooManyRequests{} err = json.Unmarshal(response, &rl) if err != nil { s.log(LogError, "rate limit unmarshal error, %s", err) return } s.log(LogInformational, "Rate Limiting %s, retry in %d", urlStr, rl.RetryAfter) s.handleEvent(rateLimitEventType, RateLimit{TooManyRequests: &rl, URL: urlStr}) time.Sleep(rl.RetryAfter * time.Millisecond) // we can make the above smarter // this method can cause longer delays than required response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence) case http.StatusUnauthorized: if strings.Index(s.Token, "Bot ") != 0 { s.log(LogInformational, ErrUnauthorized.Error()) err = ErrUnauthorized } fallthrough default: // Error condition err = newRestError(req, resp, response) } return }
go
func (s *Session) RequestWithLockedBucket(method, urlStr, contentType string, b []byte, bucket *Bucket, sequence int) (response []byte, err error) { if s.Debug { log.Printf("API REQUEST %8s :: %s\n", method, urlStr) log.Printf("API REQUEST PAYLOAD :: [%s]\n", string(b)) } req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b)) if err != nil { bucket.Release(nil) return } // Not used on initial login.. // TODO: Verify if a login, otherwise complain about no-token if s.Token != "" { req.Header.Set("authorization", s.Token) } req.Header.Set("Content-Type", contentType) // TODO: Make a configurable static variable. req.Header.Set("User-Agent", "DiscordBot (https://github.com/bwmarrin/discordgo, v"+VERSION+")") if s.Debug { for k, v := range req.Header { log.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v) } } resp, err := s.Client.Do(req) if err != nil { bucket.Release(nil) return } defer func() { err2 := resp.Body.Close() if err2 != nil { log.Println("error closing resp body") } }() err = bucket.Release(resp.Header) if err != nil { return } response, err = ioutil.ReadAll(resp.Body) if err != nil { return } if s.Debug { log.Printf("API RESPONSE STATUS :: %s\n", resp.Status) for k, v := range resp.Header { log.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v) } log.Printf("API RESPONSE BODY :: [%s]\n\n\n", response) } switch resp.StatusCode { case http.StatusOK: case http.StatusCreated: case http.StatusNoContent: case http.StatusBadGateway: // Retry sending request if possible if sequence < s.MaxRestRetries { s.log(LogInformational, "%s Failed (%s), Retrying...", urlStr, resp.Status) response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence+1) } else { err = fmt.Errorf("Exceeded Max retries HTTP %s, %s", resp.Status, response) } case 429: // TOO MANY REQUESTS - Rate limiting rl := TooManyRequests{} err = json.Unmarshal(response, &rl) if err != nil { s.log(LogError, "rate limit unmarshal error, %s", err) return } s.log(LogInformational, "Rate Limiting %s, retry in %d", urlStr, rl.RetryAfter) s.handleEvent(rateLimitEventType, RateLimit{TooManyRequests: &rl, URL: urlStr}) time.Sleep(rl.RetryAfter * time.Millisecond) // we can make the above smarter // this method can cause longer delays than required response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence) case http.StatusUnauthorized: if strings.Index(s.Token, "Bot ") != 0 { s.log(LogInformational, ErrUnauthorized.Error()) err = ErrUnauthorized } fallthrough default: // Error condition err = newRestError(req, resp, response) } return }
[ "func", "(", "s", "*", "Session", ")", "RequestWithLockedBucket", "(", "method", ",", "urlStr", ",", "contentType", "string", ",", "b", "[", "]", "byte", ",", "bucket", "*", "Bucket", ",", "sequence", "int", ")", "(", "response", "[", "]", "byte", ",", "err", "error", ")", "{", "if", "s", ".", "Debug", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "method", ",", "urlStr", ")", "\n", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "string", "(", "b", ")", ")", "\n", "}", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "urlStr", ",", "bytes", ".", "NewBuffer", "(", "b", ")", ")", "\n", "if", "err", "!=", "nil", "{", "bucket", ".", "Release", "(", "nil", ")", "\n", "return", "\n", "}", "\n\n", "// Not used on initial login..", "// TODO: Verify if a login, otherwise complain about no-token", "if", "s", ".", "Token", "!=", "\"", "\"", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "s", ".", "Token", ")", "\n", "}", "\n\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "contentType", ")", "\n", "// TODO: Make a configurable static variable.", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", "+", "VERSION", "+", "\"", "\"", ")", "\n\n", "if", "s", ".", "Debug", "{", "for", "k", ",", "v", ":=", "range", "req", ".", "Header", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "}", "\n\n", "resp", ",", "err", ":=", "s", ".", "Client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "bucket", ".", "Release", "(", "nil", ")", "\n", "return", "\n", "}", "\n", "defer", "func", "(", ")", "{", "err2", ":=", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err2", "!=", "nil", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "err", "=", "bucket", ".", "Release", "(", "resp", ".", "Header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "response", ",", "err", "=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "s", ".", "Debug", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "resp", ".", "Status", ")", "\n", "for", "k", ",", "v", ":=", "range", "resp", ".", "Header", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "response", ")", "\n", "}", "\n\n", "switch", "resp", ".", "StatusCode", "{", "case", "http", ".", "StatusOK", ":", "case", "http", ".", "StatusCreated", ":", "case", "http", ".", "StatusNoContent", ":", "case", "http", ".", "StatusBadGateway", ":", "// Retry sending request if possible", "if", "sequence", "<", "s", ".", "MaxRestRetries", "{", "s", ".", "log", "(", "LogInformational", ",", "\"", "\"", ",", "urlStr", ",", "resp", ".", "Status", ")", "\n", "response", ",", "err", "=", "s", ".", "RequestWithLockedBucket", "(", "method", ",", "urlStr", ",", "contentType", ",", "b", ",", "s", ".", "Ratelimiter", ".", "LockBucketObject", "(", "bucket", ")", ",", "sequence", "+", "1", ")", "\n", "}", "else", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "resp", ".", "Status", ",", "response", ")", "\n", "}", "\n", "case", "429", ":", "// TOO MANY REQUESTS - Rate limiting", "rl", ":=", "TooManyRequests", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "response", ",", "&", "rl", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "log", "(", "LogError", ",", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "s", ".", "log", "(", "LogInformational", ",", "\"", "\"", ",", "urlStr", ",", "rl", ".", "RetryAfter", ")", "\n", "s", ".", "handleEvent", "(", "rateLimitEventType", ",", "RateLimit", "{", "TooManyRequests", ":", "&", "rl", ",", "URL", ":", "urlStr", "}", ")", "\n\n", "time", ".", "Sleep", "(", "rl", ".", "RetryAfter", "*", "time", ".", "Millisecond", ")", "\n", "// we can make the above smarter", "// this method can cause longer delays than required", "response", ",", "err", "=", "s", ".", "RequestWithLockedBucket", "(", "method", ",", "urlStr", ",", "contentType", ",", "b", ",", "s", ".", "Ratelimiter", ".", "LockBucketObject", "(", "bucket", ")", ",", "sequence", ")", "\n", "case", "http", ".", "StatusUnauthorized", ":", "if", "strings", ".", "Index", "(", "s", ".", "Token", ",", "\"", "\"", ")", "!=", "0", "{", "s", ".", "log", "(", "LogInformational", ",", "ErrUnauthorized", ".", "Error", "(", ")", ")", "\n", "err", "=", "ErrUnauthorized", "\n", "}", "\n", "fallthrough", "\n", "default", ":", "// Error condition", "err", "=", "newRestError", "(", "req", ",", "resp", ",", "response", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// RequestWithLockedBucket makes a request using a bucket that's already been locked
[ "RequestWithLockedBucket", "makes", "a", "request", "using", "a", "bucket", "that", "s", "already", "been", "locked" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L73-L171
train
bwmarrin/discordgo
restapi.go
Register
func (s *Session) Register(username string) (token string, err error) { data := struct { Username string `json:"username"` }{username} response, err := s.RequestWithBucketID("POST", EndpointRegister, data, EndpointRegister) if err != nil { return } temp := struct { Token string `json:"token"` }{} err = unmarshal(response, &temp) if err != nil { return } token = temp.Token return }
go
func (s *Session) Register(username string) (token string, err error) { data := struct { Username string `json:"username"` }{username} response, err := s.RequestWithBucketID("POST", EndpointRegister, data, EndpointRegister) if err != nil { return } temp := struct { Token string `json:"token"` }{} err = unmarshal(response, &temp) if err != nil { return } token = temp.Token return }
[ "func", "(", "s", "*", "Session", ")", "Register", "(", "username", "string", ")", "(", "token", "string", ",", "err", "error", ")", "{", "data", ":=", "struct", "{", "Username", "string", "`json:\"username\"`", "\n", "}", "{", "username", "}", "\n\n", "response", ",", "err", ":=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointRegister", ",", "data", ",", "EndpointRegister", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "temp", ":=", "struct", "{", "Token", "string", "`json:\"token\"`", "\n", "}", "{", "}", "\n\n", "err", "=", "unmarshal", "(", "response", ",", "&", "temp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "token", "=", "temp", ".", "Token", "\n", "return", "\n", "}" ]
// Register sends a Register request to Discord, and returns the authentication token // Note that this account is temporary and should be verified for future use. // Another option is to save the authentication token external, but this isn't recommended.
[ "Register", "sends", "a", "Register", "request", "to", "Discord", "and", "returns", "the", "authentication", "token", "Note", "that", "this", "account", "is", "temporary", "and", "should", "be", "verified", "for", "future", "use", ".", "Another", "option", "is", "to", "save", "the", "authentication", "token", "external", "but", "this", "isn", "t", "recommended", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L223-L245
train
bwmarrin/discordgo
restapi.go
Logout
func (s *Session) Logout() (err error) { // _, err = s.Request("POST", LOGOUT, `{"token": "` + s.Token + `"}`) if s.Token == "" { return } data := struct { Token string `json:"token"` }{s.Token} _, err = s.RequestWithBucketID("POST", EndpointLogout, data, EndpointLogout) return }
go
func (s *Session) Logout() (err error) { // _, err = s.Request("POST", LOGOUT, `{"token": "` + s.Token + `"}`) if s.Token == "" { return } data := struct { Token string `json:"token"` }{s.Token} _, err = s.RequestWithBucketID("POST", EndpointLogout, data, EndpointLogout) return }
[ "func", "(", "s", "*", "Session", ")", "Logout", "(", ")", "(", "err", "error", ")", "{", "// _, err = s.Request(\"POST\", LOGOUT, `{\"token\": \"` + s.Token + `\"}`)", "if", "s", ".", "Token", "==", "\"", "\"", "{", "return", "\n", "}", "\n\n", "data", ":=", "struct", "{", "Token", "string", "`json:\"token\"`", "\n", "}", "{", "s", ".", "Token", "}", "\n\n", "_", ",", "err", "=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointLogout", ",", "data", ",", "EndpointLogout", ")", "\n", "return", "\n", "}" ]
// Logout sends a logout request to Discord. // This does not seem to actually invalidate the token. So you can still // make API calls even after a Logout. So, it seems almost pointless to // even use.
[ "Logout", "sends", "a", "logout", "request", "to", "Discord", ".", "This", "does", "not", "seem", "to", "actually", "invalidate", "the", "token", ".", "So", "you", "can", "still", "make", "API", "calls", "even", "after", "a", "Logout", ".", "So", "it", "seems", "almost", "pointless", "to", "even", "use", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L251-L265
train
bwmarrin/discordgo
restapi.go
UserUpdate
func (s *Session) UserUpdate(email, password, username, avatar, newPassword string) (st *User, err error) { // NOTE: Avatar must be either the hash/id of existing Avatar or // data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG // to set a new avatar. // If left blank, avatar will be set to null/blank data := struct { Email string `json:"email,omitempty"` Password string `json:"password,omitempty"` Username string `json:"username,omitempty"` Avatar string `json:"avatar,omitempty"` NewPassword string `json:"new_password,omitempty"` }{email, password, username, avatar, newPassword} body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers) if err != nil { return } err = unmarshal(body, &st) return }
go
func (s *Session) UserUpdate(email, password, username, avatar, newPassword string) (st *User, err error) { // NOTE: Avatar must be either the hash/id of existing Avatar or // data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG // to set a new avatar. // If left blank, avatar will be set to null/blank data := struct { Email string `json:"email,omitempty"` Password string `json:"password,omitempty"` Username string `json:"username,omitempty"` Avatar string `json:"avatar,omitempty"` NewPassword string `json:"new_password,omitempty"` }{email, password, username, avatar, newPassword} body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers) if err != nil { return } err = unmarshal(body, &st) return }
[ "func", "(", "s", "*", "Session", ")", "UserUpdate", "(", "email", ",", "password", ",", "username", ",", "avatar", ",", "newPassword", "string", ")", "(", "st", "*", "User", ",", "err", "error", ")", "{", "// NOTE: Avatar must be either the hash/id of existing Avatar or", "// data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG", "// to set a new avatar.", "// If left blank, avatar will be set to null/blank", "data", ":=", "struct", "{", "Email", "string", "`json:\"email,omitempty\"`", "\n", "Password", "string", "`json:\"password,omitempty\"`", "\n", "Username", "string", "`json:\"username,omitempty\"`", "\n", "Avatar", "string", "`json:\"avatar,omitempty\"`", "\n", "NewPassword", "string", "`json:\"new_password,omitempty\"`", "\n", "}", "{", "email", ",", "password", ",", "username", ",", "avatar", ",", "newPassword", "}", "\n\n", "body", ",", "err", ":=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointUser", "(", "\"", "\"", ")", ",", "data", ",", "EndpointUsers", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "unmarshal", "(", "body", ",", "&", "st", ")", "\n", "return", "\n", "}" ]
// UserUpdate updates a users settings.
[ "UserUpdate", "updates", "a", "users", "settings", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L308-L330
train
bwmarrin/discordgo
restapi.go
UserSettings
func (s *Session) UserSettings() (st *Settings, err error) { body, err := s.RequestWithBucketID("GET", EndpointUserSettings("@me"), nil, EndpointUserSettings("")) if err != nil { return } err = unmarshal(body, &st) return }
go
func (s *Session) UserSettings() (st *Settings, err error) { body, err := s.RequestWithBucketID("GET", EndpointUserSettings("@me"), nil, EndpointUserSettings("")) if err != nil { return } err = unmarshal(body, &st) return }
[ "func", "(", "s", "*", "Session", ")", "UserSettings", "(", ")", "(", "st", "*", "Settings", ",", "err", "error", ")", "{", "body", ",", "err", ":=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointUserSettings", "(", "\"", "\"", ")", ",", "nil", ",", "EndpointUserSettings", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "unmarshal", "(", "body", ",", "&", "st", ")", "\n", "return", "\n", "}" ]
// UserSettings returns the settings for a given user
[ "UserSettings", "returns", "the", "settings", "for", "a", "given", "user" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L333-L342
train
bwmarrin/discordgo
restapi.go
UserConnections
func (s *Session) UserConnections() (conn []*UserConnection, err error) { response, err := s.RequestWithBucketID("GET", EndpointUserConnections("@me"), nil, EndpointUserConnections("@me")) if err != nil { return nil, err } err = unmarshal(response, &conn) if err != nil { return } return }
go
func (s *Session) UserConnections() (conn []*UserConnection, err error) { response, err := s.RequestWithBucketID("GET", EndpointUserConnections("@me"), nil, EndpointUserConnections("@me")) if err != nil { return nil, err } err = unmarshal(response, &conn) if err != nil { return } return }
[ "func", "(", "s", "*", "Session", ")", "UserConnections", "(", ")", "(", "conn", "[", "]", "*", "UserConnection", ",", "err", "error", ")", "{", "response", ",", "err", ":=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointUserConnections", "(", "\"", "\"", ")", ",", "nil", ",", "EndpointUserConnections", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "unmarshal", "(", "response", ",", "&", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "return", "\n", "}" ]
// UserConnections returns the user's connections
[ "UserConnections", "returns", "the", "user", "s", "connections" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L366-L378
train
bwmarrin/discordgo
restapi.go
UserChannels
func (s *Session) UserChannels() (st []*Channel, err error) { body, err := s.RequestWithBucketID("GET", EndpointUserChannels("@me"), nil, EndpointUserChannels("")) if err != nil { return } err = unmarshal(body, &st) return }
go
func (s *Session) UserChannels() (st []*Channel, err error) { body, err := s.RequestWithBucketID("GET", EndpointUserChannels("@me"), nil, EndpointUserChannels("")) if err != nil { return } err = unmarshal(body, &st) return }
[ "func", "(", "s", "*", "Session", ")", "UserChannels", "(", ")", "(", "st", "[", "]", "*", "Channel", ",", "err", "error", ")", "{", "body", ",", "err", ":=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointUserChannels", "(", "\"", "\"", ")", ",", "nil", ",", "EndpointUserChannels", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "unmarshal", "(", "body", ",", "&", "st", ")", "\n", "return", "\n", "}" ]
// UserChannels returns an array of Channel structures for all private // channels.
[ "UserChannels", "returns", "an", "array", "of", "Channel", "structures", "for", "all", "private", "channels", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L382-L391
train
bwmarrin/discordgo
restapi.go
ChannelMessageEditComplex
func (s *Session) ChannelMessageEditComplex(m *MessageEdit) (st *Message, err error) { if m.Embed != nil && m.Embed.Type == "" { m.Embed.Type = "rich" } response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(m.Channel, m.ID), m, EndpointChannelMessage(m.Channel, "")) if err != nil { return } err = unmarshal(response, &st) return }
go
func (s *Session) ChannelMessageEditComplex(m *MessageEdit) (st *Message, err error) { if m.Embed != nil && m.Embed.Type == "" { m.Embed.Type = "rich" } response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(m.Channel, m.ID), m, EndpointChannelMessage(m.Channel, "")) if err != nil { return } err = unmarshal(response, &st) return }
[ "func", "(", "s", "*", "Session", ")", "ChannelMessageEditComplex", "(", "m", "*", "MessageEdit", ")", "(", "st", "*", "Message", ",", "err", "error", ")", "{", "if", "m", ".", "Embed", "!=", "nil", "&&", "m", ".", "Embed", ".", "Type", "==", "\"", "\"", "{", "m", ".", "Embed", ".", "Type", "=", "\"", "\"", "\n", "}", "\n\n", "response", ",", "err", ":=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointChannelMessage", "(", "m", ".", "Channel", ",", "m", ".", "ID", ")", ",", "m", ",", "EndpointChannelMessage", "(", "m", ".", "Channel", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "unmarshal", "(", "response", ",", "&", "st", ")", "\n", "return", "\n", "}" ]
// ChannelMessageEditComplex edits an existing message, replacing it entirely with // the given MessageEdit struct
[ "ChannelMessageEditComplex", "edits", "an", "existing", "message", "replacing", "it", "entirely", "with", "the", "given", "MessageEdit", "struct" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L1615-L1627
train
bwmarrin/discordgo
restapi.go
ChannelMessageDelete
func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) { _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, "")) return }
go
func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) { _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, "")) return }
[ "func", "(", "s", "*", "Session", ")", "ChannelMessageDelete", "(", "channelID", ",", "messageID", "string", ")", "(", "err", "error", ")", "{", "_", ",", "err", "=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointChannelMessage", "(", "channelID", ",", "messageID", ")", ",", "nil", ",", "EndpointChannelMessage", "(", "channelID", ",", "\"", "\"", ")", ")", "\n", "return", "\n", "}" ]
// ChannelMessageDelete deletes a message from the Channel.
[ "ChannelMessageDelete", "deletes", "a", "message", "from", "the", "Channel", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L1638-L1642
train
bwmarrin/discordgo
restapi.go
VoiceICE
func (s *Session) VoiceICE() (st *VoiceICE, err error) { body, err := s.RequestWithBucketID("GET", EndpointVoiceIce, nil, EndpointVoiceIce) if err != nil { return } err = unmarshal(body, &st) return }
go
func (s *Session) VoiceICE() (st *VoiceICE, err error) { body, err := s.RequestWithBucketID("GET", EndpointVoiceIce, nil, EndpointVoiceIce) if err != nil { return } err = unmarshal(body, &st) return }
[ "func", "(", "s", "*", "Session", ")", "VoiceICE", "(", ")", "(", "st", "*", "VoiceICE", ",", "err", "error", ")", "{", "body", ",", "err", ":=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointVoiceIce", ",", "nil", ",", "EndpointVoiceIce", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "unmarshal", "(", "body", ",", "&", "st", ")", "\n", "return", "\n", "}" ]
// VoiceICE returns the voice server ICE information
[ "VoiceICE", "returns", "the", "voice", "server", "ICE", "information" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L1854-L1863
train
bwmarrin/discordgo
restapi.go
GatewayBot
func (s *Session) GatewayBot() (st *GatewayBotResponse, err error) { response, err := s.RequestWithBucketID("GET", EndpointGatewayBot, nil, EndpointGatewayBot) if err != nil { return } err = unmarshal(response, &st) if err != nil { return } // Ensure the gateway always has a trailing slash. // MacOS will fail to connect if we add query params without a trailing slash on the base domain. if !strings.HasSuffix(st.URL, "/") { st.URL += "/" } return }
go
func (s *Session) GatewayBot() (st *GatewayBotResponse, err error) { response, err := s.RequestWithBucketID("GET", EndpointGatewayBot, nil, EndpointGatewayBot) if err != nil { return } err = unmarshal(response, &st) if err != nil { return } // Ensure the gateway always has a trailing slash. // MacOS will fail to connect if we add query params without a trailing slash on the base domain. if !strings.HasSuffix(st.URL, "/") { st.URL += "/" } return }
[ "func", "(", "s", "*", "Session", ")", "GatewayBot", "(", ")", "(", "st", "*", "GatewayBotResponse", ",", "err", "error", ")", "{", "response", ",", "err", ":=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointGatewayBot", ",", "nil", ",", "EndpointGatewayBot", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "unmarshal", "(", "response", ",", "&", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// Ensure the gateway always has a trailing slash.", "// MacOS will fail to connect if we add query params without a trailing slash on the base domain.", "if", "!", "strings", ".", "HasSuffix", "(", "st", ".", "URL", ",", "\"", "\"", ")", "{", "st", ".", "URL", "+=", "\"", "\"", "\n", "}", "\n\n", "return", "\n", "}" ]
// GatewayBot returns the websocket Gateway address and the recommended number of shards
[ "GatewayBot", "returns", "the", "websocket", "Gateway", "address", "and", "the", "recommended", "number", "of", "shards" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L1898-L1917
train
bwmarrin/discordgo
restapi.go
RelationshipsMutualGet
func (s *Session) RelationshipsMutualGet(userID string) (mf []*User, err error) { body, err := s.RequestWithBucketID("GET", EndpointRelationshipsMutual(userID), nil, EndpointRelationshipsMutual(userID)) if err != nil { return } err = unmarshal(body, &mf) return }
go
func (s *Session) RelationshipsMutualGet(userID string) (mf []*User, err error) { body, err := s.RequestWithBucketID("GET", EndpointRelationshipsMutual(userID), nil, EndpointRelationshipsMutual(userID)) if err != nil { return } err = unmarshal(body, &mf) return }
[ "func", "(", "s", "*", "Session", ")", "RelationshipsMutualGet", "(", "userID", "string", ")", "(", "mf", "[", "]", "*", "User", ",", "err", "error", ")", "{", "body", ",", "err", ":=", "s", ".", "RequestWithBucketID", "(", "\"", "\"", ",", "EndpointRelationshipsMutual", "(", "userID", ")", ",", "nil", ",", "EndpointRelationshipsMutual", "(", "userID", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "unmarshal", "(", "body", ",", "&", "mf", ")", "\n", "return", "\n", "}" ]
// RelationshipsMutualGet returns an array of all the users both @me and the given user is friends with. // userID: ID of the user.
[ "RelationshipsMutualGet", "returns", "an", "array", "of", "all", "the", "users", "both" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/restapi.go#L2212-L2220
train
bwmarrin/discordgo
eventhandlers.go
Handle
func (eh channelCreateEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*ChannelCreate); ok { eh(s, t) } }
go
func (eh channelCreateEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*ChannelCreate); ok { eh(s, t) } }
[ "func", "(", "eh", "channelCreateEventHandler", ")", "Handle", "(", "s", "*", "Session", ",", "i", "interface", "{", "}", ")", "{", "if", "t", ",", "ok", ":=", "i", ".", "(", "*", "ChannelCreate", ")", ";", "ok", "{", "eh", "(", "s", ",", "t", ")", "\n", "}", "\n", "}" ]
// Handle is the handler for ChannelCreate events.
[ "Handle", "is", "the", "handler", "for", "ChannelCreate", "events", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/eventhandlers.go#L70-L74
train
bwmarrin/discordgo
eventhandlers.go
Handle
func (eh channelDeleteEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*ChannelDelete); ok { eh(s, t) } }
go
func (eh channelDeleteEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*ChannelDelete); ok { eh(s, t) } }
[ "func", "(", "eh", "channelDeleteEventHandler", ")", "Handle", "(", "s", "*", "Session", ",", "i", "interface", "{", "}", ")", "{", "if", "t", ",", "ok", ":=", "i", ".", "(", "*", "ChannelDelete", ")", ";", "ok", "{", "eh", "(", "s", ",", "t", ")", "\n", "}", "\n", "}" ]
// Handle is the handler for ChannelDelete events.
[ "Handle", "is", "the", "handler", "for", "ChannelDelete", "events", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/eventhandlers.go#L90-L94
train
bwmarrin/discordgo
eventhandlers.go
Handle
func (eh channelPinsUpdateEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*ChannelPinsUpdate); ok { eh(s, t) } }
go
func (eh channelPinsUpdateEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*ChannelPinsUpdate); ok { eh(s, t) } }
[ "func", "(", "eh", "channelPinsUpdateEventHandler", ")", "Handle", "(", "s", "*", "Session", ",", "i", "interface", "{", "}", ")", "{", "if", "t", ",", "ok", ":=", "i", ".", "(", "*", "ChannelPinsUpdate", ")", ";", "ok", "{", "eh", "(", "s", ",", "t", ")", "\n", "}", "\n", "}" ]
// Handle is the handler for ChannelPinsUpdate events.
[ "Handle", "is", "the", "handler", "for", "ChannelPinsUpdate", "events", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/eventhandlers.go#L110-L114
train