From a1f2066532d6c8013a25d1054fd43bdc1431fcf8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Tue, 28 Jul 2015 21:38:35 +0100 Subject: [PATCH 001/297] Improving web authentication --- commands.go | 37 ++++-------------------- service.go | 36 +++++++++++++++++++++-- service_youtube.go | 16 +++++------ web.go | 72 +++++++++++++++++++++------------------------- 4 files changed, 81 insertions(+), 80 deletions(-) diff --git a/commands.go b/commands.go index 61c83fb..99db8fd 100644 --- a/commands.go +++ b/commands.go @@ -36,7 +36,7 @@ func parseCommand(user *gumble.User, username, command string) { // Add command case dj.conf.Aliases.AddAlias: if dj.HasPermission(username, dj.conf.Permissions.AdminAdd) { - add(user, username, argument) + add(user, argument) } else { dj.SendPrivateMessage(user, NO_PERMISSION_MSG) } @@ -166,40 +166,15 @@ func parseCommand(user *gumble.User, username, command string) { // add performs !add functionality. Checks input URL for service, and adds // the URL to the queue if the format matches. -func add(user *gumble.User, username, url string) { +func add(user *gumble.User, url string) { if url == "" { dj.SendPrivateMessage(user, NO_ARGUMENT_MSG) } else { - var urlService Service - - // Checks all services to see if any can take the URL - for _, service := range services { - if service.URLRegex(url) { - urlService = service - } - } - - if urlService == nil { - dj.SendPrivateMessage(user, INVALID_URL_MSG) + title, err := findServiceAndAdd(user, url) + if err == nil { + dj.client.Self.Channel.Send(fmt.Sprintf(SONG_ADDED_HTML, user.Name, title), false) } else { - oldLength := dj.queue.Len() - - if err := urlService.NewRequest(user, url); err == nil { - dj.client.Self.Channel.Send(SONG_ADDED_HTML, false) - - // Starts playing the new song if nothing else is playing - if oldLength == 0 && dj.queue.Len() != 0 && !dj.audioStream.IsPlaying() { - if err := dj.queue.CurrentSong().Download(); err == nil { - dj.queue.CurrentSong().Play() - } else { - dj.SendPrivateMessage(user, AUDIO_FAIL_MSG) - dj.queue.CurrentSong().Delete() - dj.queue.OnSongFinished() - } - } - } else { - dj.SendPrivateMessage(user, err.Error()) - } + dj.SendPrivateMessage(user, err.Error()) } } } diff --git a/service.go b/service.go index 541605b..7c67733 100644 --- a/service.go +++ b/service.go @@ -8,14 +8,15 @@ package main import ( + "fmt" "github.com/layeh/gumble/gumble" ) // Service interface. Each service should implement these functions type Service interface { ServiceName() string - URLRegex(string) bool // Can service deal with URL - NewRequest(*gumble.User, string) error // Create song/playlist and add to the queue + URLRegex(string) bool // Can service deal with URL + NewRequest(*gumble.User, string) (string, error) // Create song/playlist and add to the queue } // Song interface. Each service will implement these @@ -50,3 +51,34 @@ type Playlist interface { } var services = []Service{YouTube{}} + +func findServiceAndAdd(user *gumble.User, url string) (string, error) { + var urlService Service + + // Checks all services to see if any can take the URL + for _, service := range services { + if service.URLRegex(url) { + urlService = service + } + } + + if urlService == nil { + return nil, errors.New("INVALID_URL") + } else { + oldLength := dj.queue.Len() + if title, err := urlService.NewRequest(user, url); err == nil { + + // Starts playing the new song if nothing else is playing + if oldLength == 0 && dj.queue.Len() != 0 && !dj.audioStream.IsPlaying() { + if err := dj.queue.CurrentSong().Download(); err == nil { + dj.queue.CurrentSong().Play() + } else { + dj.queue.CurrentSong().Delete() + dj.queue.OnSongFinished() + return nil, errors.New("FAILED_TO_DOWNLOAD") + } + } + } + return title, err + } +} diff --git a/service_youtube.go b/service_youtube.go index 4c60cd0..a831f09 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -39,7 +39,7 @@ var youtubeVideoPatterns = []string{ // YOUTUBE SERVICE // --------------- -type YouTube struct {} +type YouTube struct{} // Name of the service func (y YouTube) ServiceName() string { @@ -63,16 +63,16 @@ func RegexpFromURL(url string, patterns []string) *regexp.Regexp { } // Creates the requested song/playlist and adds to the queue -func (y YouTube) NewRequest(user *gumble.User, url string) error { +func (y YouTube) NewRequest(user *gumble.User, url string) (string, error) { var shortURL, startOffset = "", "" if re, err := regexp.Compile(youtubePlaylistPattern); err == nil { if re.MatchString(url) { if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { shortURL = re.FindStringSubmatch(url)[1] - _, err := NewYouTubePlaylist(user.Name, shortURL) - return err + playlist, err := NewYouTubePlaylist(user.Name, shortURL) + return playlist.Title(), err } else { - return errors.New("NO_PLAYLIST_PERMISSION") + return nil, errors.New("NO_PLAYLIST_PERMISSION") } } else { re = RegexpFromURL(url, youtubeVideoPatterns) @@ -81,11 +81,11 @@ func (y YouTube) NewRequest(user *gumble.User, url string) error { if len(matches[0]) == 3 { startOffset = matches[0][2] } - _, err := NewYouTubeSong(user.Name, shortURL, startOffset, nil) - return err + song, err := NewYouTubeSong(user.Name, shortURL, startOffset, nil) + return song.Title(), err } } else { - return err + return nil, err } } diff --git a/web.go b/web.go index 76f826b..b513255 100644 --- a/web.go +++ b/web.go @@ -5,64 +5,58 @@ import ( "io/ioutil" "math/rand" "net/http" + "html" "strings" "time" "github.com/layeh/gumble/gumble" ) -var client_token = make(map[string]string) -var token_client = make(map[string]string) +var client_token = make(map[*gumble.User]string) +var token_client = make(map[string]*gumble.User) var external_ip = "" -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func handler(w http.ResponseWriter, r *http.Request) { - var uname = token_client[r.URL.Path[1:]] - if uname == "" { - fmt.Fprintf(w, "I don't know you") - } else { - fmt.Fprintf(w, "Hi there, I love %s!", uname) - } -} - func Webserver() { - http.HandleFunc("/", handler) + http.HandleFunc("/", homepage) + http.HandleFunc("/add", addSong) http.ListenAndServe(":9563", nil) rand.Seed(time.Now().UnixNano()) } +func homepage(w http.ResponseWriter, r *http.Request) { + var uname = token_client[r.FormValue("token")] + if uname == "" { + fmt.Fprintf(w, "Invalid Token") + } else { + fmt.Fprintf(w, "Hang in there %s, I haven't made the website yet!", uname.Name) + } +} + +func addSong(w http.ResponseWriter, r *http.Request) { + var uname = token_client[r.FormValue("token")] + if uname == "" { + fmt.Fprintf(w, "Invalid Token") + } else { + var url = UnescapeString(r.FormValue("url")) + + } +} + func GetWebAddress(user *gumble.User) { - if client_token[user.Name] != "" { - token_client[client_token[user.Name]] = "" + if client_token[user] != "" { + token_client[client_token[user]] = "" } // dealing with collisions var firstLoop = true - for firstLoop || token_client[client_token[user.Name]] != "" { - client_token[user.Name] = randSeq(10) + for firstLoop || token_client[client_token[user]] != "" { + client_token[user] = randSeq(10) firstLoop = false } - token_client[client_token[user.Name]] = user.Name - dj.SendPrivateMessage(user, fmt.Sprintf(WEB_ADDRESS, getIP(), client_token[user.Name], getIP(), client_token[user.Name])) + token_client[client_token[user]] = user + dj.SendPrivateMessage(user, fmt.Sprintf(WEB_ADDRESS, getIP(), client_token[user], getIP(), client_token[user])) } +// Gets the external ip address for the server func getIP() string { if external_ip != "" { return external_ip @@ -79,9 +73,9 @@ func getIP() string { } } -var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - +// Generates a pseudorandom string of characters func randSeq(n int) string { + var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") b := make([]rune, n) for i := range b { b[i] = letters[rand.Intn(len(letters))] From fb9f9cc418787b1f9acf8d745b6635e30c3a0311 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Tue, 28 Jul 2015 21:40:44 +0100 Subject: [PATCH 002/297] Fixing build issues --- service.go | 9 ++++++--- web.go | 3 +-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/service.go b/service.go index 7c67733..551fc28 100644 --- a/service.go +++ b/service.go @@ -8,7 +8,8 @@ package main import ( - "fmt" + "errors" + "github.com/layeh/gumble/gumble" ) @@ -63,9 +64,11 @@ func findServiceAndAdd(user *gumble.User, url string) (string, error) { } if urlService == nil { - return nil, errors.New("INVALID_URL") + return "", errors.New("INVALID_URL") } else { oldLength := dj.queue.Len() + var title string + var err error if title, err := urlService.NewRequest(user, url); err == nil { // Starts playing the new song if nothing else is playing @@ -75,7 +78,7 @@ func findServiceAndAdd(user *gumble.User, url string) (string, error) { } else { dj.queue.CurrentSong().Delete() dj.queue.OnSongFinished() - return nil, errors.New("FAILED_TO_DOWNLOAD") + return "", errors.New("FAILED_TO_DOWNLOAD") } } } diff --git a/web.go b/web.go index b513255..cc392b2 100644 --- a/web.go +++ b/web.go @@ -5,7 +5,6 @@ import ( "io/ioutil" "math/rand" "net/http" - "html" "strings" "time" @@ -38,7 +37,7 @@ func addSong(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Invalid Token") } else { var url = UnescapeString(r.FormValue("url")) - + } } From ad25f4bcc3b3fa3adbf1f115c5cd3ce58eb1df9d Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Tue, 28 Jul 2015 21:43:02 +0100 Subject: [PATCH 003/297] Fixing build issues --- service_youtube.go | 4 ++-- web.go | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/service_youtube.go b/service_youtube.go index a831f09..9a94723 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -72,7 +72,7 @@ func (y YouTube) NewRequest(user *gumble.User, url string) (string, error) { playlist, err := NewYouTubePlaylist(user.Name, shortURL) return playlist.Title(), err } else { - return nil, errors.New("NO_PLAYLIST_PERMISSION") + return "", errors.New("NO_PLAYLIST_PERMISSION") } } else { re = RegexpFromURL(url, youtubeVideoPatterns) @@ -85,7 +85,7 @@ func (y YouTube) NewRequest(user *gumble.User, url string) (string, error) { return song.Title(), err } } else { - return nil, err + return "", err } } diff --git a/web.go b/web.go index cc392b2..28ae8cd 100644 --- a/web.go +++ b/web.go @@ -24,7 +24,7 @@ func Webserver() { func homepage(w http.ResponseWriter, r *http.Request) { var uname = token_client[r.FormValue("token")] - if uname == "" { + if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { fmt.Fprintf(w, "Hang in there %s, I haven't made the website yet!", uname.Name) @@ -33,7 +33,7 @@ func homepage(w http.ResponseWriter, r *http.Request) { func addSong(w http.ResponseWriter, r *http.Request) { var uname = token_client[r.FormValue("token")] - if uname == "" { + if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { var url = UnescapeString(r.FormValue("url")) @@ -43,11 +43,11 @@ func addSong(w http.ResponseWriter, r *http.Request) { func GetWebAddress(user *gumble.User) { if client_token[user] != "" { - token_client[client_token[user]] = "" + token_client[client_token[user]] = nil } // dealing with collisions var firstLoop = true - for firstLoop || token_client[client_token[user]] != "" { + for firstLoop || token_client[client_token[user]] != nil { client_token[user] = randSeq(10) firstLoop = false } From 5f73536b666c5333522e2a00c088c6f0f1df5259 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Tue, 28 Jul 2015 21:43:46 +0100 Subject: [PATCH 004/297] Fixing build issues --- web.go | 1 + 1 file changed, 1 insertion(+) diff --git a/web.go b/web.go index 28ae8cd..8d5b379 100644 --- a/web.go +++ b/web.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "html" "io/ioutil" "math/rand" "net/http" From a7e6b74b9d3b9191541620c5922c56105384491a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Tue, 28 Jul 2015 21:47:05 +0100 Subject: [PATCH 005/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index 8d5b379..b44c601 100644 --- a/web.go +++ b/web.go @@ -37,7 +37,7 @@ func addSong(w http.ResponseWriter, r *http.Request) { if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { - var url = UnescapeString(r.FormValue("url")) + var url = html.UnescapeString(r.FormValue("url")) } } From a0f8ee59a1a738ad6a3787b4ad7904540fa38010 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Tue, 28 Jul 2015 21:48:20 +0100 Subject: [PATCH 006/297] Fixing build issues --- service.go | 2 +- web.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/service.go b/service.go index 551fc28..bc0db34 100644 --- a/service.go +++ b/service.go @@ -69,7 +69,7 @@ func findServiceAndAdd(user *gumble.User, url string) (string, error) { oldLength := dj.queue.Len() var title string var err error - if title, err := urlService.NewRequest(user, url); err == nil { + if title, err = urlService.NewRequest(user, url); err == nil { // Starts playing the new song if nothing else is playing if oldLength == 0 && dj.queue.Len() != 0 && !dj.audioStream.IsPlaying() { diff --git a/web.go b/web.go index b44c601..afc760f 100644 --- a/web.go +++ b/web.go @@ -38,7 +38,7 @@ func addSong(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Invalid Token") } else { var url = html.UnescapeString(r.FormValue("url")) - + fmt.Fprintf(w, url) } } From 5d68fc57b76bfe96faa427da2e5d88d635b23a0a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Tue, 28 Jul 2015 21:56:07 +0100 Subject: [PATCH 007/297] Fixing build issues --- strings.go | 4 ++-- web.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/strings.go b/strings.go index e8cf2b5..0ea151b 100644 --- a/strings.go +++ b/strings.go @@ -173,5 +173,5 @@ const CURRENT_SONG_PLAYLIST_HTML = ` // URL of the server for connecting via a web address const WEB_ADDRESS = ` - Control mumbledj from a web browser: http://%s:9563/%s -` \ No newline at end of file + Control mumbledj from a web browser: http://%s/%s +` diff --git a/web.go b/web.go index afc760f..3cb5e55 100644 --- a/web.go +++ b/web.go @@ -19,12 +19,12 @@ var external_ip = "" func Webserver() { http.HandleFunc("/", homepage) http.HandleFunc("/add", addSong) - http.ListenAndServe(":9563", nil) + http.ListenAndServe(":80", nil) rand.Seed(time.Now().UnixNano()) } func homepage(w http.ResponseWriter, r *http.Request) { - var uname = token_client[r.FormValue("token")] + var uname = token_client[r.URL.Path[1:]] if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { From 7375b4174ae6a7810bc557109a4068ad09f4266c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Tue, 28 Jul 2015 22:05:49 +0100 Subject: [PATCH 008/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index 3cb5e55..a7b43e0 100644 --- a/web.go +++ b/web.go @@ -19,7 +19,7 @@ var external_ip = "" func Webserver() { http.HandleFunc("/", homepage) http.HandleFunc("/add", addSong) - http.ListenAndServe(":80", nil) + http.ListenAndServe(":9563", nil) rand.Seed(time.Now().UnixNano()) } From cccb76d553cdbc0f95c6c99a74c951441c192302 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Tue, 28 Jul 2015 22:06:09 +0100 Subject: [PATCH 009/297] Fixing build issues --- strings.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strings.go b/strings.go index 0ea151b..9d5524f 100644 --- a/strings.go +++ b/strings.go @@ -173,5 +173,5 @@ const CURRENT_SONG_PLAYLIST_HTML = ` // URL of the server for connecting via a web address const WEB_ADDRESS = ` - Control mumbledj from a web browser: http://%s/%s + Control mumbledj from a web browser: http://%s:9563/%s ` From 90671fd1a504a736a7de8cb576863c98f53da088 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 29 Jul 2015 02:04:32 +0100 Subject: [PATCH 010/297] Fixing build issues --- Makefile | 1 + commands.go | 4 +++- index.html | 18 ++++++++++++++++++ main.go | 6 +++--- web.go | 2 +- 5 files changed, 26 insertions(+), 5 deletions(-) create mode 100644 index.html diff --git a/Makefile b/Makefile index 5de2412..36b484b 100644 --- a/Makefile +++ b/Makefile @@ -12,6 +12,7 @@ clean: install: mkdir -p ~/.mumbledj/config mkdir -p ~/.mumbledj/songs + mkdir -p ~/.mumbledj/web if [ -a ~/.mumbledj/config/mumbledj.gcfg ]; then mv ~/.mumbledj/config/mumbledj.gcfg ~/.mumbledj/config/mumbledj_backup.gcfg; fi; cp -u config.gcfg ~/.mumbledj/config/mumbledj.gcfg if [ -d ~/bin ]; then cp -f mumbledj* ~/bin/mumbledj; else sudo cp -f mumbledj* /usr/local/bin/mumbledj; fi; diff --git a/commands.go b/commands.go index 99db8fd..59d66ea 100644 --- a/commands.go +++ b/commands.go @@ -166,9 +166,10 @@ func parseCommand(user *gumble.User, username, command string) { // add performs !add functionality. Checks input URL for service, and adds // the URL to the queue if the format matches. -func add(user *gumble.User, url string) { +func add(user *gumble.User, url string) error { if url == "" { dj.SendPrivateMessage(user, NO_ARGUMENT_MSG) + return errors.New("NO_ARGUMENT") } else { title, err := findServiceAndAdd(user, url) if err == nil { @@ -176,6 +177,7 @@ func add(user *gumble.User, url string) { } else { dj.SendPrivateMessage(user, err.Error()) } + return err } } diff --git a/index.html b/index.html new file mode 100644 index 0000000..e4c1635 --- /dev/null +++ b/index.html @@ -0,0 +1,18 @@ + + + + + %s - mumbledj + + + +

Add Song Form

+ + + + \ No newline at end of file diff --git a/main.go b/main.go index bc8d710..b841957 100644 --- a/main.go +++ b/main.go @@ -102,7 +102,7 @@ func (dj *mumbledj) OnTextMessage(e *gumble.TextMessageEvent) { func (dj *mumbledj) OnUserChange(e *gumble.UserChangeEvent) { if e.Type.Has(gumble.UserChangeDisconnected) { if dj.audioStream.IsPlaying() { - if dj.queue.CurrentSong().Playlist() != nil { + if !isNull(dj.queue.CurrentSong().Playlist()) { dj.queue.CurrentSong().Playlist().RemoveSkip(e.User.Name) } dj.queue.CurrentSong().RemoveSkip(e.User.Name) @@ -228,8 +228,8 @@ func main() { if err := dj.client.Connect(); err != nil { fmt.Printf("Could not connect to Mumble server at %s:%s.\n", address, port) os.Exit(1) - } - + } + Webserver() <-dj.keepAlive diff --git a/web.go b/web.go index a7b43e0..c26bcf6 100644 --- a/web.go +++ b/web.go @@ -38,7 +38,7 @@ func addSong(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Invalid Token") } else { var url = html.UnescapeString(r.FormValue("url")) - fmt.Fprintf(w, url) + add(uname, url) } } From ef0d9691b8823ccc8cb30c061a16757af20aa4d8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 29 Jul 2015 02:05:21 +0100 Subject: [PATCH 011/297] Fixing build issues --- main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.go b/main.go index b841957..dd7bec3 100644 --- a/main.go +++ b/main.go @@ -102,7 +102,7 @@ func (dj *mumbledj) OnTextMessage(e *gumble.TextMessageEvent) { func (dj *mumbledj) OnUserChange(e *gumble.UserChangeEvent) { if e.Type.Has(gumble.UserChangeDisconnected) { if dj.audioStream.IsPlaying() { - if !isNull(dj.queue.CurrentSong().Playlist()) { + if !isNil(dj.queue.CurrentSong().Playlist()) { dj.queue.CurrentSong().Playlist().RemoveSkip(e.User.Name) } dj.queue.CurrentSong().RemoveSkip(e.User.Name) From 32006b3e50990148ed13fa54a22ad422976de71b Mon Sep 17 00:00:00 2001 From: Michael Oultram Date: Wed, 29 Jul 2015 23:34:51 +0100 Subject: [PATCH 012/297] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f58a1bd..71a878f 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ All commandline parameters are optional. Below are descriptions of all the avail * `-key`: Path to user PEM key. Defaults to no key. * `-insecure`: If included, the bot will not check the certs for the server. Try using this commandline flag if you are having connection issues. * `-accesstokens`: List of access tokens for the bot separated by spaces. Defaults to no access tokens. +* `-verbose`: Prints out song status into the console. ## FEATURES * Plays audio from both YouTube videos and YouTube playlists! @@ -50,6 +51,7 @@ Command | Description | Arguments | Admin | Example **help** | Displays this list of commands in Mumble chat. | None | No | `!help` **volume** | Either outputs the current volume or changes the current volume. If desired volume is not provided, the current volume will be displayed in chat. Otherwise, the volume for the bot will be changed to desired volume if it is within the allowed volume range. | None OR desired volume | No | `!volume 0.5`, `!volume` **move** | Moves MumbleDJ into channel if it exists. | Channel | Yes | `!move Music` +**web** | Displays a unique url for the user to control mumbledj from a web browser | None | No | `!web` **reload** | Reloads `mumbledj.gcfg` to retrieve updated configuration settings. | None | Yes | `!reload` **reset** | Stops all audio and resets the song queue. | None | Yes | `!reset` **numsongs** | Outputs the number of songs in the queue in chat. Individual songs and songs within playlists are both counted. | None | No | `!numsongs` From dbc58bd95b18c47042dfb249bea2e36e6d239d73 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 13:48:53 +0100 Subject: [PATCH 013/297] Using a web template --- commands.go | 8 +- index.html | 28 ++++++- main.go | 13 ++- service.go | 8 +- service_youtube.go | 196 ++++++++++++++++++++++----------------------- web.go | 61 ++++++++++---- 6 files changed, 185 insertions(+), 129 deletions(-) diff --git a/commands.go b/commands.go index 59d66ea..d4dc02d 100644 --- a/commands.go +++ b/commands.go @@ -171,13 +171,7 @@ func add(user *gumble.User, url string) error { dj.SendPrivateMessage(user, NO_ARGUMENT_MSG) return errors.New("NO_ARGUMENT") } else { - title, err := findServiceAndAdd(user, url) - if err == nil { - dj.client.Self.Channel.Send(fmt.Sprintf(SONG_ADDED_HTML, user.Name, title), false) - } else { - dj.SendPrivateMessage(user, err.Error()) - } - return err + return findServiceAndAdd(user, url) } } diff --git a/index.html b/index.html index e4c1635..5659235 100644 --- a/index.html +++ b/index.html @@ -2,17 +2,37 @@ - %s - mumbledj + {{user}} - mumbledj +

Add Song Form

- - + + + + + \ No newline at end of file diff --git a/main.go b/main.go index dd7bec3..91c00bb 100644 --- a/main.go +++ b/main.go @@ -152,6 +152,17 @@ func isNil(a interface{}) bool { return a == nil || reflect.ValueOf(a).IsNil() } +func RegexpFromURL(url string, patterns []string) *regexp.Regexp { + for _, pattern := range patterns { + if re, err := regexp.Compile(pattern); err == nil { + if re.MatchString(url) { + return re + } + } + } + return nil +} + // dj variable declaration. This is done outside of main() to allow global use. var dj = mumbledj{ keepAlive: make(chan bool), @@ -230,7 +241,7 @@ func main() { os.Exit(1) } - Webserver() + Webserver(9563) <-dj.keepAlive } diff --git a/service.go b/service.go index bc0db34..36c77ab 100644 --- a/service.go +++ b/service.go @@ -53,7 +53,7 @@ type Playlist interface { var services = []Service{YouTube{}} -func findServiceAndAdd(user *gumble.User, url string) (string, error) { +func findServiceAndAdd(user *gumble.User, url string) error { var urlService Service // Checks all services to see if any can take the URL @@ -69,7 +69,9 @@ func findServiceAndAdd(user *gumble.User, url string) (string, error) { oldLength := dj.queue.Len() var title string var err error + if title, err = urlService.NewRequest(user, url); err == nil { + dj.client.Self.Channel.Send(fmt.Sprintf(SONG_ADDED_HTML, user.Name, title), false) // Starts playing the new song if nothing else is playing if oldLength == 0 && dj.queue.Len() != 0 && !dj.audioStream.IsPlaying() { @@ -81,7 +83,9 @@ func findServiceAndAdd(user *gumble.User, url string) (string, error) { return "", errors.New("FAILED_TO_DOWNLOAD") } } + } else { + dj.SendPrivateMessage(user, err.Error()) } - return title, err + return err } } diff --git a/service_youtube.go b/service_youtube.go index 9a94723..63a343d 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -35,64 +35,13 @@ var youtubeVideoPatterns = []string{ `https?:\/\/www.youtube.com\/v\/([\w-]+)(\?t=\d*m?\d*s?)?`, } -// --------------- -// YOUTUBE SERVICE -// --------------- +// ------ +// TYPES +// ------ +// YouTube implements the Service interface type YouTube struct{} -// Name of the service -func (y YouTube) ServiceName() string { - return "Youtube" -} - -// Checks to see if service will accept URL -func (y YouTube) URLRegex(url string) bool { - return RegexpFromURL(url, append(youtubeVideoPatterns, []string{youtubePlaylistPattern}...)) != nil -} - -func RegexpFromURL(url string, patterns []string) *regexp.Regexp { - for _, pattern := range patterns { - if re, err := regexp.Compile(pattern); err == nil { - if re.MatchString(url) { - return re - } - } - } - return nil -} - -// Creates the requested song/playlist and adds to the queue -func (y YouTube) NewRequest(user *gumble.User, url string) (string, error) { - var shortURL, startOffset = "", "" - if re, err := regexp.Compile(youtubePlaylistPattern); err == nil { - if re.MatchString(url) { - if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { - shortURL = re.FindStringSubmatch(url)[1] - playlist, err := NewYouTubePlaylist(user.Name, shortURL) - return playlist.Title(), err - } else { - return "", errors.New("NO_PLAYLIST_PERMISSION") - } - } else { - re = RegexpFromURL(url, youtubeVideoPatterns) - matches := re.FindAllStringSubmatch(url, -1) - shortURL = matches[0][1] - if len(matches[0]) == 3 { - startOffset = matches[0][2] - } - song, err := NewYouTubeSong(user.Name, shortURL, startOffset, nil) - return song.Title(), err - } - } else { - return "", err - } -} - -// ------------ -// YOUTUBE SONG -// ------------ - // YouTubeSong holds the metadata for a song extracted from a YouTube video. type YouTubeSong struct { submitter string @@ -107,14 +56,61 @@ type YouTubeSong struct { dontSkip bool } -// NewYouTubeSong gathers the metadata for a song extracted from a YouTube video, and returns +// YouTubePlaylist holds the metadata for a YouTube playlist. +type YouTubePlaylist struct { + id string + title string +} + +// --------------- +// YOUTUBE SERVICE +// --------------- + +// Name of the service +func (yt YouTube) ServiceName() string { + return "Youtube" +} + +// Checks to see if service will accept URL +func (yt YouTube) URLRegex(url string) bool { + return RegexpFromURL(url, append(youtubeVideoPatterns, []string{youtubePlaylistPattern}...)) != nil +} + +// Creates the requested song/playlist and adds to the queue +func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { + var shortURL, startOffset = "", "" + if re, err := regexp.Compile(youtubePlaylistPattern); err == nil { + if re.MatchString(url) { + if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { + shortURL = re.FindStringSubmatch(url)[1] + playlist, err := yt.NewPlaylist(user.Name, shortURL) + return playlist.Title(), err + } else { + return "", errors.New("NO_PLAYLIST_PERMISSION") + } + } else { + re = RegexpFromURL(url, youtubeVideoPatterns) + matches := re.FindAllStringSubmatch(url, -1) + shortURL = matches[0][1] + if len(matches[0]) == 3 { + startOffset = matches[0][2] + } + song, err := yt.NewSong(user.Name, shortURL, startOffset, nil) + return song.Title(), err + } + } else { + return "", err + } +} + +// NewSong gathers the metadata for a song extracted from a YouTube video, and returns // the song. -func NewYouTubeSong(user, id, offset string, playlist *YouTubePlaylist) (*YouTubeSong, error) { +func (yt YouTube) NewSong(user, id, offset string, playlist *YouTubePlaylist) (*YouTubeSong, error) { var apiResponse *jsonq.JsonQuery var err error url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s", id, os.Getenv("YOUTUBE_API_KEY")) - if apiResponse, err = PerformGetRequest(url); err != nil { + if apiResponse, err = yt.PerformGetRequest(url); err != nil { return nil, errors.New(INVALID_API_KEY) } @@ -203,6 +199,46 @@ func NewYouTubeSong(user, id, offset string, playlist *YouTubePlaylist) (*YouTub return nil, errors.New(VIDEO_TOO_LONG_MSG) } +// NewPlaylist gathers the metadata for a YouTube playlist and returns it. +func (yt YouTube) NewPlaylist(user, id string) (*YouTubePlaylist, error) { + var apiResponse *jsonq.JsonQuery + var err error + // Retrieve title of playlist + url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=%s&key=%s", + id, os.Getenv("YOUTUBE_API_KEY")) + if apiResponse, err = yt.PerformGetRequest(url); err != nil { + return nil, err + } + title, _ := apiResponse.String("items", "0", "snippet", "title") + + playlist := &YouTubePlaylist{ + id: id, + title: title, + } + + // Retrieve items in playlist + url = fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=%s&key=%s", + id, os.Getenv("YOUTUBE_API_KEY")) + if apiResponse, err = yt.PerformGetRequest(url); err != nil { + return nil, err + } + numVideos, _ := apiResponse.Int("pageInfo", "totalResults") + if numVideos > 50 { + numVideos = 50 + } + + for i := 0; i < numVideos; i++ { + index := strconv.Itoa(i) + videoID, _ := apiResponse.String("items", index, "snippet", "resourceId", "videoId") + yt.NewSong(user, videoID, "", playlist) + } + return playlist, nil +} + +// ------------ +// YOUTUBE SONG +// ------------ + // Download downloads the song via youtube-dl if it does not already exist on disk. // All downloaded songs are stored in ~/.mumbledj/songs and should be automatically cleaned. func (s *YouTubeSong) Download() error { @@ -380,48 +416,6 @@ func (s *YouTubeSong) SetDontSkip(value bool) { // YOUTUBE PLAYLIST // ---------------- -// YouTubePlaylist holds the metadata for a YouTube playlist. -type YouTubePlaylist struct { - id string - title string -} - -// NewYouTubePlaylist gathers the metadata for a YouTube playlist and returns it. -func NewYouTubePlaylist(user, id string) (*YouTubePlaylist, error) { - var apiResponse *jsonq.JsonQuery - var err error - // Retrieve title of playlist - url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=%s&key=%s", - id, os.Getenv("YOUTUBE_API_KEY")) - if apiResponse, err = PerformGetRequest(url); err != nil { - return nil, err - } - title, _ := apiResponse.String("items", "0", "snippet", "title") - - playlist := &YouTubePlaylist{ - id: id, - title: title, - } - - // Retrieve items in playlist - url = fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=%s&key=%s", - id, os.Getenv("YOUTUBE_API_KEY")) - if apiResponse, err = PerformGetRequest(url); err != nil { - return nil, err - } - numVideos, _ := apiResponse.Int("pageInfo", "totalResults") - if numVideos > 50 { - numVideos = 50 - } - - for i := 0; i < numVideos; i++ { - index := strconv.Itoa(i) - videoID, _ := apiResponse.String("items", index, "snippet", "resourceId", "videoId") - NewYouTubeSong(user, videoID, "", playlist) - } - return playlist, nil -} - // AddSkip adds a skip to the playlist's skippers slice. func (p *YouTubePlaylist) AddSkip(username string) error { for _, user := range dj.playlistSkips[p.ID()] { @@ -475,7 +469,7 @@ func (p *YouTubePlaylist) Title() string { // ----------- // PerformGetRequest does all the grunt work for a YouTube HTTPS GET request. -func PerformGetRequest(url string) (*jsonq.JsonQuery, error) { +func (yt YouTube) PerformGetRequest(url string) (*jsonq.JsonQuery, error) { jsonString := "" if response, err := http.Get(url); err == nil { diff --git a/web.go b/web.go index c26bcf6..25ce20f 100644 --- a/web.go +++ b/web.go @@ -12,37 +12,70 @@ import ( "github.com/layeh/gumble/gumble" ) -var client_token = make(map[*gumble.User]string) -var token_client = make(map[string]*gumble.User) -var external_ip = "" - -func Webserver() { - http.HandleFunc("/", homepage) - http.HandleFunc("/add", addSong) - http.ListenAndServe(":9563", nil) - rand.Seed(time.Now().UnixNano()) +type WebServer struct { + port int + client_token map[*gumble.User]string + token_client map[string]*gumble.User } -func homepage(w http.ResponseWriter, r *http.Request) { +type Page struct { + siteUrl string + token string +} + +var external_ip = "" + +func Webserver(port int) *WebServer { + var webserver = WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} + http.HandleFunc("/", webServer.homepage) + http.HandleFunc("/add", webserver.add) + http.HandleFunc("/volume", webserver.volume) + http.HandleFunc("/skip", webserver.skip) + http.ListenAndServe(":"+port, nil) + rand.Seed(time.Now().UnixNano()) + return &webserver +} + +func (w WebServer) homepage(w http.ResponseWriter, r *http.Request) { var uname = token_client[r.URL.Path[1:]] if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { - fmt.Fprintf(w, "Hang in there %s, I haven't made the website yet!", uname.Name) + t, _ := template.ParseFiles("index.html") + t.Execute(w, Page{"http://" + getIp() + ":" + w.port + "/", r.URL.Path[1:]}) } } -func addSong(w http.ResponseWriter, r *http.Request) { +func (w WebServer) add(w http.ResponseWriter, r *http.Request) { var uname = token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { - var url = html.UnescapeString(r.FormValue("url")) + add(uname, html.UnescapeString(r.FormValue("value"))) + } +} + +func (w WebServer) volume(w http.ResponseWriter, r *http.Request) { + var uname = token_client[r.FormValue("token")] + if uname == nil { + fmt.Fprintf(w, "Invalid Token") + } else { + var url = html.UnescapeString(r.FormValue("value")) add(uname, url) } } -func GetWebAddress(user *gumble.User) { +func (w WebServer) skip(w http.ResponseWriter, r *http.Request) { + var uname = token_client[r.FormValue("token")] + if uname == nil { + fmt.Fprintf(w, "Invalid Token") + } else { + var url = html.UnescapeString(r.FormValue("value")) + add(uname, url) + } +} + +func (w WebServer) GetWebAddress(user *gumble.User) { if client_token[user] != "" { token_client[client_token[user]] = nil } From eb8afc4404d9eeca874e015f13fa75e56abe2b80 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 13:54:13 +0100 Subject: [PATCH 014/297] Fixing build issues --- main.go | 1 + service.go | 5 +++-- web.go | 10 +++++----- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/main.go b/main.go index 91c00bb..8a9d12a 100644 --- a/main.go +++ b/main.go @@ -14,6 +14,7 @@ import ( "os" "os/user" "reflect" + "regexp" "strings" "time" diff --git a/service.go b/service.go index 36c77ab..13a1d08 100644 --- a/service.go +++ b/service.go @@ -9,6 +9,7 @@ package main import ( "errors" + "fmt" "github.com/layeh/gumble/gumble" ) @@ -64,7 +65,7 @@ func findServiceAndAdd(user *gumble.User, url string) error { } if urlService == nil { - return "", errors.New("INVALID_URL") + return errors.New("INVALID_URL") } else { oldLength := dj.queue.Len() var title string @@ -80,7 +81,7 @@ func findServiceAndAdd(user *gumble.User, url string) error { } else { dj.queue.CurrentSong().Delete() dj.queue.OnSongFinished() - return "", errors.New("FAILED_TO_DOWNLOAD") + return errors.New("FAILED_TO_DOWNLOAD") } } } else { diff --git a/web.go b/web.go index 25ce20f..398cc02 100644 --- a/web.go +++ b/web.go @@ -36,7 +36,7 @@ func Webserver(port int) *WebServer { return &webserver } -func (w WebServer) homepage(w http.ResponseWriter, r *http.Request) { +func (web WebServer) homepage(w http.ResponseWriter, r *http.Request) { var uname = token_client[r.URL.Path[1:]] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -46,7 +46,7 @@ func (w WebServer) homepage(w http.ResponseWriter, r *http.Request) { } } -func (w WebServer) add(w http.ResponseWriter, r *http.Request) { +func (web WebServer) add(w http.ResponseWriter, r *http.Request) { var uname = token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -55,7 +55,7 @@ func (w WebServer) add(w http.ResponseWriter, r *http.Request) { } } -func (w WebServer) volume(w http.ResponseWriter, r *http.Request) { +func (web WebServer) volume(w http.ResponseWriter, r *http.Request) { var uname = token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -65,7 +65,7 @@ func (w WebServer) volume(w http.ResponseWriter, r *http.Request) { } } -func (w WebServer) skip(w http.ResponseWriter, r *http.Request) { +func (web WebServer) skip(w http.ResponseWriter, r *http.Request) { var uname = token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -75,7 +75,7 @@ func (w WebServer) skip(w http.ResponseWriter, r *http.Request) { } } -func (w WebServer) GetWebAddress(user *gumble.User) { +func (web WebServer) GetWebAddress(user *gumble.User) { if client_token[user] != "" { token_client[client_token[user]] = nil } From 921af2f1b05a1f9466e09db329cd9f5b024b719d Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 13:58:31 +0100 Subject: [PATCH 015/297] Fixing build issues --- web.go | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/web.go b/web.go index 398cc02..c0619c8 100644 --- a/web.go +++ b/web.go @@ -6,6 +6,7 @@ import ( "io/ioutil" "math/rand" "net/http" + "strconv" "strings" "time" @@ -27,27 +28,27 @@ var external_ip = "" func Webserver(port int) *WebServer { var webserver = WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} - http.HandleFunc("/", webServer.homepage) + http.HandleFunc("/", webserver.homepage) http.HandleFunc("/add", webserver.add) http.HandleFunc("/volume", webserver.volume) http.HandleFunc("/skip", webserver.skip) - http.ListenAndServe(":"+port, nil) + http.ListenAndServe(":"+strconv.Itoa(port), nil) rand.Seed(time.Now().UnixNano()) return &webserver } func (web WebServer) homepage(w http.ResponseWriter, r *http.Request) { - var uname = token_client[r.URL.Path[1:]] + var uname = web.token_client[r.URL.Path[1:]] if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { t, _ := template.ParseFiles("index.html") - t.Execute(w, Page{"http://" + getIp() + ":" + w.port + "/", r.URL.Path[1:]}) + t.Execute(w, Page{"http://" + getIp() + ":" + web.port + "/", r.URL.Path[1:]}) } } func (web WebServer) add(w http.ResponseWriter, r *http.Request) { - var uname = token_client[r.FormValue("token")] + var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { @@ -56,7 +57,7 @@ func (web WebServer) add(w http.ResponseWriter, r *http.Request) { } func (web WebServer) volume(w http.ResponseWriter, r *http.Request) { - var uname = token_client[r.FormValue("token")] + var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { @@ -66,7 +67,7 @@ func (web WebServer) volume(w http.ResponseWriter, r *http.Request) { } func (web WebServer) skip(w http.ResponseWriter, r *http.Request) { - var uname = token_client[r.FormValue("token")] + var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { @@ -76,17 +77,17 @@ func (web WebServer) skip(w http.ResponseWriter, r *http.Request) { } func (web WebServer) GetWebAddress(user *gumble.User) { - if client_token[user] != "" { - token_client[client_token[user]] = nil + if web.client_token[user] != "" { + web.token_client[web.client_token[user]] = nil } // dealing with collisions var firstLoop = true - for firstLoop || token_client[client_token[user]] != nil { - client_token[user] = randSeq(10) + for firstLoop || web.token_client[web.client_token[user]] != nil { + web.client_token[user] = randSeq(10) firstLoop = false } - token_client[client_token[user]] = user - dj.SendPrivateMessage(user, fmt.Sprintf(WEB_ADDRESS, getIP(), client_token[user], getIP(), client_token[user])) + web.token_client[web.client_token[user]] = user + dj.SendPrivateMessage(user, fmt.Sprintf(WEB_ADDRESS, getIP(), web.client_token[user], getIP(), web.client_token[user])) } // Gets the external ip address for the server From a4dd48007d0de9705c42ca3733f550c17c168cf1 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:01:55 +0100 Subject: [PATCH 016/297] Fixing build issues --- commands.go | 2 +- main.go | 4 +++- web.go | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/commands.go b/commands.go index d4dc02d..4be4eeb 100644 --- a/commands.go +++ b/commands.go @@ -85,7 +85,7 @@ func parseCommand(user *gumble.User, username, command string) { // Web command case dj.conf.Aliases.WebAlias: if dj.HasPermission(username, dj.conf.Permissions.AdminWeb) { - GetWebAddress(user) + web.GetWebAddress(user) } else { dj.SendPrivateMessage(user, NO_PERMISSION_MSG) } diff --git a/main.go b/main.go index 8a9d12a..abc1ca0 100644 --- a/main.go +++ b/main.go @@ -172,6 +172,8 @@ var dj = mumbledj{ cache: NewSongCache(), } +var web *Webserver + // main primarily performs startup tasks. Grabs and parses commandline // args, sets up the gumble client and its listeners, and then connects to the server. func main() { @@ -242,7 +244,7 @@ func main() { os.Exit(1) } - Webserver(9563) + web = Webserver(9563) <-dj.keepAlive } diff --git a/web.go b/web.go index c0619c8..8b9fc23 100644 --- a/web.go +++ b/web.go @@ -3,6 +3,7 @@ package main import ( "fmt" "html" + "html/template" "io/ioutil" "math/rand" "net/http" @@ -43,7 +44,7 @@ func (web WebServer) homepage(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Invalid Token") } else { t, _ := template.ParseFiles("index.html") - t.Execute(w, Page{"http://" + getIp() + ":" + web.port + "/", r.URL.Path[1:]}) + t.Execute(w, Page{"http://" + getIP() + ":" + web.port + "/", r.URL.Path[1:]}) } } From 2550e43710ae1f3a8a0191881c53a98e98eb1ff7 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:03:22 +0100 Subject: [PATCH 017/297] Fixing build issues --- main.go | 2 +- web.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index abc1ca0..77d4251 100644 --- a/main.go +++ b/main.go @@ -172,7 +172,7 @@ var dj = mumbledj{ cache: NewSongCache(), } -var web *Webserver +var web *WebServer // main primarily performs startup tasks. Grabs and parses commandline // args, sets up the gumble client and its listeners, and then connects to the server. diff --git a/web.go b/web.go index 8b9fc23..21a8377 100644 --- a/web.go +++ b/web.go @@ -44,7 +44,7 @@ func (web WebServer) homepage(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Invalid Token") } else { t, _ := template.ParseFiles("index.html") - t.Execute(w, Page{"http://" + getIP() + ":" + web.port + "/", r.URL.Path[1:]}) + t.Execute(w, Page{"http://" + getIP() + ":" + strconv.Itoa(web.port) + "/", r.URL.Path[1:]}) } } From 9ad1eda59f2d536ad08d0971a672a1b1e1cf3e48 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:05:52 +0100 Subject: [PATCH 018/297] Fixing build issues --- main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.go b/main.go index 77d4251..1a280a4 100644 --- a/main.go +++ b/main.go @@ -172,7 +172,7 @@ var dj = mumbledj{ cache: NewSongCache(), } -var web *WebServer +var web WebServer // main primarily performs startup tasks. Grabs and parses commandline // args, sets up the gumble client and its listeners, and then connects to the server. From c4242a9efd84b5599dea412a19352c3be63c96e5 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:06:17 +0100 Subject: [PATCH 019/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index 21a8377..6f8a3a7 100644 --- a/web.go +++ b/web.go @@ -27,7 +27,7 @@ type Page struct { var external_ip = "" -func Webserver(port int) *WebServer { +func Webserver(port int) WebServer { var webserver = WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} http.HandleFunc("/", webserver.homepage) http.HandleFunc("/add", webserver.add) From 03505fd44d1f201ea577e7b8a9dbd89c672f66b7 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:06:33 +0100 Subject: [PATCH 020/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index 6f8a3a7..13883f9 100644 --- a/web.go +++ b/web.go @@ -35,7 +35,7 @@ func Webserver(port int) WebServer { http.HandleFunc("/skip", webserver.skip) http.ListenAndServe(":"+strconv.Itoa(port), nil) rand.Seed(time.Now().UnixNano()) - return &webserver + return webserver } func (web WebServer) homepage(w http.ResponseWriter, r *http.Request) { From 02f6cc49d7ecdee5353adc20f055e3f6122263a8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:07:46 +0100 Subject: [PATCH 021/297] Fixing build issues --- web.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/web.go b/web.go index 13883f9..95f9ba5 100644 --- a/web.go +++ b/web.go @@ -27,7 +27,7 @@ type Page struct { var external_ip = "" -func Webserver(port int) WebServer { +func Webserver(port int) *WebServer { var webserver = WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} http.HandleFunc("/", webserver.homepage) http.HandleFunc("/add", webserver.add) @@ -35,10 +35,10 @@ func Webserver(port int) WebServer { http.HandleFunc("/skip", webserver.skip) http.ListenAndServe(":"+strconv.Itoa(port), nil) rand.Seed(time.Now().UnixNano()) - return webserver + return &webserver } -func (web WebServer) homepage(w http.ResponseWriter, r *http.Request) { +func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.URL.Path[1:]] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -48,7 +48,7 @@ func (web WebServer) homepage(w http.ResponseWriter, r *http.Request) { } } -func (web WebServer) add(w http.ResponseWriter, r *http.Request) { +func (web *WebServer) add(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -57,7 +57,7 @@ func (web WebServer) add(w http.ResponseWriter, r *http.Request) { } } -func (web WebServer) volume(w http.ResponseWriter, r *http.Request) { +func (web *WebServer) volume(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -67,7 +67,7 @@ func (web WebServer) volume(w http.ResponseWriter, r *http.Request) { } } -func (web WebServer) skip(w http.ResponseWriter, r *http.Request) { +func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -77,7 +77,7 @@ func (web WebServer) skip(w http.ResponseWriter, r *http.Request) { } } -func (web WebServer) GetWebAddress(user *gumble.User) { +func (web *WebServer) GetWebAddress(user *gumble.User) { if web.client_token[user] != "" { web.token_client[web.client_token[user]] = nil } From 05eaf4dd3632d44b3759bc96dc2678b671bfc9aa Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:08:21 +0100 Subject: [PATCH 022/297] Fixing build issues --- main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.go b/main.go index 1a280a4..77d4251 100644 --- a/main.go +++ b/main.go @@ -172,7 +172,7 @@ var dj = mumbledj{ cache: NewSongCache(), } -var web WebServer +var web *WebServer // main primarily performs startup tasks. Grabs and parses commandline // args, sets up the gumble client and its listeners, and then connects to the server. From 2be5407aa479a537426b4ce706a4095a55ae160f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:10:40 +0100 Subject: [PATCH 023/297] Fixing build issues --- main.go | 2 +- web.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 77d4251..0f87a45 100644 --- a/main.go +++ b/main.go @@ -244,7 +244,7 @@ func main() { os.Exit(1) } - web = Webserver(9563) + web = &Webserver(9563) <-dj.keepAlive } diff --git a/web.go b/web.go index 95f9ba5..be4ce6e 100644 --- a/web.go +++ b/web.go @@ -27,7 +27,7 @@ type Page struct { var external_ip = "" -func Webserver(port int) *WebServer { +func Webserver(port int) WebServer { var webserver = WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} http.HandleFunc("/", webserver.homepage) http.HandleFunc("/add", webserver.add) @@ -35,7 +35,7 @@ func Webserver(port int) *WebServer { http.HandleFunc("/skip", webserver.skip) http.ListenAndServe(":"+strconv.Itoa(port), nil) rand.Seed(time.Now().UnixNano()) - return &webserver + return webserver } func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { From aee8e95ae1a9dcda5007172aed4bd08931c7a391 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:12:13 +0100 Subject: [PATCH 024/297] Fixing build issues --- main.go | 2 +- web.go | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 0f87a45..77d4251 100644 --- a/main.go +++ b/main.go @@ -244,7 +244,7 @@ func main() { os.Exit(1) } - web = &Webserver(9563) + web = Webserver(9563) <-dj.keepAlive } diff --git a/web.go b/web.go index be4ce6e..1370628 100644 --- a/web.go +++ b/web.go @@ -27,15 +27,14 @@ type Page struct { var external_ip = "" -func Webserver(port int) WebServer { - var webserver = WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} +func Webserver(port int) *WebServer { http.HandleFunc("/", webserver.homepage) http.HandleFunc("/add", webserver.add) http.HandleFunc("/volume", webserver.volume) http.HandleFunc("/skip", webserver.skip) http.ListenAndServe(":"+strconv.Itoa(port), nil) rand.Seed(time.Now().UnixNano()) - return webserver + return &WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} } func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { From 4678298ae9bdb5e5d891794610cb12580659232d Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:12:43 +0100 Subject: [PATCH 025/297] Fixing build issues --- web.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web.go b/web.go index 1370628..026ae17 100644 --- a/web.go +++ b/web.go @@ -28,13 +28,14 @@ type Page struct { var external_ip = "" func Webserver(port int) *WebServer { + var webserver = WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} http.HandleFunc("/", webserver.homepage) http.HandleFunc("/add", webserver.add) http.HandleFunc("/volume", webserver.volume) http.HandleFunc("/skip", webserver.skip) http.ListenAndServe(":"+strconv.Itoa(port), nil) rand.Seed(time.Now().UnixNano()) - return &WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} + return webserver } func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { From a246196786d2042d66380011530abb382aa24744 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:17:01 +0100 Subject: [PATCH 026/297] Fixing build issues --- web.go | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/web.go b/web.go index 026ae17..56a302e 100644 --- a/web.go +++ b/web.go @@ -28,14 +28,17 @@ type Page struct { var external_ip = "" func Webserver(port int) *WebServer { - var webserver = WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} - http.HandleFunc("/", webserver.homepage) - http.HandleFunc("/add", webserver.add) - http.HandleFunc("/volume", webserver.volume) - http.HandleFunc("/skip", webserver.skip) - http.ListenAndServe(":"+strconv.Itoa(port), nil) + return WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)}.construct() +} + +func (web *WebServer) construct() *WebServer { + http.HandleFunc("/", web.homepage) + http.HandleFunc("/add", web.add) + http.HandleFunc("/volume", web.volume) + http.HandleFunc("/skip", web.skip) + http.ListenAndServe(":"+strconv.Itoa(web.port), nil) rand.Seed(time.Now().UnixNano()) - return webserver + return web } func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { From 2fcdb0fc97e2981ca81279598b0a50c9d1df419c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:17:37 +0100 Subject: [PATCH 027/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index 56a302e..9766c3c 100644 --- a/web.go +++ b/web.go @@ -28,7 +28,7 @@ type Page struct { var external_ip = "" func Webserver(port int) *WebServer { - return WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)}.construct() + return &WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)}.construct() } func (web *WebServer) construct() *WebServer { From 5e1bae3c4cac8aeac8c0b8b4311b760031fe4f00 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:21:13 +0100 Subject: [PATCH 028/297] Fixing build issues --- web.go | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/web.go b/web.go index 9766c3c..48e3e53 100644 --- a/web.go +++ b/web.go @@ -28,17 +28,20 @@ type Page struct { var external_ip = "" func Webserver(port int) *WebServer { - return &WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)}.construct() -} + webserver := new(WebServer) + + webserver.port = port + webserver.client_token = make(map[*gumble.User]string) + webserver.token_client = make(map[string]*gumble.User) + + http.HandleFunc("/", webserver.homepage) + http.HandleFunc("/add", webserver.add) + http.HandleFunc("/volume", webserver.volume) + http.HandleFunc("/skip", webserver.skip) + http.ListenAndServe(":"+strconv.Itoa(port), nil) -func (web *WebServer) construct() *WebServer { - http.HandleFunc("/", web.homepage) - http.HandleFunc("/add", web.add) - http.HandleFunc("/volume", web.volume) - http.HandleFunc("/skip", web.skip) - http.ListenAndServe(":"+strconv.Itoa(web.port), nil) rand.Seed(time.Now().UnixNano()) - return web + return webserver } func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { From 78cb63106cc8da0ad75c873e00e865d7a490d932 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:27:55 +0100 Subject: [PATCH 029/297] Fixing build issues --- web.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/web.go b/web.go index 48e3e53..2ef2930 100644 --- a/web.go +++ b/web.go @@ -83,18 +83,18 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { } } -func (web *WebServer) GetWebAddress(user *gumble.User) { - if web.client_token[user] != "" { - web.token_client[web.client_token[user]] = nil +func (website *websiteServer) GetwebsiteAddress(user *gumble.User) { + if website.client_token[user] != "" { + website.token_client[website.client_token[user]] = nil } // dealing with collisions var firstLoop = true - for firstLoop || web.token_client[web.client_token[user]] != nil { - web.client_token[user] = randSeq(10) + for firstLoop || website.token_client[website.client_token[user]] != nil { + website.client_token[user] = randSeq(10) firstLoop = false } - web.token_client[web.client_token[user]] = user - dj.SendPrivateMessage(user, fmt.Sprintf(WEB_ADDRESS, getIP(), web.client_token[user], getIP(), web.client_token[user])) + website.token_client[website.client_token[user]] = user + dj.SendPrivateMessage(user, fmt.Sprintf(website_ADDRESS, getIP(), website.client_token[user], getIP(), website.client_token[user])) } // Gets the external ip address for the server From a37dbe128325b7e6b0faf64046963d98caeb6eb2 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:28:39 +0100 Subject: [PATCH 030/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index 2ef2930..4e7ce2d 100644 --- a/web.go +++ b/web.go @@ -83,7 +83,7 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { } } -func (website *websiteServer) GetwebsiteAddress(user *gumble.User) { +func (website *WebServer) GetWebAddress(user *gumble.User) { if website.client_token[user] != "" { website.token_client[website.client_token[user]] = nil } From ac6979a9d895afce8b0880b2ad7aacad660e977b Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:29:06 +0100 Subject: [PATCH 031/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index 4e7ce2d..12f839e 100644 --- a/web.go +++ b/web.go @@ -94,7 +94,7 @@ func (website *WebServer) GetWebAddress(user *gumble.User) { firstLoop = false } website.token_client[website.client_token[user]] = user - dj.SendPrivateMessage(user, fmt.Sprintf(website_ADDRESS, getIP(), website.client_token[user], getIP(), website.client_token[user])) + dj.SendPrivateMessage(user, fmt.Sprintf(WEB_ADDRESS, getIP(), website.client_token[user], getIP(), website.client_token[user])) } // Gets the external ip address for the server From d9617a86c77fe400fdadc08f504d2fede0ded1e6 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:31:10 +0100 Subject: [PATCH 032/297] Fixing build issues --- web.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/web.go b/web.go index 12f839e..851c440 100644 --- a/web.go +++ b/web.go @@ -84,6 +84,12 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { } func (website *WebServer) GetWebAddress(user *gumble.User) { + if website == nil { + Verbose("WEBSITE NOT INITIALISED") + } + if website.client_token == nil { + Verbose("CLIENT_TOKEN NOT INITIALISED") + } if website.client_token[user] != "" { website.token_client[website.client_token[user]] = nil } From ebf5fa0a014d057f0f0c9b543133e87b84f89fd0 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:32:43 +0100 Subject: [PATCH 033/297] Fixing build issues --- web.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/web.go b/web.go index 851c440..3218c5e 100644 --- a/web.go +++ b/web.go @@ -84,6 +84,8 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { } func (website *WebServer) GetWebAddress(user *gumble.User) { + // A random comment + Verbose("Not fun") if website == nil { Verbose("WEBSITE NOT INITIALISED") } From 1b7167335e4f106fbd82d1306d313c4f33e41183 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:40:39 +0100 Subject: [PATCH 034/297] Fixing build issues --- main.go | 2 +- web.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 77d4251..27a94d0 100644 --- a/main.go +++ b/main.go @@ -144,7 +144,7 @@ func PerformStartupChecks() { func Verbose(msg string) { if dj.verbose { - fmt.Printf(msg) + fmt.Printf(msg + "\n") } } diff --git a/web.go b/web.go index 3218c5e..e951c39 100644 --- a/web.go +++ b/web.go @@ -28,7 +28,7 @@ type Page struct { var external_ip = "" func Webserver(port int) *WebServer { - webserver := new(WebServer) + webserver := new(WebServer{}) webserver.port = port webserver.client_token = make(map[*gumble.User]string) From e2541f119256e5594f66d3711f7246a54b86a7ae Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:42:28 +0100 Subject: [PATCH 035/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index e951c39..f0d39e6 100644 --- a/web.go +++ b/web.go @@ -28,7 +28,7 @@ type Page struct { var external_ip = "" func Webserver(port int) *WebServer { - webserver := new(WebServer{}) + webserver := WebServer{} webserver.port = port webserver.client_token = make(map[*gumble.User]string) From 759ea0f3b9473ccdc567eefdc4879d3a305854f1 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:47:34 +0100 Subject: [PATCH 036/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index f0d39e6..37a897c 100644 --- a/web.go +++ b/web.go @@ -28,7 +28,7 @@ type Page struct { var external_ip = "" func Webserver(port int) *WebServer { - webserver := WebServer{} + webserver := &WebServer{} webserver.port = port webserver.client_token = make(map[*gumble.User]string) From 7da0a68f5103845f8e58e18db58c6f73c2e8ea1a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:52:33 +0100 Subject: [PATCH 037/297] Fixing build issues --- main.go | 2 +- web.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 27a94d0..629fd3c 100644 --- a/main.go +++ b/main.go @@ -172,7 +172,7 @@ var dj = mumbledj{ cache: NewSongCache(), } -var web *WebServer +var web WebServer // main primarily performs startup tasks. Grabs and parses commandline // args, sets up the gumble client and its listeners, and then connects to the server. diff --git a/web.go b/web.go index 37a897c..cbcc8fb 100644 --- a/web.go +++ b/web.go @@ -27,8 +27,8 @@ type Page struct { var external_ip = "" -func Webserver(port int) *WebServer { - webserver := &WebServer{} +func makeWebserver(port int) WebServer { + webserver := WebServer{} webserver.port = port webserver.client_token = make(map[*gumble.User]string) From 7f913c06e49341cb033e3130cfea12cf60f70014 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:53:37 +0100 Subject: [PATCH 038/297] Fixing build issues --- main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.go b/main.go index 629fd3c..66cd711 100644 --- a/main.go +++ b/main.go @@ -244,7 +244,7 @@ func main() { os.Exit(1) } - web = Webserver(9563) + web = WebServer(9563) <-dj.keepAlive } From f26f8e9ec59e74153bf996d1b37878dbc0f8250f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:54:34 +0100 Subject: [PATCH 039/297] Fixing build issues --- main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.go b/main.go index 66cd711..4849776 100644 --- a/main.go +++ b/main.go @@ -244,7 +244,7 @@ func main() { os.Exit(1) } - web = WebServer(9563) + web = makeWebserver(9563) <-dj.keepAlive } From 2e09ec1b91105e547b94cf6ebab60fe771ebe594 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 14:56:47 +0100 Subject: [PATCH 040/297] Fixing build issues --- web.go | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/web.go b/web.go index cbcc8fb..a8e1dac 100644 --- a/web.go +++ b/web.go @@ -28,11 +28,7 @@ type Page struct { var external_ip = "" func makeWebserver(port int) WebServer { - webserver := WebServer{} - - webserver.port = port - webserver.client_token = make(map[*gumble.User]string) - webserver.token_client = make(map[string]*gumble.User) + webserver := WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} http.HandleFunc("/", webserver.homepage) http.HandleFunc("/add", webserver.add) From 3732c0e9dd6c053f33532bdaacd4c79a4db576db Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:04:58 +0100 Subject: [PATCH 041/297] Fixing build issues --- web.go | 8 -------- 1 file changed, 8 deletions(-) diff --git a/web.go b/web.go index a8e1dac..6f88810 100644 --- a/web.go +++ b/web.go @@ -80,14 +80,6 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { } func (website *WebServer) GetWebAddress(user *gumble.User) { - // A random comment - Verbose("Not fun") - if website == nil { - Verbose("WEBSITE NOT INITIALISED") - } - if website.client_token == nil { - Verbose("CLIENT_TOKEN NOT INITIALISED") - } if website.client_token[user] != "" { website.token_client[website.client_token[user]] = nil } From 6d040db236b243bda1b502bdf146bb7bf7360bdf Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:07:40 +0100 Subject: [PATCH 042/297] Fixing build issues --- web.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/web.go b/web.go index 6f88810..cd192db 100644 --- a/web.go +++ b/web.go @@ -80,17 +80,17 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { } func (website *WebServer) GetWebAddress(user *gumble.User) { - if website.client_token[user] != "" { - website.token_client[website.client_token[user]] = nil + if web.client_token[user] != "" { + web.token_client[web.client_token[user]] = nil } // dealing with collisions var firstLoop = true - for firstLoop || website.token_client[website.client_token[user]] != nil { - website.client_token[user] = randSeq(10) + for firstLoop || web.token_client[web.client_token[user]] != nil { + web.client_token[user] = randSeq(10) firstLoop = false } - website.token_client[website.client_token[user]] = user - dj.SendPrivateMessage(user, fmt.Sprintf(WEB_ADDRESS, getIP(), website.client_token[user], getIP(), website.client_token[user])) + web.token_client[web.client_token[user]] = user + dj.SendPrivateMessage(user, fmt.Sprintf(WEB_ADDRESS, getIP(), web.client_token[user], getIP(), web.client_token[user])) } // Gets the external ip address for the server From 31644719feb1ea0aee5b68f8c13df75b4014b4c0 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:10:43 +0100 Subject: [PATCH 043/297] Fixing build issues --- main.go | 2 +- web.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 4849776..16cdbc7 100644 --- a/main.go +++ b/main.go @@ -172,7 +172,7 @@ var dj = mumbledj{ cache: NewSongCache(), } -var web WebServer +var web *WebServer // main primarily performs startup tasks. Grabs and parses commandline // args, sets up the gumble client and its listeners, and then connects to the server. diff --git a/web.go b/web.go index cd192db..ba151eb 100644 --- a/web.go +++ b/web.go @@ -27,8 +27,8 @@ type Page struct { var external_ip = "" -func makeWebserver(port int) WebServer { - webserver := WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} +func makeWebserver(port int) *WebServer { + webserver := &WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} http.HandleFunc("/", webserver.homepage) http.HandleFunc("/add", webserver.add) From cf0a8b28f94a24b20977aa5f6df80b94d1f307a9 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:12:00 +0100 Subject: [PATCH 044/297] Fixing build issues --- web.go | 1 + 1 file changed, 1 insertion(+) diff --git a/web.go b/web.go index ba151eb..4da4906 100644 --- a/web.go +++ b/web.go @@ -80,6 +80,7 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { } func (website *WebServer) GetWebAddress(user *gumble.User) { + Verbose("Port number: " + strconv.Itoa(web.port)) if web.client_token[user] != "" { web.token_client[web.client_token[user]] = nil } From 4350d54c3b89d5608b23aa8c0d0a9f78b321f19f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:13:17 +0100 Subject: [PATCH 045/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index 4da4906..c0cc4c1 100644 --- a/web.go +++ b/web.go @@ -79,7 +79,7 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { } } -func (website *WebServer) GetWebAddress(user *gumble.User) { +func (website WebServer) GetWebAddress(user *gumble.User) { Verbose("Port number: " + strconv.Itoa(web.port)) if web.client_token[user] != "" { web.token_client[web.client_token[user]] = nil From d1105b75569ccfa4f321f445a9d25a0b47e6a5a0 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:14:30 +0100 Subject: [PATCH 046/297] Fixing build issues --- main.go | 2 +- web.go | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/main.go b/main.go index 16cdbc7..4849776 100644 --- a/main.go +++ b/main.go @@ -172,7 +172,7 @@ var dj = mumbledj{ cache: NewSongCache(), } -var web *WebServer +var web WebServer // main primarily performs startup tasks. Grabs and parses commandline // args, sets up the gumble client and its listeners, and then connects to the server. diff --git a/web.go b/web.go index c0cc4c1..4bb9c19 100644 --- a/web.go +++ b/web.go @@ -27,8 +27,8 @@ type Page struct { var external_ip = "" -func makeWebserver(port int) *WebServer { - webserver := &WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} +func makeWebserver(port int) WebServer { + webserver := WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} http.HandleFunc("/", webserver.homepage) http.HandleFunc("/add", webserver.add) @@ -40,7 +40,7 @@ func makeWebserver(port int) *WebServer { return webserver } -func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { +func (web WebServer) homepage(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.URL.Path[1:]] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -50,7 +50,7 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { } } -func (web *WebServer) add(w http.ResponseWriter, r *http.Request) { +func (web WebServer) add(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -59,7 +59,7 @@ func (web *WebServer) add(w http.ResponseWriter, r *http.Request) { } } -func (web *WebServer) volume(w http.ResponseWriter, r *http.Request) { +func (web WebServer) volume(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -69,7 +69,7 @@ func (web *WebServer) volume(w http.ResponseWriter, r *http.Request) { } } -func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { +func (web WebServer) skip(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") From 8013ffea116faf452ac4ae71595da53369220a0c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:17:04 +0100 Subject: [PATCH 047/297] Fixing build issues --- web.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/web.go b/web.go index 4bb9c19..b13bcf4 100644 --- a/web.go +++ b/web.go @@ -28,7 +28,11 @@ type Page struct { var external_ip = "" func makeWebserver(port int) WebServer { - webserver := WebServer{port, make(map[*gumble.User]string), make(map[string]*gumble.User)} + webserver := WebServer{} + + webserver.port = port + webserver.client_token = make(map[*gumble.User]string) + webserver.token_client = make(map[string]*gumble.User) http.HandleFunc("/", webserver.homepage) http.HandleFunc("/add", webserver.add) From dcb85e1892dc6704480d6b0e746463e12bff4bc3 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:23:05 +0100 Subject: [PATCH 048/297] Fixing build issues --- main.go | 2 +- web.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 4849776..16cdbc7 100644 --- a/main.go +++ b/main.go @@ -172,7 +172,7 @@ var dj = mumbledj{ cache: NewSongCache(), } -var web WebServer +var web *WebServer // main primarily performs startup tasks. Grabs and parses commandline // args, sets up the gumble client and its listeners, and then connects to the server. diff --git a/web.go b/web.go index b13bcf4..25a7a9a 100644 --- a/web.go +++ b/web.go @@ -27,8 +27,8 @@ type Page struct { var external_ip = "" -func makeWebserver(port int) WebServer { - webserver := WebServer{} +func makeWebserver(port int) *WebServer { + webserver := &WebServer{} webserver.port = port webserver.client_token = make(map[*gumble.User]string) From 9d6ff1ad784bec0cdab45de16ee1e4e4fdd26c2b Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:24:30 +0100 Subject: [PATCH 049/297] Fixing build issues --- main.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/main.go b/main.go index 16cdbc7..56f1066 100644 --- a/main.go +++ b/main.go @@ -246,5 +246,9 @@ func main() { web = makeWebserver(9563) + if isNil(web) { + Verbose("WEB IS NIL") + } + <-dj.keepAlive } From a55ce8a3e0d8e16c74807e89e128dd64dcc52700 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:28:41 +0100 Subject: [PATCH 050/297] Fixing build issues --- web.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/web.go b/web.go index 25a7a9a..e521602 100644 --- a/web.go +++ b/web.go @@ -44,7 +44,7 @@ func makeWebserver(port int) *WebServer { return webserver } -func (web WebServer) homepage(w http.ResponseWriter, r *http.Request) { +func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.URL.Path[1:]] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -54,7 +54,7 @@ func (web WebServer) homepage(w http.ResponseWriter, r *http.Request) { } } -func (web WebServer) add(w http.ResponseWriter, r *http.Request) { +func (web *WebServer) add(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -63,7 +63,7 @@ func (web WebServer) add(w http.ResponseWriter, r *http.Request) { } } -func (web WebServer) volume(w http.ResponseWriter, r *http.Request) { +func (web *WebServer) volume(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -73,7 +73,7 @@ func (web WebServer) volume(w http.ResponseWriter, r *http.Request) { } } -func (web WebServer) skip(w http.ResponseWriter, r *http.Request) { +func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { fmt.Fprintf(w, "Invalid Token") @@ -83,7 +83,7 @@ func (web WebServer) skip(w http.ResponseWriter, r *http.Request) { } } -func (website WebServer) GetWebAddress(user *gumble.User) { +func (website *WebServer) GetWebAddress(user *gumble.User) { Verbose("Port number: " + strconv.Itoa(web.port)) if web.client_token[user] != "" { web.token_client[web.client_token[user]] = nil From f15ff8755a917848d8c2dcb3125c92b4ecc929ef Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:34:40 +0100 Subject: [PATCH 051/297] Fixing build issues --- main.go | 3 ++- web.go | 26 +++++++++++++------------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/main.go b/main.go index 56f1066..ba85c0c 100644 --- a/main.go +++ b/main.go @@ -244,7 +244,8 @@ func main() { os.Exit(1) } - web = makeWebserver(9563) + web = NewWebServer(9563) + web.makeWeb() if isNil(web) { Verbose("WEB IS NIL") diff --git a/web.go b/web.go index e521602..7fd4bc1 100644 --- a/web.go +++ b/web.go @@ -27,21 +27,21 @@ type Page struct { var external_ip = "" -func makeWebserver(port int) *WebServer { - webserver := &WebServer{} - - webserver.port = port - webserver.client_token = make(map[*gumble.User]string) - webserver.token_client = make(map[string]*gumble.User) - - http.HandleFunc("/", webserver.homepage) - http.HandleFunc("/add", webserver.add) - http.HandleFunc("/volume", webserver.volume) - http.HandleFunc("/skip", webserver.skip) - http.ListenAndServe(":"+strconv.Itoa(port), nil) +func NewWebServer(port int) *WebServer { + return &WebServer{ + port: port, + client_token: make(map[*gumble.User]string), + token_client: make(map[string]*gumble.User), + } +} +func (web *WebServer) makeWeb() { + http.HandleFunc("/", web.homepage) + http.HandleFunc("/add", web.add) + http.HandleFunc("/volume", web.volume) + http.HandleFunc("/skip", web.skip) + http.ListenAndServe(":"+strconv.Itoa(web.port), nil) rand.Seed(time.Now().UnixNano()) - return webserver } func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { From 15ce071ef6b96b87871a475c90ba67fdef27a6b5 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:47:05 +0100 Subject: [PATCH 052/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index 7fd4bc1..2e630fd 100644 --- a/web.go +++ b/web.go @@ -50,7 +50,7 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Invalid Token") } else { t, _ := template.ParseFiles("index.html") - t.Execute(w, Page{"http://" + getIP() + ":" + strconv.Itoa(web.port) + "/", r.URL.Path[1:]}) + t.Execute(w, &Page{"http://" + getIP() + ":" + strconv.Itoa(web.port) + "/", r.URL.Path[1:]}) } } From bc3193009feb75cb1cd773821ed77b4025ef446d Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:52:10 +0100 Subject: [PATCH 053/297] Fixing build issues --- web.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/web.go b/web.go index 2e630fd..805b71e 100644 --- a/web.go +++ b/web.go @@ -49,8 +49,16 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { - t, _ := template.ParseFiles("index.html") - t.Execute(w, &Page{"http://" + getIP() + ":" + strconv.Itoa(web.port) + "/", r.URL.Path[1:]}) + t, err := template.ParseFiles("index.html") + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + err = t.Execute(w, &Page{"http://" + getIP() + ":" + strconv.Itoa(web.port) + "/", r.URL.Path[1:]}) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } } } From fcee078c0b2c38a52957b707a75a1d081fb81d36 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 15:54:46 +0100 Subject: [PATCH 054/297] Fixing build issues --- Makefile | 1 + web.go | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 36b484b..565b52e 100644 --- a/Makefile +++ b/Makefile @@ -15,6 +15,7 @@ install: mkdir -p ~/.mumbledj/web if [ -a ~/.mumbledj/config/mumbledj.gcfg ]; then mv ~/.mumbledj/config/mumbledj.gcfg ~/.mumbledj/config/mumbledj_backup.gcfg; fi; cp -u config.gcfg ~/.mumbledj/config/mumbledj.gcfg + cp -u index.html ~/.mumbledj/web/index.html if [ -d ~/bin ]; then cp -f mumbledj* ~/bin/mumbledj; else sudo cp -f mumbledj* /usr/local/bin/mumbledj; fi; build: diff --git a/web.go b/web.go index 805b71e..8dd02f2 100644 --- a/web.go +++ b/web.go @@ -49,12 +49,12 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { - t, err := template.ParseFiles("index.html") + t, err := template.ParseFiles("~/.mumbledj/web/index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } - + err = t.Execute(w, &Page{"http://" + getIP() + ":" + strconv.Itoa(web.port) + "/", r.URL.Path[1:]}) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) From 619d9100c394f235550fc6bfad78a982fc5062a3 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 17:07:59 +0100 Subject: [PATCH 055/297] Fixing build issues --- cache.go | 2 +- commands.go | 2 +- main.go | 2 +- parseconfig.go | 2 +- service.go | 2 +- service_youtube.go | 2 +- songqueue.go | 2 +- strings.go | 2 +- web.go | 4 ++-- 9 files changed, 10 insertions(+), 10 deletions(-) diff --git a/cache.go b/cache.go index 0adda0e..9f56af3 100644 --- a/cache.go +++ b/cache.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package main +package mumbledj import ( "errors" diff --git a/commands.go b/commands.go index 4be4eeb..5f0e02c 100644 --- a/commands.go +++ b/commands.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package main +package mumbledj import ( "errors" diff --git a/main.go b/main.go index ba85c0c..840aba9 100644 --- a/main.go +++ b/main.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package main +package mumbledj import ( "crypto/tls" diff --git a/parseconfig.go b/parseconfig.go index 4b4a16a..f567c4c 100644 --- a/parseconfig.go +++ b/parseconfig.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package main +package mumbledj import ( "errors" diff --git a/service.go b/service.go index 13a1d08..39f7b0c 100644 --- a/service.go +++ b/service.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package main +package mumbledj import ( "errors" diff --git a/service_youtube.go b/service_youtube.go index 63a343d..aa7ec1f 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package main +package mumbledj import ( "encoding/json" diff --git a/songqueue.go b/songqueue.go index f1bdc1c..0a6bb31 100644 --- a/songqueue.go +++ b/songqueue.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package main +package mumbledj import ( "errors" diff --git a/strings.go b/strings.go index 9d5524f..03a7e3c 100644 --- a/strings.go +++ b/strings.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package main +package mumbledj // Message shown to users when the bot has an invalid YouTube API key. const INVALID_API_KEY = "MumbleDJ does not have a valid YouTube API key." diff --git a/web.go b/web.go index 8dd02f2..bdbf3bd 100644 --- a/web.go +++ b/web.go @@ -1,4 +1,4 @@ -package main +package mumbledj import ( "fmt" @@ -49,7 +49,7 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { - t, err := template.ParseFiles("~/.mumbledj/web/index.html") + t, err := template.ParseFiles("mumbledj/index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return From 6f9e4a9c76da26454ce90e9f00e61fd97d76316a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 17:12:16 +0100 Subject: [PATCH 056/297] Fixing build issues --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 565b52e..2f0b5c3 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ all: mumbledj -mumbledj: main.go commands.go parseconfig.go strings.go service.go service_youtube.go songqueue.go cache.go +mumbledj: main.go commands.go parseconfig.go strings.go service.go service_youtube.go songqueue.go cache.go web.go go get github.com/nitrous-io/goop rm -rf Goopfile.lock goop install From 14c38799e304cfa05233467b32f8c904c9fb455c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 17:28:01 +0100 Subject: [PATCH 057/297] Fixing build issues --- cache.go | 2 +- commands.go | 2 +- main.go | 2 +- parseconfig.go | 2 +- service.go | 2 +- service_youtube.go | 2 +- songqueue.go | 2 +- strings.go | 2 +- web.go | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cache.go b/cache.go index 9f56af3..0adda0e 100644 --- a/cache.go +++ b/cache.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package mumbledj +package main import ( "errors" diff --git a/commands.go b/commands.go index 5f0e02c..4be4eeb 100644 --- a/commands.go +++ b/commands.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package mumbledj +package main import ( "errors" diff --git a/main.go b/main.go index 840aba9..ba85c0c 100644 --- a/main.go +++ b/main.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package mumbledj +package main import ( "crypto/tls" diff --git a/parseconfig.go b/parseconfig.go index f567c4c..4b4a16a 100644 --- a/parseconfig.go +++ b/parseconfig.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package mumbledj +package main import ( "errors" diff --git a/service.go b/service.go index 39f7b0c..13a1d08 100644 --- a/service.go +++ b/service.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package mumbledj +package main import ( "errors" diff --git a/service_youtube.go b/service_youtube.go index aa7ec1f..63a343d 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package mumbledj +package main import ( "encoding/json" diff --git a/songqueue.go b/songqueue.go index 0a6bb31..f1bdc1c 100644 --- a/songqueue.go +++ b/songqueue.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package mumbledj +package main import ( "errors" diff --git a/strings.go b/strings.go index 03a7e3c..9d5524f 100644 --- a/strings.go +++ b/strings.go @@ -5,7 +5,7 @@ * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) */ -package mumbledj +package main // Message shown to users when the bot has an invalid YouTube API key. const INVALID_API_KEY = "MumbleDJ does not have a valid YouTube API key." diff --git a/web.go b/web.go index bdbf3bd..bebb94b 100644 --- a/web.go +++ b/web.go @@ -1,4 +1,4 @@ -package mumbledj +package main import ( "fmt" From 5d18bd68d8e20ae9e57ffd2013de12966af8ef72 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 17:30:32 +0100 Subject: [PATCH 058/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index bebb94b..90104c2 100644 --- a/web.go +++ b/web.go @@ -49,7 +49,7 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { - t, err := template.ParseFiles("mumbledj/index.html") + t, err := template.ParseFiles("./index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return From 2606fc4cb904db0c24260b7a8b470d90fe56170d Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 17:32:56 +0100 Subject: [PATCH 059/297] Fixing build issues --- web.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/web.go b/web.go index 90104c2..95334fc 100644 --- a/web.go +++ b/web.go @@ -7,6 +7,8 @@ import ( "io/ioutil" "math/rand" "net/http" + "os" + "path/filepath" "strconv" "strings" "time" @@ -49,7 +51,8 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { - t, err := template.ParseFiles("./index.html") + cwd, _ := os.Getwd() + t, err := template.ParseFiles(filepath.Join(cwd, "./index.html")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return From e1ccad13581e708a666cadb714198da4fdbd8e96 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 17:35:03 +0100 Subject: [PATCH 060/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index 95334fc..a7f8a36 100644 --- a/web.go +++ b/web.go @@ -52,7 +52,7 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Invalid Token") } else { cwd, _ := os.Getwd() - t, err := template.ParseFiles(filepath.Join(cwd, "./index.html")) + t, err := template.ParseFiles(filepath.Join(cwd, "./.mumbledj/web/index.html")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return From 2107462d5bdc6ea23fee8e8122994c545b823e98 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 17:36:37 +0100 Subject: [PATCH 061/297] Fixing build issues --- web.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web.go b/web.go index a7f8a36..c3c67db 100644 --- a/web.go +++ b/web.go @@ -25,6 +25,7 @@ type WebServer struct { type Page struct { siteUrl string token string + user string } var external_ip = "" @@ -58,7 +59,7 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { return } - err = t.Execute(w, &Page{"http://" + getIP() + ":" + strconv.Itoa(web.port) + "/", r.URL.Path[1:]}) + err = t.Execute(w, &Page{"http://" + getIP() + ":" + strconv.Itoa(web.port) + "/", r.URL.Path[1:], uname}) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } From b7aa5dafbed0d03e7822a8811aaf491fd7a3491e Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 17:37:19 +0100 Subject: [PATCH 062/297] Fixing build issues --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index c3c67db..35a8bb7 100644 --- a/web.go +++ b/web.go @@ -59,7 +59,7 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { return } - err = t.Execute(w, &Page{"http://" + getIP() + ":" + strconv.Itoa(web.port) + "/", r.URL.Path[1:], uname}) + err = t.Execute(w, &Page{"http://" + getIP() + ":" + strconv.Itoa(web.port) + "/", r.URL.Path[1:], uname.Name}) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } From 9cd9c0ad605eb9173278ab20ad6659bdb8dd3bfd Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 30 Jul 2015 17:39:04 +0100 Subject: [PATCH 063/297] Fixing build issues --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 5659235..ea3806a 100644 --- a/index.html +++ b/index.html @@ -2,7 +2,7 @@ - {{user}} - mumbledj + {{.user}} - mumbledj - + - - -

Add Song Form

- - - - - - + function txtBox(type) { + var txt = $("#textbox"); + api(type, txt.attr("value")); + txt.attr("value", ""); + } + + + +

Add Song Form

+ + + + + +
+ + \ No newline at end of file diff --git a/main.go b/main.go index ba85c0c..1dd4907 100644 --- a/main.go +++ b/main.go @@ -142,12 +142,14 @@ func PerformStartupChecks() { } } +// Prints out messages only if verbose flag is true func Verbose(msg string) { if dj.verbose { fmt.Printf(msg + "\n") } } +// Checks to see if an object is nil func isNil(a interface{}) bool { defer func() { recover() }() return a == nil || reflect.ValueOf(a).IsNil() diff --git a/service_soundcloud.go b/service_soundcloud.go new file mode 100644 index 0000000..34944e7 --- /dev/null +++ b/service_soundcloud.go @@ -0,0 +1,96 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "os" + "os/exec" + "regexp" + "strconv" + "strings" + "time" + + "github.com/jmoiron/jsonq" + "github.com/layeh/gumble/gumble" + "github.com/layeh/gumble/gumble_ffmpeg" +) + +// Regular expressions for soundcloud urls +var soundcloudSongPattern = `https?:\/\/(www)?\.soundcloud\.com\/([\w-]+)\/([\w-]+)` +var soundcloudPlaylistPattern = `https?:\/\/(www)?\.soundcloud\.com\/([\w-]+)\/sets\/([\w-]+)` + +// ------ +// TYPES +// ------ + +// YouTube implements the Service interface +type SoundCloud struct{} + +// YouTubeSong holds the metadata for a song extracted from a YouTube video. +type SoundCloudSong struct { + submitter string + title string + id string + offset int + filename string + duration string + thumbnail string + skippers []string + playlist Playlist + dontSkip bool +} + +// YouTubePlaylist holds the metadata for a YouTube playlist. +type SoundCloudPlaylist struct { + id string + title string +} + +// ------------------ +// SOUNDCLOUD SERVICE +// ------------------ + +// Name of the service +func (sc SoundCloud) ServiceName() string { + return "SoundCloud" +} + +// Checks to see if service will accept URL +func (sc SoundCloud) URLRegex(url string) bool { + return RegexpFromURL(url, []string{soundcloudSongPattern, soundcloudPlaylistPattern}) != nil +} + +// Creates the requested song/playlist and adds to the queue +func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { + var apiResponse *jsonq.JsonQuery + var err error + url := fmt.Sprintf("http://api.soundcloud.com/resolve?url=%s&client_id=%s", url, os.Getenv("SOUNDCLOUD_API_KEY")) + if apiResponse, err = PerformGetRequest(url); err != nil { + return nil, errors.New(INVALID_API_KEY) + } + + title, _ := apiResponse.String("title") + tracks, err := apiResponse.ArrayOfObjects("tracks") + + if err == nil { + if re.MatchString(url) { + // PLAYLIST + if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { + playlist, err := sc.NewPlaylist(user.Name, url) + return playlist.Title(), err + } else { + return "", errors.New("NO_PLAYLIST_PERMISSION") + } + } else { + + // SONG + song, err := sc.NewSong(user.Name, url, nil) + return song.Title(), err + } + } else { + return "", err + } +} diff --git a/service_youtube.go b/service_youtube.go index 12b925c..5da5607 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -110,7 +110,7 @@ func (yt YouTube) NewSong(user, id, offset string, playlist *YouTubePlaylist) (* var err error url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s", id, os.Getenv("YOUTUBE_API_KEY")) - if apiResponse, err = yt.PerformGetRequest(url); err != nil { + if apiResponse, err = PerformGetRequest(url); err != nil { return nil, errors.New(INVALID_API_KEY) } @@ -206,7 +206,7 @@ func (yt YouTube) NewPlaylist(user, id string) (*YouTubePlaylist, error) { // Retrieve title of playlist url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=%s&key=%s", id, os.Getenv("YOUTUBE_API_KEY")) - if apiResponse, err = yt.PerformGetRequest(url); err != nil { + if apiResponse, err = PerformGetRequest(url); err != nil { return nil, err } title, _ := apiResponse.String("items", "0", "snippet", "title") @@ -219,7 +219,7 @@ func (yt YouTube) NewPlaylist(user, id string) (*YouTubePlaylist, error) { // Retrieve items in playlist url = fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=%s&key=%s", id, os.Getenv("YOUTUBE_API_KEY")) - if apiResponse, err = yt.PerformGetRequest(url); err != nil { + if apiResponse, err = PerformGetRequest(url); err != nil { return nil, err } numVideos, _ := apiResponse.Int("pageInfo", "totalResults") @@ -469,7 +469,7 @@ func (p *YouTubePlaylist) Title() string { // ----------- // PerformGetRequest does all the grunt work for a YouTube HTTPS GET request. -func (yt YouTube) PerformGetRequest(url string) (*jsonq.JsonQuery, error) { +func PerformGetRequest(url string) (*jsonq.JsonQuery, error) { jsonString := "" if response, err := http.Get(url); err == nil { @@ -482,7 +482,7 @@ func (yt YouTube) PerformGetRequest(url string) (*jsonq.JsonQuery, error) { if response.StatusCode == 403 { return nil, errors.New("Invalid API key supplied.") } - return nil, errors.New("Invalid YouTube ID supplied.") + return nil, errors.New("Invalid ID supplied.") } } else { return nil, errors.New("An error occurred while receiving HTTP GET response.") diff --git a/songqueue.go b/songqueue.go index f1bdc1c..54e3610 100644 --- a/songqueue.go +++ b/songqueue.go @@ -77,6 +77,14 @@ func (q *SongQueue) Traverse(visit func(i int, s Song)) { } } +// Gets the song at a specific point in the queue +func (q *SongQueue) Get(int i) (Song, error) { + if q.Len() > i+1 { + return q.queue[i], nil + } + return nil, errors.New("Out of Bounds") +} + // OnSongFinished event. Deletes Song that just finished playing, then queues the next Song (if exists). func (q *SongQueue) OnSongFinished() { resetOffset, _ := time.ParseDuration(fmt.Sprintf("%ds", 0)) diff --git a/web.go b/web.go index 4cd57e4..d9873d7 100644 --- a/web.go +++ b/web.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "fmt" "html" "html/template" @@ -28,6 +29,21 @@ type Page struct { User string } +type status struct { + Error bool + ErrorMsg string + Queue []SongInfo +} +type SongInfo struct { + TitleID string + PlaylistID string + Title string + Playlist string + Submitter string + Duration string + Thumbnail string +} + var external_ip = "" func NewWebServer(port int) *WebServer { @@ -41,9 +57,10 @@ func NewWebServer(port int) *WebServer { func (web *WebServer) makeWeb() { http.HandleFunc("/", web.homepage) - http.HandleFunc("/add", web.add) - http.HandleFunc("/volume", web.volume) - http.HandleFunc("/skip", web.skip) + http.HandleFunc("/api/add", web.add) + http.HandleFunc("/api/volume", web.volume) + http.HandleFunc("/api/skip", web.skip) + http.HandleFunc("/api/status", web.status) http.ListenAndServe(":"+strconv.Itoa(web.port), nil) } @@ -52,8 +69,14 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { if uname == nil { fmt.Fprintf(w, "Invalid Token") } else { - cwd, _ := os.Getwd() - t, err := template.ParseFiles(filepath.Join(cwd, "./.mumbledj/web/index.html")) + var webpage = uname.Name + + // Check to see if user has a custom webpage + if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/web/%s.html", dj.homeDir, uname.Name)); os.IsNotExist(err) { + webpage = "index" + } + + t, err := template.ParseFiles(fmt.Sprintf("%s/.mumbledj/songs/%s.html", dj.homeDir, uname.Name)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -103,6 +126,33 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { } } +func (web *WebServer) status(w http.ResponseWriter, r *http.Request) { + var uname = web.token_client[r.FormValue("token")] + if uname == nil { + fmt.Fprintf(w, string(json.MarshalIndent(&Status{true, "Invalid Token"}))) + } else { + // Generate song queue + var songsInQueue [dj.queue.Len()]SongInfo + for i := 0; i < dj.queue.Len(); i++ { + songItem := dj.queue.Get(i) + songs[i] = &SongInfo{ + TitleID: songItem.ID(), + Title: songItem.Title(), + Submitter: songItem.Submitter(), + Duration: songItem.Duration(), + Thumbnail: songItem.Thumbnail(), + } + if !isNil(songItem.Playlist()) { + songs[i].PlaylistID = songItem.Playlist().ID() + songs[i].Playlist = songItem.Playlist().Title() + } + } + + // Output status + fmt.Fprintf(w, string(json.MarshalIndent(&Status{false, "", songsInQueue}))) + } +} + func (website *WebServer) GetWebAddress(user *gumble.User) { Verbose("Port number: " + strconv.Itoa(web.port)) if web.client_token[user] != "" { @@ -110,7 +160,7 @@ func (website *WebServer) GetWebAddress(user *gumble.User) { } // dealing with collisions var firstLoop = true - for firstLoop || web.token_client[web.client_token[user]] != nil { + for firstLoop || web.token_client[web.client_token[user]] != nil || web.client_token[user] == "api" { web.client_token[user] = randSeq(10) firstLoop = false } From c4fe3c2f4cef7810e5cc4c742d89cf1a4d043315 Mon Sep 17 00:00:00 2001 From: Michael Oultram Date: Sun, 2 Aug 2015 20:02:14 +0100 Subject: [PATCH 073/297] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 71a878f..25704c2 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ MumbleDJ ======== **A Mumble bot that plays music fetched from YouTube videos.** +[![Build Status](https://drone.io/github.com/MichaelOultram/mumbledj/status.png)](https://drone.io/github.com/MichaelOultram/mumbledj/latest) + * [Usage](#usage) * [Features](#features) * [Commands](#commands) From 5ac83ac49de51d691f4e1d8ed22baa67b3efec90 Mon Sep 17 00:00:00 2001 From: Michael Oultram Date: Sun, 2 Aug 2015 20:08:03 +0100 Subject: [PATCH 074/297] Update README.md --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 25704c2..5918f4a 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ MumbleDJ ======== -**A Mumble bot that plays music fetched from YouTube videos.** - -[![Build Status](https://drone.io/github.com/MichaelOultram/mumbledj/status.png)](https://drone.io/github.com/MichaelOultram/mumbledj/latest) +[![Build Status](https://drone.io/github.com/MichaelOultram/mumbledj/status.png)](https://drone.io/github.com/MichaelOultram/mumbledj/latest) **A Mumble bot that plays music fetched from YouTube videos.** * [Usage](#usage) * [Features](#features) From d5b02726aff6f6aace6eb67d9e3bbfc5b07bee5f Mon Sep 17 00:00:00 2001 From: Michael Oultram Date: Sun, 2 Aug 2015 20:08:21 +0100 Subject: [PATCH 075/297] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5918f4a..50d30bc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ MumbleDJ ======== -[![Build Status](https://drone.io/github.com/MichaelOultram/mumbledj/status.png)](https://drone.io/github.com/MichaelOultram/mumbledj/latest) **A Mumble bot that plays music fetched from YouTube videos.** +**A Mumble bot that plays music fetched from YouTube videos.** [![Build Status](https://drone.io/github.com/MichaelOultram/mumbledj/status.png)](https://drone.io/github.com/MichaelOultram/mumbledj/latest) * [Usage](#usage) * [Features](#features) From 0a0116f5e1bd26f15386c51c0454ff730d70e7f2 Mon Sep 17 00:00:00 2001 From: Michael Oultram Date: Mon, 3 Aug 2015 13:14:18 +0100 Subject: [PATCH 076/297] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 50d30bc..94fff05 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -MumbleDJ +MumbleDJ [![Build Status](https://drone.io/github.com/MichaelOultram/mumbledj/status.png)](https://drone.io/github.com/MichaelOultram/mumbledj/latest) ======== -**A Mumble bot that plays music fetched from YouTube videos.** [![Build Status](https://drone.io/github.com/MichaelOultram/mumbledj/status.png)](https://drone.io/github.com/MichaelOultram/mumbledj/latest) +**A Mumble bot that plays music fetched from YouTube videos.** * [Usage](#usage) * [Features](#features) From 1e615261523538f70dd79c9af2f6261af0eb03b6 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 13:58:49 +0100 Subject: [PATCH 077/297] Testing travis-ci --- .travis.yaml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .travis.yaml diff --git a/.travis.yaml b/.travis.yaml new file mode 100644 index 0000000..9e89bcf --- /dev/null +++ b/.travis.yaml @@ -0,0 +1,16 @@ +language: go + +install: + - wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz + - tar -xvf ffmpeg-release-64bit-static.tar.xz --strip 1 --no-anchored ffmpeg ffprobe + - sudo chmod a+rx ffmpeg + - sudo chmod a+rx ffprobe + - sudo mv ffmpeg /usr/local/bin/ffmpeg + - sudo mv ffprobe /usr/local/bin/ffprobe + - wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz + - tar xzvf opus-1.0.3.tar.gz + - ./opus-1.0.3/configure + - make opus-1.0.3 + - sudo make install opus-1.0.3 + - sudo curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o /usr/local/bin/youtube-dl + - sudo chmod a+rx /usr/local/bin/youtube-dl \ No newline at end of file From 14aec3ae2d0a1a8995caad1dc3dfd4cd2bd5b96f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 13:59:47 +0100 Subject: [PATCH 078/297] Testing travis-ci --- .travis.yaml => .travis.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .travis.yaml => .travis.yml (100%) diff --git a/.travis.yaml b/.travis.yml similarity index 100% rename from .travis.yaml rename to .travis.yml From 4a95548e14463b975be60188380e9abd5fd40b34 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 14:06:47 +0100 Subject: [PATCH 079/297] Testing travis-ci --- .travis.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..9e89bcf --- /dev/null +++ b/.travis.yml @@ -0,0 +1,16 @@ +language: go + +install: + - wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz + - tar -xvf ffmpeg-release-64bit-static.tar.xz --strip 1 --no-anchored ffmpeg ffprobe + - sudo chmod a+rx ffmpeg + - sudo chmod a+rx ffprobe + - sudo mv ffmpeg /usr/local/bin/ffmpeg + - sudo mv ffprobe /usr/local/bin/ffprobe + - wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz + - tar xzvf opus-1.0.3.tar.gz + - ./opus-1.0.3/configure + - make opus-1.0.3 + - sudo make install opus-1.0.3 + - sudo curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o /usr/local/bin/youtube-dl + - sudo chmod a+rx /usr/local/bin/youtube-dl \ No newline at end of file From e0a922c048446bbc0f30702d22d7884c272c0a67 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 14:11:51 +0100 Subject: [PATCH 080/297] Testing travis-ci --- .travis.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9e89bcf..0fa366f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,8 +9,10 @@ install: - sudo mv ffprobe /usr/local/bin/ffprobe - wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz - tar xzvf opus-1.0.3.tar.gz - - ./opus-1.0.3/configure - - make opus-1.0.3 - - sudo make install opus-1.0.3 + - cd opus-1.0.3 + - ./configure + - make + - sudo make install + - cd .. - sudo curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o /usr/local/bin/youtube-dl - sudo chmod a+rx /usr/local/bin/youtube-dl \ No newline at end of file From 7de791ccead3b77b426c08c13478275d58301157 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 14:15:33 +0100 Subject: [PATCH 081/297] Added build badge to README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 71a878f..d1abe37 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -MumbleDJ +MumbleDJ [![Build Status](https://travis-ci.org/MichaelOultram/mumbledj.svg?branch=dev)](https://travis-ci.org/MichaelOultram/mumbledj) ======== **A Mumble bot that plays music fetched from YouTube videos.** From b7c6ecbf35350c364c0933ab77db9d071c454f10 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 14:16:12 +0100 Subject: [PATCH 082/297] Added build badge to README --- .travis.yml | 8 +++++--- README.md | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9e89bcf..0fa366f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,8 +9,10 @@ install: - sudo mv ffprobe /usr/local/bin/ffprobe - wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz - tar xzvf opus-1.0.3.tar.gz - - ./opus-1.0.3/configure - - make opus-1.0.3 - - sudo make install opus-1.0.3 + - cd opus-1.0.3 + - ./configure + - make + - sudo make install + - cd .. - sudo curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o /usr/local/bin/youtube-dl - sudo chmod a+rx /usr/local/bin/youtube-dl \ No newline at end of file diff --git a/README.md b/README.md index 94fff05..fd54ba5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -MumbleDJ [![Build Status](https://drone.io/github.com/MichaelOultram/mumbledj/status.png)](https://drone.io/github.com/MichaelOultram/mumbledj/latest) +MumbleDJ [![Build Status](https://travis-ci.org/MichaelOultram/mumbledj.svg?branch=master)](https://travis-ci.org/MichaelOultram/mumbledj) ======== **A Mumble bot that plays music fetched from YouTube videos.** From 8ae7816303c4e5c1fad2a8e62744c921bd76529e Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 21:40:19 +0100 Subject: [PATCH 083/297] Fixing build errors --- service_soundcloud.go | 134 ++++++++++++++++++++++++++++-------- youtube_dl.go | 154 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 259 insertions(+), 29 deletions(-) create mode 100644 youtube_dl.go diff --git a/service_soundcloud.go b/service_soundcloud.go index 34944e7..fed2a3b 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -29,20 +29,6 @@ var soundcloudPlaylistPattern = `https?:\/\/(www)?\.soundcloud\.com\/([\w-]+)\/s // YouTube implements the Service interface type SoundCloud struct{} -// YouTubeSong holds the metadata for a song extracted from a YouTube video. -type SoundCloudSong struct { - submitter string - title string - id string - offset int - filename string - duration string - thumbnail string - skippers []string - playlist Playlist - dontSkip bool -} - // YouTubePlaylist holds the metadata for a YouTube playlist. type SoundCloudPlaylist struct { id string @@ -72,25 +58,115 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { return nil, errors.New(INVALID_API_KEY) } - title, _ := apiResponse.String("title") tracks, err := apiResponse.ArrayOfObjects("tracks") - if err == nil { - if re.MatchString(url) { - // PLAYLIST - if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { - playlist, err := sc.NewPlaylist(user.Name, url) - return playlist.Title(), err - } else { - return "", errors.New("NO_PLAYLIST_PERMISSION") - } - } else { + // PLAYLIST + if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { + // Check duration of playlist + // duration, _ := apiResponse.Int("duration") - // SONG - song, err := sc.NewSong(user.Name, url, nil) - return song.Title(), err + // Create playlist + title, _ := apiResponse.String("title") + permalink, _ := apiResponse.String("permalink_url") + playlist := &SoundCloudPlaylist{ + id: permalink, + title: title, + } + + // Add all tracks + for _, t := range tracks { + sc.NewSong(user.Name, jsonq.NewQuery(t), playlist) + } + return playlist.Title(), err + } else { + return "", errors.New("NO_PLAYLIST_PERMISSION") } } else { - return "", err + return sc.NewSong(user.Name, apiResponse, nil) } } + +// Creates a track and adds to the queue +func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist SoundCloudPlaylist) (string, error) { + title, err := trackData.String("title") + if err != nil { + return "", err + } + id, err := trackData.String("id") + if err != nil { + return "", err + } + duration, err := trackData.Int("duration") + if err != nil { + return "", err + } + thumbnail, err := trackData.String("artwork_uri") + if err != nil { + return "", err + } + + song := &YoutubeDL{ + id: id, + title: title, + thumbnail: thumbnail, + submitter: user.Name, + duration: duration, + playlist: playlist, + skippers: make([]string, 0), + dontSkip: false, + } + dj.queue.AddSong(song) + return title, nil +} + +// ---------------- +// YOUTUBE PLAYLIST +// ---------------- + +// AddSkip adds a skip to the playlist's skippers slice. +func (p *SoundCloudPlaylist) AddSkip(username string) error { + for _, user := range dj.playlistSkips[p.ID()] { + if username == user { + return errors.New("This user has already skipped the current song.") + } + } + dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()], username) + return nil +} + +// RemoveSkip removes a skip from the playlist's skippers slice. If username is not in the slice +// an error is returned. +func (p *YouTubePlaylist) RemoveSkip(username string) error { + for i, user := range dj.playlistSkips[p.ID()] { + if username == user { + dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()][:i], dj.playlistSkips[p.ID()][i+1:]...) + return nil + } + } + return errors.New("This user has not skipped the song.") +} + +// DeleteSkippers removes the skippers entry in dj.playlistSkips. +func (p *YouTubePlaylist) DeleteSkippers() { + delete(dj.playlistSkips, p.ID()) +} + +// SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's +// channel and the number of usernames in the skippers slice. If the value is greater than or equal +// to the skip ratio defined in the config, the function returns true, and returns false otherwise. +func (p *YouTubePlaylist) SkipReached(channelUsers int) bool { + if float32(len(dj.playlistSkips[p.ID()]))/float32(channelUsers) >= dj.conf.General.PlaylistSkipRatio { + return true + } + return false +} + +// ID returns the id of the YouTubePlaylist. +func (p *YouTubePlaylist) ID() string { + return p.id +} + +// Title returns the title of the YouTubePlaylist. +func (p *YouTubePlaylist) Title() string { + return p.title +} diff --git a/youtube_dl.go b/youtube_dl.go new file mode 100644 index 0000000..d830eab --- /dev/null +++ b/youtube_dl.go @@ -0,0 +1,154 @@ +package main + +import () + +type YouTubeDL struct { + id string + title string + thumbnail string + submitter string + duration string + playlist Playlist + skippers []string + dontSkip bool +} + +// Download downloads the song via youtube-dl if it does not already exist on disk. +// All downloaded songs are stored in ~/.mumbledj/songs and should be automatically cleaned. +func (dl *YouTubeDL) Download() error { + + // Checks to see if song is already downloaded + if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, id+".m4a")); os.IsNotExist(err) { + cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, id+".m4a"), "--format", "m4a", "--", url) + if err := cmd.Run(); err == nil { + if dj.conf.Cache.Enabled { + dj.cache.CheckMaximumDirectorySize() + } + return nil + } + return errors.New("Song download failed.") + } + return nil +} + +// Play plays the song. Once the song is playing, a notification is displayed in a text message that features the song +// thumbnail, URL, title, duration, and submitter. +func (dl *YouTubeDL) Play() { + if s.offset != 0 { + offsetDuration, _ := time.ParseDuration(fmt.Sprintf("%ds", dl.offset)) + dj.audioStream.Offset = offsetDuration + } + dj.audioStream.Source = gumble_ffmpeg.SourceFile(fmt.Sprintf("%s/.mumbledj/songs/%s.m4a", dj.homeDir, dl.id)) + if err := dj.audioStream.Play(); err != nil { + panic(err) + } else { + message := `` + message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.duration, dl.submitter) + if isNil(dl.playlist) { + dj.client.Self.Channel.Send(message+`
%s (%s)
Added by %s
`, false) + } else { + message += `From playlist "%s"` + dj.client.Self.Channel.Send(fmt.Sprintf(message, dl.playlist.Title()), false) + } + Verbose("Now playing " + dl.title) + + go func() { + dj.audioStream.Wait() + dj.queue.OnSongFinished() + }() + } +} + +// Delete deletes the song from ~/.mumbledj/songs if the cache is disabled. +func (dl *YouTubeDL) Delete() error { + if dj.conf.Cache.Enabled == false { + filePath := fmt.Sprintf("%s/.mumbledj/songs/%s.m4a", dj.homeDir, dl.id) + if _, err := os.Stat(filePath); err == nil { + if err := os.Remove(filePath); err == nil { + return nil + } + return errors.New("Error occurred while deleting audio file.") + } + return nil + } + return nil +} + +// AddSkip adds a skip to the skippers slice. If the user is already in the slice, AddSkip +// returns an error and does not add a duplicate skip. +func (dl *YouTubeDL) AddSkip(username string) error { + for _, user := range dl.skippers { + if username == user { + return errors.New("This user has already skipped the current song.") + } + } + dl.skippers = append(dl.skippers, username) + return nil +} + +// RemoveSkip removes a skip from the skippers slice. If username is not in slice, an error is +// returned. +func (dl *YouTubeDL) RemoveSkip(username string) error { + for i, user := range dl.skippers { + if username == user { + dl.skippers = append(s.skippers[:i], s.skippers[i+1:]...) + return nil + } + } + return errors.New("This user has not skipped the song.") +} + +// SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's +// channel and the number of usernames in the skippers slice. If the value is greater than or equal +// to the skip ratio defined in the config, the function returns true, and returns false otherwise. +func (dl *YouTubeDL) SkipReached(channelUsers int) bool { + if float32(len(dl.skippers))/float32(channelUsers) >= dj.conf.General.SkipRatio { + return true + } + return false +} + +// Submitter returns the name of the submitter of the Song. +func (dl *YouTubeDL) Submitter() string { + return dl.submitter +} + +// Title returns the title of the Song. +func (dl *YouTubeDL) Title() string { + return dl.title +} + +// ID returns the id of the Song. +func (dl *YouTubeDL) ID() string { + return dl.id +} + +// Filename returns the filename of the Song. +func (dl *YouTubeDL) Filename() string { + return dl.id + ".m4a" +} + +// Duration returns the duration of the Song. +func (dl *YouTubeDL) Duration() string { + return dl.duration +} + +// Thumbnail returns the thumbnail URL for the Song. +func (dl *YouTubeDL) Thumbnail() string { + return dl.thumbnail +} + +// Playlist returns the playlist type for the Song (may be nil). +func (dl *YouTubeDL) Playlist() Playlist { + return dl.playlist +} + +// DontSkip returns the DontSkip boolean value for the Song. +func (dl *YouTubeDL) DontSkip() bool { + return dl.dontSkip +} + +// SetDontSkip sets the DontSkip boolean value for the Song. +func (dl *YouTubeDL) SetDontSkip(value bool) { + dl.dontSkip = value +} From 62ec49eee7980f965db901670b48b4161fd61402 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 21:48:21 +0100 Subject: [PATCH 084/297] Fixing build errors --- .travis.yml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0fa366f..37f8ad4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,18 +1,19 @@ language: go install: + - export PATH=$PATH:~/bin/ - wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz - tar -xvf ffmpeg-release-64bit-static.tar.xz --strip 1 --no-anchored ffmpeg ffprobe - - sudo chmod a+rx ffmpeg - - sudo chmod a+rx ffprobe - - sudo mv ffmpeg /usr/local/bin/ffmpeg - - sudo mv ffprobe /usr/local/bin/ffprobe + - chmod a+rx ffmpeg + - chmod a+rx ffprobe + - mv ffmpeg ~/bin/ffmpeg + - mv ffprobe ~/bin/ffprobe - wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz - tar xzvf opus-1.0.3.tar.gz - cd opus-1.0.3 - ./configure - make - - sudo make install + - make install - cd .. - - sudo curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o /usr/local/bin/youtube-dl - - sudo chmod a+rx /usr/local/bin/youtube-dl \ No newline at end of file + - curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o ~/bin/youtube-dl + - chmod a+rx ~/bin/youtube-dl \ No newline at end of file From 7bb415a5df00d7c9368c5c3c1e6afa8b03283686 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:00:37 +0100 Subject: [PATCH 085/297] Updated .travis.yml --- .travis.yml | 29 ++++++++++++++--------------- install-opus.sh | 10 ++++++++++ 2 files changed, 24 insertions(+), 15 deletions(-) create mode 100644 install-opus.sh diff --git a/.travis.yml b/.travis.yml index 37f8ad4..77db788 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,19 +1,18 @@ language: go -install: +cache: + directories: + - $HOME/opus + +before_script: - export PATH=$PATH:~/bin/ - - wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz - - tar -xvf ffmpeg-release-64bit-static.tar.xz --strip 1 --no-anchored ffmpeg ffprobe - - chmod a+rx ffmpeg - - chmod a+rx ffprobe - - mv ffmpeg ~/bin/ffmpeg - - mv ffprobe ~/bin/ffprobe - - wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz - - tar xzvf opus-1.0.3.tar.gz - - cd opus-1.0.3 - - ./configure - - make - - make install - - cd .. + - wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz + - tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe + - chmod a+rx ffmpeg ffprobe + - mv ff* ~/bin - curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o ~/bin/youtube-dl - - chmod a+rx ~/bin/youtube-dl \ No newline at end of file + - chmod a+rx ~/bin/youtube-dl + - bash install-opus.sh + +install: + - ls -R $HOME/opus diff --git a/install-opus.sh b/install-opus.sh new file mode 100644 index 0000000..cf818c4 --- /dev/null +++ b/install-opus.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -e +# check to see if opus folder is empty +if [ ! -d "$HOME/opus/lib" ]; then + wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz + tar xzvf opus-1.0.3.tar.gz + cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install +else + echo 'Using cached directory.'; +fi \ No newline at end of file From de1828e51021d31691ecff817e17a682e21b03e8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:05:21 +0100 Subject: [PATCH 086/297] Updated .travis.yml --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 77db788..e369d96 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,6 +13,7 @@ before_script: - curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o ~/bin/youtube-dl - chmod a+rx ~/bin/youtube-dl - bash install-opus.sh + - export PATH=$PATH:$HOME/opus/lib install: - ls -R $HOME/opus From 3a443e30a2a5adee71086455cf54cc6a8d5376d5 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:07:01 +0100 Subject: [PATCH 087/297] Updated .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index e369d96..259668b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ before_script: - curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o ~/bin/youtube-dl - chmod a+rx ~/bin/youtube-dl - bash install-opus.sh - - export PATH=$PATH:$HOME/opus/lib + - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib install: - ls -R $HOME/opus From 733fe94e2bfc36ade7c99769ecb6a99868069346 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:08:49 +0100 Subject: [PATCH 088/297] Updated .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 259668b..cc85e8e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ before_script: - curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o ~/bin/youtube-dl - chmod a+rx ~/bin/youtube-dl - bash install-opus.sh - - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib + - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig install: - ls -R $HOME/opus From d3b2afe8a0ea3241a82c55dd03f47103b388c08b Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:11:52 +0100 Subject: [PATCH 089/297] Fixing build errors --- service_soundcloud.go | 9 --------- 1 file changed, 9 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index fed2a3b..08f2a06 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -1,21 +1,12 @@ package main import ( - "encoding/json" "errors" "fmt" - "io/ioutil" - "net/http" "os" - "os/exec" - "regexp" - "strconv" - "strings" - "time" "github.com/jmoiron/jsonq" "github.com/layeh/gumble/gumble" - "github.com/layeh/gumble/gumble_ffmpeg" ) // Regular expressions for soundcloud urls From afb05faecbdd4d689291d6395b15d9241542c46e Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:15:51 +0100 Subject: [PATCH 090/297] Fixing build errors --- service_soundcloud.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 08f2a06..20e636e 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -44,9 +44,9 @@ func (sc SoundCloud) URLRegex(url string) bool { func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { var apiResponse *jsonq.JsonQuery var err error - url := fmt.Sprintf("http://api.soundcloud.com/resolve?url=%s&client_id=%s", url, os.Getenv("SOUNDCLOUD_API_KEY")) + url = fmt.Sprintf("http://api.soundcloud.com/resolve?url=%s&client_id=%s", url, os.Getenv("SOUNDCLOUD_API_KEY")) if apiResponse, err = PerformGetRequest(url); err != nil { - return nil, errors.New(INVALID_API_KEY) + return "", errors.New(INVALID_API_KEY) } tracks, err := apiResponse.ArrayOfObjects("tracks") @@ -78,7 +78,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { } // Creates a track and adds to the queue -func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist SoundCloudPlaylist) (string, error) { +func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist Playlist) (string, error) { title, err := trackData.String("title") if err != nil { return "", err @@ -127,7 +127,7 @@ func (p *SoundCloudPlaylist) AddSkip(username string) error { // RemoveSkip removes a skip from the playlist's skippers slice. If username is not in the slice // an error is returned. -func (p *YouTubePlaylist) RemoveSkip(username string) error { +func (p *SoundCloudPlaylist) RemoveSkip(username string) error { for i, user := range dj.playlistSkips[p.ID()] { if username == user { dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()][:i], dj.playlistSkips[p.ID()][i+1:]...) @@ -138,14 +138,14 @@ func (p *YouTubePlaylist) RemoveSkip(username string) error { } // DeleteSkippers removes the skippers entry in dj.playlistSkips. -func (p *YouTubePlaylist) DeleteSkippers() { +func (p *SoundCloudPlaylist) DeleteSkippers() { delete(dj.playlistSkips, p.ID()) } // SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's // channel and the number of usernames in the skippers slice. If the value is greater than or equal // to the skip ratio defined in the config, the function returns true, and returns false otherwise. -func (p *YouTubePlaylist) SkipReached(channelUsers int) bool { +func (p *SoundCloudPlaylist) SkipReached(channelUsers int) bool { if float32(len(dj.playlistSkips[p.ID()]))/float32(channelUsers) >= dj.conf.General.PlaylistSkipRatio { return true } @@ -153,11 +153,11 @@ func (p *YouTubePlaylist) SkipReached(channelUsers int) bool { } // ID returns the id of the YouTubePlaylist. -func (p *YouTubePlaylist) ID() string { +func (p *SoundCloudPlaylist) ID() string { return p.id } // Title returns the title of the YouTubePlaylist. -func (p *YouTubePlaylist) Title() string { +func (p *SoundCloudPlaylist) Title() string { return p.title } From b95aeee62d431585d0786bbbfb3becc36db5c9e0 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:18:49 +0100 Subject: [PATCH 091/297] Fixing build errors --- service_soundcloud.go | 2 +- songqueue.go | 2 +- web.go | 3 +-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 20e636e..c6f5d71 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -96,7 +96,7 @@ func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist P return "", err } - song := &YoutubeDL{ + song := &YouTubeDL{ id: id, title: title, thumbnail: thumbnail, diff --git a/songqueue.go b/songqueue.go index 54e3610..d00f771 100644 --- a/songqueue.go +++ b/songqueue.go @@ -78,7 +78,7 @@ func (q *SongQueue) Traverse(visit func(i int, s Song)) { } // Gets the song at a specific point in the queue -func (q *SongQueue) Get(int i) (Song, error) { +func (q *SongQueue) Get(i int) (Song, error) { if q.Len() > i+1 { return q.queue[i], nil } diff --git a/web.go b/web.go index d9873d7..e44ccbf 100644 --- a/web.go +++ b/web.go @@ -9,7 +9,6 @@ import ( "math/rand" "net/http" "os" - "path/filepath" "strconv" "strings" "time" @@ -29,7 +28,7 @@ type Page struct { User string } -type status struct { +type Status struct { Error bool ErrorMsg string Queue []SongInfo From 004129ad9b452e486cf48b35b6b95e0e59ff0e9e Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:25:11 +0100 Subject: [PATCH 092/297] Fixing build errors --- .travis.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index cc85e8e..8dabcbe 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,9 +3,9 @@ language: go cache: directories: - $HOME/opus + - $TRAVIS_BUILD_DIR/.vendor before_script: - - export PATH=$PATH:~/bin/ - wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz - tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe - chmod a+rx ffmpeg ffprobe @@ -17,3 +17,6 @@ before_script: install: - ls -R $HOME/opus + +env: + - PATH=$PATH:~/bin/ \ No newline at end of file From 334c1fcfe4fc8242e2706c4205bbe7e5bf055095 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:33:39 +0100 Subject: [PATCH 093/297] Updated .travis.yml --- .travis.yml | 13 ++++--------- install-dependencies.sh | 29 +++++++++++++++++++++++++++++ install-opus.sh | 10 ---------- 3 files changed, 33 insertions(+), 19 deletions(-) create mode 100644 install-dependencies.sh delete mode 100644 install-opus.sh diff --git a/.travis.yml b/.travis.yml index 8dabcbe..cb3fe06 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,20 +3,15 @@ language: go cache: directories: - $HOME/opus + - $HOME/bin - $TRAVIS_BUILD_DIR/.vendor before_script: - - wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz - - tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe - - chmod a+rx ffmpeg ffprobe - - mv ff* ~/bin - - curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o ~/bin/youtube-dl - - chmod a+rx ~/bin/youtube-dl - - bash install-opus.sh - - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig + - bash install-dependencies.sh install: - ls -R $HOME/opus env: - - PATH=$PATH:~/bin/ \ No newline at end of file + - PATH=$PATH:~/bin/ + - PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig \ No newline at end of file diff --git a/install-dependencies.sh b/install-dependencies.sh new file mode 100644 index 0000000..90d3db1 --- /dev/null +++ b/install-dependencies.sh @@ -0,0 +1,29 @@ +#!/bin/sh +set -e + +# check to see if ffmpeg is installed +if [ ! -f "$HOME/bin/ffmpeg" ]; then + wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz + tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe + chmod a+rx ffmpeg ffprobe + mv ff* $HOME/bin +else + echo 'Using cached version of ffmpeg.'; +fi + +# check to see if opus is installed +if [ ! -d "$HOME/opus/lib" ]; then + wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz + tar xzvf opus-1.0.3.tar.gz + cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install +else + echo 'Using cached version of opus.'; +fi + +# check to see if youtube-dl is installed +if [ ! -f "$HOME/bin/youtube-dl" ]; then + curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o ~/bin/youtube-dl + chmod a+rx ~/bin/youtube-dl +else + echo 'Using cached version of youtube-dl.'; +fi \ No newline at end of file diff --git a/install-opus.sh b/install-opus.sh deleted file mode 100644 index cf818c4..0000000 --- a/install-opus.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -set -e -# check to see if opus folder is empty -if [ ! -d "$HOME/opus/lib" ]; then - wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz - tar xzvf opus-1.0.3.tar.gz - cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install -else - echo 'Using cached directory.'; -fi \ No newline at end of file From 54cfa1de5aba5920aa80a630f1270f70c3308e41 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:35:08 +0100 Subject: [PATCH 094/297] Updated .travis.yml --- .travis.yml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index cb3fe06..cb112de 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,11 +7,9 @@ cache: - $TRAVIS_BUILD_DIR/.vendor before_script: + - export PATH=$PATH:~/bin/ + - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig - bash install-dependencies.sh install: - - ls -R $HOME/opus - -env: - - PATH=$PATH:~/bin/ - - PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig \ No newline at end of file + - ls -R $HOME/opus \ No newline at end of file From 335c19aa816dc7de2e6a04210f94225efb75756b Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:39:45 +0100 Subject: [PATCH 095/297] Fixing build errors --- service_soundcloud.go | 7 ++++--- web.go | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index c6f5d71..7cd328a 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "os" + "strconv" "github.com/jmoiron/jsonq" "github.com/layeh/gumble/gumble" @@ -100,14 +101,14 @@ func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist P id: id, title: title, thumbnail: thumbnail, - submitter: user.Name, - duration: duration, + submitter: user, + duration: strconv.ParseInt(duration), playlist: playlist, skippers: make([]string, 0), dontSkip: false, } dj.queue.AddSong(song) - return title, nil + return title, nil } // ---------------- diff --git a/web.go b/web.go index e44ccbf..7608e2d 100644 --- a/web.go +++ b/web.go @@ -128,7 +128,7 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { func (web *WebServer) status(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { - fmt.Fprintf(w, string(json.MarshalIndent(&Status{true, "Invalid Token"}))) + fmt.Fprintf(w, string(json.Marshal(&Status{true, "Invalid Token"}))) } else { // Generate song queue var songsInQueue [dj.queue.Len()]SongInfo From b5034097536faf6707cb0e05fd418fd115685da4 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:44:03 +0100 Subject: [PATCH 096/297] Fixing build errors --- .travis.yml | 4 +++- service_soundcloud.go | 5 ++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index cb112de..095beee 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,9 @@ cache: directories: - $HOME/opus - $HOME/bin - - $TRAVIS_BUILD_DIR/.vendor + - $HOME/gopath/bin + - $HOME/gopath/src/github.com/nitrous-io/goop + - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor before_script: - export PATH=$PATH:~/bin/ diff --git a/service_soundcloud.go b/service_soundcloud.go index 7cd328a..0d63bc4 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "os" - "strconv" "github.com/jmoiron/jsonq" "github.com/layeh/gumble/gumble" @@ -88,7 +87,7 @@ func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist P if err != nil { return "", err } - duration, err := trackData.Int("duration") + duration, err := trackData.String("duration") if err != nil { return "", err } @@ -102,7 +101,7 @@ func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist P title: title, thumbnail: thumbnail, submitter: user, - duration: strconv.ParseInt(duration), + duration: duration, playlist: playlist, skippers: make([]string, 0), dontSkip: false, From a135b4fe4d072b84e010d71c8afae703f3482536 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:45:23 +0100 Subject: [PATCH 097/297] Updated .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 095beee..800a9af 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,7 @@ cache: - $HOME/opus - $HOME/bin - $HOME/gopath/bin - - $HOME/gopath/src/github.com/nitrous-io/goop + - $HOME/gopath/pkg - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor before_script: From b36cb3de37d8b32cbe01e87672251d9e22d434a3 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:51:38 +0100 Subject: [PATCH 098/297] Fixing build errors --- web.go | 12 +++++++----- youtube_dl.go | 18 +++++++++++++++++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/web.go b/web.go index 7608e2d..b3923f3 100644 --- a/web.go +++ b/web.go @@ -128,13 +128,15 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { func (web *WebServer) status(w http.ResponseWriter, r *http.Request) { var uname = web.token_client[r.FormValue("token")] if uname == nil { - fmt.Fprintf(w, string(json.Marshal(&Status{true, "Invalid Token"}))) + str, ok := json.Marshal(&Status{true, "Invalid Token"}).(string) + fmt.Fprintf(w, str) } else { // Generate song queue - var songsInQueue [dj.queue.Len()]SongInfo + queueLength := dj.queue.Len() + var songsInQueue [queueLength]SongInfo for i := 0; i < dj.queue.Len(); i++ { songItem := dj.queue.Get(i) - songs[i] = &SongInfo{ + songsInQueue[i] = &SongInfo{ TitleID: songItem.ID(), Title: songItem.Title(), Submitter: songItem.Submitter(), @@ -142,8 +144,8 @@ func (web *WebServer) status(w http.ResponseWriter, r *http.Request) { Thumbnail: songItem.Thumbnail(), } if !isNil(songItem.Playlist()) { - songs[i].PlaylistID = songItem.Playlist().ID() - songs[i].Playlist = songItem.Playlist().Title() + songsInQueuei].PlaylistID = songItem.Playlist().ID() + songsInQueue[i].Playlist = songItem.Playlist().Title() } } diff --git a/youtube_dl.go b/youtube_dl.go index d830eab..52245a2 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -1,6 +1,22 @@ package main -import () +import ( + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "os" + "os/exec" + "regexp" + "strconv" + "strings" + "time" + + "github.com/jmoiron/jsonq" + "github.com/layeh/gumble/gumble" + "github.com/layeh/gumble/gumble_ffmpeg" +) type YouTubeDL struct { id string From 202221e52618e4310a7b6bc3269322b4738758a1 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:53:32 +0100 Subject: [PATCH 099/297] Fixing build errors --- web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web.go b/web.go index b3923f3..c87eff6 100644 --- a/web.go +++ b/web.go @@ -144,7 +144,7 @@ func (web *WebServer) status(w http.ResponseWriter, r *http.Request) { Thumbnail: songItem.Thumbnail(), } if !isNil(songItem.Playlist()) { - songsInQueuei].PlaylistID = songItem.Playlist().ID() + songsInQueue[i].PlaylistID = songItem.Playlist().ID() songsInQueue[i].Playlist = songItem.Playlist().Title() } } From 974a52df7e9aae152a3fc66ab48b560425431227 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:56:27 +0100 Subject: [PATCH 100/297] Fixing build errors --- .travis.yml | 1 + youtube_dl.go | 8 -------- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index 800a9af..8864edb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,6 +6,7 @@ cache: - $HOME/bin - $HOME/gopath/bin - $HOME/gopath/pkg + - $HOME/gopath/src/github.com/nitrous-io - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor before_script: diff --git a/youtube_dl.go b/youtube_dl.go index 52245a2..6484f95 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -1,20 +1,12 @@ package main import ( - "encoding/json" "errors" "fmt" - "io/ioutil" - "net/http" "os" "os/exec" - "regexp" - "strconv" - "strings" "time" - "github.com/jmoiron/jsonq" - "github.com/layeh/gumble/gumble" "github.com/layeh/gumble/gumble_ffmpeg" ) From 5e70e69222b62329d5682feaa74298fe5851d5ef Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 22:59:37 +0100 Subject: [PATCH 101/297] Fixing build errors --- web.go | 58 +++++++++++++++++++++++++-------------------------- youtube_dl.go | 6 +++--- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/web.go b/web.go index c87eff6..b59ff7f 100644 --- a/web.go +++ b/web.go @@ -59,7 +59,7 @@ func (web *WebServer) makeWeb() { http.HandleFunc("/api/add", web.add) http.HandleFunc("/api/volume", web.volume) http.HandleFunc("/api/skip", web.skip) - http.HandleFunc("/api/status", web.status) + //http.HandleFunc("/api/status", web.status) http.ListenAndServe(":"+strconv.Itoa(web.port), nil) } @@ -125,34 +125,34 @@ func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { } } -func (web *WebServer) status(w http.ResponseWriter, r *http.Request) { - var uname = web.token_client[r.FormValue("token")] - if uname == nil { - str, ok := json.Marshal(&Status{true, "Invalid Token"}).(string) - fmt.Fprintf(w, str) - } else { - // Generate song queue - queueLength := dj.queue.Len() - var songsInQueue [queueLength]SongInfo - for i := 0; i < dj.queue.Len(); i++ { - songItem := dj.queue.Get(i) - songsInQueue[i] = &SongInfo{ - TitleID: songItem.ID(), - Title: songItem.Title(), - Submitter: songItem.Submitter(), - Duration: songItem.Duration(), - Thumbnail: songItem.Thumbnail(), - } - if !isNil(songItem.Playlist()) { - songsInQueue[i].PlaylistID = songItem.Playlist().ID() - songsInQueue[i].Playlist = songItem.Playlist().Title() - } - } - - // Output status - fmt.Fprintf(w, string(json.MarshalIndent(&Status{false, "", songsInQueue}))) - } -} +//func (web *WebServer) status(w http.ResponseWriter, r *http.Request) { +// var uname = web.token_client[r.FormValue("token")] +// if uname == nil { +// str, ok := json.Marshal(&Status{true, "Invalid Token"}).(string) +// fmt.Fprintf(w, str) +// } else { +// // Generate song queue +// queueLength := dj.queue.Len() +// var songsInQueue [queueLength]SongInfo +// for i := 0; i < dj.queue.Len(); i++ { +// songItem := dj.queue.Get(i) +// songsInQueue[i] = &SongInfo{ +// TitleID: songItem.ID(), +// Title: songItem.Title(), +// Submitter: songItem.Submitter(), +// Duration: songItem.Duration(), +// Thumbnail: songItem.Thumbnail(), +// } +// if !isNil(songItem.Playlist()) { +// songsInQueue[i].PlaylistID = songItem.Playlist().ID() +// songsInQueue[i].Playlist = songItem.Playlist().Title() +// } +// } +// +// // Output status +// fmt.Fprintf(w, string(json.MarshalIndent(&Status{false, "", songsInQueue}))) +// } +//} func (website *WebServer) GetWebAddress(user *gumble.User) { Verbose("Port number: " + strconv.Itoa(web.port)) diff --git a/youtube_dl.go b/youtube_dl.go index 6484f95..df4e963 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -26,8 +26,8 @@ type YouTubeDL struct { func (dl *YouTubeDL) Download() error { // Checks to see if song is already downloaded - if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, id+".m4a")); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, id+".m4a"), "--format", "m4a", "--", url) + if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.id+".m4a")); os.IsNotExist(err) { + cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, dl.id+".m4a"), "--format", "m4a", "--", dl.url) if err := cmd.Run(); err == nil { if dj.conf.Cache.Enabled { dj.cache.CheckMaximumDirectorySize() @@ -42,7 +42,7 @@ func (dl *YouTubeDL) Download() error { // Play plays the song. Once the song is playing, a notification is displayed in a text message that features the song // thumbnail, URL, title, duration, and submitter. func (dl *YouTubeDL) Play() { - if s.offset != 0 { + if dl.offset != 0 { offsetDuration, _ := time.ParseDuration(fmt.Sprintf("%ds", dl.offset)) dj.audioStream.Offset = offsetDuration } From e73761dc82c9292a8cdb0e58e2275b8cd66f23f1 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 23:02:16 +0100 Subject: [PATCH 102/297] Fixing build errors --- youtube_dl.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/youtube_dl.go b/youtube_dl.go index df4e963..b2cb7df 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -16,6 +16,8 @@ type YouTubeDL struct { thumbnail string submitter string duration string + url string + offset string playlist Playlist skippers []string dontSkip bool @@ -99,7 +101,7 @@ func (dl *YouTubeDL) AddSkip(username string) error { func (dl *YouTubeDL) RemoveSkip(username string) error { for i, user := range dl.skippers { if username == user { - dl.skippers = append(s.skippers[:i], s.skippers[i+1:]...) + dl.skippers = append(dl.skippers[:i], dl.skippers[i+1:]...) return nil } } From 3dd6272028aeedd5e295622a76bcef9af924ccec Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 23:04:41 +0100 Subject: [PATCH 103/297] Fixing build errors --- youtube_dl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/youtube_dl.go b/youtube_dl.go index b2cb7df..5e713cb 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -17,7 +17,7 @@ type YouTubeDL struct { submitter string duration string url string - offset string + offset int playlist Playlist skippers []string dontSkip bool From 6c67d731c12405fecf0e044f29cdd4e5557ff19f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 23:06:32 +0100 Subject: [PATCH 104/297] Fixing build errors --- .travis.yml | 8 ++++---- web.go | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8864edb..199d525 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,10 +4,10 @@ cache: directories: - $HOME/opus - $HOME/bin - - $HOME/gopath/bin - - $HOME/gopath/pkg - - $HOME/gopath/src/github.com/nitrous-io - - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor + - $GOPATH/bin + - $GOPATH/pkg + - $GOPATH/src/github.com/nitrous-io + - $GOPATH/src/github.com/MichaelOultram/mumbledj/.vendor before_script: - export PATH=$PATH:~/bin/ diff --git a/web.go b/web.go index b59ff7f..1fb2c40 100644 --- a/web.go +++ b/web.go @@ -1,7 +1,7 @@ package main import ( - "encoding/json" + //"encoding/json" "fmt" "html" "html/template" From 3e08b50bd2d0509bac868aea39ef48d88bcfcc6c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 23:08:37 +0100 Subject: [PATCH 105/297] Updated .travis.yml --- .travis.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 199d525..8864edb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,10 +4,10 @@ cache: directories: - $HOME/opus - $HOME/bin - - $GOPATH/bin - - $GOPATH/pkg - - $GOPATH/src/github.com/nitrous-io - - $GOPATH/src/github.com/MichaelOultram/mumbledj/.vendor + - $HOME/gopath/bin + - $HOME/gopath/pkg + - $HOME/gopath/src/github.com/nitrous-io + - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor before_script: - export PATH=$PATH:~/bin/ From d6a57387009a5f07eee13d1adeeae38472cbfc00 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 23:11:11 +0100 Subject: [PATCH 106/297] Fixing build errors --- Makefile | 2 +- web.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 2f0b5c3..92851ce 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ all: mumbledj mumbledj: main.go commands.go parseconfig.go strings.go service.go service_youtube.go songqueue.go cache.go web.go - go get github.com/nitrous-io/goop + if [! -f $GOPATH/bin/goop ]; then go get github.com/nitrous-io/goop; fi; rm -rf Goopfile.lock goop install goop go build diff --git a/web.go b/web.go index 1fb2c40..73d7c23 100644 --- a/web.go +++ b/web.go @@ -75,7 +75,7 @@ func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { webpage = "index" } - t, err := template.ParseFiles(fmt.Sprintf("%s/.mumbledj/songs/%s.html", dj.homeDir, uname.Name)) + t, err := template.ParseFiles(fmt.Sprintf("%s/.mumbledj/songs/%s.html", dj.homeDir, webpage)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return From ca7446b863ed384d650b35ffb60e5f40268cd1be Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 23:12:44 +0100 Subject: [PATCH 107/297] Updated Makefile --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 92851ce..7aec1d8 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ all: mumbledj mumbledj: main.go commands.go parseconfig.go strings.go service.go service_youtube.go songqueue.go cache.go web.go - if [! -f $GOPATH/bin/goop ]; then go get github.com/nitrous-io/goop; fi; + if [ ! -f $GOPATH/bin/goop ]; then go get github.com/nitrous-io/goop; fi; rm -rf Goopfile.lock goop install goop go build From e562c689e41c515f69501dd88b28255990e1dd03 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 3 Aug 2015 23:15:06 +0100 Subject: [PATCH 108/297] Updated Makefile --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 7aec1d8..23a95e1 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ all: mumbledj mumbledj: main.go commands.go parseconfig.go strings.go service.go service_youtube.go songqueue.go cache.go web.go - if [ ! -f $GOPATH/bin/goop ]; then go get github.com/nitrous-io/goop; fi; + if [ ! -f $(GOPATH)/bin/goop ]; then go get github.com/nitrous-io/goop; fi; rm -rf Goopfile.lock goop install goop go build From 508afd963a0314afb807926b0c0420ed610d4226 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 7 Aug 2015 13:54:44 +0100 Subject: [PATCH 109/297] Fixed check for error in youtube link --- service_youtube.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/service_youtube.go b/service_youtube.go index 12b925c..62c422f 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -96,7 +96,11 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { startOffset = matches[0][2] } song, err := yt.NewSong(user.Name, shortURL, startOffset, nil) - return song.Title(), err + if !isNil(song) { + return song.Title(), err + } else { + return "", err + } } } else { return "", err From a7a8cc0bf062f6037e237e053275b3c6cdb98aad Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 9 Aug 2015 23:48:55 +0100 Subject: [PATCH 110/297] Updated .travis.yml --- .travis.yml | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0fa366f..8864edb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,18 +1,18 @@ language: go +cache: + directories: + - $HOME/opus + - $HOME/bin + - $HOME/gopath/bin + - $HOME/gopath/pkg + - $HOME/gopath/src/github.com/nitrous-io + - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor + +before_script: + - export PATH=$PATH:~/bin/ + - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig + - bash install-dependencies.sh + install: - - wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz - - tar -xvf ffmpeg-release-64bit-static.tar.xz --strip 1 --no-anchored ffmpeg ffprobe - - sudo chmod a+rx ffmpeg - - sudo chmod a+rx ffprobe - - sudo mv ffmpeg /usr/local/bin/ffmpeg - - sudo mv ffprobe /usr/local/bin/ffprobe - - wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz - - tar xzvf opus-1.0.3.tar.gz - - cd opus-1.0.3 - - ./configure - - make - - sudo make install - - cd .. - - sudo curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o /usr/local/bin/youtube-dl - - sudo chmod a+rx /usr/local/bin/youtube-dl \ No newline at end of file + - ls -R $HOME/opus \ No newline at end of file From 906adab101fe6c18da999ebbdeff19d4570425c4 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 9 Aug 2015 23:50:39 +0100 Subject: [PATCH 111/297] Added missing dependancy installer --- install-dependencies.sh | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 install-dependencies.sh diff --git a/install-dependencies.sh b/install-dependencies.sh new file mode 100644 index 0000000..90d3db1 --- /dev/null +++ b/install-dependencies.sh @@ -0,0 +1,29 @@ +#!/bin/sh +set -e + +# check to see if ffmpeg is installed +if [ ! -f "$HOME/bin/ffmpeg" ]; then + wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz + tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe + chmod a+rx ffmpeg ffprobe + mv ff* $HOME/bin +else + echo 'Using cached version of ffmpeg.'; +fi + +# check to see if opus is installed +if [ ! -d "$HOME/opus/lib" ]; then + wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz + tar xzvf opus-1.0.3.tar.gz + cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install +else + echo 'Using cached version of opus.'; +fi + +# check to see if youtube-dl is installed +if [ ! -f "$HOME/bin/youtube-dl" ]; then + curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o ~/bin/youtube-dl + chmod a+rx ~/bin/youtube-dl +else + echo 'Using cached version of youtube-dl.'; +fi \ No newline at end of file From 61d5a6fd66100a3ebc9fc8235550467ce333973a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 00:01:12 +0100 Subject: [PATCH 112/297] Added .gitattributes file --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..73ec672 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +README.md merge=ours \ No newline at end of file From d1c0905a78cbae2daf5397f7d9c74dc073c04a49 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 00:03:19 +0100 Subject: [PATCH 113/297] Updated MakeFile to improve compile times --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 2f0b5c3..23a95e1 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ all: mumbledj mumbledj: main.go commands.go parseconfig.go strings.go service.go service_youtube.go songqueue.go cache.go web.go - go get github.com/nitrous-io/goop + if [ ! -f $(GOPATH)/bin/goop ]; then go get github.com/nitrous-io/goop; fi; rm -rf Goopfile.lock goop install goop go build From a34d8b991b52317b86e60770f327f5184035815f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 00:41:26 +0100 Subject: [PATCH 114/297] Written first test --- .travis.yml | 6 +++--- test.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 3 deletions(-) create mode 100644 test.go diff --git a/.travis.yml b/.travis.yml index 8864edb..c5ea4fd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,10 +9,10 @@ cache: - $HOME/gopath/src/github.com/nitrous-io - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor -before_script: +before_install: - export PATH=$PATH:~/bin/ - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig - bash install-dependencies.sh -install: - - ls -R $HOME/opus \ No newline at end of file +after_success: + - go test \ No newline at end of file diff --git a/test.go b/test.go new file mode 100644 index 0000000..47b9931 --- /dev/null +++ b/test.go @@ -0,0 +1,49 @@ +package main + +import "testing" + +func createClient(uname string) *gumble.Client { + return gumble.NewClient(&gumble.Config{ + Username: uname, + Password: password, + Address: address + ":" + port, + Tokens: strings.Split(accesstokens, " ")}) +} + +func TestYoutubeSong(t *testing.T) { + dummy1Client := createClient("dummy") + dummy1Client.Connect() + dummy1 := gumble.Find("dummy") + + // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist + songs := map[string]string{ + "http://www.youtube.com/watch?v=QcIy9NiNbmo": "Taylor Swift - Bad Blood ft. Kendrick Lamar", + "https://www.youtube.com/watch?v=vjW8wmF5VWc": "Silentó - Watch Me (Whip/Nae Nae) (Official)", + "http://youtu.be/nsDwItoNlLc": "Tinie Tempah ft. Jess Glynne - Not Letting Go (Official Video)", + "https://youtu.be/hXTAn4ELEwM": "Years & Years - Shine", + "http://youtube.com/watch?v=RgKAFK5djSk": "Wiz Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack", + "https://youtube.com/watch?v=qWWSM3wCiKY": "Calvin Harris & Disciples - How Deep Is Your Love (Audio)", + "http://www.youtube.com/v/yzTuBuRdAyA": "The Weeknd - The Hills", + "https://www.youtube.com/v/cNw8A5pwbVI": "Pia Mia - Do It Again ft. Chris Brown, Tyga", + } + + for url, title := range songs { + err := add(dummy1, url) + if err != nil { + t.Error( + "For", url, + "expected", title, + "got", err, + ) + } else if dj.queue.CurrentSong().Title() != title { + t.Error( + "For", url, + "expected", title, + "got", dj.queue.CurrentSong().Title(), + ) + } + skip(dummy1, false, false) + } + + dummy1Client.Disconnect() +} From 1b6a52b63e9197bf224f985928cf234cd1f13628 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 00:42:41 +0100 Subject: [PATCH 115/297] Added missing import for test --- test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test.go b/test.go index 47b9931..889bdd0 100644 --- a/test.go +++ b/test.go @@ -1,6 +1,9 @@ package main -import "testing" +import ( + "github.com/layeh/gumble/gumble" + "testing" +) func createClient(uname string) *gumble.Client { return gumble.NewClient(&gumble.Config{ From 7c96195dc6345fe06c888ccf8c6104c6564b4866 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 00:50:37 +0100 Subject: [PATCH 116/297] Made a hacky change to use environment variable during test --- test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test.go b/test.go index 889bdd0..403adbe 100644 --- a/test.go +++ b/test.go @@ -2,15 +2,15 @@ package main import ( "github.com/layeh/gumble/gumble" + "os" "testing" ) func createClient(uname string) *gumble.Client { return gumble.NewClient(&gumble.Config{ Username: uname, - Password: password, - Address: address + ":" + port, - Tokens: strings.Split(accesstokens, " ")}) + Password: os.Getenv("MUMBLE_PASSWORD"), + Address: os.Getenv("MUMBLE_IP") + ":" + os.Getenv("MUMBLE_PORT")}) } func TestYoutubeSong(t *testing.T) { From 51daba26f058b4a80feb613d676fbb312b94949a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 00:52:45 +0100 Subject: [PATCH 117/297] Fixing build errors --- test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test.go b/test.go index 403adbe..07e6752 100644 --- a/test.go +++ b/test.go @@ -16,7 +16,7 @@ func createClient(uname string) *gumble.Client { func TestYoutubeSong(t *testing.T) { dummy1Client := createClient("dummy") dummy1Client.Connect() - dummy1 := gumble.Find("dummy") + dummy1 := gumble.Users.Find("dummy") // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist songs := map[string]string{ From 2d80b9ecb7e03bcff48e8c45fe605b64a30dc0a2 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 00:57:08 +0100 Subject: [PATCH 118/297] Fixing build errors --- test.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test.go b/test.go index 07e6752..feb5e67 100644 --- a/test.go +++ b/test.go @@ -14,9 +14,9 @@ func createClient(uname string) *gumble.Client { } func TestYoutubeSong(t *testing.T) { - dummy1Client := createClient("dummy") - dummy1Client.Connect() - dummy1 := gumble.Users.Find("dummy") + dummyClient := createClient("dummy") + dummyClient.Connect() + dummyUser := dj.client.Find("dummy") // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist songs := map[string]string{ @@ -31,7 +31,7 @@ func TestYoutubeSong(t *testing.T) { } for url, title := range songs { - err := add(dummy1, url) + err := add(dummyUser, url) if err != nil { t.Error( "For", url, @@ -45,8 +45,8 @@ func TestYoutubeSong(t *testing.T) { "got", dj.queue.CurrentSong().Title(), ) } - skip(dummy1, false, false) + skip(dummyUser, false, false) } - dummy1Client.Disconnect() + dummyClient.Disconnect() } From a03933e3a9d3d5a3c0dc7129d2b679ed04fdc8d9 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 00:59:06 +0100 Subject: [PATCH 119/297] Fixing build errors --- test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test.go b/test.go index feb5e67..daa47ca 100644 --- a/test.go +++ b/test.go @@ -16,7 +16,7 @@ func createClient(uname string) *gumble.Client { func TestYoutubeSong(t *testing.T) { dummyClient := createClient("dummy") dummyClient.Connect() - dummyUser := dj.client.Find("dummy") + dummyUser := dj.client.Users.Find("dummy") // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist songs := map[string]string{ From 2a42e4456cde7cc5e56db2cf571f3f7e56910551 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:06:56 +0100 Subject: [PATCH 120/297] Renamed test to try and get it to work --- test.go => main_test.go | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename test.go => main_test.go (100%) diff --git a/test.go b/main_test.go similarity index 100% rename from test.go rename to main_test.go From 2bb84599ea00fb0a4872ebd45cc5cb9fa173e6cb Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:19:27 +0100 Subject: [PATCH 121/297] Given up on go test, using my own --- .travis.yml | 2 +- main.go | 10 ++++++++-- main_test.go => test.go | 20 +++++++++++--------- 3 files changed, 20 insertions(+), 12 deletions(-) rename main_test.go => test.go (84%) diff --git a/.travis.yml b/.travis.yml index c5ea4fd..a7f2baa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,4 +15,4 @@ before_install: - bash install-dependencies.sh after_success: - - go test \ No newline at end of file + - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=travis -password=$MUMBLE_PASSWORD -test=true \ No newline at end of file diff --git a/main.go b/main.go index 1dd4907..f59a93c 100644 --- a/main.go +++ b/main.go @@ -193,7 +193,7 @@ func main() { } var address, port, username, password, channel, pemCert, pemKey, accesstokens string - var insecure, verbose bool + var insecure, verbose, test bool flag.StringVar(&address, "server", "localhost", "address for Mumble server") flag.StringVar(&port, "port", "64738", "port for Mumble server") @@ -204,7 +204,8 @@ func main() { flag.StringVar(&pemKey, "key", "", "path to user PEM key for MumbleDJ") flag.StringVar(&accesstokens, "accesstokens", "", "list of access tokens for channel auth") flag.BoolVar(&insecure, "insecure", false, "skip certificate checking") - flag.BoolVar(&verbose, "verbose", false, "prints out debug messages to the console") + flag.BoolVar(&verbose, "verbose", false, "[debug] prints out debug messages to the console") + flag.BoolVar(&test, "test", false, "[debug] tests the features of mumbledj") flag.Parse() dj.config = gumble.Config{ @@ -254,4 +255,9 @@ func main() { } <-dj.keepAlive + + if test { + Test(password, address, port) + kill() + } } diff --git a/main_test.go b/test.go similarity index 84% rename from main_test.go rename to test.go index daa47ca..9641d70 100644 --- a/main_test.go +++ b/test.go @@ -2,19 +2,21 @@ package main import ( "github.com/layeh/gumble/gumble" - "os" - "testing" ) -func createClient(uname string) *gumble.Client { - return gumble.NewClient(&gumble.Config{ - Username: uname, - Password: os.Getenv("MUMBLE_PASSWORD"), - Address: os.Getenv("MUMBLE_IP") + ":" + os.Getenv("MUMBLE_PORT")}) +func Test(password, ip, port string) { + } -func TestYoutubeSong(t *testing.T) { - dummyClient := createClient("dummy") +func createClient(uname, password, ip, port string) *gumble.Client { + return gumble.NewClient(&gumble.Config{ + Username: uname, + Password: password, + Address: ip + ":" + port}) +} + +func testYoutubeSong(password, ip, port string) { + dummyClient := createClient("dummy", password, ip, port) dummyClient.Connect() dummyUser := dj.client.Users.Find("dummy") From 1d1c3e08f25f0c4ed45daa279438620f98a736d1 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:22:32 +0100 Subject: [PATCH 122/297] Fixing build errors --- test.go | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/test.go b/test.go index 9641d70..ba8067c 100644 --- a/test.go +++ b/test.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "github.com/layeh/gumble/gumble" ) @@ -35,17 +36,9 @@ func testYoutubeSong(password, ip, port string) { for url, title := range songs { err := add(dummyUser, url) if err != nil { - t.Error( - "For", url, - "expected", title, - "got", err, - ) + fmt.Printf("For: %s; Expected: %s; Got: %s", url, title, err.Error()) } else if dj.queue.CurrentSong().Title() != title { - t.Error( - "For", url, - "expected", title, - "got", dj.queue.CurrentSong().Title(), - ) + fmt.Printf("For: %s; Expected: %s; Got: %s", url, title, dj.queue.CurrentSong().Title()) } skip(dummyUser, false, false) } From bb023a468a70d73622e20a435b7d0183b4321562 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:24:48 +0100 Subject: [PATCH 123/297] Fixing build errors --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index a7f2baa..4959d26 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,6 +11,7 @@ cache: before_install: - export PATH=$PATH:~/bin/ + - export PATH=$PATH:$GOPATH/bin/ - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig - bash install-dependencies.sh From 75b0e7c9c68c5fc5abd862799c25935e905fd706 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:27:26 +0100 Subject: [PATCH 124/297] Fixing build errors --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index 4959d26..2ae6095 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,5 +15,9 @@ before_install: - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig - bash install-dependencies.sh +install: + - make + - make install + after_success: - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=travis -password=$MUMBLE_PASSWORD -test=true \ No newline at end of file From e52ed9a2d168989504c08101831189471e61147c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:33:46 +0100 Subject: [PATCH 125/297] Moved opus into bin folder --- Makefile | 2 +- install-dependencies.sh | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 23a95e1..8c48293 100644 --- a/Makefile +++ b/Makefile @@ -13,7 +13,7 @@ install: mkdir -p ~/.mumbledj/config mkdir -p ~/.mumbledj/songs mkdir -p ~/.mumbledj/web - if [ -a ~/.mumbledj/config/mumbledj.gcfg ]; then mv ~/.mumbledj/config/mumbledj.gcfg ~/.mumbledj/config/mumbledj_backup.gcfg; fi; + if [ -f ~/.mumbledj/config/mumbledj.gcfg ]; then mv ~/.mumbledj/config/mumbledj.gcfg ~/.mumbledj/config/mumbledj_backup.gcfg; fi; cp -u config.gcfg ~/.mumbledj/config/mumbledj.gcfg cp -u index.html ~/.mumbledj/web/index.html if [ -d ~/bin ]; then cp -f mumbledj* ~/bin/mumbledj; else sudo cp -f mumbledj* /usr/local/bin/mumbledj; fi; diff --git a/install-dependencies.sh b/install-dependencies.sh index 90d3db1..bdd8241 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -12,10 +12,10 @@ else fi # check to see if opus is installed -if [ ! -d "$HOME/opus/lib" ]; then +if [ ! -d "$HOME/bin/lib" ]; then wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz tar xzvf opus-1.0.3.tar.gz - cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install + cd opus-1.0.3 && ./configure --prefix=$HOME/bin && make && make install else echo 'Using cached version of opus.'; fi @@ -26,4 +26,9 @@ if [ ! -f "$HOME/bin/youtube-dl" ]; then chmod a+rx ~/bin/youtube-dl else echo 'Using cached version of youtube-dl.'; -fi \ No newline at end of file +fi + +ls -l $HOME/bin +ls -l $HOME/bin/lib +ls -l $HOME/opus +ls -l $HOME/opus/lib \ No newline at end of file From 80a4cd01b2e0118814c57204aa87dd40bcb0c7bc Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:39:58 +0100 Subject: [PATCH 126/297] Moved opus back to its original place --- .travis.yml | 7 ++++--- install-dependencies.sh | 11 +++-------- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2ae6095..2cff0da 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,9 +10,10 @@ cache: - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor before_install: - - export PATH=$PATH:~/bin/ - - export PATH=$PATH:$GOPATH/bin/ - - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig + - export PATH=$PATH:$HOME/bin/ + - export LD_RUN_PATH=$LD_RUN_PATH:$HOME/opus/lib + - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/opus/lib + - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib - bash install-dependencies.sh install: diff --git a/install-dependencies.sh b/install-dependencies.sh index bdd8241..90d3db1 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -12,10 +12,10 @@ else fi # check to see if opus is installed -if [ ! -d "$HOME/bin/lib" ]; then +if [ ! -d "$HOME/opus/lib" ]; then wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz tar xzvf opus-1.0.3.tar.gz - cd opus-1.0.3 && ./configure --prefix=$HOME/bin && make && make install + cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install else echo 'Using cached version of opus.'; fi @@ -26,9 +26,4 @@ if [ ! -f "$HOME/bin/youtube-dl" ]; then chmod a+rx ~/bin/youtube-dl else echo 'Using cached version of youtube-dl.'; -fi - -ls -l $HOME/bin -ls -l $HOME/bin/lib -ls -l $HOME/opus -ls -l $HOME/opus/lib \ No newline at end of file +fi \ No newline at end of file From 380fc75a014702fa976eee3b4f6422b634ae1074 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:45:48 +0100 Subject: [PATCH 127/297] Fixing errors that the cache was hiding --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 2cff0da..2bf3c56 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ before_install: - export PATH=$PATH:$HOME/bin/ - export LD_RUN_PATH=$LD_RUN_PATH:$HOME/opus/lib - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/opus/lib - - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib + - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig - bash install-dependencies.sh install: From e3f4e2fababaf0d697eda2a7b4747a05ebee2285 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:49:10 +0100 Subject: [PATCH 128/297] Fixing errors that the cache was hiding --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 2bf3c56..c56e0be 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ before_install: - export PATH=$PATH:$HOME/bin/ - export LD_RUN_PATH=$LD_RUN_PATH:$HOME/opus/lib - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/opus/lib - - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig + - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/include - bash install-dependencies.sh install: From 8fbdde89b9c7799a44708c480a56343afe07b5f8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:50:53 +0100 Subject: [PATCH 129/297] Fixing errors that the cache was hiding --- install-dependencies.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/install-dependencies.sh b/install-dependencies.sh index 90d3db1..6bf067a 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -26,4 +26,6 @@ if [ ! -f "$HOME/bin/youtube-dl" ]; then chmod a+rx ~/bin/youtube-dl else echo 'Using cached version of youtube-dl.'; -fi \ No newline at end of file +fi + +ls -lR $HOME/opus \ No newline at end of file From defe9f36cd63e724d3be4ee752159ae19b590dc3 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:52:58 +0100 Subject: [PATCH 130/297] Fixing errors that the cache was hiding --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index c56e0be..2bf3c56 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ before_install: - export PATH=$PATH:$HOME/bin/ - export LD_RUN_PATH=$LD_RUN_PATH:$HOME/opus/lib - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/opus/lib - - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/include + - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig - bash install-dependencies.sh install: From e114268c30988a09fd49e3592677dc7232bb6238 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 01:57:24 +0100 Subject: [PATCH 131/297] Correcting .travis.yml sections --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2bf3c56..16ee276 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,14 +9,14 @@ cache: - $HOME/gopath/src/github.com/nitrous-io - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor -before_install: +before_script: - export PATH=$PATH:$HOME/bin/ - export LD_RUN_PATH=$LD_RUN_PATH:$HOME/opus/lib - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/opus/lib - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig - bash install-dependencies.sh -install: +script: - make - make install From 4b24ac56b405808ae79d5c0b4764fca51bd7beec Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 16:00:47 +0100 Subject: [PATCH 132/297] Seporated Service APIs and youtube-dl --- service.go | 2 +- service_soundcloud.go | 71 +----------- service_youtube.go | 261 +----------------------------------------- youtube_dl.go | 94 ++++++++++++--- 4 files changed, 88 insertions(+), 340 deletions(-) diff --git a/service.go b/service.go index 13a1d08..a83ddba 100644 --- a/service.go +++ b/service.go @@ -52,7 +52,7 @@ type Playlist interface { Title() string } -var services = []Service{YouTube{}} +var services = []Service{YouTube{}, SoundCloud{}} func findServiceAndAdd(user *gumble.User, url string) error { var urlService Service diff --git a/service_soundcloud.go b/service_soundcloud.go index 0d63bc4..01def80 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -13,19 +13,9 @@ import ( var soundcloudSongPattern = `https?:\/\/(www)?\.soundcloud\.com\/([\w-]+)\/([\w-]+)` var soundcloudPlaylistPattern = `https?:\/\/(www)?\.soundcloud\.com\/([\w-]+)\/sets\/([\w-]+)` -// ------ -// TYPES -// ------ - -// YouTube implements the Service interface +// SoundCloud implements the Service interface type SoundCloud struct{} -// YouTubePlaylist holds the metadata for a YouTube playlist. -type SoundCloudPlaylist struct { - id string - title string -} - // ------------------ // SOUNDCLOUD SERVICE // ------------------ @@ -59,7 +49,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { // Create playlist title, _ := apiResponse.String("title") permalink, _ := apiResponse.String("permalink_url") - playlist := &SoundCloudPlaylist{ + playlist := &YouTubeDLPlaylist{ id: permalink, title: title, } @@ -73,6 +63,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { return "", errors.New("NO_PLAYLIST_PERMISSION") } } else { + // SONG return sc.NewSong(user.Name, apiResponse, nil) } } @@ -96,7 +87,7 @@ func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist P return "", err } - song := &YouTubeDL{ + song := &YouTubeDLSong{ id: id, title: title, thumbnail: thumbnail, @@ -107,57 +98,5 @@ func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist P dontSkip: false, } dj.queue.AddSong(song) - return title, nil -} - -// ---------------- -// YOUTUBE PLAYLIST -// ---------------- - -// AddSkip adds a skip to the playlist's skippers slice. -func (p *SoundCloudPlaylist) AddSkip(username string) error { - for _, user := range dj.playlistSkips[p.ID()] { - if username == user { - return errors.New("This user has already skipped the current song.") - } - } - dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()], username) - return nil -} - -// RemoveSkip removes a skip from the playlist's skippers slice. If username is not in the slice -// an error is returned. -func (p *SoundCloudPlaylist) RemoveSkip(username string) error { - for i, user := range dj.playlistSkips[p.ID()] { - if username == user { - dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()][:i], dj.playlistSkips[p.ID()][i+1:]...) - return nil - } - } - return errors.New("This user has not skipped the song.") -} - -// DeleteSkippers removes the skippers entry in dj.playlistSkips. -func (p *SoundCloudPlaylist) DeleteSkippers() { - delete(dj.playlistSkips, p.ID()) -} - -// SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's -// channel and the number of usernames in the skippers slice. If the value is greater than or equal -// to the skip ratio defined in the config, the function returns true, and returns false otherwise. -func (p *SoundCloudPlaylist) SkipReached(channelUsers int) bool { - if float32(len(dj.playlistSkips[p.ID()]))/float32(channelUsers) >= dj.conf.General.PlaylistSkipRatio { - return true - } - return false -} - -// ID returns the id of the YouTubePlaylist. -func (p *SoundCloudPlaylist) ID() string { - return p.id -} - -// Title returns the title of the YouTubePlaylist. -func (p *SoundCloudPlaylist) Title() string { - return p.title + return title, nil } diff --git a/service_youtube.go b/service_youtube.go index 5da5607..4e457d9 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -42,26 +42,6 @@ var youtubeVideoPatterns = []string{ // YouTube implements the Service interface type YouTube struct{} -// YouTubeSong holds the metadata for a song extracted from a YouTube video. -type YouTubeSong struct { - submitter string - title string - id string - offset int - filename string - duration string - thumbnail string - skippers []string - playlist Playlist - dontSkip bool -} - -// YouTubePlaylist holds the metadata for a YouTube playlist. -type YouTubePlaylist struct { - id string - title string -} - // --------------- // YOUTUBE SERVICE // --------------- @@ -105,7 +85,7 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { // NewSong gathers the metadata for a song extracted from a YouTube video, and returns // the song. -func (yt YouTube) NewSong(user, id, offset string, playlist *YouTubePlaylist) (*YouTubeSong, error) { +func (yt YouTube) NewSong(user, id, offset string, playlist *Playlist) (*Song, error) { var apiResponse *jsonq.JsonQuery var err error url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s", @@ -179,7 +159,7 @@ func (yt YouTube) NewSong(user, id, offset string, playlist *YouTubePlaylist) (* } if dj.conf.General.MaxSongDuration == 0 || totalSeconds <= dj.conf.General.MaxSongDuration { - song := &YouTubeSong{ + song := &YouTubeDLSong{ submitter: user, title: title, id: id, @@ -200,7 +180,7 @@ func (yt YouTube) NewSong(user, id, offset string, playlist *YouTubePlaylist) (* } // NewPlaylist gathers the metadata for a YouTube playlist and returns it. -func (yt YouTube) NewPlaylist(user, id string) (*YouTubePlaylist, error) { +func (yt YouTube) NewPlaylist(user, id string) (*Playlist, error) { var apiResponse *jsonq.JsonQuery var err error // Retrieve title of playlist @@ -211,7 +191,7 @@ func (yt YouTube) NewPlaylist(user, id string) (*YouTubePlaylist, error) { } title, _ := apiResponse.String("items", "0", "snippet", "title") - playlist := &YouTubePlaylist{ + playlist := &YouTubeDLPlaylist{ id: id, title: title, } @@ -235,239 +215,6 @@ func (yt YouTube) NewPlaylist(user, id string) (*YouTubePlaylist, error) { return playlist, nil } -// ------------ -// YOUTUBE SONG -// ------------ - -// Download downloads the song via youtube-dl if it does not already exist on disk. -// All downloaded songs are stored in ~/.mumbledj/songs and should be automatically cleaned. -func (s *YouTubeSong) Download() error { - - // Checks to see if song is already downloaded - if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, s.Filename())); os.IsNotExist(err) { - Verbose("Downloading " + s.Title()) - cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, s.Filename()), "--format", "m4a", "--", s.ID()) - if err := cmd.Run(); err == nil { - if dj.conf.Cache.Enabled { - dj.cache.CheckMaximumDirectorySize() - } - Verbose(s.Title() + " downloaded") - return nil - } - Verbose(s.Title() + " failed to download") - return errors.New("Song download failed.") - } - return nil -} - -// Play plays the song. Once the song is playing, a notification is displayed in a text message that features the video -// thumbnail, URL, title, duration, and submitter. -func (s *YouTubeSong) Play() { - if s.offset != 0 { - offsetDuration, _ := time.ParseDuration(fmt.Sprintf("%ds", s.offset)) - dj.audioStream.Offset = offsetDuration - } - dj.audioStream.Source = gumble_ffmpeg.SourceFile(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, s.Filename())) - if err := dj.audioStream.Play(); err != nil { - panic(err) - } else { - if isNil(s.Playlist()) { - message := ` - - - - - - - - - - -
%s (%s)
Added by %s
- ` - dj.client.Self.Channel.Send(fmt.Sprintf(message, s.Thumbnail(), s.ID(), s.Title(), - s.Duration(), s.Submitter()), false) - } else { - message := ` - - - - - - - - - - - - - -
%s (%s)
Added by %s
From playlist "%s"
- ` - dj.client.Self.Channel.Send(fmt.Sprintf(message, s.Thumbnail(), s.ID(), - s.Title(), s.Duration(), s.Submitter(), s.Playlist().Title()), false) - } - Verbose("Now playing " + s.Title()) - - go func() { - dj.audioStream.Wait() - dj.queue.OnSongFinished() - }() - } -} - -// Delete deletes the song from ~/.mumbledj/songs if the cache is disabled. -func (s *YouTubeSong) Delete() error { - if dj.conf.Cache.Enabled == false { - filePath := fmt.Sprintf("%s/.mumbledj/songs/%s.m4a", dj.homeDir, s.ID()) - if _, err := os.Stat(filePath); err == nil { - if err := os.Remove(filePath); err == nil { - Verbose("Deleted " + s.Title()) - return nil - } - Verbose("Failed to delete " + s.Title()) - return errors.New("Error occurred while deleting audio file.") - } - return nil - } - return nil -} - -// AddSkip adds a skip to the skippers slice. If the user is already in the slice, AddSkip -// returns an error and does not add a duplicate skip. -func (s *YouTubeSong) AddSkip(username string) error { - for _, user := range s.skippers { - if username == user { - return errors.New("This user has already skipped the current song.") - } - } - s.skippers = append(s.skippers, username) - return nil -} - -// RemoveSkip removes a skip from the skippers slice. If username is not in slice, an error is -// returned. -func (s *YouTubeSong) RemoveSkip(username string) error { - for i, user := range s.skippers { - if username == user { - s.skippers = append(s.skippers[:i], s.skippers[i+1:]...) - return nil - } - } - return errors.New("This user has not skipped the song.") -} - -// SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's -// channel and the number of usernames in the skippers slice. If the value is greater than or equal -// to the skip ratio defined in the config, the function returns true, and returns false otherwise. -func (s *YouTubeSong) SkipReached(channelUsers int) bool { - if float32(len(s.skippers))/float32(channelUsers) >= dj.conf.General.SkipRatio { - return true - } - return false -} - -// Submitter returns the name of the submitter of the YouTubeSong. -func (s *YouTubeSong) Submitter() string { - return s.submitter -} - -// Title returns the title of the YouTubeSong. -func (s *YouTubeSong) Title() string { - return s.title -} - -// ID returns the id of the YouTubeSong. -func (s *YouTubeSong) ID() string { - return s.id -} - -// Filename returns the filename of the YouTubeSong. -func (s *YouTubeSong) Filename() string { - return s.filename -} - -// Duration returns the duration of the YouTubeSong. -func (s *YouTubeSong) Duration() string { - return s.duration -} - -// Thumbnail returns the thumbnail URL for the YouTubeSong. -func (s *YouTubeSong) Thumbnail() string { - return s.thumbnail -} - -// Playlist returns the playlist type for the YouTubeSong (may be nil). -func (s *YouTubeSong) Playlist() Playlist { - return s.playlist -} - -// DontSkip returns the DontSkip boolean value for the YouTubeSong. -func (s *YouTubeSong) DontSkip() bool { - return s.dontSkip -} - -// SetDontSkip sets the DontSkip boolean value for the YouTubeSong. -func (s *YouTubeSong) SetDontSkip(value bool) { - s.dontSkip = value -} - -// ---------------- -// YOUTUBE PLAYLIST -// ---------------- - -// AddSkip adds a skip to the playlist's skippers slice. -func (p *YouTubePlaylist) AddSkip(username string) error { - for _, user := range dj.playlistSkips[p.ID()] { - if username == user { - return errors.New("This user has already skipped the current song.") - } - } - dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()], username) - return nil -} - -// RemoveSkip removes a skip from the playlist's skippers slice. If username is not in the slice -// an error is returned. -func (p *YouTubePlaylist) RemoveSkip(username string) error { - for i, user := range dj.playlistSkips[p.ID()] { - if username == user { - dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()][:i], dj.playlistSkips[p.ID()][i+1:]...) - return nil - } - } - return errors.New("This user has not skipped the song.") -} - -// DeleteSkippers removes the skippers entry in dj.playlistSkips. -func (p *YouTubePlaylist) DeleteSkippers() { - delete(dj.playlistSkips, p.ID()) -} - -// SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's -// channel and the number of usernames in the skippers slice. If the value is greater than or equal -// to the skip ratio defined in the config, the function returns true, and returns false otherwise. -func (p *YouTubePlaylist) SkipReached(channelUsers int) bool { - if float32(len(dj.playlistSkips[p.ID()]))/float32(channelUsers) >= dj.conf.General.PlaylistSkipRatio { - return true - } - return false -} - -// ID returns the id of the YouTubePlaylist. -func (p *YouTubePlaylist) ID() string { - return p.id -} - -// Title returns the title of the YouTubePlaylist. -func (p *YouTubePlaylist) Title() string { - return p.title -} - -// ----------- -// YOUTUBE API -// ----------- - // PerformGetRequest does all the grunt work for a YouTube HTTPS GET request. func PerformGetRequest(url string) (*jsonq.JsonQuery, error) { jsonString := "" diff --git a/youtube_dl.go b/youtube_dl.go index 5e713cb..b7afff2 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -10,7 +10,8 @@ import ( "github.com/layeh/gumble/gumble_ffmpeg" ) -type YouTubeDL struct { +// Extends a Song +type YouTubeDLSong struct { id string title string thumbnail string @@ -23,9 +24,18 @@ type YouTubeDL struct { dontSkip bool } +type YouTubeDLPlaylist struct { + id string + title string +} + +// ------------- +// YouTubeDLSong +// ------------- + // Download downloads the song via youtube-dl if it does not already exist on disk. // All downloaded songs are stored in ~/.mumbledj/songs and should be automatically cleaned. -func (dl *YouTubeDL) Download() error { +func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.id+".m4a")); os.IsNotExist(err) { @@ -43,7 +53,7 @@ func (dl *YouTubeDL) Download() error { // Play plays the song. Once the song is playing, a notification is displayed in a text message that features the song // thumbnail, URL, title, duration, and submitter. -func (dl *YouTubeDL) Play() { +func (dl *YouTubeDLSong) Play() { if dl.offset != 0 { offsetDuration, _ := time.ParseDuration(fmt.Sprintf("%ds", dl.offset)) dj.audioStream.Offset = offsetDuration @@ -70,7 +80,7 @@ func (dl *YouTubeDL) Play() { } // Delete deletes the song from ~/.mumbledj/songs if the cache is disabled. -func (dl *YouTubeDL) Delete() error { +func (dl *YouTubeDLSong) Delete() error { if dj.conf.Cache.Enabled == false { filePath := fmt.Sprintf("%s/.mumbledj/songs/%s.m4a", dj.homeDir, dl.id) if _, err := os.Stat(filePath); err == nil { @@ -86,7 +96,7 @@ func (dl *YouTubeDL) Delete() error { // AddSkip adds a skip to the skippers slice. If the user is already in the slice, AddSkip // returns an error and does not add a duplicate skip. -func (dl *YouTubeDL) AddSkip(username string) error { +func (dl *YouTubeDLSong) AddSkip(username string) error { for _, user := range dl.skippers { if username == user { return errors.New("This user has already skipped the current song.") @@ -98,7 +108,7 @@ func (dl *YouTubeDL) AddSkip(username string) error { // RemoveSkip removes a skip from the skippers slice. If username is not in slice, an error is // returned. -func (dl *YouTubeDL) RemoveSkip(username string) error { +func (dl *YouTubeDLSong) RemoveSkip(username string) error { for i, user := range dl.skippers { if username == user { dl.skippers = append(dl.skippers[:i], dl.skippers[i+1:]...) @@ -111,7 +121,7 @@ func (dl *YouTubeDL) RemoveSkip(username string) error { // SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's // channel and the number of usernames in the skippers slice. If the value is greater than or equal // to the skip ratio defined in the config, the function returns true, and returns false otherwise. -func (dl *YouTubeDL) SkipReached(channelUsers int) bool { +func (dl *YouTubeDLSong) SkipReached(channelUsers int) bool { if float32(len(dl.skippers))/float32(channelUsers) >= dj.conf.General.SkipRatio { return true } @@ -119,46 +129,98 @@ func (dl *YouTubeDL) SkipReached(channelUsers int) bool { } // Submitter returns the name of the submitter of the Song. -func (dl *YouTubeDL) Submitter() string { +func (dl *YouTubeDLSong) Submitter() string { return dl.submitter } // Title returns the title of the Song. -func (dl *YouTubeDL) Title() string { +func (dl *YouTubeDLSong) Title() string { return dl.title } // ID returns the id of the Song. -func (dl *YouTubeDL) ID() string { +func (dl *YouTubeDLSong) ID() string { return dl.id } // Filename returns the filename of the Song. -func (dl *YouTubeDL) Filename() string { +func (dl *YouTubeDLSong) Filename() string { return dl.id + ".m4a" } // Duration returns the duration of the Song. -func (dl *YouTubeDL) Duration() string { +func (dl *YouTubeDLSong) Duration() string { return dl.duration } // Thumbnail returns the thumbnail URL for the Song. -func (dl *YouTubeDL) Thumbnail() string { +func (dl *YouTubeDLSong) Thumbnail() string { return dl.thumbnail } // Playlist returns the playlist type for the Song (may be nil). -func (dl *YouTubeDL) Playlist() Playlist { +func (dl *YouTubeDLSong) Playlist() Playlist { return dl.playlist } // DontSkip returns the DontSkip boolean value for the Song. -func (dl *YouTubeDL) DontSkip() bool { +func (dl *YouTubeDLSong) DontSkip() bool { return dl.dontSkip } // SetDontSkip sets the DontSkip boolean value for the Song. -func (dl *YouTubeDL) SetDontSkip(value bool) { +func (dl *YouTubeDLSong) SetDontSkip(value bool) { dl.dontSkip = value } + +// ---------------- +// YOUTUBE PLAYLIST +// ---------------- + +// AddSkip adds a skip to the playlist's skippers slice. +func (p *YouTubeDLPlaylist) AddSkip(username string) error { + for _, user := range dj.playlistSkips[p.ID()] { + if username == user { + return errors.New("This user has already skipped the current song.") + } + } + dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()], username) + return nil +} + +// RemoveSkip removes a skip from the playlist's skippers slice. If username is not in the slice +// an error is returned. +func (p *YouTubeDLPlaylist) RemoveSkip(username string) error { + for i, user := range dj.playlistSkips[p.ID()] { + if username == user { + dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()][:i], dj.playlistSkips[p.ID()][i+1:]...) + return nil + } + } + return errors.New("This user has not skipped the song.") +} + +// DeleteSkippers removes the skippers entry in dj.playlistSkips. +func (p *YouTubeDLPlaylist) DeleteSkippers() { + delete(dj.playlistSkips, p.ID()) +} + +// SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's +// channel and the number of usernames in the skippers slice. If the value is greater than or equal +// to the skip ratio defined in the config, the function returns true, and returns false otherwise. +func (p *YouTubeDLPlaylist) SkipReached(channelUsers int) bool { + if float32(len(dj.playlistSkips[p.ID()]))/float32(channelUsers) >= dj.conf.General.PlaylistSkipRatio { + return true + } + return false +} + +// ID returns the id of the YouTubeDLPlaylist. +func (p *YouTubeDLPlaylist) ID() string { + return p.id +} + +// Title returns the title of the YouTubeDLPlaylist. +func (p *YouTubeDLPlaylist) Title() string { + return p.title +} From c85b04cd45122b47e77f26b4a0fc65e08852c7bb Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 16:04:31 +0100 Subject: [PATCH 133/297] Fixing build errors --- service_youtube.go | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/service_youtube.go b/service_youtube.go index 4e457d9..aa8561c 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -14,15 +14,12 @@ import ( "io/ioutil" "net/http" "os" - "os/exec" "regexp" "strconv" "strings" - "time" "github.com/jmoiron/jsonq" "github.com/layeh/gumble/gumble" - "github.com/layeh/gumble/gumble_ffmpeg" ) // Regular expressions for youtube urls @@ -85,7 +82,7 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { // NewSong gathers the metadata for a song extracted from a YouTube video, and returns // the song. -func (yt YouTube) NewSong(user, id, offset string, playlist *Playlist) (*Song, error) { +func (yt YouTube) NewSong(user, id, offset string, playlist Playlist) (Song, error) { var apiResponse *jsonq.JsonQuery var err error url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s", @@ -180,7 +177,7 @@ func (yt YouTube) NewSong(user, id, offset string, playlist *Playlist) (*Song, e } // NewPlaylist gathers the metadata for a YouTube playlist and returns it. -func (yt YouTube) NewPlaylist(user, id string) (*Playlist, error) { +func (yt YouTube) NewPlaylist(user, id string) (Playlist, error) { var apiResponse *jsonq.JsonQuery var err error // Retrieve title of playlist From 9c6c65a03688ec16c73c6e559138fd9962434828 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 16:06:20 +0100 Subject: [PATCH 134/297] Fixing build errors --- service_youtube.go | 1 - 1 file changed, 1 deletion(-) diff --git a/service_youtube.go b/service_youtube.go index aa8561c..a8c2b44 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -161,7 +161,6 @@ func (yt YouTube) NewSong(user, id, offset string, playlist Playlist) (Song, err title: title, id: id, offset: int((offsetDays * 86400) + (offsetHours * 3600) + (offsetMinutes * 60) + offsetSeconds), - filename: id + ".m4a", duration: durationString, thumbnail: thumbnail, skippers: make([]string, 0), From f77045f80ba6fa79cdb951e3966695105fd2ed6f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 18:42:12 +0100 Subject: [PATCH 135/297] Using godeps for Heroku --- Godeps/Godeps.json | 34 + Godeps/Readme | 5 + Godeps/_workspace/.gitignore | 2 + .../src/code.google.com/p/gcfg/LICENSE | 57 + .../src/code.google.com/p/gcfg/README | 7 + .../src/code.google.com/p/gcfg/doc.go | 118 + .../code.google.com/p/gcfg/example_test.go | 132 + .../src/code.google.com/p/gcfg/go1_0.go | 7 + .../src/code.google.com/p/gcfg/go1_2.go | 9 + .../src/code.google.com/p/gcfg/issues_test.go | 63 + .../src/code.google.com/p/gcfg/read.go | 181 ++ .../src/code.google.com/p/gcfg/read_test.go | 333 ++ .../code.google.com/p/gcfg/scanner/errors.go | 121 + .../p/gcfg/scanner/example_test.go | 46 + .../code.google.com/p/gcfg/scanner/scanner.go | 342 ++ .../p/gcfg/scanner/scanner_test.go | 417 +++ .../src/code.google.com/p/gcfg/set.go | 281 ++ .../p/gcfg/testdata/gcfg_test.gcfg | 3 + .../p/gcfg/testdata/gcfg_unicode_test.gcfg | 3 + .../code.google.com/p/gcfg/token/position.go | 435 +++ .../p/gcfg/token/position_test.go | 181 ++ .../code.google.com/p/gcfg/token/serialize.go | 56 + .../p/gcfg/token/serialize_test.go | 111 + .../src/code.google.com/p/gcfg/token/token.go | 83 + .../src/code.google.com/p/gcfg/types/bool.go | 23 + .../src/code.google.com/p/gcfg/types/doc.go | 4 + .../src/code.google.com/p/gcfg/types/enum.go | 44 + .../code.google.com/p/gcfg/types/enum_test.go | 29 + .../src/code.google.com/p/gcfg/types/int.go | 86 + .../code.google.com/p/gcfg/types/int_test.go | 67 + .../src/code.google.com/p/gcfg/types/scan.go | 23 + .../code.google.com/p/gcfg/types/scan_test.go | 36 + .../github.com/golang/protobuf/proto/Makefile | 43 + .../golang/protobuf/proto/all_test.go | 2083 +++++++++++++ .../github.com/golang/protobuf/proto/clone.go | 212 ++ .../golang/protobuf/proto/clone_test.go | 245 ++ .../golang/protobuf/proto/decode.go | 827 +++++ .../golang/protobuf/proto/encode.go | 1293 ++++++++ .../github.com/golang/protobuf/proto/equal.go | 256 ++ .../golang/protobuf/proto/equal_test.go | 191 ++ .../golang/protobuf/proto/extensions.go | 400 +++ .../golang/protobuf/proto/extensions_test.go | 292 ++ .../github.com/golang/protobuf/proto/lib.go | 813 +++++ .../golang/protobuf/proto/message_set.go | 287 ++ .../golang/protobuf/proto/message_set_test.go | 66 + .../golang/protobuf/proto/pointer_reflect.go | 479 +++ .../golang/protobuf/proto/pointer_unsafe.go | 266 ++ .../golang/protobuf/proto/properties.go | 742 +++++ .../protobuf/proto/proto3_proto/proto3.pb.go | 122 + .../protobuf/proto/proto3_proto/proto3.proto | 68 + .../golang/protobuf/proto/proto3_test.go | 125 + .../golang/protobuf/proto/size2_test.go | 63 + .../golang/protobuf/proto/size_test.go | 142 + .../golang/protobuf/proto/testdata/Makefile | 50 + .../protobuf/proto/testdata/golden_test.go | 86 + .../golang/protobuf/proto/testdata/test.pb.go | 2746 +++++++++++++++++ .../golang/protobuf/proto/testdata/test.proto | 480 +++ .../github.com/golang/protobuf/proto/text.go | 769 +++++ .../golang/protobuf/proto/text_parser.go | 772 +++++ .../golang/protobuf/proto/text_parser_test.go | 511 +++ .../golang/protobuf/proto/text_test.go | 441 +++ .../src/github.com/jmoiron/jsonq/.gitignore | 1 + .../src/github.com/jmoiron/jsonq/LICENSE | 23 + .../src/github.com/jmoiron/jsonq/README.md | 83 + .../src/github.com/jmoiron/jsonq/autotest.sh | 13 + .../src/github.com/jmoiron/jsonq/doc.go | 68 + .../src/github.com/jmoiron/jsonq/jsonq.go | 311 ++ .../github.com/jmoiron/jsonq/jsonq_test.go | 186 ++ .../src/github.com/layeh/gopus/LICENSE | 19 + .../src/github.com/layeh/gopus/README.md | 20 + .../src/github.com/layeh/gopus/decoder.go | 71 + .../src/github.com/layeh/gopus/encoder.go | 119 + .../src/github.com/layeh/gopus/gopus.go | 53 + .../layeh/gumble/gumble/MumbleProto/LICENSE | 37 + .../gumble/gumble/MumbleProto/Mumble.pb.go | 2092 +++++++++++++ .../gumble/gumble/MumbleProto/Mumble.proto | 544 ++++ .../gumble/gumble/MumbleProto/generate.go | 2 + .../src/github.com/layeh/gumble/gumble/acl.go | 58 + .../github.com/layeh/gumble/gumble/audio.go | 85 + .../layeh/gumble/gumble/audiomultiplexer.go | 47 + .../github.com/layeh/gumble/gumble/bans.go | 102 + .../github.com/layeh/gumble/gumble/channel.go | 147 + .../layeh/gumble/gumble/channels.go | 32 + .../github.com/layeh/gumble/gumble/client.go | 230 ++ .../github.com/layeh/gumble/gumble/config.go | 72 + .../github.com/layeh/gumble/gumble/conn.go | 197 ++ .../layeh/gumble/gumble/contextaction.go | 57 + .../layeh/gumble/gumble/contextactions.go | 12 + .../src/github.com/layeh/gumble/gumble/doc.go | 39 + .../github.com/layeh/gumble/gumble/event.go | 202 ++ .../layeh/gumble/gumble/eventmultiplexer.go | 106 + .../layeh/gumble/gumble/handlers.go | 962 ++++++ .../github.com/layeh/gumble/gumble/message.go | 8 + .../layeh/gumble/gumble/permission.go | 27 + .../github.com/layeh/gumble/gumble/ping.go | 73 + .../layeh/gumble/gumble/pingstats.go | 5 + .../layeh/gumble/gumble/protomessage.go | 16 + .../github.com/layeh/gumble/gumble/request.go | 18 + .../layeh/gumble/gumble/textmessage.go | 50 + .../github.com/layeh/gumble/gumble/user.go | 231 ++ .../layeh/gumble/gumble/userlist.go | 69 + .../github.com/layeh/gumble/gumble/users.go | 30 + .../layeh/gumble/gumble/userstats.go | 34 + .../layeh/gumble/gumble/varint/read.go | 48 + .../layeh/gumble/gumble/varint/varint.go | 9 + .../layeh/gumble/gumble/varint/write.go | 51 + .../github.com/layeh/gumble/gumble/version.go | 24 + .../layeh/gumble/gumble/voicetarget.go | 81 + .../gumble/gumble_ffmpeg/gumble_ffmpeg.go | 134 + .../layeh/gumble/gumble_ffmpeg/source.go | 55 + .../layeh/gumble/gumbleutil/bitrate.go | 25 + .../gumble/gumbleutil/certificatelock.go | 75 + .../github.com/layeh/gumble/gumbleutil/doc.go | 2 + .../layeh/gumble/gumbleutil/listener.go | 90 + .../layeh/gumble/gumbleutil/listenerfunc.go | 73 + .../layeh/gumble/gumbleutil/main.go | 67 + .../layeh/gumble/gumbleutil/path.go | 18 + .../layeh/gumble/gumbleutil/textmessage.go | 45 + 118 files changed, 25557 insertions(+) create mode 100644 Godeps/Godeps.json create mode 100644 Godeps/Readme create mode 100644 Godeps/_workspace/.gitignore create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/LICENSE create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/README create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/doc.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/example_test.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/go1_0.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/go1_2.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/issues_test.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/read.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/read_test.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/scanner/errors.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/scanner/example_test.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner_test.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/set.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_test.gcfg create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_unicode_test.gcfg create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/token/position.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/token/position_test.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize_test.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/token/token.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/bool.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/doc.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/enum.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/enum_test.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/int.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/int_test.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/scan.go create mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/scan_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go create mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go create mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/.gitignore create mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/LICENSE create mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/README.md create mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/autotest.sh create mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/doc.go create mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq.go create mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq_test.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gopus/LICENSE create mode 100644 Godeps/_workspace/src/github.com/layeh/gopus/README.md create mode 100644 Godeps/_workspace/src/github.com/layeh/gopus/decoder.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gopus/encoder.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gopus/gopus.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/LICENSE create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.pb.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.proto create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/generate.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/acl.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/audio.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/audiomultiplexer.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/bans.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/channel.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/channels.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/client.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/config.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/conn.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextaction.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextactions.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/doc.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/event.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/eventmultiplexer.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/handlers.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/message.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/permission.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/ping.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/pingstats.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/protomessage.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/request.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/textmessage.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/user.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/userlist.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/users.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/userstats.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/read.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/varint.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/write.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/version.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/voicetarget.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/gumble_ffmpeg.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/source.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/bitrate.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/certificatelock.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/doc.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listener.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listenerfunc.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/main.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/path.go create mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/textmessage.go diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json new file mode 100644 index 0000000..b5049e8 --- /dev/null +++ b/Godeps/Godeps.json @@ -0,0 +1,34 @@ +{ + "ImportPath": "github.com/MichaelOultram/mumbledj", + "GoVersion": "go1.4.2", + "Deps": [ + { + "ImportPath": "code.google.com/p/gcfg", + "Rev": "c2d3050044d05357eaf6c3547249ba57c5e235cb" + }, + { + "ImportPath": "github.com/golang/protobuf/proto", + "Rev": "0f7a9caded1fb3c9cc5a9b4bcf2ff633cc8ae644" + }, + { + "ImportPath": "github.com/jmoiron/jsonq", + "Rev": "7c27c8eb9f6831555a4209f6a7d579159e766a3c" + }, + { + "ImportPath": "github.com/layeh/gopus", + "Rev": "2f86fa22bc209cc0ccbc6418dfbad9199e3dbc78" + }, + { + "ImportPath": "github.com/layeh/gumble/gumble", + "Rev": "c9fcce8fc4b71c7c53a5d3d9d48a1e001ad19a19" + }, + { + "ImportPath": "github.com/layeh/gumble/gumble_ffmpeg", + "Rev": "c9fcce8fc4b71c7c53a5d3d9d48a1e001ad19a19" + }, + { + "ImportPath": "github.com/layeh/gumble/gumbleutil", + "Rev": "c9fcce8fc4b71c7c53a5d3d9d48a1e001ad19a19" + } + ] +} diff --git a/Godeps/Readme b/Godeps/Readme new file mode 100644 index 0000000..4cdaa53 --- /dev/null +++ b/Godeps/Readme @@ -0,0 +1,5 @@ +This directory tree is generated automatically by godep. + +Please do not edit. + +See https://github.com/tools/godep for more information. diff --git a/Godeps/_workspace/.gitignore b/Godeps/_workspace/.gitignore new file mode 100644 index 0000000..f037d68 --- /dev/null +++ b/Godeps/_workspace/.gitignore @@ -0,0 +1,2 @@ +/pkg +/bin diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/LICENSE b/Godeps/_workspace/src/code.google.com/p/gcfg/LICENSE new file mode 100644 index 0000000..b0a9e76 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/LICENSE @@ -0,0 +1,57 @@ +Copyright (c) 2012 Péter Surányi. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +---------------------------------------------------------------------- +Portions of gcfg's source code have been derived from Go, and are +covered by the following license: +---------------------------------------------------------------------- + +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/README b/Godeps/_workspace/src/code.google.com/p/gcfg/README new file mode 100644 index 0000000..8f621c3 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/README @@ -0,0 +1,7 @@ +Gcfg reads INI-style configuration files into Go structs; +supports user-defined types and subsections. + +Project page: https://code.google.com/p/gcfg +Package docs: http://godoc.org/code.google.com/p/gcfg + +My other projects: https://speter.net diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/doc.go b/Godeps/_workspace/src/code.google.com/p/gcfg/doc.go new file mode 100644 index 0000000..99687b4 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/doc.go @@ -0,0 +1,118 @@ +// Package gcfg reads "INI-style" text-based configuration files with +// "name=value" pairs grouped into sections (gcfg files). +// +// This package is still a work in progress; see the sections below for planned +// changes. +// +// Syntax +// +// The syntax is based on that used by git config: +// http://git-scm.com/docs/git-config#_syntax . +// There are some (planned) differences compared to the git config format: +// - improve data portability: +// - must be encoded in UTF-8 (for now) and must not contain the 0 byte +// - include and "path" type is not supported +// (path type may be implementable as a user-defined type) +// - internationalization +// - section and variable names can contain unicode letters, unicode digits +// (as defined in http://golang.org/ref/spec#Characters ) and hyphens +// (U+002D), starting with a unicode letter +// - disallow potentially ambiguous or misleading definitions: +// - `[sec.sub]` format is not allowed (deprecated in gitconfig) +// - `[sec ""]` is not allowed +// - use `[sec]` for section name "sec" and empty subsection name +// - (planned) within a single file, definitions must be contiguous for each: +// - section: '[secA]' -> '[secB]' -> '[secA]' is an error +// - subsection: '[sec "A"]' -> '[sec "B"]' -> '[sec "A"]' is an error +// - multivalued variable: 'multi=a' -> 'other=x' -> 'multi=b' is an error +// +// Data structure +// +// The functions in this package read values into a user-defined struct. +// Each section corresponds to a struct field in the config struct, and each +// variable in a section corresponds to a data field in the section struct. +// The mapping of each section or variable name to fields is done either based +// on the "gcfg" struct tag or by matching the name of the section or variable, +// ignoring case. In the latter case, hyphens '-' in section and variable names +// correspond to underscores '_' in field names. +// Fields must be exported; to use a section or variable name starting with a +// letter that is neither upper- or lower-case, prefix the field name with 'X'. +// (See https://code.google.com/p/go/issues/detail?id=5763#c4 .) +// +// For sections with subsections, the corresponding field in config must be a +// map, rather than a struct, with string keys and pointer-to-struct values. +// Values for subsection variables are stored in the map with the subsection +// name used as the map key. +// (Note that unlike section and variable names, subsection names are case +// sensitive.) +// When using a map, and there is a section with the same section name but +// without a subsection name, its values are stored with the empty string used +// as the key. +// +// The functions in this package panic if config is not a pointer to a struct, +// or when a field is not of a suitable type (either a struct or a map with +// string keys and pointer-to-struct values). +// +// Parsing of values +// +// The section structs in the config struct may contain single-valued or +// multi-valued variables. Variables of unnamed slice type (that is, a type +// starting with `[]`) are treated as multi-value; all others (including named +// slice types) are treated as single-valued variables. +// +// Single-valued variables are handled based on the type as follows. +// Unnamed pointer types (that is, types starting with `*`) are dereferenced, +// and if necessary, a new instance is allocated. +// +// For types implementing the encoding.TextUnmarshaler interface, the +// UnmarshalText method is used to set the value. Implementing this method is +// the recommended way for parsing user-defined types. +// +// For fields of string kind, the value string is assigned to the field, after +// unquoting and unescaping as needed. +// For fields of bool kind, the field is set to true if the value is "true", +// "yes", "on" or "1", and set to false if the value is "false", "no", "off" or +// "0", ignoring case. In addition, single-valued bool fields can be specified +// with a "blank" value (variable name without equals sign and value); in such +// case the value is set to true. +// +// Predefined integer types [u]int(|8|16|32|64) and big.Int are parsed as +// decimal or hexadecimal (if having '0x' prefix). (This is to prevent +// unintuitively handling zero-padded numbers as octal.) Other types having +// [u]int* as the underlying type, such as os.FileMode and uintptr allow +// decimal, hexadecimal, or octal values. +// Parsing mode for integer types can be overridden using the struct tag option +// ",int=mode" where mode is a combination of the 'd', 'h', and 'o' characters +// (each standing for decimal, hexadecimal, and octal, respectively.) +// +// All other types are parsed using fmt.Sscanf with the "%v" verb. +// +// For multi-valued variables, each individual value is parsed as above and +// appended to the slice. If the first value is specified as a "blank" value +// (variable name without equals sign and value), a new slice is allocated; +// that is any values previously set in the slice will be ignored. +// +// The types subpackage for provides helpers for parsing "enum-like" and integer +// types. +// +// TODO +// +// The following is a list of changes under consideration: +// - documentation +// - self-contained syntax documentation +// - more practical examples +// - move TODOs to issue tracker (eventually) +// - syntax +// - reconsider valid escape sequences +// (gitconfig doesn't support \r in value, \t in subsection name, etc.) +// - reading / parsing gcfg files +// - define internal representation structure +// - support multiple inputs (readers, strings, files) +// - support declaring encoding (?) +// - support varying fields sets for subsections (?) +// - writing gcfg files +// - error handling +// - make error context accessible programmatically? +// - limit input size? +// +package gcfg diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/example_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/example_test.go new file mode 100644 index 0000000..884f3fb --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/example_test.go @@ -0,0 +1,132 @@ +package gcfg_test + +import ( + "fmt" + "log" +) + +import "code.google.com/p/gcfg" + +func ExampleReadStringInto() { + cfgStr := `; Comment line +[section] +name=value # comment` + cfg := struct { + Section struct { + Name string + } + }{} + err := gcfg.ReadStringInto(&cfg, cfgStr) + if err != nil { + log.Fatalf("Failed to parse gcfg data: %s", err) + } + fmt.Println(cfg.Section.Name) + // Output: value +} + +func ExampleReadStringInto_bool() { + cfgStr := `; Comment line +[section] +switch=on` + cfg := struct { + Section struct { + Switch bool + } + }{} + err := gcfg.ReadStringInto(&cfg, cfgStr) + if err != nil { + log.Fatalf("Failed to parse gcfg data: %s", err) + } + fmt.Println(cfg.Section.Switch) + // Output: true +} + +func ExampleReadStringInto_hyphens() { + cfgStr := `; Comment line +[section-name] +variable-name=value # comment` + cfg := struct { + Section_Name struct { + Variable_Name string + } + }{} + err := gcfg.ReadStringInto(&cfg, cfgStr) + if err != nil { + log.Fatalf("Failed to parse gcfg data: %s", err) + } + fmt.Println(cfg.Section_Name.Variable_Name) + // Output: value +} + +func ExampleReadStringInto_tags() { + cfgStr := `; Comment line +[section] +var-name=value # comment` + cfg := struct { + Section struct { + FieldName string `gcfg:"var-name"` + } + }{} + err := gcfg.ReadStringInto(&cfg, cfgStr) + if err != nil { + log.Fatalf("Failed to parse gcfg data: %s", err) + } + fmt.Println(cfg.Section.FieldName) + // Output: value +} + +func ExampleReadStringInto_subsections() { + cfgStr := `; Comment line +[profile "A"] +color = white + +[profile "B"] +color = black +` + cfg := struct { + Profile map[string]*struct { + Color string + } + }{} + err := gcfg.ReadStringInto(&cfg, cfgStr) + if err != nil { + log.Fatalf("Failed to parse gcfg data: %s", err) + } + fmt.Printf("%s %s\n", cfg.Profile["A"].Color, cfg.Profile["B"].Color) + // Output: white black +} + +func ExampleReadStringInto_multivalue() { + cfgStr := `; Comment line +[section] +multi=value1 +multi=value2` + cfg := struct { + Section struct { + Multi []string + } + }{} + err := gcfg.ReadStringInto(&cfg, cfgStr) + if err != nil { + log.Fatalf("Failed to parse gcfg data: %s", err) + } + fmt.Println(cfg.Section.Multi) + // Output: [value1 value2] +} + +func ExampleReadStringInto_unicode() { + cfgStr := `; Comment line +[甲] +乙=丙 # comment` + cfg := struct { + X甲 struct { + X乙 string + } + }{} + err := gcfg.ReadStringInto(&cfg, cfgStr) + if err != nil { + log.Fatalf("Failed to parse gcfg data: %s", err) + } + fmt.Println(cfg.X甲.X乙) + // Output: 丙 +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/go1_0.go b/Godeps/_workspace/src/code.google.com/p/gcfg/go1_0.go new file mode 100644 index 0000000..6670210 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/go1_0.go @@ -0,0 +1,7 @@ +// +build !go1.2 + +package gcfg + +type textUnmarshaler interface { + UnmarshalText(text []byte) error +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/go1_2.go b/Godeps/_workspace/src/code.google.com/p/gcfg/go1_2.go new file mode 100644 index 0000000..6f5843b --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/go1_2.go @@ -0,0 +1,9 @@ +// +build go1.2 + +package gcfg + +import ( + "encoding" +) + +type textUnmarshaler encoding.TextUnmarshaler diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/issues_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/issues_test.go new file mode 100644 index 0000000..796dd10 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/issues_test.go @@ -0,0 +1,63 @@ +package gcfg + +import ( + "fmt" + "math/big" + "strings" + "testing" +) + +type Config1 struct { + Section struct { + Int int + BigInt big.Int + } +} + +var testsIssue1 = []struct { + cfg string + typename string +}{ + {"[section]\nint=X", "int"}, + {"[section]\nint=", "int"}, + {"[section]\nint=1A", "int"}, + {"[section]\nbigint=X", "big.Int"}, + {"[section]\nbigint=", "big.Int"}, + {"[section]\nbigint=1A", "big.Int"}, +} + +// Value parse error should: +// - include plain type name +// - not include reflect internals +func TestIssue1(t *testing.T) { + for i, tt := range testsIssue1 { + var c Config1 + err := ReadStringInto(&c, tt.cfg) + switch { + case err == nil: + t.Errorf("%d fail: got ok; wanted error", i) + case !strings.Contains(err.Error(), tt.typename): + t.Errorf("%d fail: error message doesn't contain type name %q: %v", + i, tt.typename, err) + case strings.Contains(err.Error(), "reflect"): + t.Errorf("%d fail: error message includes reflect internals: %v", + i, err) + default: + t.Logf("%d pass: %v", i, err) + } + } +} + +type confIssue2 struct{ Main struct{ Foo string } } + +var testsIssue2 = []readtest{ + {"[main]\n;\nfoo = bar\n", &confIssue2{struct{ Foo string }{"bar"}}, true}, + {"[main]\r\n;\r\nfoo = bar\r\n", &confIssue2{struct{ Foo string }{"bar"}}, true}, +} + +func TestIssue2(t *testing.T) { + for i, tt := range testsIssue2 { + id := fmt.Sprintf("issue2:%d", i) + testRead(t, id, tt) + } +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/read.go b/Godeps/_workspace/src/code.google.com/p/gcfg/read.go new file mode 100644 index 0000000..4719c2b --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/read.go @@ -0,0 +1,181 @@ +package gcfg + +import ( + "fmt" + "io" + "io/ioutil" + "os" + "strings" +) + +import ( + "code.google.com/p/gcfg/scanner" + "code.google.com/p/gcfg/token" +) + +var unescape = map[rune]rune{'\\': '\\', '"': '"', 'n': '\n', 't': '\t'} + +// no error: invalid literals should be caught by scanner +func unquote(s string) string { + u, q, esc := make([]rune, 0, len(s)), false, false + for _, c := range s { + if esc { + uc, ok := unescape[c] + switch { + case ok: + u = append(u, uc) + fallthrough + case !q && c == '\n': + esc = false + continue + } + panic("invalid escape sequence") + } + switch c { + case '"': + q = !q + case '\\': + esc = true + default: + u = append(u, c) + } + } + if q { + panic("missing end quote") + } + if esc { + panic("invalid escape sequence") + } + return string(u) +} + +func readInto(config interface{}, fset *token.FileSet, file *token.File, src []byte) error { + var s scanner.Scanner + var errs scanner.ErrorList + s.Init(file, src, func(p token.Position, m string) { errs.Add(p, m) }, 0) + sect, sectsub := "", "" + pos, tok, lit := s.Scan() + errfn := func(msg string) error { + return fmt.Errorf("%s: %s", fset.Position(pos), msg) + } + for { + if errs.Len() > 0 { + return errs.Err() + } + switch tok { + case token.EOF: + return nil + case token.EOL, token.COMMENT: + pos, tok, lit = s.Scan() + case token.LBRACK: + pos, tok, lit = s.Scan() + if errs.Len() > 0 { + return errs.Err() + } + if tok != token.IDENT { + return errfn("expected section name") + } + sect, sectsub = lit, "" + pos, tok, lit = s.Scan() + if errs.Len() > 0 { + return errs.Err() + } + if tok == token.STRING { + sectsub = unquote(lit) + if sectsub == "" { + return errfn("empty subsection name") + } + pos, tok, lit = s.Scan() + if errs.Len() > 0 { + return errs.Err() + } + } + if tok != token.RBRACK { + if sectsub == "" { + return errfn("expected subsection name or right bracket") + } + return errfn("expected right bracket") + } + pos, tok, lit = s.Scan() + if tok != token.EOL && tok != token.EOF && tok != token.COMMENT { + return errfn("expected EOL, EOF, or comment") + } + case token.IDENT: + if sect == "" { + return errfn("expected section header") + } + n := lit + pos, tok, lit = s.Scan() + if errs.Len() > 0 { + return errs.Err() + } + blank, v := tok == token.EOF || tok == token.EOL || tok == token.COMMENT, "" + if !blank { + if tok != token.ASSIGN { + return errfn("expected '='") + } + pos, tok, lit = s.Scan() + if errs.Len() > 0 { + return errs.Err() + } + if tok != token.STRING { + return errfn("expected value") + } + v = unquote(lit) + pos, tok, lit = s.Scan() + if errs.Len() > 0 { + return errs.Err() + } + if tok != token.EOL && tok != token.EOF && tok != token.COMMENT { + return errfn("expected EOL, EOF, or comment") + } + } + err := set(config, sect, sectsub, n, blank, v) + if err != nil { + return err + } + default: + if sect == "" { + return errfn("expected section header") + } + return errfn("expected section header or variable declaration") + } + } + panic("never reached") +} + +// ReadInto reads gcfg formatted data from reader and sets the values into the +// corresponding fields in config. +func ReadInto(config interface{}, reader io.Reader) error { + src, err := ioutil.ReadAll(reader) + if err != nil { + return err + } + fset := token.NewFileSet() + file := fset.AddFile("", fset.Base(), len(src)) + return readInto(config, fset, file, src) +} + +// ReadStringInto reads gcfg formatted data from str and sets the values into +// the corresponding fields in config. +func ReadStringInto(config interface{}, str string) error { + r := strings.NewReader(str) + return ReadInto(config, r) +} + +// ReadFileInto reads gcfg formatted data from the file filename and sets the +// values into the corresponding fields in config. +func ReadFileInto(config interface{}, filename string) error { + f, err := os.Open(filename) + if err != nil { + return err + } + defer f.Close() + src, err := ioutil.ReadAll(f) + if err != nil { + return err + } + fset := token.NewFileSet() + file := fset.AddFile(filename, fset.Base(), len(src)) + return readInto(config, fset, file, src) +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/read_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/read_test.go new file mode 100644 index 0000000..4a7d8e1 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/read_test.go @@ -0,0 +1,333 @@ +package gcfg + +import ( + "fmt" + "math/big" + "os" + "reflect" + "testing" +) + +const ( + // 64 spaces + sp64 = " " + // 512 spaces + sp512 = sp64 + sp64 + sp64 + sp64 + sp64 + sp64 + sp64 + sp64 + // 4096 spaces + sp4096 = sp512 + sp512 + sp512 + sp512 + sp512 + sp512 + sp512 + sp512 +) + +type cBasic struct { + Section cBasicS1 + Hyphen_In_Section cBasicS2 + unexported cBasicS1 + Exported cBasicS3 + TagName cBasicS1 `gcfg:"tag-name"` +} +type cBasicS1 struct { + Name string + Int int + PName *string +} +type cBasicS2 struct { + Hyphen_In_Name string +} +type cBasicS3 struct { + unexported string +} + +type nonMulti []string + +type unmarshalable string + +func (u *unmarshalable) UnmarshalText(text []byte) error { + s := string(text) + if s == "error" { + return fmt.Errorf("%s", s) + } + *u = unmarshalable(s) + return nil +} + +var _ textUnmarshaler = new(unmarshalable) + +type cUni struct { + X甲 cUniS1 + XSection cUniS2 +} +type cUniS1 struct { + X乙 string +} +type cUniS2 struct { + XName string +} + +type cMulti struct { + M1 cMultiS1 + M2 cMultiS2 + M3 cMultiS3 +} +type cMultiS1 struct{ Multi []string } +type cMultiS2 struct{ NonMulti nonMulti } +type cMultiS3 struct{ MultiInt []int } + +type cSubs struct{ Sub map[string]*cSubsS1 } +type cSubsS1 struct{ Name string } + +type cBool struct{ Section cBoolS1 } +type cBoolS1 struct{ Bool bool } + +type cTxUnm struct{ Section cTxUnmS1 } +type cTxUnmS1 struct{ Name unmarshalable } + +type cNum struct { + N1 cNumS1 + N2 cNumS2 + N3 cNumS3 +} +type cNumS1 struct { + Int int + IntDHO int `gcfg:",int=dho"` + Big *big.Int +} +type cNumS2 struct { + MultiInt []int + MultiBig []*big.Int +} +type cNumS3 struct{ FileMode os.FileMode } +type readtest struct { + gcfg string + exp interface{} + ok bool +} + +func newString(s string) *string { + return &s +} + +var readtests = []struct { + group string + tests []readtest +}{{"scanning", []readtest{ + {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + // hyphen in name + {"[hyphen-in-section]\nhyphen-in-name=value", &cBasic{Hyphen_In_Section: cBasicS2{Hyphen_In_Name: "value"}}, true}, + // quoted string value + {"[section]\nname=\"\"", &cBasic{Section: cBasicS1{Name: ""}}, true}, + {"[section]\nname=\" \"", &cBasic{Section: cBasicS1{Name: " "}}, true}, + {"[section]\nname=\"value\"", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\nname=\" value \"", &cBasic{Section: cBasicS1{Name: " value "}}, true}, + {"\n[section]\nname=\"va ; lue\"", &cBasic{Section: cBasicS1{Name: "va ; lue"}}, true}, + {"[section]\nname=\"val\" \"ue\"", &cBasic{Section: cBasicS1{Name: "val ue"}}, true}, + {"[section]\nname=\"value", &cBasic{}, false}, + // escape sequences + {"[section]\nname=\"va\\\\lue\"", &cBasic{Section: cBasicS1{Name: "va\\lue"}}, true}, + {"[section]\nname=\"va\\\"lue\"", &cBasic{Section: cBasicS1{Name: "va\"lue"}}, true}, + {"[section]\nname=\"va\\nlue\"", &cBasic{Section: cBasicS1{Name: "va\nlue"}}, true}, + {"[section]\nname=\"va\\tlue\"", &cBasic{Section: cBasicS1{Name: "va\tlue"}}, true}, + {"\n[section]\nname=\\", &cBasic{}, false}, + {"\n[section]\nname=\\a", &cBasic{}, false}, + {"\n[section]\nname=\"val\\a\"", &cBasic{}, false}, + {"\n[section]\nname=val\\", &cBasic{}, false}, + {"\n[sub \"A\\\n\"]\nname=value", &cSubs{}, false}, + {"\n[sub \"A\\\t\"]\nname=value", &cSubs{}, false}, + // broken line + {"[section]\nname=value \\\n value", &cBasic{Section: cBasicS1{Name: "value value"}}, true}, + {"[section]\nname=\"value \\\n value\"", &cBasic{}, false}, +}}, {"scanning:whitespace", []readtest{ + {" \n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {" [section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"\t[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[ section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section ]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\n name=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\nname =value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\nname= value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\nname=value ", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\r\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\r\nname=value\r\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {";cmnt\r\n[section]\r\nname=value\r\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + // long lines + {sp4096 + "[section]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[" + sp4096 + "section]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section" + sp4096 + "]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]" + sp4096 + "\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\n" + sp4096 + "name=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\nname" + sp4096 + "=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\nname=" + sp4096 + "value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\nname=value\n" + sp4096, &cBasic{Section: cBasicS1{Name: "value"}}, true}, +}}, {"scanning:comments", []readtest{ + {"; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"# cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {" ; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"\t; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"\n[section]; cmnt\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"\n[section] ; cmnt\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"\n[section]\nname=value; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"\n[section]\nname=value ; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"\n[section]\nname=\"value\" ; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"\n[section]\nname=value ; \"cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"\n[section]\nname=\"va ; lue\" ; cmnt", &cBasic{Section: cBasicS1{Name: "va ; lue"}}, true}, + {"\n[section]\nname=; cmnt", &cBasic{Section: cBasicS1{Name: ""}}, true}, +}}, {"scanning:subsections", []readtest{ + {"\n[sub \"A\"]\nname=value", &cSubs{map[string]*cSubsS1{"A": &cSubsS1{"value"}}}, true}, + {"\n[sub \"b\"]\nname=value", &cSubs{map[string]*cSubsS1{"b": &cSubsS1{"value"}}}, true}, + {"\n[sub \"A\\\\\"]\nname=value", &cSubs{map[string]*cSubsS1{"A\\": &cSubsS1{"value"}}}, true}, + {"\n[sub \"A\\\"\"]\nname=value", &cSubs{map[string]*cSubsS1{"A\"": &cSubsS1{"value"}}}, true}, +}}, {"syntax", []readtest{ + // invalid line + {"\n[section]\n=", &cBasic{}, false}, + // no section + {"name=value", &cBasic{}, false}, + // empty section + {"\n[]\nname=value", &cBasic{}, false}, + // empty subsection + {"\n[sub \"\"]\nname=value", &cSubs{}, false}, +}}, {"setting", []readtest{ + {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + // pointer + {"[section]", &cBasic{Section: cBasicS1{PName: nil}}, true}, + {"[section]\npname=value", &cBasic{Section: cBasicS1{PName: newString("value")}}, true}, + // section name not matched + {"\n[nonexistent]\nname=value", &cBasic{}, false}, + // subsection name not matched + {"\n[section \"nonexistent\"]\nname=value", &cBasic{}, false}, + // variable name not matched + {"\n[section]\nnonexistent=value", &cBasic{}, false}, + // hyphen in name + {"[hyphen-in-section]\nhyphen-in-name=value", &cBasic{Hyphen_In_Section: cBasicS2{Hyphen_In_Name: "value"}}, true}, + // ignore unexported fields + {"[unexported]\nname=value", &cBasic{}, false}, + {"[exported]\nunexported=value", &cBasic{}, false}, + // 'X' prefix for non-upper/lower-case letters + {"[甲]\n乙=丙", &cUni{X甲: cUniS1{X乙: "丙"}}, true}, + //{"[section]\nxname=value", &cBasic{XSection: cBasicS4{XName: "value"}}, false}, + //{"[xsection]\nname=value", &cBasic{XSection: cBasicS4{XName: "value"}}, false}, + // name specified as struct tag + {"[tag-name]\nname=value", &cBasic{TagName: cBasicS1{Name: "value"}}, true}, +}}, {"multivalue", []readtest{ + // unnamed slice type: treat as multi-value + {"\n[m1]", &cMulti{M1: cMultiS1{}}, true}, + {"\n[m1]\nmulti=value", &cMulti{M1: cMultiS1{[]string{"value"}}}, true}, + {"\n[m1]\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true}, + // "blank" empties multi-valued slice -- here same result as above + {"\n[m1]\nmulti\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true}, + // named slice type: do not treat as multi-value + {"\n[m2]", &cMulti{}, true}, + {"\n[m2]\nmulti=value", &cMulti{}, false}, + {"\n[m2]\nmulti=value1\nmulti=value2", &cMulti{}, false}, +}}, {"type:string", []readtest{ + {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, + {"[section]\nname=", &cBasic{Section: cBasicS1{Name: ""}}, true}, +}}, {"type:bool", []readtest{ + // explicit values + {"[section]\nbool=true", &cBool{cBoolS1{true}}, true}, + {"[section]\nbool=yes", &cBool{cBoolS1{true}}, true}, + {"[section]\nbool=on", &cBool{cBoolS1{true}}, true}, + {"[section]\nbool=1", &cBool{cBoolS1{true}}, true}, + {"[section]\nbool=tRuE", &cBool{cBoolS1{true}}, true}, + {"[section]\nbool=false", &cBool{cBoolS1{false}}, true}, + {"[section]\nbool=no", &cBool{cBoolS1{false}}, true}, + {"[section]\nbool=off", &cBool{cBoolS1{false}}, true}, + {"[section]\nbool=0", &cBool{cBoolS1{false}}, true}, + {"[section]\nbool=NO", &cBool{cBoolS1{false}}, true}, + // "blank" value handled as true + {"[section]\nbool", &cBool{cBoolS1{true}}, true}, + // bool parse errors + {"[section]\nbool=maybe", &cBool{}, false}, + {"[section]\nbool=t", &cBool{}, false}, + {"[section]\nbool=truer", &cBool{}, false}, + {"[section]\nbool=2", &cBool{}, false}, + {"[section]\nbool=-1", &cBool{}, false}, +}}, {"type:numeric", []readtest{ + {"[section]\nint=0", &cBasic{Section: cBasicS1{Int: 0}}, true}, + {"[section]\nint=1", &cBasic{Section: cBasicS1{Int: 1}}, true}, + {"[section]\nint=-1", &cBasic{Section: cBasicS1{Int: -1}}, true}, + {"[section]\nint=0.2", &cBasic{}, false}, + {"[section]\nint=1e3", &cBasic{}, false}, + // primitive [u]int(|8|16|32|64) and big.Int is parsed as dec or hex (not octal) + {"[n1]\nint=010", &cNum{N1: cNumS1{Int: 10}}, true}, + {"[n1]\nint=0x10", &cNum{N1: cNumS1{Int: 0x10}}, true}, + {"[n1]\nbig=1", &cNum{N1: cNumS1{Big: big.NewInt(1)}}, true}, + {"[n1]\nbig=0x10", &cNum{N1: cNumS1{Big: big.NewInt(0x10)}}, true}, + {"[n1]\nbig=010", &cNum{N1: cNumS1{Big: big.NewInt(10)}}, true}, + {"[n2]\nmultiint=010", &cNum{N2: cNumS2{MultiInt: []int{10}}}, true}, + {"[n2]\nmultibig=010", &cNum{N2: cNumS2{MultiBig: []*big.Int{big.NewInt(10)}}}, true}, + // set parse mode for int types via struct tag + {"[n1]\nintdho=010", &cNum{N1: cNumS1{IntDHO: 010}}, true}, + // octal allowed for named type + {"[n3]\nfilemode=0777", &cNum{N3: cNumS3{FileMode: 0777}}, true}, +}}, {"type:textUnmarshaler", []readtest{ + {"[section]\nname=value", &cTxUnm{Section: cTxUnmS1{Name: "value"}}, true}, + {"[section]\nname=error", &cTxUnm{}, false}, +}}, +} + +func TestReadStringInto(t *testing.T) { + for _, tg := range readtests { + for i, tt := range tg.tests { + id := fmt.Sprintf("%s:%d", tg.group, i) + testRead(t, id, tt) + } + } +} + +func TestReadStringIntoMultiBlankPreset(t *testing.T) { + tt := readtest{"\n[m1]\nmulti\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true} + cfg := &cMulti{M1: cMultiS1{[]string{"preset1", "preset2"}}} + testReadInto(t, "multi:blank", tt, cfg) +} + +func testRead(t *testing.T, id string, tt readtest) { + // get the type of the expected result + restyp := reflect.TypeOf(tt.exp).Elem() + // create a new instance to hold the actual result + res := reflect.New(restyp).Interface() + testReadInto(t, id, tt, res) +} + +func testReadInto(t *testing.T, id string, tt readtest, res interface{}) { + err := ReadStringInto(res, tt.gcfg) + if tt.ok { + if err != nil { + t.Errorf("%s fail: got error %v, wanted ok", id, err) + return + } else if !reflect.DeepEqual(res, tt.exp) { + t.Errorf("%s fail: got value %#v, wanted value %#v", id, res, tt.exp) + return + } + if !testing.Short() { + t.Logf("%s pass: got value %#v", id, res) + } + } else { // !tt.ok + if err == nil { + t.Errorf("%s fail: got value %#v, wanted error", id, res) + return + } + if !testing.Short() { + t.Logf("%s pass: got error %v", id, err) + } + } +} + +func TestReadFileInto(t *testing.T) { + res := &struct{ Section struct{ Name string } }{} + err := ReadFileInto(res, "testdata/gcfg_test.gcfg") + if err != nil { + t.Errorf(err.Error()) + } + if "value" != res.Section.Name { + t.Errorf("got %q, wanted %q", res.Section.Name, "value") + } +} + +func TestReadFileIntoUnicode(t *testing.T) { + res := &struct{ X甲 struct{ X乙 string } }{} + err := ReadFileInto(res, "testdata/gcfg_unicode_test.gcfg") + if err != nil { + t.Errorf(err.Error()) + } + if "丙" != res.X甲.X乙 { + t.Errorf("got %q, wanted %q", res.X甲.X乙, "丙") + } +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/errors.go b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/errors.go new file mode 100644 index 0000000..4ff920a --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/errors.go @@ -0,0 +1,121 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package scanner + +import ( + "fmt" + "io" + "sort" +) + +import ( + "code.google.com/p/gcfg/token" +) + +// In an ErrorList, an error is represented by an *Error. +// The position Pos, if valid, points to the beginning of +// the offending token, and the error condition is described +// by Msg. +// +type Error struct { + Pos token.Position + Msg string +} + +// Error implements the error interface. +func (e Error) Error() string { + if e.Pos.Filename != "" || e.Pos.IsValid() { + // don't print "" + // TODO(gri) reconsider the semantics of Position.IsValid + return e.Pos.String() + ": " + e.Msg + } + return e.Msg +} + +// ErrorList is a list of *Errors. +// The zero value for an ErrorList is an empty ErrorList ready to use. +// +type ErrorList []*Error + +// Add adds an Error with given position and error message to an ErrorList. +func (p *ErrorList) Add(pos token.Position, msg string) { + *p = append(*p, &Error{pos, msg}) +} + +// Reset resets an ErrorList to no errors. +func (p *ErrorList) Reset() { *p = (*p)[0:0] } + +// ErrorList implements the sort Interface. +func (p ErrorList) Len() int { return len(p) } +func (p ErrorList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +func (p ErrorList) Less(i, j int) bool { + e := &p[i].Pos + f := &p[j].Pos + if e.Filename < f.Filename { + return true + } + if e.Filename == f.Filename { + return e.Offset < f.Offset + } + return false +} + +// Sort sorts an ErrorList. *Error entries are sorted by position, +// other errors are sorted by error message, and before any *Error +// entry. +// +func (p ErrorList) Sort() { + sort.Sort(p) +} + +// RemoveMultiples sorts an ErrorList and removes all but the first error per line. +func (p *ErrorList) RemoveMultiples() { + sort.Sort(p) + var last token.Position // initial last.Line is != any legal error line + i := 0 + for _, e := range *p { + if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line { + last = e.Pos + (*p)[i] = e + i++ + } + } + (*p) = (*p)[0:i] +} + +// An ErrorList implements the error interface. +func (p ErrorList) Error() string { + switch len(p) { + case 0: + return "no errors" + case 1: + return p[0].Error() + } + return fmt.Sprintf("%s (and %d more errors)", p[0], len(p)-1) +} + +// Err returns an error equivalent to this error list. +// If the list is empty, Err returns nil. +func (p ErrorList) Err() error { + if len(p) == 0 { + return nil + } + return p +} + +// PrintError is a utility function that prints a list of errors to w, +// one error per line, if the err parameter is an ErrorList. Otherwise +// it prints the err string. +// +func PrintError(w io.Writer, err error) { + if list, ok := err.(ErrorList); ok { + for _, e := range list { + fmt.Fprintf(w, "%s\n", e) + } + } else if err != nil { + fmt.Fprintf(w, "%s\n", err) + } +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/example_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/example_test.go new file mode 100644 index 0000000..05eadf5 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/example_test.go @@ -0,0 +1,46 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package scanner_test + +import ( + "fmt" +) + +import ( + "code.google.com/p/gcfg/scanner" + "code.google.com/p/gcfg/token" +) + +func ExampleScanner_Scan() { + // src is the input that we want to tokenize. + src := []byte(`[profile "A"] +color = blue ; Comment`) + + // Initialize the scanner. + var s scanner.Scanner + fset := token.NewFileSet() // positions are relative to fset + file := fset.AddFile("", fset.Base(), len(src)) // register input "file" + s.Init(file, src, nil /* no error handler */, scanner.ScanComments) + + // Repeated calls to Scan yield the token sequence found in the input. + for { + pos, tok, lit := s.Scan() + if tok == token.EOF { + break + } + fmt.Printf("%s\t%q\t%q\n", fset.Position(pos), tok, lit) + } + + // output: + // 1:1 "[" "" + // 1:2 "IDENT" "profile" + // 1:10 "STRING" "\"A\"" + // 1:13 "]" "" + // 1:14 "\n" "" + // 2:1 "IDENT" "color" + // 2:7 "=" "" + // 2:9 "STRING" "blue" + // 2:14 "COMMENT" "; Comment" +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner.go b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner.go new file mode 100644 index 0000000..f65a4f5 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner.go @@ -0,0 +1,342 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package scanner implements a scanner for gcfg configuration text. +// It takes a []byte as source which can then be tokenized +// through repeated calls to the Scan method. +// +// Note that the API for the scanner package may change to accommodate new +// features or implementation changes in gcfg. +// +package scanner + +import ( + "fmt" + "path/filepath" + "unicode" + "unicode/utf8" +) + +import ( + "code.google.com/p/gcfg/token" +) + +// An ErrorHandler may be provided to Scanner.Init. If a syntax error is +// encountered and a handler was installed, the handler is called with a +// position and an error message. The position points to the beginning of +// the offending token. +// +type ErrorHandler func(pos token.Position, msg string) + +// A Scanner holds the scanner's internal state while processing +// a given text. It can be allocated as part of another data +// structure but must be initialized via Init before use. +// +type Scanner struct { + // immutable state + file *token.File // source file handle + dir string // directory portion of file.Name() + src []byte // source + err ErrorHandler // error reporting; or nil + mode Mode // scanning mode + + // scanning state + ch rune // current character + offset int // character offset + rdOffset int // reading offset (position after current character) + lineOffset int // current line offset + nextVal bool // next token is expected to be a value + + // public state - ok to modify + ErrorCount int // number of errors encountered +} + +// Read the next Unicode char into s.ch. +// s.ch < 0 means end-of-file. +// +func (s *Scanner) next() { + if s.rdOffset < len(s.src) { + s.offset = s.rdOffset + if s.ch == '\n' { + s.lineOffset = s.offset + s.file.AddLine(s.offset) + } + r, w := rune(s.src[s.rdOffset]), 1 + switch { + case r == 0: + s.error(s.offset, "illegal character NUL") + case r >= 0x80: + // not ASCII + r, w = utf8.DecodeRune(s.src[s.rdOffset:]) + if r == utf8.RuneError && w == 1 { + s.error(s.offset, "illegal UTF-8 encoding") + } + } + s.rdOffset += w + s.ch = r + } else { + s.offset = len(s.src) + if s.ch == '\n' { + s.lineOffset = s.offset + s.file.AddLine(s.offset) + } + s.ch = -1 // eof + } +} + +// A mode value is a set of flags (or 0). +// They control scanner behavior. +// +type Mode uint + +const ( + ScanComments Mode = 1 << iota // return comments as COMMENT tokens +) + +// Init prepares the scanner s to tokenize the text src by setting the +// scanner at the beginning of src. The scanner uses the file set file +// for position information and it adds line information for each line. +// It is ok to re-use the same file when re-scanning the same file as +// line information which is already present is ignored. Init causes a +// panic if the file size does not match the src size. +// +// Calls to Scan will invoke the error handler err if they encounter a +// syntax error and err is not nil. Also, for each error encountered, +// the Scanner field ErrorCount is incremented by one. The mode parameter +// determines how comments are handled. +// +// Note that Init may call err if there is an error in the first character +// of the file. +// +func (s *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode Mode) { + // Explicitly initialize all fields since a scanner may be reused. + if file.Size() != len(src) { + panic(fmt.Sprintf("file size (%d) does not match src len (%d)", file.Size(), len(src))) + } + s.file = file + s.dir, _ = filepath.Split(file.Name()) + s.src = src + s.err = err + s.mode = mode + + s.ch = ' ' + s.offset = 0 + s.rdOffset = 0 + s.lineOffset = 0 + s.ErrorCount = 0 + s.nextVal = false + + s.next() +} + +func (s *Scanner) error(offs int, msg string) { + if s.err != nil { + s.err(s.file.Position(s.file.Pos(offs)), msg) + } + s.ErrorCount++ +} + +func (s *Scanner) scanComment() string { + // initial [;#] already consumed + offs := s.offset - 1 // position of initial [;#] + + for s.ch != '\n' && s.ch >= 0 { + s.next() + } + return string(s.src[offs:s.offset]) +} + +func isLetter(ch rune) bool { + return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch >= 0x80 && unicode.IsLetter(ch) +} + +func isDigit(ch rune) bool { + return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch) +} + +func (s *Scanner) scanIdentifier() string { + offs := s.offset + for isLetter(s.ch) || isDigit(s.ch) || s.ch == '-' { + s.next() + } + return string(s.src[offs:s.offset]) +} + +func (s *Scanner) scanEscape(val bool) { + offs := s.offset + ch := s.ch + s.next() // always make progress + switch ch { + case '\\', '"': + // ok + case 'n', 't': + if val { + break // ok + } + fallthrough + default: + s.error(offs, "unknown escape sequence") + } +} + +func (s *Scanner) scanString() string { + // '"' opening already consumed + offs := s.offset - 1 + + for s.ch != '"' { + ch := s.ch + s.next() + if ch == '\n' || ch < 0 { + s.error(offs, "string not terminated") + break + } + if ch == '\\' { + s.scanEscape(false) + } + } + + s.next() + + return string(s.src[offs:s.offset]) +} + +func stripCR(b []byte) []byte { + c := make([]byte, len(b)) + i := 0 + for _, ch := range b { + if ch != '\r' { + c[i] = ch + i++ + } + } + return c[:i] +} + +func (s *Scanner) scanValString() string { + offs := s.offset + + hasCR := false + end := offs + inQuote := false +loop: + for inQuote || s.ch >= 0 && s.ch != '\n' && s.ch != ';' && s.ch != '#' { + ch := s.ch + s.next() + switch { + case inQuote && ch == '\\': + s.scanEscape(true) + case !inQuote && ch == '\\': + if s.ch == '\r' { + hasCR = true + s.next() + } + if s.ch != '\n' { + s.error(offs, "unquoted '\\' must be followed by new line") + break loop + } + s.next() + case ch == '"': + inQuote = !inQuote + case ch == '\r': + hasCR = true + case ch < 0 || inQuote && ch == '\n': + s.error(offs, "string not terminated") + break loop + } + if inQuote || !isWhiteSpace(ch) { + end = s.offset + } + } + + lit := s.src[offs:end] + if hasCR { + lit = stripCR(lit) + } + + return string(lit) +} + +func isWhiteSpace(ch rune) bool { + return ch == ' ' || ch == '\t' || ch == '\r' +} + +func (s *Scanner) skipWhitespace() { + for isWhiteSpace(s.ch) { + s.next() + } +} + +// Scan scans the next token and returns the token position, the token, +// and its literal string if applicable. The source end is indicated by +// token.EOF. +// +// If the returned token is a literal (token.IDENT, token.STRING) or +// token.COMMENT, the literal string has the corresponding value. +// +// If the returned token is token.ILLEGAL, the literal string is the +// offending character. +// +// In all other cases, Scan returns an empty literal string. +// +// For more tolerant parsing, Scan will return a valid token if +// possible even if a syntax error was encountered. Thus, even +// if the resulting token sequence contains no illegal tokens, +// a client may not assume that no error occurred. Instead it +// must check the scanner's ErrorCount or the number of calls +// of the error handler, if there was one installed. +// +// Scan adds line information to the file added to the file +// set with Init. Token positions are relative to that file +// and thus relative to the file set. +// +func (s *Scanner) Scan() (pos token.Pos, tok token.Token, lit string) { +scanAgain: + s.skipWhitespace() + + // current token start + pos = s.file.Pos(s.offset) + + // determine token value + switch ch := s.ch; { + case s.nextVal: + lit = s.scanValString() + tok = token.STRING + s.nextVal = false + case isLetter(ch): + lit = s.scanIdentifier() + tok = token.IDENT + default: + s.next() // always make progress + switch ch { + case -1: + tok = token.EOF + case '\n': + tok = token.EOL + case '"': + tok = token.STRING + lit = s.scanString() + case '[': + tok = token.LBRACK + case ']': + tok = token.RBRACK + case ';', '#': + // comment + lit = s.scanComment() + if s.mode&ScanComments == 0 { + // skip comment + goto scanAgain + } + tok = token.COMMENT + case '=': + tok = token.ASSIGN + s.nextVal = true + default: + s.error(s.file.Offset(pos), fmt.Sprintf("illegal character %#U", ch)) + tok = token.ILLEGAL + lit = string(ch) + } + } + + return +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner_test.go new file mode 100644 index 0000000..33227c1 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner_test.go @@ -0,0 +1,417 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package scanner + +import ( + "os" + "strings" + "testing" +) + +import ( + "code.google.com/p/gcfg/token" +) + +var fset = token.NewFileSet() + +const /* class */ ( + special = iota + literal + operator +) + +func tokenclass(tok token.Token) int { + switch { + case tok.IsLiteral(): + return literal + case tok.IsOperator(): + return operator + } + return special +} + +type elt struct { + tok token.Token + lit string + class int + pre string + suf string +} + +var tokens = [...]elt{ + // Special tokens + {token.COMMENT, "; a comment", special, "", "\n"}, + {token.COMMENT, "# a comment", special, "", "\n"}, + + // Operators and delimiters + {token.ASSIGN, "=", operator, "", "value"}, + {token.LBRACK, "[", operator, "", ""}, + {token.RBRACK, "]", operator, "", ""}, + {token.EOL, "\n", operator, "", ""}, + + // Identifiers + {token.IDENT, "foobar", literal, "", ""}, + {token.IDENT, "a۰۱۸", literal, "", ""}, + {token.IDENT, "foo६४", literal, "", ""}, + {token.IDENT, "bar9876", literal, "", ""}, + {token.IDENT, "foo-bar", literal, "", ""}, + {token.IDENT, "foo", literal, ";\n", ""}, + // String literals (subsection names) + {token.STRING, `"foobar"`, literal, "", ""}, + {token.STRING, `"\""`, literal, "", ""}, + // String literals (values) + {token.STRING, `"\n"`, literal, "=", ""}, + {token.STRING, `"foobar"`, literal, "=", ""}, + {token.STRING, `"foo\nbar"`, literal, "=", ""}, + {token.STRING, `"foo\"bar"`, literal, "=", ""}, + {token.STRING, `"foo\\bar"`, literal, "=", ""}, + {token.STRING, `"foobar"`, literal, "=", ""}, + {token.STRING, `"foobar"`, literal, "= ", ""}, + {token.STRING, `"foobar"`, literal, "=", "\n"}, + {token.STRING, `"foobar"`, literal, "=", ";"}, + {token.STRING, `"foobar"`, literal, "=", " ;"}, + {token.STRING, `"foobar"`, literal, "=", "#"}, + {token.STRING, `"foobar"`, literal, "=", " #"}, + {token.STRING, "foobar", literal, "=", ""}, + {token.STRING, "foobar", literal, "= ", ""}, + {token.STRING, "foobar", literal, "=", " "}, + {token.STRING, `"foo" "bar"`, literal, "=", " "}, + {token.STRING, "foo\\\nbar", literal, "=", ""}, + {token.STRING, "foo\\\r\nbar", literal, "=", ""}, +} + +const whitespace = " \t \n\n\n" // to separate tokens + +var source = func() []byte { + var src []byte + for _, t := range tokens { + src = append(src, t.pre...) + src = append(src, t.lit...) + src = append(src, t.suf...) + src = append(src, whitespace...) + } + return src +}() + +func newlineCount(s string) int { + n := 0 + for i := 0; i < len(s); i++ { + if s[i] == '\n' { + n++ + } + } + return n +} + +func checkPos(t *testing.T, lit string, p token.Pos, expected token.Position) { + pos := fset.Position(p) + if pos.Filename != expected.Filename { + t.Errorf("bad filename for %q: got %s, expected %s", lit, pos.Filename, expected.Filename) + } + if pos.Offset != expected.Offset { + t.Errorf("bad position for %q: got %d, expected %d", lit, pos.Offset, expected.Offset) + } + if pos.Line != expected.Line { + t.Errorf("bad line for %q: got %d, expected %d", lit, pos.Line, expected.Line) + } + if pos.Column != expected.Column { + t.Errorf("bad column for %q: got %d, expected %d", lit, pos.Column, expected.Column) + } +} + +// Verify that calling Scan() provides the correct results. +func TestScan(t *testing.T) { + // make source + src_linecount := newlineCount(string(source)) + whitespace_linecount := newlineCount(whitespace) + + index := 0 + + // error handler + eh := func(_ token.Position, msg string) { + t.Errorf("%d: error handler called (msg = %s)", index, msg) + } + + // verify scan + var s Scanner + s.Init(fset.AddFile("", fset.Base(), len(source)), source, eh, ScanComments) + // epos is the expected position + epos := token.Position{ + Filename: "", + Offset: 0, + Line: 1, + Column: 1, + } + for { + pos, tok, lit := s.Scan() + if lit == "" { + // no literal value for non-literal tokens + lit = tok.String() + } + e := elt{token.EOF, "", special, "", ""} + if index < len(tokens) { + e = tokens[index] + } + if tok == token.EOF { + lit = "" + epos.Line = src_linecount + epos.Column = 2 + } + if e.pre != "" && strings.ContainsRune("=;#", rune(e.pre[0])) { + epos.Column = 1 + checkPos(t, lit, pos, epos) + var etok token.Token + if e.pre[0] == '=' { + etok = token.ASSIGN + } else { + etok = token.COMMENT + } + if tok != etok { + t.Errorf("bad token for %q: got %q, expected %q", lit, tok, etok) + } + pos, tok, lit = s.Scan() + } + epos.Offset += len(e.pre) + if tok != token.EOF { + epos.Column = 1 + len(e.pre) + } + if e.pre != "" && e.pre[len(e.pre)-1] == '\n' { + epos.Offset-- + epos.Column-- + checkPos(t, lit, pos, epos) + if tok != token.EOL { + t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.EOL) + } + epos.Line++ + epos.Offset++ + epos.Column = 1 + pos, tok, lit = s.Scan() + } + checkPos(t, lit, pos, epos) + if tok != e.tok { + t.Errorf("bad token for %q: got %q, expected %q", lit, tok, e.tok) + } + if e.tok.IsLiteral() { + // no CRs in value string literals + elit := e.lit + if strings.ContainsRune(e.pre, '=') { + elit = string(stripCR([]byte(elit))) + epos.Offset += len(e.lit) - len(lit) // correct position + } + if lit != elit { + t.Errorf("bad literal for %q: got %q, expected %q", lit, lit, elit) + } + } + if tokenclass(tok) != e.class { + t.Errorf("bad class for %q: got %d, expected %d", lit, tokenclass(tok), e.class) + } + epos.Offset += len(lit) + len(e.suf) + len(whitespace) + epos.Line += newlineCount(lit) + newlineCount(e.suf) + whitespace_linecount + index++ + if tok == token.EOF { + break + } + if e.suf == "value" { + pos, tok, lit = s.Scan() + if tok != token.STRING { + t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.STRING) + } + } else if strings.ContainsRune(e.suf, ';') || strings.ContainsRune(e.suf, '#') { + pos, tok, lit = s.Scan() + if tok != token.COMMENT { + t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.COMMENT) + } + } + // skip EOLs + for i := 0; i < whitespace_linecount+newlineCount(e.suf); i++ { + pos, tok, lit = s.Scan() + if tok != token.EOL { + t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.EOL) + } + } + } + if s.ErrorCount != 0 { + t.Errorf("found %d errors", s.ErrorCount) + } +} + +func TestScanValStringEOF(t *testing.T) { + var s Scanner + src := "= value" + f := fset.AddFile("src", fset.Base(), len(src)) + s.Init(f, []byte(src), nil, 0) + s.Scan() // = + s.Scan() // value + _, tok, _ := s.Scan() // EOF + if tok != token.EOF { + t.Errorf("bad token: got %s, expected %s", tok, token.EOF) + } + if s.ErrorCount > 0 { + t.Error("scanning error") + } +} + +// Verify that initializing the same scanner more then once works correctly. +func TestInit(t *testing.T) { + var s Scanner + + // 1st init + src1 := "\nname = value" + f1 := fset.AddFile("src1", fset.Base(), len(src1)) + s.Init(f1, []byte(src1), nil, 0) + if f1.Size() != len(src1) { + t.Errorf("bad file size: got %d, expected %d", f1.Size(), len(src1)) + } + s.Scan() // \n + s.Scan() // name + _, tok, _ := s.Scan() // = + if tok != token.ASSIGN { + t.Errorf("bad token: got %s, expected %s", tok, token.ASSIGN) + } + + // 2nd init + src2 := "[section]" + f2 := fset.AddFile("src2", fset.Base(), len(src2)) + s.Init(f2, []byte(src2), nil, 0) + if f2.Size() != len(src2) { + t.Errorf("bad file size: got %d, expected %d", f2.Size(), len(src2)) + } + _, tok, _ = s.Scan() // [ + if tok != token.LBRACK { + t.Errorf("bad token: got %s, expected %s", tok, token.LBRACK) + } + + if s.ErrorCount != 0 { + t.Errorf("found %d errors", s.ErrorCount) + } +} + +func TestStdErrorHandler(t *testing.T) { + const src = "@\n" + // illegal character, cause an error + "@ @\n" // two errors on the same line + + var list ErrorList + eh := func(pos token.Position, msg string) { list.Add(pos, msg) } + + var s Scanner + s.Init(fset.AddFile("File1", fset.Base(), len(src)), []byte(src), eh, 0) + for { + if _, tok, _ := s.Scan(); tok == token.EOF { + break + } + } + + if len(list) != s.ErrorCount { + t.Errorf("found %d errors, expected %d", len(list), s.ErrorCount) + } + + if len(list) != 3 { + t.Errorf("found %d raw errors, expected 3", len(list)) + PrintError(os.Stderr, list) + } + + list.Sort() + if len(list) != 3 { + t.Errorf("found %d sorted errors, expected 3", len(list)) + PrintError(os.Stderr, list) + } + + list.RemoveMultiples() + if len(list) != 2 { + t.Errorf("found %d one-per-line errors, expected 2", len(list)) + PrintError(os.Stderr, list) + } +} + +type errorCollector struct { + cnt int // number of errors encountered + msg string // last error message encountered + pos token.Position // last error position encountered +} + +func checkError(t *testing.T, src string, tok token.Token, pos int, err string) { + var s Scanner + var h errorCollector + eh := func(pos token.Position, msg string) { + h.cnt++ + h.msg = msg + h.pos = pos + } + s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), eh, ScanComments) + if src[0] == '=' { + _, _, _ = s.Scan() + } + _, tok0, _ := s.Scan() + _, tok1, _ := s.Scan() + if tok0 != tok { + t.Errorf("%q: got %s, expected %s", src, tok0, tok) + } + if tok1 != token.EOF { + t.Errorf("%q: got %s, expected EOF", src, tok1) + } + cnt := 0 + if err != "" { + cnt = 1 + } + if h.cnt != cnt { + t.Errorf("%q: got cnt %d, expected %d", src, h.cnt, cnt) + } + if h.msg != err { + t.Errorf("%q: got msg %q, expected %q", src, h.msg, err) + } + if h.pos.Offset != pos { + t.Errorf("%q: got offset %d, expected %d", src, h.pos.Offset, pos) + } +} + +var errors = []struct { + src string + tok token.Token + pos int + err string +}{ + {"\a", token.ILLEGAL, 0, "illegal character U+0007"}, + {"/", token.ILLEGAL, 0, "illegal character U+002F '/'"}, + {"_", token.ILLEGAL, 0, "illegal character U+005F '_'"}, + {`…`, token.ILLEGAL, 0, "illegal character U+2026 '…'"}, + {`""`, token.STRING, 0, ""}, + {`"`, token.STRING, 0, "string not terminated"}, + {"\"\n", token.STRING, 0, "string not terminated"}, + {`="`, token.STRING, 1, "string not terminated"}, + {"=\"\n", token.STRING, 1, "string not terminated"}, + {"=\\", token.STRING, 1, "unquoted '\\' must be followed by new line"}, + {"=\\\r", token.STRING, 1, "unquoted '\\' must be followed by new line"}, + {`"\z"`, token.STRING, 2, "unknown escape sequence"}, + {`"\a"`, token.STRING, 2, "unknown escape sequence"}, + {`"\b"`, token.STRING, 2, "unknown escape sequence"}, + {`"\f"`, token.STRING, 2, "unknown escape sequence"}, + {`"\r"`, token.STRING, 2, "unknown escape sequence"}, + {`"\t"`, token.STRING, 2, "unknown escape sequence"}, + {`"\v"`, token.STRING, 2, "unknown escape sequence"}, + {`"\0"`, token.STRING, 2, "unknown escape sequence"}, +} + +func TestScanErrors(t *testing.T) { + for _, e := range errors { + checkError(t, e.src, e.tok, e.pos, e.err) + } +} + +func BenchmarkScan(b *testing.B) { + b.StopTimer() + fset := token.NewFileSet() + file := fset.AddFile("", fset.Base(), len(source)) + var s Scanner + b.StartTimer() + for i := b.N - 1; i >= 0; i-- { + s.Init(file, source, nil, ScanComments) + for { + _, tok, _ := s.Scan() + if tok == token.EOF { + break + } + } + } +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/set.go b/Godeps/_workspace/src/code.google.com/p/gcfg/set.go new file mode 100644 index 0000000..4e15604 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/set.go @@ -0,0 +1,281 @@ +package gcfg + +import ( + "fmt" + "math/big" + "reflect" + "strings" + "unicode" + "unicode/utf8" + + "code.google.com/p/gcfg/types" +) + +type tag struct { + ident string + intMode string +} + +func newTag(ts string) tag { + t := tag{} + s := strings.Split(ts, ",") + t.ident = s[0] + for _, tse := range s[1:] { + if strings.HasPrefix(tse, "int=") { + t.intMode = tse[len("int="):] + } + } + return t +} + +func fieldFold(v reflect.Value, name string) (reflect.Value, tag) { + var n string + r0, _ := utf8.DecodeRuneInString(name) + if unicode.IsLetter(r0) && !unicode.IsLower(r0) && !unicode.IsUpper(r0) { + n = "X" + } + n += strings.Replace(name, "-", "_", -1) + f, ok := v.Type().FieldByNameFunc(func(fieldName string) bool { + if !v.FieldByName(fieldName).CanSet() { + return false + } + f, _ := v.Type().FieldByName(fieldName) + t := newTag(f.Tag.Get("gcfg")) + if t.ident != "" { + return strings.EqualFold(t.ident, name) + } + return strings.EqualFold(n, fieldName) + }) + if !ok { + return reflect.Value{}, tag{} + } + return v.FieldByName(f.Name), newTag(f.Tag.Get("gcfg")) +} + +type setter func(destp interface{}, blank bool, val string, t tag) error + +var errUnsupportedType = fmt.Errorf("unsupported type") +var errBlankUnsupported = fmt.Errorf("blank value not supported for type") + +var setters = []setter{ + typeSetter, textUnmarshalerSetter, kindSetter, scanSetter, +} + +func textUnmarshalerSetter(d interface{}, blank bool, val string, t tag) error { + dtu, ok := d.(textUnmarshaler) + if !ok { + return errUnsupportedType + } + if blank { + return errBlankUnsupported + } + return dtu.UnmarshalText([]byte(val)) +} + +func boolSetter(d interface{}, blank bool, val string, t tag) error { + if blank { + reflect.ValueOf(d).Elem().Set(reflect.ValueOf(true)) + return nil + } + b, err := types.ParseBool(val) + if err == nil { + reflect.ValueOf(d).Elem().Set(reflect.ValueOf(b)) + } + return err +} + +func intMode(mode string) types.IntMode { + var m types.IntMode + if strings.ContainsAny(mode, "dD") { + m |= types.Dec + } + if strings.ContainsAny(mode, "hH") { + m |= types.Hex + } + if strings.ContainsAny(mode, "oO") { + m |= types.Oct + } + return m +} + +var typeModes = map[reflect.Type]types.IntMode{ + reflect.TypeOf(int(0)): types.Dec | types.Hex, + reflect.TypeOf(int8(0)): types.Dec | types.Hex, + reflect.TypeOf(int16(0)): types.Dec | types.Hex, + reflect.TypeOf(int32(0)): types.Dec | types.Hex, + reflect.TypeOf(int64(0)): types.Dec | types.Hex, + reflect.TypeOf(uint(0)): types.Dec | types.Hex, + reflect.TypeOf(uint8(0)): types.Dec | types.Hex, + reflect.TypeOf(uint16(0)): types.Dec | types.Hex, + reflect.TypeOf(uint32(0)): types.Dec | types.Hex, + reflect.TypeOf(uint64(0)): types.Dec | types.Hex, + // use default mode (allow dec/hex/oct) for uintptr type + reflect.TypeOf(big.Int{}): types.Dec | types.Hex, +} + +func intModeDefault(t reflect.Type) types.IntMode { + m, ok := typeModes[t] + if !ok { + m = types.Dec | types.Hex | types.Oct + } + return m +} + +func intSetter(d interface{}, blank bool, val string, t tag) error { + if blank { + return errBlankUnsupported + } + mode := intMode(t.intMode) + if mode == 0 { + mode = intModeDefault(reflect.TypeOf(d).Elem()) + } + return types.ParseInt(d, val, mode) +} + +func stringSetter(d interface{}, blank bool, val string, t tag) error { + if blank { + return errBlankUnsupported + } + dsp, ok := d.(*string) + if !ok { + return errUnsupportedType + } + *dsp = val + return nil +} + +var kindSetters = map[reflect.Kind]setter{ + reflect.String: stringSetter, + reflect.Bool: boolSetter, + reflect.Int: intSetter, + reflect.Int8: intSetter, + reflect.Int16: intSetter, + reflect.Int32: intSetter, + reflect.Int64: intSetter, + reflect.Uint: intSetter, + reflect.Uint8: intSetter, + reflect.Uint16: intSetter, + reflect.Uint32: intSetter, + reflect.Uint64: intSetter, + reflect.Uintptr: intSetter, +} + +var typeSetters = map[reflect.Type]setter{ + reflect.TypeOf(big.Int{}): intSetter, +} + +func typeSetter(d interface{}, blank bool, val string, tt tag) error { + t := reflect.ValueOf(d).Type().Elem() + setter, ok := typeSetters[t] + if !ok { + return errUnsupportedType + } + return setter(d, blank, val, tt) +} + +func kindSetter(d interface{}, blank bool, val string, tt tag) error { + k := reflect.ValueOf(d).Type().Elem().Kind() + setter, ok := kindSetters[k] + if !ok { + return errUnsupportedType + } + return setter(d, blank, val, tt) +} + +func scanSetter(d interface{}, blank bool, val string, tt tag) error { + if blank { + return errBlankUnsupported + } + return types.ScanFully(d, val, 'v') +} + +func set(cfg interface{}, sect, sub, name string, blank bool, value string) error { + vPCfg := reflect.ValueOf(cfg) + if vPCfg.Kind() != reflect.Ptr || vPCfg.Elem().Kind() != reflect.Struct { + panic(fmt.Errorf("config must be a pointer to a struct")) + } + vCfg := vPCfg.Elem() + vSect, _ := fieldFold(vCfg, sect) + if !vSect.IsValid() { + return fmt.Errorf("invalid section: section %q", sect) + } + if vSect.Kind() == reflect.Map { + vst := vSect.Type() + if vst.Key().Kind() != reflect.String || + vst.Elem().Kind() != reflect.Ptr || + vst.Elem().Elem().Kind() != reflect.Struct { + panic(fmt.Errorf("map field for section must have string keys and "+ + " pointer-to-struct values: section %q", sect)) + } + if vSect.IsNil() { + vSect.Set(reflect.MakeMap(vst)) + } + k := reflect.ValueOf(sub) + pv := vSect.MapIndex(k) + if !pv.IsValid() { + vType := vSect.Type().Elem().Elem() + pv = reflect.New(vType) + vSect.SetMapIndex(k, pv) + } + vSect = pv.Elem() + } else if vSect.Kind() != reflect.Struct { + panic(fmt.Errorf("field for section must be a map or a struct: "+ + "section %q", sect)) + } else if sub != "" { + return fmt.Errorf("invalid subsection: "+ + "section %q subsection %q", sect, sub) + } + vVar, t := fieldFold(vSect, name) + if !vVar.IsValid() { + return fmt.Errorf("invalid variable: "+ + "section %q subsection %q variable %q", sect, sub, name) + } + // vVal is either single-valued var, or newly allocated value within multi-valued var + var vVal reflect.Value + // multi-value if unnamed slice type + isMulti := vVar.Type().Name() == "" && vVar.Kind() == reflect.Slice + if isMulti && blank { + vVar.Set(reflect.Zero(vVar.Type())) + return nil + } + if isMulti { + vVal = reflect.New(vVar.Type().Elem()).Elem() + } else { + vVal = vVar + } + isDeref := vVal.Type().Name() == "" && vVal.Type().Kind() == reflect.Ptr + isNew := isDeref && vVal.IsNil() + // vAddr is address of value to set (dereferenced & allocated as needed) + var vAddr reflect.Value + switch { + case isNew: + vAddr = reflect.New(vVal.Type().Elem()) + case isDeref && !isNew: + vAddr = vVal + default: + vAddr = vVal.Addr() + } + vAddrI := vAddr.Interface() + err, ok := error(nil), false + for _, s := range setters { + err = s(vAddrI, blank, value, t) + if err == nil { + ok = true + break + } + if err != errUnsupportedType { + return err + } + } + if !ok { + // in case all setters returned errUnsupportedType + return err + } + if isNew { // set reference if it was dereferenced and newly allocated + vVal.Set(vAddr) + } + if isMulti { // append if multi-valued + vVar.Set(reflect.Append(vVar, vVal)) + } + return nil +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_test.gcfg b/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_test.gcfg new file mode 100644 index 0000000..cddff29 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_test.gcfg @@ -0,0 +1,3 @@ +; Comment line +[section] +name=value # comment diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_unicode_test.gcfg b/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_unicode_test.gcfg new file mode 100644 index 0000000..3762a20 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_unicode_test.gcfg @@ -0,0 +1,3 @@ +; Comment line +[甲] +乙=丙 # comment diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/token/position.go b/Godeps/_workspace/src/code.google.com/p/gcfg/token/position.go new file mode 100644 index 0000000..fc45c1e --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/token/position.go @@ -0,0 +1,435 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// TODO(gri) consider making this a separate package outside the go directory. + +package token + +import ( + "fmt" + "sort" + "sync" +) + +// ----------------------------------------------------------------------------- +// Positions + +// Position describes an arbitrary source position +// including the file, line, and column location. +// A Position is valid if the line number is > 0. +// +type Position struct { + Filename string // filename, if any + Offset int // offset, starting at 0 + Line int // line number, starting at 1 + Column int // column number, starting at 1 (character count) +} + +// IsValid returns true if the position is valid. +func (pos *Position) IsValid() bool { return pos.Line > 0 } + +// String returns a string in one of several forms: +// +// file:line:column valid position with file name +// line:column valid position without file name +// file invalid position with file name +// - invalid position without file name +// +func (pos Position) String() string { + s := pos.Filename + if pos.IsValid() { + if s != "" { + s += ":" + } + s += fmt.Sprintf("%d:%d", pos.Line, pos.Column) + } + if s == "" { + s = "-" + } + return s +} + +// Pos is a compact encoding of a source position within a file set. +// It can be converted into a Position for a more convenient, but much +// larger, representation. +// +// The Pos value for a given file is a number in the range [base, base+size], +// where base and size are specified when adding the file to the file set via +// AddFile. +// +// To create the Pos value for a specific source offset, first add +// the respective file to the current file set (via FileSet.AddFile) +// and then call File.Pos(offset) for that file. Given a Pos value p +// for a specific file set fset, the corresponding Position value is +// obtained by calling fset.Position(p). +// +// Pos values can be compared directly with the usual comparison operators: +// If two Pos values p and q are in the same file, comparing p and q is +// equivalent to comparing the respective source file offsets. If p and q +// are in different files, p < q is true if the file implied by p was added +// to the respective file set before the file implied by q. +// +type Pos int + +// The zero value for Pos is NoPos; there is no file and line information +// associated with it, and NoPos().IsValid() is false. NoPos is always +// smaller than any other Pos value. The corresponding Position value +// for NoPos is the zero value for Position. +// +const NoPos Pos = 0 + +// IsValid returns true if the position is valid. +func (p Pos) IsValid() bool { + return p != NoPos +} + +// ----------------------------------------------------------------------------- +// File + +// A File is a handle for a file belonging to a FileSet. +// A File has a name, size, and line offset table. +// +type File struct { + set *FileSet + name string // file name as provided to AddFile + base int // Pos value range for this file is [base...base+size] + size int // file size as provided to AddFile + + // lines and infos are protected by set.mutex + lines []int + infos []lineInfo +} + +// Name returns the file name of file f as registered with AddFile. +func (f *File) Name() string { + return f.name +} + +// Base returns the base offset of file f as registered with AddFile. +func (f *File) Base() int { + return f.base +} + +// Size returns the size of file f as registered with AddFile. +func (f *File) Size() int { + return f.size +} + +// LineCount returns the number of lines in file f. +func (f *File) LineCount() int { + f.set.mutex.RLock() + n := len(f.lines) + f.set.mutex.RUnlock() + return n +} + +// AddLine adds the line offset for a new line. +// The line offset must be larger than the offset for the previous line +// and smaller than the file size; otherwise the line offset is ignored. +// +func (f *File) AddLine(offset int) { + f.set.mutex.Lock() + if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size { + f.lines = append(f.lines, offset) + } + f.set.mutex.Unlock() +} + +// SetLines sets the line offsets for a file and returns true if successful. +// The line offsets are the offsets of the first character of each line; +// for instance for the content "ab\nc\n" the line offsets are {0, 3}. +// An empty file has an empty line offset table. +// Each line offset must be larger than the offset for the previous line +// and smaller than the file size; otherwise SetLines fails and returns +// false. +// +func (f *File) SetLines(lines []int) bool { + // verify validity of lines table + size := f.size + for i, offset := range lines { + if i > 0 && offset <= lines[i-1] || size <= offset { + return false + } + } + + // set lines table + f.set.mutex.Lock() + f.lines = lines + f.set.mutex.Unlock() + return true +} + +// SetLinesForContent sets the line offsets for the given file content. +func (f *File) SetLinesForContent(content []byte) { + var lines []int + line := 0 + for offset, b := range content { + if line >= 0 { + lines = append(lines, line) + } + line = -1 + if b == '\n' { + line = offset + 1 + } + } + + // set lines table + f.set.mutex.Lock() + f.lines = lines + f.set.mutex.Unlock() +} + +// A lineInfo object describes alternative file and line number +// information (such as provided via a //line comment in a .go +// file) for a given file offset. +type lineInfo struct { + // fields are exported to make them accessible to gob + Offset int + Filename string + Line int +} + +// AddLineInfo adds alternative file and line number information for +// a given file offset. The offset must be larger than the offset for +// the previously added alternative line info and smaller than the +// file size; otherwise the information is ignored. +// +// AddLineInfo is typically used to register alternative position +// information for //line filename:line comments in source files. +// +func (f *File) AddLineInfo(offset int, filename string, line int) { + f.set.mutex.Lock() + if i := len(f.infos); i == 0 || f.infos[i-1].Offset < offset && offset < f.size { + f.infos = append(f.infos, lineInfo{offset, filename, line}) + } + f.set.mutex.Unlock() +} + +// Pos returns the Pos value for the given file offset; +// the offset must be <= f.Size(). +// f.Pos(f.Offset(p)) == p. +// +func (f *File) Pos(offset int) Pos { + if offset > f.size { + panic("illegal file offset") + } + return Pos(f.base + offset) +} + +// Offset returns the offset for the given file position p; +// p must be a valid Pos value in that file. +// f.Offset(f.Pos(offset)) == offset. +// +func (f *File) Offset(p Pos) int { + if int(p) < f.base || int(p) > f.base+f.size { + panic("illegal Pos value") + } + return int(p) - f.base +} + +// Line returns the line number for the given file position p; +// p must be a Pos value in that file or NoPos. +// +func (f *File) Line(p Pos) int { + // TODO(gri) this can be implemented much more efficiently + return f.Position(p).Line +} + +func searchLineInfos(a []lineInfo, x int) int { + return sort.Search(len(a), func(i int) bool { return a[i].Offset > x }) - 1 +} + +// info returns the file name, line, and column number for a file offset. +func (f *File) info(offset int) (filename string, line, column int) { + filename = f.name + if i := searchInts(f.lines, offset); i >= 0 { + line, column = i+1, offset-f.lines[i]+1 + } + if len(f.infos) > 0 { + // almost no files have extra line infos + if i := searchLineInfos(f.infos, offset); i >= 0 { + alt := &f.infos[i] + filename = alt.Filename + if i := searchInts(f.lines, alt.Offset); i >= 0 { + line += alt.Line - i - 1 + } + } + } + return +} + +func (f *File) position(p Pos) (pos Position) { + offset := int(p) - f.base + pos.Offset = offset + pos.Filename, pos.Line, pos.Column = f.info(offset) + return +} + +// Position returns the Position value for the given file position p; +// p must be a Pos value in that file or NoPos. +// +func (f *File) Position(p Pos) (pos Position) { + if p != NoPos { + if int(p) < f.base || int(p) > f.base+f.size { + panic("illegal Pos value") + } + pos = f.position(p) + } + return +} + +// ----------------------------------------------------------------------------- +// FileSet + +// A FileSet represents a set of source files. +// Methods of file sets are synchronized; multiple goroutines +// may invoke them concurrently. +// +type FileSet struct { + mutex sync.RWMutex // protects the file set + base int // base offset for the next file + files []*File // list of files in the order added to the set + last *File // cache of last file looked up +} + +// NewFileSet creates a new file set. +func NewFileSet() *FileSet { + s := new(FileSet) + s.base = 1 // 0 == NoPos + return s +} + +// Base returns the minimum base offset that must be provided to +// AddFile when adding the next file. +// +func (s *FileSet) Base() int { + s.mutex.RLock() + b := s.base + s.mutex.RUnlock() + return b + +} + +// AddFile adds a new file with a given filename, base offset, and file size +// to the file set s and returns the file. Multiple files may have the same +// name. The base offset must not be smaller than the FileSet's Base(), and +// size must not be negative. +// +// Adding the file will set the file set's Base() value to base + size + 1 +// as the minimum base value for the next file. The following relationship +// exists between a Pos value p for a given file offset offs: +// +// int(p) = base + offs +// +// with offs in the range [0, size] and thus p in the range [base, base+size]. +// For convenience, File.Pos may be used to create file-specific position +// values from a file offset. +// +func (s *FileSet) AddFile(filename string, base, size int) *File { + s.mutex.Lock() + defer s.mutex.Unlock() + if base < s.base || size < 0 { + panic("illegal base or size") + } + // base >= s.base && size >= 0 + f := &File{s, filename, base, size, []int{0}, nil} + base += size + 1 // +1 because EOF also has a position + if base < 0 { + panic("token.Pos offset overflow (> 2G of source code in file set)") + } + // add the file to the file set + s.base = base + s.files = append(s.files, f) + s.last = f + return f +} + +// Iterate calls f for the files in the file set in the order they were added +// until f returns false. +// +func (s *FileSet) Iterate(f func(*File) bool) { + for i := 0; ; i++ { + var file *File + s.mutex.RLock() + if i < len(s.files) { + file = s.files[i] + } + s.mutex.RUnlock() + if file == nil || !f(file) { + break + } + } +} + +func searchFiles(a []*File, x int) int { + return sort.Search(len(a), func(i int) bool { return a[i].base > x }) - 1 +} + +func (s *FileSet) file(p Pos) *File { + // common case: p is in last file + if f := s.last; f != nil && f.base <= int(p) && int(p) <= f.base+f.size { + return f + } + // p is not in last file - search all files + if i := searchFiles(s.files, int(p)); i >= 0 { + f := s.files[i] + // f.base <= int(p) by definition of searchFiles + if int(p) <= f.base+f.size { + s.last = f + return f + } + } + return nil +} + +// File returns the file that contains the position p. +// If no such file is found (for instance for p == NoPos), +// the result is nil. +// +func (s *FileSet) File(p Pos) (f *File) { + if p != NoPos { + s.mutex.RLock() + f = s.file(p) + s.mutex.RUnlock() + } + return +} + +// Position converts a Pos in the fileset into a general Position. +func (s *FileSet) Position(p Pos) (pos Position) { + if p != NoPos { + s.mutex.RLock() + if f := s.file(p); f != nil { + pos = f.position(p) + } + s.mutex.RUnlock() + } + return +} + +// ----------------------------------------------------------------------------- +// Helper functions + +func searchInts(a []int, x int) int { + // This function body is a manually inlined version of: + // + // return sort.Search(len(a), func(i int) bool { return a[i] > x }) - 1 + // + // With better compiler optimizations, this may not be needed in the + // future, but at the moment this change improves the go/printer + // benchmark performance by ~30%. This has a direct impact on the + // speed of gofmt and thus seems worthwhile (2011-04-29). + // TODO(gri): Remove this when compilers have caught up. + i, j := 0, len(a) + for i < j { + h := i + (j-i)/2 // avoid overflow when computing h + // i ≤ h < j + if a[h] <= x { + i = h + 1 + } else { + j = h + } + } + return i - 1 +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/token/position_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/token/position_test.go new file mode 100644 index 0000000..160107d --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/token/position_test.go @@ -0,0 +1,181 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package token + +import ( + "fmt" + "testing" +) + +func checkPos(t *testing.T, msg string, p, q Position) { + if p.Filename != q.Filename { + t.Errorf("%s: expected filename = %q; got %q", msg, q.Filename, p.Filename) + } + if p.Offset != q.Offset { + t.Errorf("%s: expected offset = %d; got %d", msg, q.Offset, p.Offset) + } + if p.Line != q.Line { + t.Errorf("%s: expected line = %d; got %d", msg, q.Line, p.Line) + } + if p.Column != q.Column { + t.Errorf("%s: expected column = %d; got %d", msg, q.Column, p.Column) + } +} + +func TestNoPos(t *testing.T) { + if NoPos.IsValid() { + t.Errorf("NoPos should not be valid") + } + var fset *FileSet + checkPos(t, "nil NoPos", fset.Position(NoPos), Position{}) + fset = NewFileSet() + checkPos(t, "fset NoPos", fset.Position(NoPos), Position{}) +} + +var tests = []struct { + filename string + source []byte // may be nil + size int + lines []int +}{ + {"a", []byte{}, 0, []int{}}, + {"b", []byte("01234"), 5, []int{0}}, + {"c", []byte("\n\n\n\n\n\n\n\n\n"), 9, []int{0, 1, 2, 3, 4, 5, 6, 7, 8}}, + {"d", nil, 100, []int{0, 5, 10, 20, 30, 70, 71, 72, 80, 85, 90, 99}}, + {"e", nil, 777, []int{0, 80, 100, 120, 130, 180, 267, 455, 500, 567, 620}}, + {"f", []byte("package p\n\nimport \"fmt\""), 23, []int{0, 10, 11}}, + {"g", []byte("package p\n\nimport \"fmt\"\n"), 24, []int{0, 10, 11}}, + {"h", []byte("package p\n\nimport \"fmt\"\n "), 25, []int{0, 10, 11, 24}}, +} + +func linecol(lines []int, offs int) (int, int) { + prevLineOffs := 0 + for line, lineOffs := range lines { + if offs < lineOffs { + return line, offs - prevLineOffs + 1 + } + prevLineOffs = lineOffs + } + return len(lines), offs - prevLineOffs + 1 +} + +func verifyPositions(t *testing.T, fset *FileSet, f *File, lines []int) { + for offs := 0; offs < f.Size(); offs++ { + p := f.Pos(offs) + offs2 := f.Offset(p) + if offs2 != offs { + t.Errorf("%s, Offset: expected offset %d; got %d", f.Name(), offs, offs2) + } + line, col := linecol(lines, offs) + msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) + checkPos(t, msg, f.Position(f.Pos(offs)), Position{f.Name(), offs, line, col}) + checkPos(t, msg, fset.Position(p), Position{f.Name(), offs, line, col}) + } +} + +func makeTestSource(size int, lines []int) []byte { + src := make([]byte, size) + for _, offs := range lines { + if offs > 0 { + src[offs-1] = '\n' + } + } + return src +} + +func TestPositions(t *testing.T) { + const delta = 7 // a non-zero base offset increment + fset := NewFileSet() + for _, test := range tests { + // verify consistency of test case + if test.source != nil && len(test.source) != test.size { + t.Errorf("%s: inconsistent test case: expected file size %d; got %d", test.filename, test.size, len(test.source)) + } + + // add file and verify name and size + f := fset.AddFile(test.filename, fset.Base()+delta, test.size) + if f.Name() != test.filename { + t.Errorf("expected filename %q; got %q", test.filename, f.Name()) + } + if f.Size() != test.size { + t.Errorf("%s: expected file size %d; got %d", f.Name(), test.size, f.Size()) + } + if fset.File(f.Pos(0)) != f { + t.Errorf("%s: f.Pos(0) was not found in f", f.Name()) + } + + // add lines individually and verify all positions + for i, offset := range test.lines { + f.AddLine(offset) + if f.LineCount() != i+1 { + t.Errorf("%s, AddLine: expected line count %d; got %d", f.Name(), i+1, f.LineCount()) + } + // adding the same offset again should be ignored + f.AddLine(offset) + if f.LineCount() != i+1 { + t.Errorf("%s, AddLine: expected unchanged line count %d; got %d", f.Name(), i+1, f.LineCount()) + } + verifyPositions(t, fset, f, test.lines[0:i+1]) + } + + // add lines with SetLines and verify all positions + if ok := f.SetLines(test.lines); !ok { + t.Errorf("%s: SetLines failed", f.Name()) + } + if f.LineCount() != len(test.lines) { + t.Errorf("%s, SetLines: expected line count %d; got %d", f.Name(), len(test.lines), f.LineCount()) + } + verifyPositions(t, fset, f, test.lines) + + // add lines with SetLinesForContent and verify all positions + src := test.source + if src == nil { + // no test source available - create one from scratch + src = makeTestSource(test.size, test.lines) + } + f.SetLinesForContent(src) + if f.LineCount() != len(test.lines) { + t.Errorf("%s, SetLinesForContent: expected line count %d; got %d", f.Name(), len(test.lines), f.LineCount()) + } + verifyPositions(t, fset, f, test.lines) + } +} + +func TestLineInfo(t *testing.T) { + fset := NewFileSet() + f := fset.AddFile("foo", fset.Base(), 500) + lines := []int{0, 42, 77, 100, 210, 220, 277, 300, 333, 401} + // add lines individually and provide alternative line information + for _, offs := range lines { + f.AddLine(offs) + f.AddLineInfo(offs, "bar", 42) + } + // verify positions for all offsets + for offs := 0; offs <= f.Size(); offs++ { + p := f.Pos(offs) + _, col := linecol(lines, offs) + msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) + checkPos(t, msg, f.Position(f.Pos(offs)), Position{"bar", offs, 42, col}) + checkPos(t, msg, fset.Position(p), Position{"bar", offs, 42, col}) + } +} + +func TestFiles(t *testing.T) { + fset := NewFileSet() + for i, test := range tests { + fset.AddFile(test.filename, fset.Base(), test.size) + j := 0 + fset.Iterate(func(f *File) bool { + if f.Name() != tests[j].filename { + t.Errorf("expected filename = %s; got %s", tests[j].filename, f.Name()) + } + j++ + return true + }) + if j != i+1 { + t.Errorf("expected %d files; got %d", i+1, j) + } + } +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize.go b/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize.go new file mode 100644 index 0000000..4adc8f9 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize.go @@ -0,0 +1,56 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package token + +type serializedFile struct { + // fields correspond 1:1 to fields with same (lower-case) name in File + Name string + Base int + Size int + Lines []int + Infos []lineInfo +} + +type serializedFileSet struct { + Base int + Files []serializedFile +} + +// Read calls decode to deserialize a file set into s; s must not be nil. +func (s *FileSet) Read(decode func(interface{}) error) error { + var ss serializedFileSet + if err := decode(&ss); err != nil { + return err + } + + s.mutex.Lock() + s.base = ss.Base + files := make([]*File, len(ss.Files)) + for i := 0; i < len(ss.Files); i++ { + f := &ss.Files[i] + files[i] = &File{s, f.Name, f.Base, f.Size, f.Lines, f.Infos} + } + s.files = files + s.last = nil + s.mutex.Unlock() + + return nil +} + +// Write calls encode to serialize the file set s. +func (s *FileSet) Write(encode func(interface{}) error) error { + var ss serializedFileSet + + s.mutex.Lock() + ss.Base = s.base + files := make([]serializedFile, len(s.files)) + for i, f := range s.files { + files[i] = serializedFile{f.name, f.base, f.size, f.lines, f.infos} + } + ss.Files = files + s.mutex.Unlock() + + return encode(ss) +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize_test.go new file mode 100644 index 0000000..4e925ad --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize_test.go @@ -0,0 +1,111 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package token + +import ( + "bytes" + "encoding/gob" + "fmt" + "testing" +) + +// equal returns nil if p and q describe the same file set; +// otherwise it returns an error describing the discrepancy. +func equal(p, q *FileSet) error { + if p == q { + // avoid deadlock if p == q + return nil + } + + // not strictly needed for the test + p.mutex.Lock() + q.mutex.Lock() + defer q.mutex.Unlock() + defer p.mutex.Unlock() + + if p.base != q.base { + return fmt.Errorf("different bases: %d != %d", p.base, q.base) + } + + if len(p.files) != len(q.files) { + return fmt.Errorf("different number of files: %d != %d", len(p.files), len(q.files)) + } + + for i, f := range p.files { + g := q.files[i] + if f.set != p { + return fmt.Errorf("wrong fileset for %q", f.name) + } + if g.set != q { + return fmt.Errorf("wrong fileset for %q", g.name) + } + if f.name != g.name { + return fmt.Errorf("different filenames: %q != %q", f.name, g.name) + } + if f.base != g.base { + return fmt.Errorf("different base for %q: %d != %d", f.name, f.base, g.base) + } + if f.size != g.size { + return fmt.Errorf("different size for %q: %d != %d", f.name, f.size, g.size) + } + for j, l := range f.lines { + m := g.lines[j] + if l != m { + return fmt.Errorf("different offsets for %q", f.name) + } + } + for j, l := range f.infos { + m := g.infos[j] + if l.Offset != m.Offset || l.Filename != m.Filename || l.Line != m.Line { + return fmt.Errorf("different infos for %q", f.name) + } + } + } + + // we don't care about .last - it's just a cache + return nil +} + +func checkSerialize(t *testing.T, p *FileSet) { + var buf bytes.Buffer + encode := func(x interface{}) error { + return gob.NewEncoder(&buf).Encode(x) + } + if err := p.Write(encode); err != nil { + t.Errorf("writing fileset failed: %s", err) + return + } + q := NewFileSet() + decode := func(x interface{}) error { + return gob.NewDecoder(&buf).Decode(x) + } + if err := q.Read(decode); err != nil { + t.Errorf("reading fileset failed: %s", err) + return + } + if err := equal(p, q); err != nil { + t.Errorf("filesets not identical: %s", err) + } +} + +func TestSerialization(t *testing.T) { + p := NewFileSet() + checkSerialize(t, p) + // add some files + for i := 0; i < 10; i++ { + f := p.AddFile(fmt.Sprintf("file%d", i), p.Base()+i, i*100) + checkSerialize(t, p) + // add some lines and alternative file infos + line := 1000 + for offs := 0; offs < f.Size(); offs += 40 + i { + f.AddLine(offs) + if offs%7 == 0 { + f.AddLineInfo(offs, fmt.Sprintf("file%d", offs), line) + line += 33 + } + } + checkSerialize(t, p) + } +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/token/token.go b/Godeps/_workspace/src/code.google.com/p/gcfg/token/token.go new file mode 100644 index 0000000..b3c7c83 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/token/token.go @@ -0,0 +1,83 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package token defines constants representing the lexical tokens of the gcfg +// configuration syntax and basic operations on tokens (printing, predicates). +// +// Note that the API for the token package may change to accommodate new +// features or implementation changes in gcfg. +// +package token + +import "strconv" + +// Token is the set of lexical tokens of the gcfg configuration syntax. +type Token int + +// The list of tokens. +const ( + // Special tokens + ILLEGAL Token = iota + EOF + COMMENT + + literal_beg + // Identifiers and basic type literals + // (these tokens stand for classes of literals) + IDENT // section-name, variable-name + STRING // "subsection-name", variable value + literal_end + + operator_beg + // Operators and delimiters + ASSIGN // = + LBRACK // [ + RBRACK // ] + EOL // \n + operator_end +) + +var tokens = [...]string{ + ILLEGAL: "ILLEGAL", + + EOF: "EOF", + COMMENT: "COMMENT", + + IDENT: "IDENT", + STRING: "STRING", + + ASSIGN: "=", + LBRACK: "[", + RBRACK: "]", + EOL: "\n", +} + +// String returns the string corresponding to the token tok. +// For operators and delimiters, the string is the actual token character +// sequence (e.g., for the token ASSIGN, the string is "="). For all other +// tokens the string corresponds to the token constant name (e.g. for the +// token IDENT, the string is "IDENT"). +// +func (tok Token) String() string { + s := "" + if 0 <= tok && tok < Token(len(tokens)) { + s = tokens[tok] + } + if s == "" { + s = "token(" + strconv.Itoa(int(tok)) + ")" + } + return s +} + +// Predicates + +// IsLiteral returns true for tokens corresponding to identifiers +// and basic type literals; it returns false otherwise. +// +func (tok Token) IsLiteral() bool { return literal_beg < tok && tok < literal_end } + +// IsOperator returns true for tokens corresponding to operators and +// delimiters; it returns false otherwise. +// +func (tok Token) IsOperator() bool { return operator_beg < tok && tok < operator_end } diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/bool.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/bool.go new file mode 100644 index 0000000..8dcae0d --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/types/bool.go @@ -0,0 +1,23 @@ +package types + +// BoolValues defines the name and value mappings for ParseBool. +var BoolValues = map[string]interface{}{ + "true": true, "yes": true, "on": true, "1": true, + "false": false, "no": false, "off": false, "0": false, +} + +var boolParser = func() *EnumParser { + ep := &EnumParser{} + ep.AddVals(BoolValues) + return ep +}() + +// ParseBool parses bool values according to the definitions in BoolValues. +// Parsing is case-insensitive. +func ParseBool(s string) (bool, error) { + v, err := boolParser.Parse(s) + if err != nil { + return false, err + } + return v.(bool), nil +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/doc.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/doc.go new file mode 100644 index 0000000..9f9c345 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/types/doc.go @@ -0,0 +1,4 @@ +// Package types defines helpers for type conversions. +// +// The API for this package is not finalized yet. +package types diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum.go new file mode 100644 index 0000000..1a0c7ef --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum.go @@ -0,0 +1,44 @@ +package types + +import ( + "fmt" + "reflect" + "strings" +) + +// EnumParser parses "enum" values; i.e. a predefined set of strings to +// predefined values. +type EnumParser struct { + Type string // type name; if not set, use type of first value added + CaseMatch bool // if true, matching of strings is case-sensitive + // PrefixMatch bool + vals map[string]interface{} +} + +// AddVals adds strings and values to an EnumParser. +func (ep *EnumParser) AddVals(vals map[string]interface{}) { + if ep.vals == nil { + ep.vals = make(map[string]interface{}) + } + for k, v := range vals { + if ep.Type == "" { + ep.Type = reflect.TypeOf(v).Name() + } + if !ep.CaseMatch { + k = strings.ToLower(k) + } + ep.vals[k] = v + } +} + +// Parse parses the string and returns the value or an error. +func (ep EnumParser) Parse(s string) (interface{}, error) { + if !ep.CaseMatch { + s = strings.ToLower(s) + } + v, ok := ep.vals[s] + if !ok { + return false, fmt.Errorf("failed to parse %s %#q", ep.Type, s) + } + return v, nil +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum_test.go new file mode 100644 index 0000000..4bf135e --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum_test.go @@ -0,0 +1,29 @@ +package types + +import ( + "testing" +) + +func TestEnumParserBool(t *testing.T) { + for _, tt := range []struct { + val string + res bool + ok bool + }{ + {val: "tRuE", res: true, ok: true}, + {val: "False", res: false, ok: true}, + {val: "t", ok: false}, + } { + b, err := ParseBool(tt.val) + switch { + case tt.ok && err != nil: + t.Errorf("%q: got error %v, want %v", tt.val, err, tt.res) + case !tt.ok && err == nil: + t.Errorf("%q: got %v, want error", tt.val, b) + case tt.ok && b != tt.res: + t.Errorf("%q: got %v, want %v", tt.val, b, tt.res) + default: + t.Logf("%q: got %v, %v", tt.val, b, err) + } + } +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/int.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/int.go new file mode 100644 index 0000000..af7e75c --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/types/int.go @@ -0,0 +1,86 @@ +package types + +import ( + "fmt" + "strings" +) + +// An IntMode is a mode for parsing integer values, representing a set of +// accepted bases. +type IntMode uint8 + +// IntMode values for ParseInt; can be combined using binary or. +const ( + Dec IntMode = 1 << iota + Hex + Oct +) + +// String returns a string representation of IntMode; e.g. `IntMode(Dec|Hex)`. +func (m IntMode) String() string { + var modes []string + if m&Dec != 0 { + modes = append(modes, "Dec") + } + if m&Hex != 0 { + modes = append(modes, "Hex") + } + if m&Oct != 0 { + modes = append(modes, "Oct") + } + return "IntMode(" + strings.Join(modes, "|") + ")" +} + +var errIntAmbig = fmt.Errorf("ambiguous integer value; must include '0' prefix") + +func prefix0(val string) bool { + return strings.HasPrefix(val, "0") || strings.HasPrefix(val, "-0") +} + +func prefix0x(val string) bool { + return strings.HasPrefix(val, "0x") || strings.HasPrefix(val, "-0x") +} + +// ParseInt parses val using mode into intptr, which must be a pointer to an +// integer kind type. Non-decimal value require prefix `0` or `0x` in the cases +// when mode permits ambiguity of base; otherwise the prefix can be omitted. +func ParseInt(intptr interface{}, val string, mode IntMode) error { + val = strings.TrimSpace(val) + verb := byte(0) + switch mode { + case Dec: + verb = 'd' + case Dec + Hex: + if prefix0x(val) { + verb = 'v' + } else { + verb = 'd' + } + case Dec + Oct: + if prefix0(val) && !prefix0x(val) { + verb = 'v' + } else { + verb = 'd' + } + case Dec + Hex + Oct: + verb = 'v' + case Hex: + if prefix0x(val) { + verb = 'v' + } else { + verb = 'x' + } + case Oct: + verb = 'o' + case Hex + Oct: + if prefix0(val) { + verb = 'v' + } else { + return errIntAmbig + } + } + if verb == 0 { + panic("unsupported mode") + } + return ScanFully(intptr, val, verb) +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/int_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/int_test.go new file mode 100644 index 0000000..b63dbcb --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/types/int_test.go @@ -0,0 +1,67 @@ +package types + +import ( + "reflect" + "testing" +) + +func elem(p interface{}) interface{} { + return reflect.ValueOf(p).Elem().Interface() +} + +func TestParseInt(t *testing.T) { + for _, tt := range []struct { + val string + mode IntMode + exp interface{} + ok bool + }{ + {"0", Dec, int(0), true}, + {"10", Dec, int(10), true}, + {"-10", Dec, int(-10), true}, + {"x", Dec, int(0), false}, + {"0xa", Hex, int(0xa), true}, + {"a", Hex, int(0xa), true}, + {"10", Hex, int(0x10), true}, + {"-0xa", Hex, int(-0xa), true}, + {"0x", Hex, int(0x0), true}, // Scanf doesn't require digit behind 0x + {"-0x", Hex, int(0x0), true}, // Scanf doesn't require digit behind 0x + {"-a", Hex, int(-0xa), true}, + {"-10", Hex, int(-0x10), true}, + {"x", Hex, int(0), false}, + {"10", Oct, int(010), true}, + {"010", Oct, int(010), true}, + {"-10", Oct, int(-010), true}, + {"-010", Oct, int(-010), true}, + {"10", Dec | Hex, int(10), true}, + {"010", Dec | Hex, int(10), true}, + {"0x10", Dec | Hex, int(0x10), true}, + {"10", Dec | Oct, int(10), true}, + {"010", Dec | Oct, int(010), true}, + {"0x10", Dec | Oct, int(0), false}, + {"10", Hex | Oct, int(0), false}, // need prefix to distinguish Hex/Oct + {"010", Hex | Oct, int(010), true}, + {"0x10", Hex | Oct, int(0x10), true}, + {"10", Dec | Hex | Oct, int(10), true}, + {"010", Dec | Hex | Oct, int(010), true}, + {"0x10", Dec | Hex | Oct, int(0x10), true}, + } { + typ := reflect.TypeOf(tt.exp) + res := reflect.New(typ).Interface() + err := ParseInt(res, tt.val, tt.mode) + switch { + case tt.ok && err != nil: + t.Errorf("ParseInt(%v, %#v, %v): fail; got error %v, want ok", + typ, tt.val, tt.mode, err) + case !tt.ok && err == nil: + t.Errorf("ParseInt(%v, %#v, %v): fail; got %v, want error", + typ, tt.val, tt.mode, elem(res)) + case tt.ok && !reflect.DeepEqual(elem(res), tt.exp): + t.Errorf("ParseInt(%v, %#v, %v): fail; got %v, want %v", + typ, tt.val, tt.mode, elem(res), tt.exp) + default: + t.Logf("ParseInt(%v, %#v, %s): pass; got %v, error %v", + typ, tt.val, tt.mode, elem(res), err) + } + } +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan.go new file mode 100644 index 0000000..db2f6ed --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan.go @@ -0,0 +1,23 @@ +package types + +import ( + "fmt" + "io" + "reflect" +) + +// ScanFully uses fmt.Sscanf with verb to fully scan val into ptr. +func ScanFully(ptr interface{}, val string, verb byte) error { + t := reflect.ValueOf(ptr).Elem().Type() + // attempt to read extra bytes to make sure the value is consumed + var b []byte + n, err := fmt.Sscanf(val, "%"+string(verb)+"%s", ptr, &b) + switch { + case n < 1 || n == 1 && err != io.EOF: + return fmt.Errorf("failed to parse %q as %v: %v", val, t, err) + case n > 1: + return fmt.Errorf("failed to parse %q as %v: extra characters %q", val, t, string(b)) + } + // n == 1 && err == io.EOF + return nil +} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan_test.go new file mode 100644 index 0000000..a8083e0 --- /dev/null +++ b/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan_test.go @@ -0,0 +1,36 @@ +package types + +import ( + "reflect" + "testing" +) + +func TestScanFully(t *testing.T) { + for _, tt := range []struct { + val string + verb byte + res interface{} + ok bool + }{ + {"a", 'v', int(0), false}, + {"0x", 'v', int(0), true}, + {"0x", 'd', int(0), false}, + } { + d := reflect.New(reflect.TypeOf(tt.res)).Interface() + err := ScanFully(d, tt.val, tt.verb) + switch { + case tt.ok && err != nil: + t.Errorf("ScanFully(%T, %q, '%c'): want ok, got error %v", + d, tt.val, tt.verb, err) + case !tt.ok && err == nil: + t.Errorf("ScanFully(%T, %q, '%c'): want error, got %v", + d, tt.val, tt.verb, elem(d)) + case tt.ok && err == nil && !reflect.DeepEqual(tt.res, elem(d)): + t.Errorf("ScanFully(%T, %q, '%c'): want %v, got %v", + d, tt.val, tt.verb, tt.res, elem(d)) + default: + t.Logf("ScanFully(%T, %q, '%c') = %v; *ptr==%v", + d, tt.val, tt.verb, err, elem(d)) + } + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile new file mode 100644 index 0000000..f1f0656 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile @@ -0,0 +1,43 @@ +# Go support for Protocol Buffers - Google's data interchange format +# +# Copyright 2010 The Go Authors. All rights reserved. +# https://github.com/golang/protobuf +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +install: + go install + +test: install generate-test-pbs + go test + + +generate-test-pbs: + make install + make -C testdata + protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata:. proto3_proto/proto3.proto + make diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go new file mode 100644 index 0000000..5a9b6a4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go @@ -0,0 +1,2083 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto_test + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "math" + "math/rand" + "reflect" + "runtime/debug" + "strings" + "testing" + "time" + + . "github.com/golang/protobuf/proto" + . "github.com/golang/protobuf/proto/testdata" +) + +var globalO *Buffer + +func old() *Buffer { + if globalO == nil { + globalO = NewBuffer(nil) + } + globalO.Reset() + return globalO +} + +func equalbytes(b1, b2 []byte, t *testing.T) { + if len(b1) != len(b2) { + t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) + return + } + for i := 0; i < len(b1); i++ { + if b1[i] != b2[i] { + t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) + } + } +} + +func initGoTestField() *GoTestField { + f := new(GoTestField) + f.Label = String("label") + f.Type = String("type") + return f +} + +// These are all structurally equivalent but the tag numbers differ. +// (It's remarkable that required, optional, and repeated all have +// 8 letters.) +func initGoTest_RequiredGroup() *GoTest_RequiredGroup { + return &GoTest_RequiredGroup{ + RequiredField: String("required"), + } +} + +func initGoTest_OptionalGroup() *GoTest_OptionalGroup { + return &GoTest_OptionalGroup{ + RequiredField: String("optional"), + } +} + +func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { + return &GoTest_RepeatedGroup{ + RequiredField: String("repeated"), + } +} + +func initGoTest(setdefaults bool) *GoTest { + pb := new(GoTest) + if setdefaults { + pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) + pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) + pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) + pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) + pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) + pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) + pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) + pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) + pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) + pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) + pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted + pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) + pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) + } + + pb.Kind = GoTest_TIME.Enum() + pb.RequiredField = initGoTestField() + pb.F_BoolRequired = Bool(true) + pb.F_Int32Required = Int32(3) + pb.F_Int64Required = Int64(6) + pb.F_Fixed32Required = Uint32(32) + pb.F_Fixed64Required = Uint64(64) + pb.F_Uint32Required = Uint32(3232) + pb.F_Uint64Required = Uint64(6464) + pb.F_FloatRequired = Float32(3232) + pb.F_DoubleRequired = Float64(6464) + pb.F_StringRequired = String("string") + pb.F_BytesRequired = []byte("bytes") + pb.F_Sint32Required = Int32(-32) + pb.F_Sint64Required = Int64(-64) + pb.Requiredgroup = initGoTest_RequiredGroup() + + return pb +} + +func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { + data := b.Bytes() + ld := len(data) + ls := len(s) / 2 + + fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) + + // find the interesting spot - n + n := ls + if ld < ls { + n = ld + } + j := 0 + for i := 0; i < n; i++ { + bs := hex(s[j])*16 + hex(s[j+1]) + j += 2 + if data[i] == bs { + continue + } + n = i + break + } + l := n - 10 + if l < 0 { + l = 0 + } + h := n + 10 + + // find the interesting spot - n + fmt.Printf("is[%d]:", l) + for i := l; i < h; i++ { + if i >= ld { + fmt.Printf(" --") + continue + } + fmt.Printf(" %.2x", data[i]) + } + fmt.Printf("\n") + + fmt.Printf("sb[%d]:", l) + for i := l; i < h; i++ { + if i >= ls { + fmt.Printf(" --") + continue + } + bs := hex(s[j])*16 + hex(s[j+1]) + j += 2 + fmt.Printf(" %.2x", bs) + } + fmt.Printf("\n") + + t.Fail() + + // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) + // Print the output in a partially-decoded format; can + // be helpful when updating the test. It produces the output + // that is pasted, with minor edits, into the argument to verify(). + // data := b.Bytes() + // nesting := 0 + // for b.Len() > 0 { + // start := len(data) - b.Len() + // var u uint64 + // u, err := DecodeVarint(b) + // if err != nil { + // fmt.Printf("decode error on varint:", err) + // return + // } + // wire := u & 0x7 + // tag := u >> 3 + // switch wire { + // case WireVarint: + // v, err := DecodeVarint(b) + // if err != nil { + // fmt.Printf("decode error on varint:", err) + // return + // } + // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", + // data[start:len(data)-b.Len()], tag, wire, v) + // case WireFixed32: + // v, err := DecodeFixed32(b) + // if err != nil { + // fmt.Printf("decode error on fixed32:", err) + // return + // } + // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", + // data[start:len(data)-b.Len()], tag, wire, v) + // case WireFixed64: + // v, err := DecodeFixed64(b) + // if err != nil { + // fmt.Printf("decode error on fixed64:", err) + // return + // } + // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", + // data[start:len(data)-b.Len()], tag, wire, v) + // case WireBytes: + // nb, err := DecodeVarint(b) + // if err != nil { + // fmt.Printf("decode error on bytes:", err) + // return + // } + // after_tag := len(data) - b.Len() + // str := make([]byte, nb) + // _, err = b.Read(str) + // if err != nil { + // fmt.Printf("decode error on bytes:", err) + // return + // } + // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", + // data[start:after_tag], str, tag, wire) + // case WireStartGroup: + // nesting++ + // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", + // data[start:len(data)-b.Len()], tag, nesting) + // case WireEndGroup: + // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", + // data[start:len(data)-b.Len()], tag, nesting) + // nesting-- + // default: + // fmt.Printf("unrecognized wire type %d\n", wire) + // return + // } + // } +} + +func hex(c uint8) uint8 { + if '0' <= c && c <= '9' { + return c - '0' + } + if 'a' <= c && c <= 'f' { + return 10 + c - 'a' + } + if 'A' <= c && c <= 'F' { + return 10 + c - 'A' + } + return 0 +} + +func equal(b []byte, s string, t *testing.T) bool { + if 2*len(b) != len(s) { + // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) + fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) + return false + } + for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { + x := hex(s[j])*16 + hex(s[j+1]) + if b[i] != x { + // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) + fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) + return false + } + } + return true +} + +func overify(t *testing.T, pb *GoTest, expected string) { + o := old() + err := o.Marshal(pb) + if err != nil { + fmt.Printf("overify marshal-1 err = %v", err) + o.DebugPrint("", o.Bytes()) + t.Fatalf("expected = %s", expected) + } + if !equal(o.Bytes(), expected, t) { + o.DebugPrint("overify neq 1", o.Bytes()) + t.Fatalf("expected = %s", expected) + } + + // Now test Unmarshal by recreating the original buffer. + pbd := new(GoTest) + err = o.Unmarshal(pbd) + if err != nil { + t.Fatalf("overify unmarshal err = %v", err) + o.DebugPrint("", o.Bytes()) + t.Fatalf("string = %s", expected) + } + o.Reset() + err = o.Marshal(pbd) + if err != nil { + t.Errorf("overify marshal-2 err = %v", err) + o.DebugPrint("", o.Bytes()) + t.Fatalf("string = %s", expected) + } + if !equal(o.Bytes(), expected, t) { + o.DebugPrint("overify neq 2", o.Bytes()) + t.Fatalf("string = %s", expected) + } +} + +// Simple tests for numeric encode/decode primitives (varint, etc.) +func TestNumericPrimitives(t *testing.T) { + for i := uint64(0); i < 1e6; i += 111 { + o := old() + if o.EncodeVarint(i) != nil { + t.Error("EncodeVarint") + break + } + x, e := o.DecodeVarint() + if e != nil { + t.Fatal("DecodeVarint") + } + if x != i { + t.Fatal("varint decode fail:", i, x) + } + + o = old() + if o.EncodeFixed32(i) != nil { + t.Fatal("encFixed32") + } + x, e = o.DecodeFixed32() + if e != nil { + t.Fatal("decFixed32") + } + if x != i { + t.Fatal("fixed32 decode fail:", i, x) + } + + o = old() + if o.EncodeFixed64(i*1234567) != nil { + t.Error("encFixed64") + break + } + x, e = o.DecodeFixed64() + if e != nil { + t.Error("decFixed64") + break + } + if x != i*1234567 { + t.Error("fixed64 decode fail:", i*1234567, x) + break + } + + o = old() + i32 := int32(i - 12345) + if o.EncodeZigzag32(uint64(i32)) != nil { + t.Fatal("EncodeZigzag32") + } + x, e = o.DecodeZigzag32() + if e != nil { + t.Fatal("DecodeZigzag32") + } + if x != uint64(uint32(i32)) { + t.Fatal("zigzag32 decode fail:", i32, x) + } + + o = old() + i64 := int64(i - 12345) + if o.EncodeZigzag64(uint64(i64)) != nil { + t.Fatal("EncodeZigzag64") + } + x, e = o.DecodeZigzag64() + if e != nil { + t.Fatal("DecodeZigzag64") + } + if x != uint64(i64) { + t.Fatal("zigzag64 decode fail:", i64, x) + } + } +} + +// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. +type fakeMarshaler struct { + b []byte + err error +} + +func (f fakeMarshaler) Marshal() ([]byte, error) { + return f.b, f.err +} + +func (f fakeMarshaler) String() string { + return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) +} + +func (f fakeMarshaler) ProtoMessage() {} + +func (f fakeMarshaler) Reset() {} + +// Simple tests for proto messages that implement the Marshaler interface. +func TestMarshalerEncoding(t *testing.T) { + tests := []struct { + name string + m Message + want []byte + wantErr error + }{ + { + name: "Marshaler that fails", + m: fakeMarshaler{ + err: errors.New("some marshal err"), + b: []byte{5, 6, 7}, + }, + // Since there's an error, nothing should be written to buffer. + want: nil, + wantErr: errors.New("some marshal err"), + }, + { + name: "Marshaler that succeeds", + m: fakeMarshaler{ + b: []byte{0, 1, 2, 3, 4, 127, 255}, + }, + want: []byte{0, 1, 2, 3, 4, 127, 255}, + wantErr: nil, + }, + } + for _, test := range tests { + b := NewBuffer(nil) + err := b.Marshal(test.m) + if !reflect.DeepEqual(test.wantErr, err) { + t.Errorf("%s: got err %v wanted %v", test.name, err, test.wantErr) + } + if !reflect.DeepEqual(test.want, b.Bytes()) { + t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) + } + } +} + +// Simple tests for bytes +func TestBytesPrimitives(t *testing.T) { + o := old() + bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} + if o.EncodeRawBytes(bytes) != nil { + t.Error("EncodeRawBytes") + } + decb, e := o.DecodeRawBytes(false) + if e != nil { + t.Error("DecodeRawBytes") + } + equalbytes(bytes, decb, t) +} + +// Simple tests for strings +func TestStringPrimitives(t *testing.T) { + o := old() + s := "now is the time" + if o.EncodeStringBytes(s) != nil { + t.Error("enc_string") + } + decs, e := o.DecodeStringBytes() + if e != nil { + t.Error("dec_string") + } + if s != decs { + t.Error("string encode/decode fail:", s, decs) + } +} + +// Do we catch the "required bit not set" case? +func TestRequiredBit(t *testing.T) { + o := old() + pb := new(GoTest) + err := o.Marshal(pb) + if err == nil { + t.Error("did not catch missing required fields") + } else if strings.Index(err.Error(), "Kind") < 0 { + t.Error("wrong error type:", err) + } +} + +// Check that all fields are nil. +// Clearly silly, and a residue from a more interesting test with an earlier, +// different initialization property, but it once caught a compiler bug so +// it lives. +func checkInitialized(pb *GoTest, t *testing.T) { + if pb.F_BoolDefaulted != nil { + t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) + } + if pb.F_Int32Defaulted != nil { + t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) + } + if pb.F_Int64Defaulted != nil { + t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) + } + if pb.F_Fixed32Defaulted != nil { + t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) + } + if pb.F_Fixed64Defaulted != nil { + t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) + } + if pb.F_Uint32Defaulted != nil { + t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) + } + if pb.F_Uint64Defaulted != nil { + t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) + } + if pb.F_FloatDefaulted != nil { + t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) + } + if pb.F_DoubleDefaulted != nil { + t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) + } + if pb.F_StringDefaulted != nil { + t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) + } + if pb.F_BytesDefaulted != nil { + t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) + } + if pb.F_Sint32Defaulted != nil { + t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) + } + if pb.F_Sint64Defaulted != nil { + t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) + } +} + +// Does Reset() reset? +func TestReset(t *testing.T) { + pb := initGoTest(true) + // muck with some values + pb.F_BoolDefaulted = Bool(false) + pb.F_Int32Defaulted = Int32(237) + pb.F_Int64Defaulted = Int64(12346) + pb.F_Fixed32Defaulted = Uint32(32000) + pb.F_Fixed64Defaulted = Uint64(666) + pb.F_Uint32Defaulted = Uint32(323232) + pb.F_Uint64Defaulted = nil + pb.F_FloatDefaulted = nil + pb.F_DoubleDefaulted = Float64(0) + pb.F_StringDefaulted = String("gotcha") + pb.F_BytesDefaulted = []byte("asdfasdf") + pb.F_Sint32Defaulted = Int32(123) + pb.F_Sint64Defaulted = Int64(789) + pb.Reset() + checkInitialized(pb, t) +} + +// All required fields set, no defaults provided. +func TestEncodeDecode1(t *testing.T) { + pb := initGoTest(false) + overify(t, pb, + "0807"+ // field 1, encoding 0, value 7 + "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) + "5001"+ // field 10, encoding 0, value 1 + "5803"+ // field 11, encoding 0, value 3 + "6006"+ // field 12, encoding 0, value 6 + "6d20000000"+ // field 13, encoding 5, value 0x20 + "714000000000000000"+ // field 14, encoding 1, value 0x40 + "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 + "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 + "8d0100004a45"+ // field 17, encoding 5, value 3232.0 + "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 + "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" + "b304"+ // field 70, encoding 3, start group + "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" + "b404"+ // field 70, encoding 4, end group + "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" + "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 + "b8067f") // field 103, encoding 0, 0x7f zigzag64 +} + +// All required fields set, defaults provided. +func TestEncodeDecode2(t *testing.T) { + pb := initGoTest(true) + overify(t, pb, + "0807"+ // field 1, encoding 0, value 7 + "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) + "5001"+ // field 10, encoding 0, value 1 + "5803"+ // field 11, encoding 0, value 3 + "6006"+ // field 12, encoding 0, value 6 + "6d20000000"+ // field 13, encoding 5, value 32 + "714000000000000000"+ // field 14, encoding 1, value 64 + "78a019"+ // field 15, encoding 0, value 3232 + "8001c032"+ // field 16, encoding 0, value 6464 + "8d0100004a45"+ // field 17, encoding 5, value 3232.0 + "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 + "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" + "c00201"+ // field 40, encoding 0, value 1 + "c80220"+ // field 41, encoding 0, value 32 + "d00240"+ // field 42, encoding 0, value 64 + "dd0240010000"+ // field 43, encoding 5, value 320 + "e1028002000000000000"+ // field 44, encoding 1, value 640 + "e8028019"+ // field 45, encoding 0, value 3200 + "f0028032"+ // field 46, encoding 0, value 6400 + "fd02e0659948"+ // field 47, encoding 5, value 314159.0 + "81030000000050971041"+ // field 48, encoding 1, value 271828.0 + "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" + "b304"+ // start group field 70 level 1 + "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" + "b404"+ // end group field 70 level 1 + "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" + "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 + "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 + "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" + "90193f"+ // field 402, encoding 0, value 63 + "98197f") // field 403, encoding 0, value 127 + +} + +// All default fields set to their default value by hand +func TestEncodeDecode3(t *testing.T) { + pb := initGoTest(false) + pb.F_BoolDefaulted = Bool(true) + pb.F_Int32Defaulted = Int32(32) + pb.F_Int64Defaulted = Int64(64) + pb.F_Fixed32Defaulted = Uint32(320) + pb.F_Fixed64Defaulted = Uint64(640) + pb.F_Uint32Defaulted = Uint32(3200) + pb.F_Uint64Defaulted = Uint64(6400) + pb.F_FloatDefaulted = Float32(314159) + pb.F_DoubleDefaulted = Float64(271828) + pb.F_StringDefaulted = String("hello, \"world!\"\n") + pb.F_BytesDefaulted = []byte("Bignose") + pb.F_Sint32Defaulted = Int32(-32) + pb.F_Sint64Defaulted = Int64(-64) + + overify(t, pb, + "0807"+ // field 1, encoding 0, value 7 + "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) + "5001"+ // field 10, encoding 0, value 1 + "5803"+ // field 11, encoding 0, value 3 + "6006"+ // field 12, encoding 0, value 6 + "6d20000000"+ // field 13, encoding 5, value 32 + "714000000000000000"+ // field 14, encoding 1, value 64 + "78a019"+ // field 15, encoding 0, value 3232 + "8001c032"+ // field 16, encoding 0, value 6464 + "8d0100004a45"+ // field 17, encoding 5, value 3232.0 + "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 + "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" + "c00201"+ // field 40, encoding 0, value 1 + "c80220"+ // field 41, encoding 0, value 32 + "d00240"+ // field 42, encoding 0, value 64 + "dd0240010000"+ // field 43, encoding 5, value 320 + "e1028002000000000000"+ // field 44, encoding 1, value 640 + "e8028019"+ // field 45, encoding 0, value 3200 + "f0028032"+ // field 46, encoding 0, value 6400 + "fd02e0659948"+ // field 47, encoding 5, value 314159.0 + "81030000000050971041"+ // field 48, encoding 1, value 271828.0 + "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" + "b304"+ // start group field 70 level 1 + "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" + "b404"+ // end group field 70 level 1 + "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" + "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 + "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 + "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" + "90193f"+ // field 402, encoding 0, value 63 + "98197f") // field 403, encoding 0, value 127 + +} + +// All required fields set, defaults provided, all non-defaulted optional fields have values. +func TestEncodeDecode4(t *testing.T) { + pb := initGoTest(true) + pb.Table = String("hello") + pb.Param = Int32(7) + pb.OptionalField = initGoTestField() + pb.F_BoolOptional = Bool(true) + pb.F_Int32Optional = Int32(32) + pb.F_Int64Optional = Int64(64) + pb.F_Fixed32Optional = Uint32(3232) + pb.F_Fixed64Optional = Uint64(6464) + pb.F_Uint32Optional = Uint32(323232) + pb.F_Uint64Optional = Uint64(646464) + pb.F_FloatOptional = Float32(32.) + pb.F_DoubleOptional = Float64(64.) + pb.F_StringOptional = String("hello") + pb.F_BytesOptional = []byte("Bignose") + pb.F_Sint32Optional = Int32(-32) + pb.F_Sint64Optional = Int64(-64) + pb.Optionalgroup = initGoTest_OptionalGroup() + + overify(t, pb, + "0807"+ // field 1, encoding 0, value 7 + "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" + "1807"+ // field 3, encoding 0, value 7 + "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) + "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) + "5001"+ // field 10, encoding 0, value 1 + "5803"+ // field 11, encoding 0, value 3 + "6006"+ // field 12, encoding 0, value 6 + "6d20000000"+ // field 13, encoding 5, value 32 + "714000000000000000"+ // field 14, encoding 1, value 64 + "78a019"+ // field 15, encoding 0, value 3232 + "8001c032"+ // field 16, encoding 0, value 6464 + "8d0100004a45"+ // field 17, encoding 5, value 3232.0 + "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 + "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" + "f00101"+ // field 30, encoding 0, value 1 + "f80120"+ // field 31, encoding 0, value 32 + "800240"+ // field 32, encoding 0, value 64 + "8d02a00c0000"+ // field 33, encoding 5, value 3232 + "91024019000000000000"+ // field 34, encoding 1, value 6464 + "9802a0dd13"+ // field 35, encoding 0, value 323232 + "a002c0ba27"+ // field 36, encoding 0, value 646464 + "ad0200000042"+ // field 37, encoding 5, value 32.0 + "b1020000000000005040"+ // field 38, encoding 1, value 64.0 + "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" + "c00201"+ // field 40, encoding 0, value 1 + "c80220"+ // field 41, encoding 0, value 32 + "d00240"+ // field 42, encoding 0, value 64 + "dd0240010000"+ // field 43, encoding 5, value 320 + "e1028002000000000000"+ // field 44, encoding 1, value 640 + "e8028019"+ // field 45, encoding 0, value 3200 + "f0028032"+ // field 46, encoding 0, value 6400 + "fd02e0659948"+ // field 47, encoding 5, value 314159.0 + "81030000000050971041"+ // field 48, encoding 1, value 271828.0 + "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" + "b304"+ // start group field 70 level 1 + "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" + "b404"+ // end group field 70 level 1 + "d305"+ // start group field 90 level 1 + "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" + "d405"+ // end group field 90 level 1 + "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" + "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 + "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 + "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" + "f0123f"+ // field 302, encoding 0, value 63 + "f8127f"+ // field 303, encoding 0, value 127 + "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" + "90193f"+ // field 402, encoding 0, value 63 + "98197f") // field 403, encoding 0, value 127 + +} + +// All required fields set, defaults provided, all repeated fields given two values. +func TestEncodeDecode5(t *testing.T) { + pb := initGoTest(true) + pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} + pb.F_BoolRepeated = []bool{false, true} + pb.F_Int32Repeated = []int32{32, 33} + pb.F_Int64Repeated = []int64{64, 65} + pb.F_Fixed32Repeated = []uint32{3232, 3333} + pb.F_Fixed64Repeated = []uint64{6464, 6565} + pb.F_Uint32Repeated = []uint32{323232, 333333} + pb.F_Uint64Repeated = []uint64{646464, 656565} + pb.F_FloatRepeated = []float32{32., 33.} + pb.F_DoubleRepeated = []float64{64., 65.} + pb.F_StringRepeated = []string{"hello", "sailor"} + pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} + pb.F_Sint32Repeated = []int32{32, -32} + pb.F_Sint64Repeated = []int64{64, -64} + pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} + + overify(t, pb, + "0807"+ // field 1, encoding 0, value 7 + "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) + "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) + "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) + "5001"+ // field 10, encoding 0, value 1 + "5803"+ // field 11, encoding 0, value 3 + "6006"+ // field 12, encoding 0, value 6 + "6d20000000"+ // field 13, encoding 5, value 32 + "714000000000000000"+ // field 14, encoding 1, value 64 + "78a019"+ // field 15, encoding 0, value 3232 + "8001c032"+ // field 16, encoding 0, value 6464 + "8d0100004a45"+ // field 17, encoding 5, value 3232.0 + "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 + "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" + "a00100"+ // field 20, encoding 0, value 0 + "a00101"+ // field 20, encoding 0, value 1 + "a80120"+ // field 21, encoding 0, value 32 + "a80121"+ // field 21, encoding 0, value 33 + "b00140"+ // field 22, encoding 0, value 64 + "b00141"+ // field 22, encoding 0, value 65 + "bd01a00c0000"+ // field 23, encoding 5, value 3232 + "bd01050d0000"+ // field 23, encoding 5, value 3333 + "c1014019000000000000"+ // field 24, encoding 1, value 6464 + "c101a519000000000000"+ // field 24, encoding 1, value 6565 + "c801a0dd13"+ // field 25, encoding 0, value 323232 + "c80195ac14"+ // field 25, encoding 0, value 333333 + "d001c0ba27"+ // field 26, encoding 0, value 646464 + "d001b58928"+ // field 26, encoding 0, value 656565 + "dd0100000042"+ // field 27, encoding 5, value 32.0 + "dd0100000442"+ // field 27, encoding 5, value 33.0 + "e1010000000000005040"+ // field 28, encoding 1, value 64.0 + "e1010000000000405040"+ // field 28, encoding 1, value 65.0 + "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" + "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" + "c00201"+ // field 40, encoding 0, value 1 + "c80220"+ // field 41, encoding 0, value 32 + "d00240"+ // field 42, encoding 0, value 64 + "dd0240010000"+ // field 43, encoding 5, value 320 + "e1028002000000000000"+ // field 44, encoding 1, value 640 + "e8028019"+ // field 45, encoding 0, value 3200 + "f0028032"+ // field 46, encoding 0, value 6400 + "fd02e0659948"+ // field 47, encoding 5, value 314159.0 + "81030000000050971041"+ // field 48, encoding 1, value 271828.0 + "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" + "b304"+ // start group field 70 level 1 + "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" + "b404"+ // end group field 70 level 1 + "8305"+ // start group field 80 level 1 + "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" + "8405"+ // end group field 80 level 1 + "8305"+ // start group field 80 level 1 + "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" + "8405"+ // end group field 80 level 1 + "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" + "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 + "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 + "ca0c03"+"626967"+ // field 201, encoding 2, string "big" + "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" + "d00c40"+ // field 202, encoding 0, value 32 + "d00c3f"+ // field 202, encoding 0, value -32 + "d80c8001"+ // field 203, encoding 0, value 64 + "d80c7f"+ // field 203, encoding 0, value -64 + "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" + "90193f"+ // field 402, encoding 0, value 63 + "98197f") // field 403, encoding 0, value 127 + +} + +// All required fields set, all packed repeated fields given two values. +func TestEncodeDecode6(t *testing.T) { + pb := initGoTest(false) + pb.F_BoolRepeatedPacked = []bool{false, true} + pb.F_Int32RepeatedPacked = []int32{32, 33} + pb.F_Int64RepeatedPacked = []int64{64, 65} + pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} + pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} + pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} + pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} + pb.F_FloatRepeatedPacked = []float32{32., 33.} + pb.F_DoubleRepeatedPacked = []float64{64., 65.} + pb.F_Sint32RepeatedPacked = []int32{32, -32} + pb.F_Sint64RepeatedPacked = []int64{64, -64} + + overify(t, pb, + "0807"+ // field 1, encoding 0, value 7 + "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) + "5001"+ // field 10, encoding 0, value 1 + "5803"+ // field 11, encoding 0, value 3 + "6006"+ // field 12, encoding 0, value 6 + "6d20000000"+ // field 13, encoding 5, value 32 + "714000000000000000"+ // field 14, encoding 1, value 64 + "78a019"+ // field 15, encoding 0, value 3232 + "8001c032"+ // field 16, encoding 0, value 6464 + "8d0100004a45"+ // field 17, encoding 5, value 3232.0 + "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 + "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" + "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 + "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 + "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 + "aa0308"+ // field 53, encoding 2, 8 bytes + "a00c0000050d0000"+ // value 3232, value 3333 + "b20310"+ // field 54, encoding 2, 16 bytes + "4019000000000000a519000000000000"+ // value 6464, value 6565 + "ba0306"+ // field 55, encoding 2, 6 bytes + "a0dd1395ac14"+ // value 323232, value 333333 + "c20306"+ // field 56, encoding 2, 6 bytes + "c0ba27b58928"+ // value 646464, value 656565 + "ca0308"+ // field 57, encoding 2, 8 bytes + "0000004200000442"+ // value 32.0, value 33.0 + "d20310"+ // field 58, encoding 2, 16 bytes + "00000000000050400000000000405040"+ // value 64.0, value 65.0 + "b304"+ // start group field 70 level 1 + "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" + "b404"+ // end group field 70 level 1 + "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" + "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 + "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 + "b21f02"+ // field 502, encoding 2, 2 bytes + "403f"+ // value 32, value -32 + "ba1f03"+ // field 503, encoding 2, 3 bytes + "80017f") // value 64, value -64 +} + +// Test that we can encode empty bytes fields. +func TestEncodeDecodeBytes1(t *testing.T) { + pb := initGoTest(false) + + // Create our bytes + pb.F_BytesRequired = []byte{} + pb.F_BytesRepeated = [][]byte{{}} + pb.F_BytesOptional = []byte{} + + d, err := Marshal(pb) + if err != nil { + t.Error(err) + } + + pbd := new(GoTest) + if err := Unmarshal(d, pbd); err != nil { + t.Error(err) + } + + if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { + t.Error("required empty bytes field is incorrect") + } + if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { + t.Error("repeated empty bytes field is incorrect") + } + if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { + t.Error("optional empty bytes field is incorrect") + } +} + +// Test that we encode nil-valued fields of a repeated bytes field correctly. +// Since entries in a repeated field cannot be nil, nil must mean empty value. +func TestEncodeDecodeBytes2(t *testing.T) { + pb := initGoTest(false) + + // Create our bytes + pb.F_BytesRepeated = [][]byte{nil} + + d, err := Marshal(pb) + if err != nil { + t.Error(err) + } + + pbd := new(GoTest) + if err := Unmarshal(d, pbd); err != nil { + t.Error(err) + } + + if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { + t.Error("Unexpected value for repeated bytes field") + } +} + +// All required fields set, defaults provided, all repeated fields given two values. +func TestSkippingUnrecognizedFields(t *testing.T) { + o := old() + pb := initGoTestField() + + // Marshal it normally. + o.Marshal(pb) + + // Now new a GoSkipTest record. + skip := &GoSkipTest{ + SkipInt32: Int32(32), + SkipFixed32: Uint32(3232), + SkipFixed64: Uint64(6464), + SkipString: String("skipper"), + Skipgroup: &GoSkipTest_SkipGroup{ + GroupInt32: Int32(75), + GroupString: String("wxyz"), + }, + } + + // Marshal it into same buffer. + o.Marshal(skip) + + pbd := new(GoTestField) + o.Unmarshal(pbd) + + // The __unrecognized field should be a marshaling of GoSkipTest + skipd := new(GoSkipTest) + + o.SetBuf(pbd.XXX_unrecognized) + o.Unmarshal(skipd) + + if *skipd.SkipInt32 != *skip.SkipInt32 { + t.Error("skip int32", skipd.SkipInt32) + } + if *skipd.SkipFixed32 != *skip.SkipFixed32 { + t.Error("skip fixed32", skipd.SkipFixed32) + } + if *skipd.SkipFixed64 != *skip.SkipFixed64 { + t.Error("skip fixed64", skipd.SkipFixed64) + } + if *skipd.SkipString != *skip.SkipString { + t.Error("skip string", *skipd.SkipString) + } + if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { + t.Error("skip group int32", skipd.Skipgroup.GroupInt32) + } + if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { + t.Error("skip group string", *skipd.Skipgroup.GroupString) + } +} + +// Check that unrecognized fields of a submessage are preserved. +func TestSubmessageUnrecognizedFields(t *testing.T) { + nm := &NewMessage{ + Nested: &NewMessage_Nested{ + Name: String("Nigel"), + FoodGroup: String("carbs"), + }, + } + b, err := Marshal(nm) + if err != nil { + t.Fatalf("Marshal of NewMessage: %v", err) + } + + // Unmarshal into an OldMessage. + om := new(OldMessage) + if err := Unmarshal(b, om); err != nil { + t.Fatalf("Unmarshal to OldMessage: %v", err) + } + exp := &OldMessage{ + Nested: &OldMessage_Nested{ + Name: String("Nigel"), + // normal protocol buffer users should not do this + XXX_unrecognized: []byte("\x12\x05carbs"), + }, + } + if !Equal(om, exp) { + t.Errorf("om = %v, want %v", om, exp) + } + + // Clone the OldMessage. + om = Clone(om).(*OldMessage) + if !Equal(om, exp) { + t.Errorf("Clone(om) = %v, want %v", om, exp) + } + + // Marshal the OldMessage, then unmarshal it into an empty NewMessage. + if b, err = Marshal(om); err != nil { + t.Fatalf("Marshal of OldMessage: %v", err) + } + t.Logf("Marshal(%v) -> %q", om, b) + nm2 := new(NewMessage) + if err := Unmarshal(b, nm2); err != nil { + t.Fatalf("Unmarshal to NewMessage: %v", err) + } + if !Equal(nm, nm2) { + t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) + } +} + +// Check that an int32 field can be upgraded to an int64 field. +func TestNegativeInt32(t *testing.T) { + om := &OldMessage{ + Num: Int32(-1), + } + b, err := Marshal(om) + if err != nil { + t.Fatalf("Marshal of OldMessage: %v", err) + } + + // Check the size. It should be 11 bytes; + // 1 for the field/wire type, and 10 for the negative number. + if len(b) != 11 { + t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) + } + + // Unmarshal into a NewMessage. + nm := new(NewMessage) + if err := Unmarshal(b, nm); err != nil { + t.Fatalf("Unmarshal to NewMessage: %v", err) + } + want := &NewMessage{ + Num: Int64(-1), + } + if !Equal(nm, want) { + t.Errorf("nm = %v, want %v", nm, want) + } +} + +// Check that we can grow an array (repeated field) to have many elements. +// This test doesn't depend only on our encoding; for variety, it makes sure +// we create, encode, and decode the correct contents explicitly. It's therefore +// a bit messier. +// This test also uses (and hence tests) the Marshal/Unmarshal functions +// instead of the methods. +func TestBigRepeated(t *testing.T) { + pb := initGoTest(true) + + // Create the arrays + const N = 50 // Internally the library starts much smaller. + pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) + pb.F_Sint64Repeated = make([]int64, N) + pb.F_Sint32Repeated = make([]int32, N) + pb.F_BytesRepeated = make([][]byte, N) + pb.F_StringRepeated = make([]string, N) + pb.F_DoubleRepeated = make([]float64, N) + pb.F_FloatRepeated = make([]float32, N) + pb.F_Uint64Repeated = make([]uint64, N) + pb.F_Uint32Repeated = make([]uint32, N) + pb.F_Fixed64Repeated = make([]uint64, N) + pb.F_Fixed32Repeated = make([]uint32, N) + pb.F_Int64Repeated = make([]int64, N) + pb.F_Int32Repeated = make([]int32, N) + pb.F_BoolRepeated = make([]bool, N) + pb.RepeatedField = make([]*GoTestField, N) + + // Fill in the arrays with checkable values. + igtf := initGoTestField() + igtrg := initGoTest_RepeatedGroup() + for i := 0; i < N; i++ { + pb.Repeatedgroup[i] = igtrg + pb.F_Sint64Repeated[i] = int64(i) + pb.F_Sint32Repeated[i] = int32(i) + s := fmt.Sprint(i) + pb.F_BytesRepeated[i] = []byte(s) + pb.F_StringRepeated[i] = s + pb.F_DoubleRepeated[i] = float64(i) + pb.F_FloatRepeated[i] = float32(i) + pb.F_Uint64Repeated[i] = uint64(i) + pb.F_Uint32Repeated[i] = uint32(i) + pb.F_Fixed64Repeated[i] = uint64(i) + pb.F_Fixed32Repeated[i] = uint32(i) + pb.F_Int64Repeated[i] = int64(i) + pb.F_Int32Repeated[i] = int32(i) + pb.F_BoolRepeated[i] = i%2 == 0 + pb.RepeatedField[i] = igtf + } + + // Marshal. + buf, _ := Marshal(pb) + + // Now test Unmarshal by recreating the original buffer. + pbd := new(GoTest) + Unmarshal(buf, pbd) + + // Check the checkable values + for i := uint64(0); i < N; i++ { + if pbd.Repeatedgroup[i] == nil { // TODO: more checking? + t.Error("pbd.Repeatedgroup bad") + } + var x uint64 + x = uint64(pbd.F_Sint64Repeated[i]) + if x != i { + t.Error("pbd.F_Sint64Repeated bad", x, i) + } + x = uint64(pbd.F_Sint32Repeated[i]) + if x != i { + t.Error("pbd.F_Sint32Repeated bad", x, i) + } + s := fmt.Sprint(i) + equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) + if pbd.F_StringRepeated[i] != s { + t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) + } + x = uint64(pbd.F_DoubleRepeated[i]) + if x != i { + t.Error("pbd.F_DoubleRepeated bad", x, i) + } + x = uint64(pbd.F_FloatRepeated[i]) + if x != i { + t.Error("pbd.F_FloatRepeated bad", x, i) + } + x = pbd.F_Uint64Repeated[i] + if x != i { + t.Error("pbd.F_Uint64Repeated bad", x, i) + } + x = uint64(pbd.F_Uint32Repeated[i]) + if x != i { + t.Error("pbd.F_Uint32Repeated bad", x, i) + } + x = pbd.F_Fixed64Repeated[i] + if x != i { + t.Error("pbd.F_Fixed64Repeated bad", x, i) + } + x = uint64(pbd.F_Fixed32Repeated[i]) + if x != i { + t.Error("pbd.F_Fixed32Repeated bad", x, i) + } + x = uint64(pbd.F_Int64Repeated[i]) + if x != i { + t.Error("pbd.F_Int64Repeated bad", x, i) + } + x = uint64(pbd.F_Int32Repeated[i]) + if x != i { + t.Error("pbd.F_Int32Repeated bad", x, i) + } + if pbd.F_BoolRepeated[i] != (i%2 == 0) { + t.Error("pbd.F_BoolRepeated bad", x, i) + } + if pbd.RepeatedField[i] == nil { // TODO: more checking? + t.Error("pbd.RepeatedField bad") + } + } +} + +// Verify we give a useful message when decoding to the wrong structure type. +func TestTypeMismatch(t *testing.T) { + pb1 := initGoTest(true) + + // Marshal + o := old() + o.Marshal(pb1) + + // Now Unmarshal it to the wrong type. + pb2 := initGoTestField() + err := o.Unmarshal(pb2) + if err == nil { + t.Error("expected error, got no error") + } else if !strings.Contains(err.Error(), "bad wiretype") { + t.Error("expected bad wiretype error, got", err) + } +} + +func encodeDecode(t *testing.T, in, out Message, msg string) { + buf, err := Marshal(in) + if err != nil { + t.Fatalf("failed marshaling %v: %v", msg, err) + } + if err := Unmarshal(buf, out); err != nil { + t.Fatalf("failed unmarshaling %v: %v", msg, err) + } +} + +func TestPackedNonPackedDecoderSwitching(t *testing.T) { + np, p := new(NonPackedTest), new(PackedTest) + + // non-packed -> packed + np.A = []int32{0, 1, 1, 2, 3, 5} + encodeDecode(t, np, p, "non-packed -> packed") + if !reflect.DeepEqual(np.A, p.B) { + t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) + } + + // packed -> non-packed + np.Reset() + p.B = []int32{3, 1, 4, 1, 5, 9} + encodeDecode(t, p, np, "packed -> non-packed") + if !reflect.DeepEqual(p.B, np.A) { + t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) + } +} + +func TestProto1RepeatedGroup(t *testing.T) { + pb := &MessageList{ + Message: []*MessageList_Message{ + { + Name: String("blah"), + Count: Int32(7), + }, + // NOTE: pb.Message[1] is a nil + nil, + }, + } + + o := old() + err := o.Marshal(pb) + if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { + t.Fatalf("unexpected or no error when marshaling: %v", err) + } +} + +// Test that enums work. Checks for a bug introduced by making enums +// named types instead of int32: newInt32FromUint64 would crash with +// a type mismatch in reflect.PointTo. +func TestEnum(t *testing.T) { + pb := new(GoEnum) + pb.Foo = FOO_FOO1.Enum() + o := old() + if err := o.Marshal(pb); err != nil { + t.Fatal("error encoding enum:", err) + } + pb1 := new(GoEnum) + if err := o.Unmarshal(pb1); err != nil { + t.Fatal("error decoding enum:", err) + } + if *pb1.Foo != FOO_FOO1 { + t.Error("expected 7 but got ", *pb1.Foo) + } +} + +// Enum types have String methods. Check that enum fields can be printed. +// We don't care what the value actually is, just as long as it doesn't crash. +func TestPrintingNilEnumFields(t *testing.T) { + pb := new(GoEnum) + fmt.Sprintf("%+v", pb) +} + +// Verify that absent required fields cause Marshal/Unmarshal to return errors. +func TestRequiredFieldEnforcement(t *testing.T) { + pb := new(GoTestField) + _, err := Marshal(pb) + if err == nil { + t.Error("marshal: expected error, got nil") + } else if strings.Index(err.Error(), "Label") < 0 { + t.Errorf("marshal: bad error type: %v", err) + } + + // A slightly sneaky, yet valid, proto. It encodes the same required field twice, + // so simply counting the required fields is insufficient. + // field 1, encoding 2, value "hi" + buf := []byte("\x0A\x02hi\x0A\x02hi") + err = Unmarshal(buf, pb) + if err == nil { + t.Error("unmarshal: expected error, got nil") + } else if strings.Index(err.Error(), "{Unknown}") < 0 { + t.Errorf("unmarshal: bad error type: %v", err) + } +} + +func TestTypedNilMarshal(t *testing.T) { + // A typed nil should return ErrNil and not crash. + _, err := Marshal((*GoEnum)(nil)) + if err != ErrNil { + t.Errorf("Marshal: got err %v, want ErrNil", err) + } +} + +// A type that implements the Marshaler interface, but is not nillable. +type nonNillableInt uint64 + +func (nni nonNillableInt) Marshal() ([]byte, error) { + return EncodeVarint(uint64(nni)), nil +} + +type NNIMessage struct { + nni nonNillableInt +} + +func (*NNIMessage) Reset() {} +func (*NNIMessage) String() string { return "" } +func (*NNIMessage) ProtoMessage() {} + +// A type that implements the Marshaler interface and is nillable. +type nillableMessage struct { + x uint64 +} + +func (nm *nillableMessage) Marshal() ([]byte, error) { + return EncodeVarint(nm.x), nil +} + +type NMMessage struct { + nm *nillableMessage +} + +func (*NMMessage) Reset() {} +func (*NMMessage) String() string { return "" } +func (*NMMessage) ProtoMessage() {} + +// Verify a type that uses the Marshaler interface, but has a nil pointer. +func TestNilMarshaler(t *testing.T) { + // Try a struct with a Marshaler field that is nil. + // It should be directly marshable. + nmm := new(NMMessage) + if _, err := Marshal(nmm); err != nil { + t.Error("unexpected error marshaling nmm: ", err) + } + + // Try a struct with a Marshaler field that is not nillable. + nnim := new(NNIMessage) + nnim.nni = 7 + var _ Marshaler = nnim.nni // verify it is truly a Marshaler + if _, err := Marshal(nnim); err != nil { + t.Error("unexpected error marshaling nnim: ", err) + } +} + +func TestAllSetDefaults(t *testing.T) { + // Exercise SetDefaults with all scalar field types. + m := &Defaults{ + // NaN != NaN, so override that here. + F_Nan: Float32(1.7), + } + expected := &Defaults{ + F_Bool: Bool(true), + F_Int32: Int32(32), + F_Int64: Int64(64), + F_Fixed32: Uint32(320), + F_Fixed64: Uint64(640), + F_Uint32: Uint32(3200), + F_Uint64: Uint64(6400), + F_Float: Float32(314159), + F_Double: Float64(271828), + F_String: String(`hello, "world!"` + "\n"), + F_Bytes: []byte("Bignose"), + F_Sint32: Int32(-32), + F_Sint64: Int64(-64), + F_Enum: Defaults_GREEN.Enum(), + F_Pinf: Float32(float32(math.Inf(1))), + F_Ninf: Float32(float32(math.Inf(-1))), + F_Nan: Float32(1.7), + StrZero: String(""), + } + SetDefaults(m) + if !Equal(m, expected) { + t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) + } +} + +func TestSetDefaultsWithSetField(t *testing.T) { + // Check that a set value is not overridden. + m := &Defaults{ + F_Int32: Int32(12), + } + SetDefaults(m) + if v := m.GetF_Int32(); v != 12 { + t.Errorf("m.FInt32 = %v, want 12", v) + } +} + +func TestSetDefaultsWithSubMessage(t *testing.T) { + m := &OtherMessage{ + Key: Int64(123), + Inner: &InnerMessage{ + Host: String("gopher"), + }, + } + expected := &OtherMessage{ + Key: Int64(123), + Inner: &InnerMessage{ + Host: String("gopher"), + Port: Int32(4000), + }, + } + SetDefaults(m) + if !Equal(m, expected) { + t.Errorf("\n got %v\nwant %v", m, expected) + } +} + +func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { + m := &MyMessage{ + RepInner: []*InnerMessage{{}}, + } + expected := &MyMessage{ + RepInner: []*InnerMessage{{ + Port: Int32(4000), + }}, + } + SetDefaults(m) + if !Equal(m, expected) { + t.Errorf("\n got %v\nwant %v", m, expected) + } +} + +func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { + m := &MyMessage{ + Pet: []string{"turtle", "wombat"}, + } + expected := Clone(m) + SetDefaults(m) + if !Equal(m, expected) { + t.Errorf("\n got %v\nwant %v", m, expected) + } +} + +func TestMaximumTagNumber(t *testing.T) { + m := &MaxTag{ + LastField: String("natural goat essence"), + } + buf, err := Marshal(m) + if err != nil { + t.Fatalf("proto.Marshal failed: %v", err) + } + m2 := new(MaxTag) + if err := Unmarshal(buf, m2); err != nil { + t.Fatalf("proto.Unmarshal failed: %v", err) + } + if got, want := m2.GetLastField(), *m.LastField; got != want { + t.Errorf("got %q, want %q", got, want) + } +} + +func TestJSON(t *testing.T) { + m := &MyMessage{ + Count: Int32(4), + Pet: []string{"bunny", "kitty"}, + Inner: &InnerMessage{ + Host: String("cauchy"), + }, + Bikeshed: MyMessage_GREEN.Enum(), + } + const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` + + b, err := json.Marshal(m) + if err != nil { + t.Fatalf("json.Marshal failed: %v", err) + } + s := string(b) + if s != expected { + t.Errorf("got %s\nwant %s", s, expected) + } + + received := new(MyMessage) + if err := json.Unmarshal(b, received); err != nil { + t.Fatalf("json.Unmarshal failed: %v", err) + } + if !Equal(received, m) { + t.Fatalf("got %s, want %s", received, m) + } + + // Test unmarshalling of JSON with symbolic enum name. + const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` + received.Reset() + if err := json.Unmarshal([]byte(old), received); err != nil { + t.Fatalf("json.Unmarshal failed: %v", err) + } + if !Equal(received, m) { + t.Fatalf("got %s, want %s", received, m) + } +} + +func TestBadWireType(t *testing.T) { + b := []byte{7<<3 | 6} // field 7, wire type 6 + pb := new(OtherMessage) + if err := Unmarshal(b, pb); err == nil { + t.Errorf("Unmarshal did not fail") + } else if !strings.Contains(err.Error(), "unknown wire type") { + t.Errorf("wrong error: %v", err) + } +} + +func TestBytesWithInvalidLength(t *testing.T) { + // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. + b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} + Unmarshal(b, new(MyMessage)) +} + +func TestLengthOverflow(t *testing.T) { + // Overflowing a length should not panic. + b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} + Unmarshal(b, new(MyMessage)) +} + +func TestVarintOverflow(t *testing.T) { + // Overflowing a 64-bit length should not be allowed. + b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} + if err := Unmarshal(b, new(MyMessage)); err == nil { + t.Fatalf("Overflowed uint64 length without error") + } +} + +func TestUnmarshalFuzz(t *testing.T) { + const N = 1000 + seed := time.Now().UnixNano() + t.Logf("RNG seed is %d", seed) + rng := rand.New(rand.NewSource(seed)) + buf := make([]byte, 20) + for i := 0; i < N; i++ { + for j := range buf { + buf[j] = byte(rng.Intn(256)) + } + fuzzUnmarshal(t, buf) + } +} + +func TestMergeMessages(t *testing.T) { + pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} + data, err := Marshal(pb) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + + pb1 := new(MessageList) + if err := Unmarshal(data, pb1); err != nil { + t.Fatalf("first Unmarshal: %v", err) + } + if err := Unmarshal(data, pb1); err != nil { + t.Fatalf("second Unmarshal: %v", err) + } + if len(pb1.Message) != 1 { + t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) + } + + pb2 := new(MessageList) + if err := UnmarshalMerge(data, pb2); err != nil { + t.Fatalf("first UnmarshalMerge: %v", err) + } + if err := UnmarshalMerge(data, pb2); err != nil { + t.Fatalf("second UnmarshalMerge: %v", err) + } + if len(pb2.Message) != 2 { + t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) + } +} + +func TestExtensionMarshalOrder(t *testing.T) { + m := &MyMessage{Count: Int(123)} + if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { + t.Fatalf("SetExtension: %v", err) + } + if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { + t.Fatalf("SetExtension: %v", err) + } + if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { + t.Fatalf("SetExtension: %v", err) + } + + // Serialize m several times, and check we get the same bytes each time. + var orig []byte + for i := 0; i < 100; i++ { + b, err := Marshal(m) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if i == 0 { + orig = b + continue + } + if !bytes.Equal(b, orig) { + t.Errorf("Bytes differ on attempt #%d", i) + } + } +} + +// Many extensions, because small maps might not iterate differently on each iteration. +var exts = []*ExtensionDesc{ + E_X201, + E_X202, + E_X203, + E_X204, + E_X205, + E_X206, + E_X207, + E_X208, + E_X209, + E_X210, + E_X211, + E_X212, + E_X213, + E_X214, + E_X215, + E_X216, + E_X217, + E_X218, + E_X219, + E_X220, + E_X221, + E_X222, + E_X223, + E_X224, + E_X225, + E_X226, + E_X227, + E_X228, + E_X229, + E_X230, + E_X231, + E_X232, + E_X233, + E_X234, + E_X235, + E_X236, + E_X237, + E_X238, + E_X239, + E_X240, + E_X241, + E_X242, + E_X243, + E_X244, + E_X245, + E_X246, + E_X247, + E_X248, + E_X249, + E_X250, +} + +func TestMessageSetMarshalOrder(t *testing.T) { + m := &MyMessageSet{} + for _, x := range exts { + if err := SetExtension(m, x, &Empty{}); err != nil { + t.Fatalf("SetExtension: %v", err) + } + } + + buf, err := Marshal(m) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + + // Serialize m several times, and check we get the same bytes each time. + for i := 0; i < 10; i++ { + b1, err := Marshal(m) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if !bytes.Equal(b1, buf) { + t.Errorf("Bytes differ on re-Marshal #%d", i) + } + + m2 := &MyMessageSet{} + if err := Unmarshal(buf, m2); err != nil { + t.Errorf("Unmarshal: %v", err) + } + b2, err := Marshal(m2) + if err != nil { + t.Errorf("re-Marshal: %v", err) + } + if !bytes.Equal(b2, buf) { + t.Errorf("Bytes differ on round-trip #%d", i) + } + } +} + +func TestUnmarshalMergesMessages(t *testing.T) { + // If a nested message occurs twice in the input, + // the fields should be merged when decoding. + a := &OtherMessage{ + Key: Int64(123), + Inner: &InnerMessage{ + Host: String("polhode"), + Port: Int32(1234), + }, + } + aData, err := Marshal(a) + if err != nil { + t.Fatalf("Marshal(a): %v", err) + } + b := &OtherMessage{ + Weight: Float32(1.2), + Inner: &InnerMessage{ + Host: String("herpolhode"), + Connected: Bool(true), + }, + } + bData, err := Marshal(b) + if err != nil { + t.Fatalf("Marshal(b): %v", err) + } + want := &OtherMessage{ + Key: Int64(123), + Weight: Float32(1.2), + Inner: &InnerMessage{ + Host: String("herpolhode"), + Port: Int32(1234), + Connected: Bool(true), + }, + } + got := new(OtherMessage) + if err := Unmarshal(append(aData, bData...), got); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + if !Equal(got, want) { + t.Errorf("\n got %v\nwant %v", got, want) + } +} + +func TestEncodingSizes(t *testing.T) { + tests := []struct { + m Message + n int + }{ + {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, + {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, + {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, + {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, + } + for _, test := range tests { + b, err := Marshal(test.m) + if err != nil { + t.Errorf("Marshal(%v): %v", test.m, err) + continue + } + if len(b) != test.n { + t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) + } + } +} + +func TestRequiredNotSetError(t *testing.T) { + pb := initGoTest(false) + pb.RequiredField.Label = nil + pb.F_Int32Required = nil + pb.F_Int64Required = nil + + expected := "0807" + // field 1, encoding 0, value 7 + "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) + "5001" + // field 10, encoding 0, value 1 + "6d20000000" + // field 13, encoding 5, value 0x20 + "714000000000000000" + // field 14, encoding 1, value 0x40 + "78a019" + // field 15, encoding 0, value 0xca0 = 3232 + "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 + "8d0100004a45" + // field 17, encoding 5, value 3232.0 + "9101000000000040b940" + // field 18, encoding 1, value 6464.0 + "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" + "b304" + // field 70, encoding 3, start group + "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" + "b404" + // field 70, encoding 4, end group + "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" + "b0063f" + // field 102, encoding 0, 0x3f zigzag32 + "b8067f" // field 103, encoding 0, 0x7f zigzag64 + + o := old() + bytes, err := Marshal(pb) + if _, ok := err.(*RequiredNotSetError); !ok { + fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) + o.DebugPrint("", bytes) + t.Fatalf("expected = %s", expected) + } + if strings.Index(err.Error(), "RequiredField.Label") < 0 { + t.Errorf("marshal-1 wrong err msg: %v", err) + } + if !equal(bytes, expected, t) { + o.DebugPrint("neq 1", bytes) + t.Fatalf("expected = %s", expected) + } + + // Now test Unmarshal by recreating the original buffer. + pbd := new(GoTest) + err = Unmarshal(bytes, pbd) + if _, ok := err.(*RequiredNotSetError); !ok { + t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) + o.DebugPrint("", bytes) + t.Fatalf("string = %s", expected) + } + if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { + t.Errorf("unmarshal wrong err msg: %v", err) + } + bytes, err = Marshal(pbd) + if _, ok := err.(*RequiredNotSetError); !ok { + t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) + o.DebugPrint("", bytes) + t.Fatalf("string = %s", expected) + } + if strings.Index(err.Error(), "RequiredField.Label") < 0 { + t.Errorf("marshal-2 wrong err msg: %v", err) + } + if !equal(bytes, expected, t) { + o.DebugPrint("neq 2", bytes) + t.Fatalf("string = %s", expected) + } +} + +func fuzzUnmarshal(t *testing.T, data []byte) { + defer func() { + if e := recover(); e != nil { + t.Errorf("These bytes caused a panic: %+v", data) + t.Logf("Stack:\n%s", debug.Stack()) + t.FailNow() + } + }() + + pb := new(MyMessage) + Unmarshal(data, pb) +} + +func TestMapFieldMarshal(t *testing.T) { + m := &MessageWithMap{ + NameMapping: map[int32]string{ + 1: "Rob", + 4: "Ian", + 8: "Dave", + }, + } + b, err := Marshal(m) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + + // b should be the concatenation of these three byte sequences in some order. + parts := []string{ + "\n\a\b\x01\x12\x03Rob", + "\n\a\b\x04\x12\x03Ian", + "\n\b\b\x08\x12\x04Dave", + } + ok := false + for i := range parts { + for j := range parts { + if j == i { + continue + } + for k := range parts { + if k == i || k == j { + continue + } + try := parts[i] + parts[j] + parts[k] + if bytes.Equal(b, []byte(try)) { + ok = true + break + } + } + } + } + if !ok { + t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) + } + t.Logf("FYI b: %q", b) + + (new(Buffer)).DebugPrint("Dump of b", b) +} + +func TestMapFieldRoundTrips(t *testing.T) { + m := &MessageWithMap{ + NameMapping: map[int32]string{ + 1: "Rob", + 4: "Ian", + 8: "Dave", + }, + MsgMapping: map[int64]*FloatingPoint{ + 0x7001: &FloatingPoint{F: Float64(2.0)}, + }, + ByteMapping: map[bool][]byte{ + false: []byte("that's not right!"), + true: []byte("aye, 'tis true!"), + }, + } + b, err := Marshal(m) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + t.Logf("FYI b: %q", b) + m2 := new(MessageWithMap) + if err := Unmarshal(b, m2); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + for _, pair := range [][2]interface{}{ + {m.NameMapping, m2.NameMapping}, + {m.MsgMapping, m2.MsgMapping}, + {m.ByteMapping, m2.ByteMapping}, + } { + if !reflect.DeepEqual(pair[0], pair[1]) { + t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) + } + } +} + +func TestMapFieldWithNil(t *testing.T) { + m := &MessageWithMap{ + MsgMapping: map[int64]*FloatingPoint{ + 1: nil, + }, + } + b, err := Marshal(m) + if err == nil { + t.Fatalf("Marshal of bad map should have failed, got these bytes: %v", b) + } +} + +// Benchmarks + +func testMsg() *GoTest { + pb := initGoTest(true) + const N = 1000 // Internally the library starts much smaller. + pb.F_Int32Repeated = make([]int32, N) + pb.F_DoubleRepeated = make([]float64, N) + for i := 0; i < N; i++ { + pb.F_Int32Repeated[i] = int32(i) + pb.F_DoubleRepeated[i] = float64(i) + } + return pb +} + +func bytesMsg() *GoTest { + pb := initGoTest(true) + buf := make([]byte, 4000) + for i := range buf { + buf[i] = byte(i) + } + pb.F_BytesDefaulted = buf + return pb +} + +func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { + d, _ := marshal(pb) + b.SetBytes(int64(len(d))) + b.ResetTimer() + for i := 0; i < b.N; i++ { + marshal(pb) + } +} + +func benchmarkBufferMarshal(b *testing.B, pb Message) { + p := NewBuffer(nil) + benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { + p.Reset() + err := p.Marshal(pb0) + return p.Bytes(), err + }) +} + +func benchmarkSize(b *testing.B, pb Message) { + benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { + Size(pb) + return nil, nil + }) +} + +func newOf(pb Message) Message { + in := reflect.ValueOf(pb) + if in.IsNil() { + return pb + } + return reflect.New(in.Type().Elem()).Interface().(Message) +} + +func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { + d, _ := Marshal(pb) + b.SetBytes(int64(len(d))) + pbd := newOf(pb) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + unmarshal(d, pbd) + } +} + +func benchmarkBufferUnmarshal(b *testing.B, pb Message) { + p := NewBuffer(nil) + benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { + p.SetBuf(d) + return p.Unmarshal(pb0) + }) +} + +// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} + +func BenchmarkMarshal(b *testing.B) { + benchmarkMarshal(b, testMsg(), Marshal) +} + +func BenchmarkBufferMarshal(b *testing.B) { + benchmarkBufferMarshal(b, testMsg()) +} + +func BenchmarkSize(b *testing.B) { + benchmarkSize(b, testMsg()) +} + +func BenchmarkUnmarshal(b *testing.B) { + benchmarkUnmarshal(b, testMsg(), Unmarshal) +} + +func BenchmarkBufferUnmarshal(b *testing.B) { + benchmarkBufferUnmarshal(b, testMsg()) +} + +func BenchmarkMarshalBytes(b *testing.B) { + benchmarkMarshal(b, bytesMsg(), Marshal) +} + +func BenchmarkBufferMarshalBytes(b *testing.B) { + benchmarkBufferMarshal(b, bytesMsg()) +} + +func BenchmarkSizeBytes(b *testing.B) { + benchmarkSize(b, bytesMsg()) +} + +func BenchmarkUnmarshalBytes(b *testing.B) { + benchmarkUnmarshal(b, bytesMsg(), Unmarshal) +} + +func BenchmarkBufferUnmarshalBytes(b *testing.B) { + benchmarkBufferUnmarshal(b, bytesMsg()) +} + +func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { + b.StopTimer() + pb := initGoTestField() + skip := &GoSkipTest{ + SkipInt32: Int32(32), + SkipFixed32: Uint32(3232), + SkipFixed64: Uint64(6464), + SkipString: String("skipper"), + Skipgroup: &GoSkipTest_SkipGroup{ + GroupInt32: Int32(75), + GroupString: String("wxyz"), + }, + } + + pbd := new(GoTestField) + p := NewBuffer(nil) + p.Marshal(pb) + p.Marshal(skip) + p2 := NewBuffer(nil) + + b.StartTimer() + for i := 0; i < b.N; i++ { + p2.SetBuf(p.Bytes()) + p2.Unmarshal(pbd) + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go new file mode 100644 index 0000000..915a68b --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go @@ -0,0 +1,212 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2011 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Protocol buffer deep copy and merge. +// TODO: MessageSet and RawMessage. + +package proto + +import ( + "log" + "reflect" + "strings" +) + +// Clone returns a deep copy of a protocol buffer. +func Clone(pb Message) Message { + in := reflect.ValueOf(pb) + if in.IsNil() { + return pb + } + + out := reflect.New(in.Type().Elem()) + // out is empty so a merge is a deep copy. + mergeStruct(out.Elem(), in.Elem()) + return out.Interface().(Message) +} + +// Merge merges src into dst. +// Required and optional fields that are set in src will be set to that value in dst. +// Elements of repeated fields will be appended. +// Merge panics if src and dst are not the same type, or if dst is nil. +func Merge(dst, src Message) { + in := reflect.ValueOf(src) + out := reflect.ValueOf(dst) + if out.IsNil() { + panic("proto: nil destination") + } + if in.Type() != out.Type() { + // Explicit test prior to mergeStruct so that mistyped nils will fail + panic("proto: type mismatch") + } + if in.IsNil() { + // Merging nil into non-nil is a quiet no-op + return + } + mergeStruct(out.Elem(), in.Elem()) +} + +func mergeStruct(out, in reflect.Value) { + sprop := GetProperties(in.Type()) + for i := 0; i < in.NumField(); i++ { + f := in.Type().Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) + } + + if emIn, ok := in.Addr().Interface().(extendableProto); ok { + emOut := out.Addr().Interface().(extendableProto) + mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap()) + } + + uf := in.FieldByName("XXX_unrecognized") + if !uf.IsValid() { + return + } + uin := uf.Bytes() + if len(uin) > 0 { + out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) + } +} + +// mergeAny performs a merge between two values of the same type. +// viaPtr indicates whether the values were indirected through a pointer (implying proto2). +// prop is set if this is a struct field (it may be nil). +func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { + if in.Type() == protoMessageType { + if !in.IsNil() { + if out.IsNil() { + out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) + } else { + Merge(out.Interface().(Message), in.Interface().(Message)) + } + } + return + } + switch in.Kind() { + case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, + reflect.String, reflect.Uint32, reflect.Uint64: + if !viaPtr && isProto3Zero(in) { + return + } + out.Set(in) + case reflect.Map: + if in.Len() == 0 { + return + } + if out.IsNil() { + out.Set(reflect.MakeMap(in.Type())) + } + // For maps with value types of *T or []byte we need to deep copy each value. + elemKind := in.Type().Elem().Kind() + for _, key := range in.MapKeys() { + var val reflect.Value + switch elemKind { + case reflect.Ptr: + val = reflect.New(in.Type().Elem().Elem()) + mergeAny(val, in.MapIndex(key), false, nil) + case reflect.Slice: + val = in.MapIndex(key) + val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) + default: + val = in.MapIndex(key) + } + out.SetMapIndex(key, val) + } + case reflect.Ptr: + if in.IsNil() { + return + } + if out.IsNil() { + out.Set(reflect.New(in.Elem().Type())) + } + mergeAny(out.Elem(), in.Elem(), true, nil) + case reflect.Slice: + if in.IsNil() { + return + } + if in.Type().Elem().Kind() == reflect.Uint8 { + // []byte is a scalar bytes field, not a repeated field. + + // Edge case: if this is in a proto3 message, a zero length + // bytes field is considered the zero value, and should not + // be merged. + if prop != nil && prop.proto3 && in.Len() == 0 { + return + } + + // Make a deep copy. + // Append to []byte{} instead of []byte(nil) so that we never end up + // with a nil result. + out.SetBytes(append([]byte{}, in.Bytes()...)) + return + } + n := in.Len() + if out.IsNil() { + out.Set(reflect.MakeSlice(in.Type(), 0, n)) + } + switch in.Type().Elem().Kind() { + case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, + reflect.String, reflect.Uint32, reflect.Uint64: + out.Set(reflect.AppendSlice(out, in)) + default: + for i := 0; i < n; i++ { + x := reflect.Indirect(reflect.New(in.Type().Elem())) + mergeAny(x, in.Index(i), false, nil) + out.Set(reflect.Append(out, x)) + } + } + case reflect.Struct: + mergeStruct(out, in) + default: + // unknown type, so not a protocol buffer + log.Printf("proto: don't know how to copy %v", in) + } +} + +func mergeExtension(out, in map[int32]Extension) { + for extNum, eIn := range in { + eOut := Extension{desc: eIn.desc} + if eIn.value != nil { + v := reflect.New(reflect.TypeOf(eIn.value)).Elem() + mergeAny(v, reflect.ValueOf(eIn.value), false, nil) + eOut.value = v.Interface() + } + if eIn.enc != nil { + eOut.enc = make([]byte, len(eIn.enc)) + copy(eOut.enc, eIn.enc) + } + + out[extNum] = eOut + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go new file mode 100644 index 0000000..a1c697b --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go @@ -0,0 +1,245 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2011 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto_test + +import ( + "testing" + + "github.com/golang/protobuf/proto" + + proto3pb "github.com/golang/protobuf/proto/proto3_proto" + pb "github.com/golang/protobuf/proto/testdata" +) + +var cloneTestMessage = &pb.MyMessage{ + Count: proto.Int32(42), + Name: proto.String("Dave"), + Pet: []string{"bunny", "kitty", "horsey"}, + Inner: &pb.InnerMessage{ + Host: proto.String("niles"), + Port: proto.Int32(9099), + Connected: proto.Bool(true), + }, + Others: []*pb.OtherMessage{ + { + Value: []byte("some bytes"), + }, + }, + Somegroup: &pb.MyMessage_SomeGroup{ + GroupField: proto.Int32(6), + }, + RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, +} + +func init() { + ext := &pb.Ext{ + Data: proto.String("extension"), + } + if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { + panic("SetExtension: " + err.Error()) + } +} + +func TestClone(t *testing.T) { + m := proto.Clone(cloneTestMessage).(*pb.MyMessage) + if !proto.Equal(m, cloneTestMessage) { + t.Errorf("Clone(%v) = %v", cloneTestMessage, m) + } + + // Verify it was a deep copy. + *m.Inner.Port++ + if proto.Equal(m, cloneTestMessage) { + t.Error("Mutating clone changed the original") + } + // Byte fields and repeated fields should be copied. + if &m.Pet[0] == &cloneTestMessage.Pet[0] { + t.Error("Pet: repeated field not copied") + } + if &m.Others[0] == &cloneTestMessage.Others[0] { + t.Error("Others: repeated field not copied") + } + if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { + t.Error("Others[0].Value: bytes field not copied") + } + if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { + t.Error("RepBytes: repeated field not copied") + } + if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { + t.Error("RepBytes[0]: bytes field not copied") + } +} + +func TestCloneNil(t *testing.T) { + var m *pb.MyMessage + if c := proto.Clone(m); !proto.Equal(m, c) { + t.Errorf("Clone(%v) = %v", m, c) + } +} + +var mergeTests = []struct { + src, dst, want proto.Message +}{ + { + src: &pb.MyMessage{ + Count: proto.Int32(42), + }, + dst: &pb.MyMessage{ + Name: proto.String("Dave"), + }, + want: &pb.MyMessage{ + Count: proto.Int32(42), + Name: proto.String("Dave"), + }, + }, + { + src: &pb.MyMessage{ + Inner: &pb.InnerMessage{ + Host: proto.String("hey"), + Connected: proto.Bool(true), + }, + Pet: []string{"horsey"}, + Others: []*pb.OtherMessage{ + { + Value: []byte("some bytes"), + }, + }, + }, + dst: &pb.MyMessage{ + Inner: &pb.InnerMessage{ + Host: proto.String("niles"), + Port: proto.Int32(9099), + }, + Pet: []string{"bunny", "kitty"}, + Others: []*pb.OtherMessage{ + { + Key: proto.Int64(31415926535), + }, + { + // Explicitly test a src=nil field + Inner: nil, + }, + }, + }, + want: &pb.MyMessage{ + Inner: &pb.InnerMessage{ + Host: proto.String("hey"), + Connected: proto.Bool(true), + Port: proto.Int32(9099), + }, + Pet: []string{"bunny", "kitty", "horsey"}, + Others: []*pb.OtherMessage{ + { + Key: proto.Int64(31415926535), + }, + {}, + { + Value: []byte("some bytes"), + }, + }, + }, + }, + { + src: &pb.MyMessage{ + RepBytes: [][]byte{[]byte("wow")}, + }, + dst: &pb.MyMessage{ + Somegroup: &pb.MyMessage_SomeGroup{ + GroupField: proto.Int32(6), + }, + RepBytes: [][]byte{[]byte("sham")}, + }, + want: &pb.MyMessage{ + Somegroup: &pb.MyMessage_SomeGroup{ + GroupField: proto.Int32(6), + }, + RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, + }, + }, + // Check that a scalar bytes field replaces rather than appends. + { + src: &pb.OtherMessage{Value: []byte("foo")}, + dst: &pb.OtherMessage{Value: []byte("bar")}, + want: &pb.OtherMessage{Value: []byte("foo")}, + }, + { + src: &pb.MessageWithMap{ + NameMapping: map[int32]string{6: "Nigel"}, + MsgMapping: map[int64]*pb.FloatingPoint{ + 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, + }, + ByteMapping: map[bool][]byte{true: []byte("wowsa")}, + }, + dst: &pb.MessageWithMap{ + NameMapping: map[int32]string{ + 6: "Bruce", // should be overwritten + 7: "Andrew", + }, + }, + want: &pb.MessageWithMap{ + NameMapping: map[int32]string{ + 6: "Nigel", + 7: "Andrew", + }, + MsgMapping: map[int64]*pb.FloatingPoint{ + 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, + }, + ByteMapping: map[bool][]byte{true: []byte("wowsa")}, + }, + }, + // proto3 shouldn't merge zero values, + // in the same way that proto2 shouldn't merge nils. + { + src: &proto3pb.Message{ + Name: "Aaron", + Data: []byte(""), // zero value, but not nil + }, + dst: &proto3pb.Message{ + HeightInCm: 176, + Data: []byte("texas!"), + }, + want: &proto3pb.Message{ + Name: "Aaron", + HeightInCm: 176, + Data: []byte("texas!"), + }, + }, +} + +func TestMerge(t *testing.T) { + for _, m := range mergeTests { + got := proto.Clone(m.dst) + proto.Merge(got, m.src) + if !proto.Equal(got, m.want) { + t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) + } + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go new file mode 100644 index 0000000..bf71dca --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go @@ -0,0 +1,827 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Routines for decoding protocol buffer data to construct in-memory representations. + */ + +import ( + "errors" + "fmt" + "io" + "os" + "reflect" +) + +// errOverflow is returned when an integer is too large to be represented. +var errOverflow = errors.New("proto: integer overflow") + +// The fundamental decoders that interpret bytes on the wire. +// Those that take integer types all return uint64 and are +// therefore of type valueDecoder. + +// DecodeVarint reads a varint-encoded integer from the slice. +// It returns the integer and the number of bytes consumed, or +// zero if there is not enough. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func DecodeVarint(buf []byte) (x uint64, n int) { + // x, n already 0 + for shift := uint(0); shift < 64; shift += 7 { + if n >= len(buf) { + return 0, 0 + } + b := uint64(buf[n]) + n++ + x |= (b & 0x7F) << shift + if (b & 0x80) == 0 { + return x, n + } + } + + // The number is too large to represent in a 64-bit value. + return 0, 0 +} + +// DecodeVarint reads a varint-encoded integer from the Buffer. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func (p *Buffer) DecodeVarint() (x uint64, err error) { + // x, err already 0 + + i := p.index + l := len(p.buf) + + for shift := uint(0); shift < 64; shift += 7 { + if i >= l { + err = io.ErrUnexpectedEOF + return + } + b := p.buf[i] + i++ + x |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + p.index = i + return + } + } + + // The number is too large to represent in a 64-bit value. + err = errOverflow + return +} + +// DecodeFixed64 reads a 64-bit integer from the Buffer. +// This is the format for the +// fixed64, sfixed64, and double protocol buffer types. +func (p *Buffer) DecodeFixed64() (x uint64, err error) { + // x, err already 0 + i := p.index + 8 + if i < 0 || i > len(p.buf) { + err = io.ErrUnexpectedEOF + return + } + p.index = i + + x = uint64(p.buf[i-8]) + x |= uint64(p.buf[i-7]) << 8 + x |= uint64(p.buf[i-6]) << 16 + x |= uint64(p.buf[i-5]) << 24 + x |= uint64(p.buf[i-4]) << 32 + x |= uint64(p.buf[i-3]) << 40 + x |= uint64(p.buf[i-2]) << 48 + x |= uint64(p.buf[i-1]) << 56 + return +} + +// DecodeFixed32 reads a 32-bit integer from the Buffer. +// This is the format for the +// fixed32, sfixed32, and float protocol buffer types. +func (p *Buffer) DecodeFixed32() (x uint64, err error) { + // x, err already 0 + i := p.index + 4 + if i < 0 || i > len(p.buf) { + err = io.ErrUnexpectedEOF + return + } + p.index = i + + x = uint64(p.buf[i-4]) + x |= uint64(p.buf[i-3]) << 8 + x |= uint64(p.buf[i-2]) << 16 + x |= uint64(p.buf[i-1]) << 24 + return +} + +// DecodeZigzag64 reads a zigzag-encoded 64-bit integer +// from the Buffer. +// This is the format used for the sint64 protocol buffer type. +func (p *Buffer) DecodeZigzag64() (x uint64, err error) { + x, err = p.DecodeVarint() + if err != nil { + return + } + x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) + return +} + +// DecodeZigzag32 reads a zigzag-encoded 32-bit integer +// from the Buffer. +// This is the format used for the sint32 protocol buffer type. +func (p *Buffer) DecodeZigzag32() (x uint64, err error) { + x, err = p.DecodeVarint() + if err != nil { + return + } + x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) + return +} + +// These are not ValueDecoders: they produce an array of bytes or a string. +// bytes, embedded messages + +// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. +// This is the format used for the bytes protocol buffer +// type and for embedded messages. +func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { + n, err := p.DecodeVarint() + if err != nil { + return nil, err + } + + nb := int(n) + if nb < 0 { + return nil, fmt.Errorf("proto: bad byte length %d", nb) + } + end := p.index + nb + if end < p.index || end > len(p.buf) { + return nil, io.ErrUnexpectedEOF + } + + if !alloc { + // todo: check if can get more uses of alloc=false + buf = p.buf[p.index:end] + p.index += nb + return + } + + buf = make([]byte, nb) + copy(buf, p.buf[p.index:]) + p.index += nb + return +} + +// DecodeStringBytes reads an encoded string from the Buffer. +// This is the format used for the proto2 string type. +func (p *Buffer) DecodeStringBytes() (s string, err error) { + buf, err := p.DecodeRawBytes(false) + if err != nil { + return + } + return string(buf), nil +} + +// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. +// If the protocol buffer has extensions, and the field matches, add it as an extension. +// Otherwise, if the XXX_unrecognized field exists, append the skipped data there. +func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { + oi := o.index + + err := o.skip(t, tag, wire) + if err != nil { + return err + } + + if !unrecField.IsValid() { + return nil + } + + ptr := structPointer_Bytes(base, unrecField) + + // Add the skipped field to struct field + obuf := o.buf + + o.buf = *ptr + o.EncodeVarint(uint64(tag<<3 | wire)) + *ptr = append(o.buf, obuf[oi:o.index]...) + + o.buf = obuf + + return nil +} + +// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. +func (o *Buffer) skip(t reflect.Type, tag, wire int) error { + + var u uint64 + var err error + + switch wire { + case WireVarint: + _, err = o.DecodeVarint() + case WireFixed64: + _, err = o.DecodeFixed64() + case WireBytes: + _, err = o.DecodeRawBytes(false) + case WireFixed32: + _, err = o.DecodeFixed32() + case WireStartGroup: + for { + u, err = o.DecodeVarint() + if err != nil { + break + } + fwire := int(u & 0x7) + if fwire == WireEndGroup { + break + } + ftag := int(u >> 3) + err = o.skip(t, ftag, fwire) + if err != nil { + break + } + } + default: + err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) + } + return err +} + +// Unmarshaler is the interface representing objects that can +// unmarshal themselves. The method should reset the receiver before +// decoding starts. The argument points to data that may be +// overwritten, so implementations should not keep references to the +// buffer. +type Unmarshaler interface { + Unmarshal([]byte) error +} + +// Unmarshal parses the protocol buffer representation in buf and places the +// decoded result in pb. If the struct underlying pb does not match +// the data in buf, the results can be unpredictable. +// +// Unmarshal resets pb before starting to unmarshal, so any +// existing data in pb is always removed. Use UnmarshalMerge +// to preserve and append to existing data. +func Unmarshal(buf []byte, pb Message) error { + pb.Reset() + return UnmarshalMerge(buf, pb) +} + +// UnmarshalMerge parses the protocol buffer representation in buf and +// writes the decoded result to pb. If the struct underlying pb does not match +// the data in buf, the results can be unpredictable. +// +// UnmarshalMerge merges into existing data in pb. +// Most code should use Unmarshal instead. +func UnmarshalMerge(buf []byte, pb Message) error { + // If the object can unmarshal itself, let it. + if u, ok := pb.(Unmarshaler); ok { + return u.Unmarshal(buf) + } + return NewBuffer(buf).Unmarshal(pb) +} + +// Unmarshal parses the protocol buffer representation in the +// Buffer and places the decoded result in pb. If the struct +// underlying pb does not match the data in the buffer, the results can be +// unpredictable. +func (p *Buffer) Unmarshal(pb Message) error { + // If the object can unmarshal itself, let it. + if u, ok := pb.(Unmarshaler); ok { + err := u.Unmarshal(p.buf[p.index:]) + p.index = len(p.buf) + return err + } + + typ, base, err := getbase(pb) + if err != nil { + return err + } + + err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) + + if collectStats { + stats.Decode++ + } + + return err +} + +// unmarshalType does the work of unmarshaling a structure. +func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { + var state errorState + required, reqFields := prop.reqCount, uint64(0) + + var err error + for err == nil && o.index < len(o.buf) { + oi := o.index + var u uint64 + u, err = o.DecodeVarint() + if err != nil { + break + } + wire := int(u & 0x7) + if wire == WireEndGroup { + if is_group { + return nil // input is satisfied + } + return fmt.Errorf("proto: %s: wiretype end group for non-group", st) + } + tag := int(u >> 3) + if tag <= 0 { + return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire) + } + fieldnum, ok := prop.decoderTags.get(tag) + if !ok { + // Maybe it's an extension? + if prop.extendable { + if e := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) { + if err = o.skip(st, tag, wire); err == nil { + ext := e.ExtensionMap()[int32(tag)] // may be missing + ext.enc = append(ext.enc, o.buf[oi:o.index]...) + e.ExtensionMap()[int32(tag)] = ext + } + continue + } + } + err = o.skipAndSave(st, tag, wire, base, prop.unrecField) + continue + } + p := prop.Prop[fieldnum] + + if p.dec == nil { + fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) + continue + } + dec := p.dec + if wire != WireStartGroup && wire != p.WireType { + if wire == WireBytes && p.packedDec != nil { + // a packable field + dec = p.packedDec + } else { + err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) + continue + } + } + decErr := dec(o, p, base) + if decErr != nil && !state.shouldContinue(decErr, p) { + err = decErr + } + if err == nil && p.Required { + // Successfully decoded a required field. + if tag <= 64 { + // use bitmap for fields 1-64 to catch field reuse. + var mask uint64 = 1 << uint64(tag-1) + if reqFields&mask == 0 { + // new required field + reqFields |= mask + required-- + } + } else { + // This is imprecise. It can be fooled by a required field + // with a tag > 64 that is encoded twice; that's very rare. + // A fully correct implementation would require allocating + // a data structure, which we would like to avoid. + required-- + } + } + } + if err == nil { + if is_group { + return io.ErrUnexpectedEOF + } + if state.err != nil { + return state.err + } + if required > 0 { + // Not enough information to determine the exact field. If we use extra + // CPU, we could determine the field only if the missing required field + // has a tag <= 64 and we check reqFields. + return &RequiredNotSetError{"{Unknown}"} + } + } + return err +} + +// Individual type decoders +// For each, +// u is the decoded value, +// v is a pointer to the field (pointer) in the struct + +// Sizes of the pools to allocate inside the Buffer. +// The goal is modest amortization and allocation +// on at least 16-byte boundaries. +const ( + boolPoolSize = 16 + uint32PoolSize = 8 + uint64PoolSize = 4 +) + +// Decode a bool. +func (o *Buffer) dec_bool(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + if len(o.bools) == 0 { + o.bools = make([]bool, boolPoolSize) + } + o.bools[0] = u != 0 + *structPointer_Bool(base, p.field) = &o.bools[0] + o.bools = o.bools[1:] + return nil +} + +func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + *structPointer_BoolVal(base, p.field) = u != 0 + return nil +} + +// Decode an int32. +func (o *Buffer) dec_int32(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) + return nil +} + +func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u)) + return nil +} + +// Decode an int64. +func (o *Buffer) dec_int64(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + word64_Set(structPointer_Word64(base, p.field), o, u) + return nil +} + +func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + word64Val_Set(structPointer_Word64Val(base, p.field), o, u) + return nil +} + +// Decode a string. +func (o *Buffer) dec_string(p *Properties, base structPointer) error { + s, err := o.DecodeStringBytes() + if err != nil { + return err + } + *structPointer_String(base, p.field) = &s + return nil +} + +func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error { + s, err := o.DecodeStringBytes() + if err != nil { + return err + } + *structPointer_StringVal(base, p.field) = s + return nil +} + +// Decode a slice of bytes ([]byte). +func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { + b, err := o.DecodeRawBytes(true) + if err != nil { + return err + } + *structPointer_Bytes(base, p.field) = b + return nil +} + +// Decode a slice of bools ([]bool). +func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + v := structPointer_BoolSlice(base, p.field) + *v = append(*v, u != 0) + return nil +} + +// Decode a slice of bools ([]bool) in packed format. +func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { + v := structPointer_BoolSlice(base, p.field) + + nn, err := o.DecodeVarint() + if err != nil { + return err + } + nb := int(nn) // number of bytes of encoded bools + + y := *v + for i := 0; i < nb; i++ { + u, err := p.valDec(o) + if err != nil { + return err + } + y = append(y, u != 0) + } + + *v = y + return nil +} + +// Decode a slice of int32s ([]int32). +func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + structPointer_Word32Slice(base, p.field).Append(uint32(u)) + return nil +} + +// Decode a slice of int32s ([]int32) in packed format. +func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { + v := structPointer_Word32Slice(base, p.field) + + nn, err := o.DecodeVarint() + if err != nil { + return err + } + nb := int(nn) // number of bytes of encoded int32s + + fin := o.index + nb + if fin < o.index { + return errOverflow + } + for o.index < fin { + u, err := p.valDec(o) + if err != nil { + return err + } + v.Append(uint32(u)) + } + return nil +} + +// Decode a slice of int64s ([]int64). +func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + + structPointer_Word64Slice(base, p.field).Append(u) + return nil +} + +// Decode a slice of int64s ([]int64) in packed format. +func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { + v := structPointer_Word64Slice(base, p.field) + + nn, err := o.DecodeVarint() + if err != nil { + return err + } + nb := int(nn) // number of bytes of encoded int64s + + fin := o.index + nb + if fin < o.index { + return errOverflow + } + for o.index < fin { + u, err := p.valDec(o) + if err != nil { + return err + } + v.Append(u) + } + return nil +} + +// Decode a slice of strings ([]string). +func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { + s, err := o.DecodeStringBytes() + if err != nil { + return err + } + v := structPointer_StringSlice(base, p.field) + *v = append(*v, s) + return nil +} + +// Decode a slice of slice of bytes ([][]byte). +func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { + b, err := o.DecodeRawBytes(true) + if err != nil { + return err + } + v := structPointer_BytesSlice(base, p.field) + *v = append(*v, b) + return nil +} + +// Decode a map field. +func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { + raw, err := o.DecodeRawBytes(false) + if err != nil { + return err + } + oi := o.index // index at the end of this map entry + o.index -= len(raw) // move buffer back to start of map entry + + mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V + if mptr.Elem().IsNil() { + mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) + } + v := mptr.Elem() // map[K]V + + // Prepare addressable doubly-indirect placeholders for the key and value types. + // See enc_new_map for why. + keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K + keybase := toStructPointer(keyptr.Addr()) // **K + + var valbase structPointer + var valptr reflect.Value + switch p.mtype.Elem().Kind() { + case reflect.Slice: + // []byte + var dummy []byte + valptr = reflect.ValueOf(&dummy) // *[]byte + valbase = toStructPointer(valptr) // *[]byte + case reflect.Ptr: + // message; valptr is **Msg; need to allocate the intermediate pointer + valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V + valptr.Set(reflect.New(valptr.Type().Elem())) + valbase = toStructPointer(valptr) + default: + // everything else + valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V + valbase = toStructPointer(valptr.Addr()) // **V + } + + // Decode. + // This parses a restricted wire format, namely the encoding of a message + // with two fields. See enc_new_map for the format. + for o.index < oi { + // tagcode for key and value properties are always a single byte + // because they have tags 1 and 2. + tagcode := o.buf[o.index] + o.index++ + switch tagcode { + case p.mkeyprop.tagcode[0]: + if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil { + return err + } + case p.mvalprop.tagcode[0]: + if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil { + return err + } + default: + // TODO: Should we silently skip this instead? + return fmt.Errorf("proto: bad map data tag %d", raw[0]) + } + } + keyelem, valelem := keyptr.Elem(), valptr.Elem() + if !keyelem.IsValid() || !valelem.IsValid() { + // We did not decode the key or the value in the map entry. + // Either way, it's an invalid map entry. + return fmt.Errorf("proto: bad map data: missing key/val") + } + + v.SetMapIndex(keyelem, valelem) + return nil +} + +// Decode a group. +func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { + bas := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(bas) { + // allocate new nested message + bas = toStructPointer(reflect.New(p.stype)) + structPointer_SetStructPointer(base, p.field, bas) + } + return o.unmarshalType(p.stype, p.sprop, true, bas) +} + +// Decode an embedded message. +func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { + raw, e := o.DecodeRawBytes(false) + if e != nil { + return e + } + + bas := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(bas) { + // allocate new nested message + bas = toStructPointer(reflect.New(p.stype)) + structPointer_SetStructPointer(base, p.field, bas) + } + + // If the object can unmarshal itself, let it. + if p.isUnmarshaler { + iv := structPointer_Interface(bas, p.stype) + return iv.(Unmarshaler).Unmarshal(raw) + } + + obuf := o.buf + oi := o.index + o.buf = raw + o.index = 0 + + err = o.unmarshalType(p.stype, p.sprop, false, bas) + o.buf = obuf + o.index = oi + + return err +} + +// Decode a slice of embedded messages. +func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { + return o.dec_slice_struct(p, false, base) +} + +// Decode a slice of embedded groups. +func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { + return o.dec_slice_struct(p, true, base) +} + +// Decode a slice of structs ([]*struct). +func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { + v := reflect.New(p.stype) + bas := toStructPointer(v) + structPointer_StructPointerSlice(base, p.field).Append(bas) + + if is_group { + err := o.unmarshalType(p.stype, p.sprop, is_group, bas) + return err + } + + raw, err := o.DecodeRawBytes(false) + if err != nil { + return err + } + + // If the object can unmarshal itself, let it. + if p.isUnmarshaler { + iv := v.Interface() + return iv.(Unmarshaler).Unmarshal(raw) + } + + obuf := o.buf + oi := o.index + o.buf = raw + o.index = 0 + + err = o.unmarshalType(p.stype, p.sprop, is_group, bas) + + o.buf = obuf + o.index = oi + + return err +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go new file mode 100644 index 0000000..72c780b --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go @@ -0,0 +1,1293 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Routines for encoding data into the wire format for protocol buffers. + */ + +import ( + "errors" + "fmt" + "reflect" + "sort" +) + +// RequiredNotSetError is the error returned if Marshal is called with +// a protocol buffer struct whose required fields have not +// all been initialized. It is also the error returned if Unmarshal is +// called with an encoded protocol buffer that does not include all the +// required fields. +// +// When printed, RequiredNotSetError reports the first unset required field in a +// message. If the field cannot be precisely determined, it is reported as +// "{Unknown}". +type RequiredNotSetError struct { + field string +} + +func (e *RequiredNotSetError) Error() string { + return fmt.Sprintf("proto: required field %q not set", e.field) +} + +var ( + // errRepeatedHasNil is the error returned if Marshal is called with + // a struct with a repeated field containing a nil element. + errRepeatedHasNil = errors.New("proto: repeated field has nil element") + + // ErrNil is the error returned if Marshal is called with nil. + ErrNil = errors.New("proto: Marshal called with nil") +) + +// The fundamental encoders that put bytes on the wire. +// Those that take integer types all accept uint64 and are +// therefore of type valueEncoder. + +const maxVarintBytes = 10 // maximum length of a varint + +// EncodeVarint returns the varint encoding of x. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +// Not used by the package itself, but helpful to clients +// wishing to use the same encoding. +func EncodeVarint(x uint64) []byte { + var buf [maxVarintBytes]byte + var n int + for n = 0; x > 127; n++ { + buf[n] = 0x80 | uint8(x&0x7F) + x >>= 7 + } + buf[n] = uint8(x) + n++ + return buf[0:n] +} + +// EncodeVarint writes a varint-encoded integer to the Buffer. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func (p *Buffer) EncodeVarint(x uint64) error { + for x >= 1<<7 { + p.buf = append(p.buf, uint8(x&0x7f|0x80)) + x >>= 7 + } + p.buf = append(p.buf, uint8(x)) + return nil +} + +func sizeVarint(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} + +// EncodeFixed64 writes a 64-bit integer to the Buffer. +// This is the format for the +// fixed64, sfixed64, and double protocol buffer types. +func (p *Buffer) EncodeFixed64(x uint64) error { + p.buf = append(p.buf, + uint8(x), + uint8(x>>8), + uint8(x>>16), + uint8(x>>24), + uint8(x>>32), + uint8(x>>40), + uint8(x>>48), + uint8(x>>56)) + return nil +} + +func sizeFixed64(x uint64) int { + return 8 +} + +// EncodeFixed32 writes a 32-bit integer to the Buffer. +// This is the format for the +// fixed32, sfixed32, and float protocol buffer types. +func (p *Buffer) EncodeFixed32(x uint64) error { + p.buf = append(p.buf, + uint8(x), + uint8(x>>8), + uint8(x>>16), + uint8(x>>24)) + return nil +} + +func sizeFixed32(x uint64) int { + return 4 +} + +// EncodeZigzag64 writes a zigzag-encoded 64-bit integer +// to the Buffer. +// This is the format used for the sint64 protocol buffer type. +func (p *Buffer) EncodeZigzag64(x uint64) error { + // use signed number to get arithmetic right shift. + return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} + +func sizeZigzag64(x uint64) int { + return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} + +// EncodeZigzag32 writes a zigzag-encoded 32-bit integer +// to the Buffer. +// This is the format used for the sint32 protocol buffer type. +func (p *Buffer) EncodeZigzag32(x uint64) error { + // use signed number to get arithmetic right shift. + return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) +} + +func sizeZigzag32(x uint64) int { + return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) +} + +// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. +// This is the format used for the bytes protocol buffer +// type and for embedded messages. +func (p *Buffer) EncodeRawBytes(b []byte) error { + p.EncodeVarint(uint64(len(b))) + p.buf = append(p.buf, b...) + return nil +} + +func sizeRawBytes(b []byte) int { + return sizeVarint(uint64(len(b))) + + len(b) +} + +// EncodeStringBytes writes an encoded string to the Buffer. +// This is the format used for the proto2 string type. +func (p *Buffer) EncodeStringBytes(s string) error { + p.EncodeVarint(uint64(len(s))) + p.buf = append(p.buf, s...) + return nil +} + +func sizeStringBytes(s string) int { + return sizeVarint(uint64(len(s))) + + len(s) +} + +// Marshaler is the interface representing objects that can marshal themselves. +type Marshaler interface { + Marshal() ([]byte, error) +} + +// Marshal takes the protocol buffer +// and encodes it into the wire format, returning the data. +func Marshal(pb Message) ([]byte, error) { + // Can the object marshal itself? + if m, ok := pb.(Marshaler); ok { + return m.Marshal() + } + p := NewBuffer(nil) + err := p.Marshal(pb) + var state errorState + if err != nil && !state.shouldContinue(err, nil) { + return nil, err + } + if p.buf == nil && err == nil { + // Return a non-nil slice on success. + return []byte{}, nil + } + return p.buf, err +} + +// Marshal takes the protocol buffer +// and encodes it into the wire format, writing the result to the +// Buffer. +func (p *Buffer) Marshal(pb Message) error { + // Can the object marshal itself? + if m, ok := pb.(Marshaler); ok { + data, err := m.Marshal() + if err != nil { + return err + } + p.buf = append(p.buf, data...) + return nil + } + + t, base, err := getbase(pb) + if structPointer_IsNil(base) { + return ErrNil + } + if err == nil { + err = p.enc_struct(GetProperties(t.Elem()), base) + } + + if collectStats { + stats.Encode++ + } + + return err +} + +// Size returns the encoded size of a protocol buffer. +func Size(pb Message) (n int) { + // Can the object marshal itself? If so, Size is slow. + // TODO: add Size to Marshaler, or add a Sizer interface. + if m, ok := pb.(Marshaler); ok { + b, _ := m.Marshal() + return len(b) + } + + t, base, err := getbase(pb) + if structPointer_IsNil(base) { + return 0 + } + if err == nil { + n = size_struct(GetProperties(t.Elem()), base) + } + + if collectStats { + stats.Size++ + } + + return +} + +// Individual type encoders. + +// Encode a bool. +func (o *Buffer) enc_bool(p *Properties, base structPointer) error { + v := *structPointer_Bool(base, p.field) + if v == nil { + return ErrNil + } + x := 0 + if *v { + x = 1 + } + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, uint64(x)) + return nil +} + +func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error { + v := *structPointer_BoolVal(base, p.field) + if !v { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, 1) + return nil +} + +func size_bool(p *Properties, base structPointer) int { + v := *structPointer_Bool(base, p.field) + if v == nil { + return 0 + } + return len(p.tagcode) + 1 // each bool takes exactly one byte +} + +func size_proto3_bool(p *Properties, base structPointer) int { + v := *structPointer_BoolVal(base, p.field) + if !v { + return 0 + } + return len(p.tagcode) + 1 // each bool takes exactly one byte +} + +// Encode an int32. +func (o *Buffer) enc_int32(p *Properties, base structPointer) error { + v := structPointer_Word32(base, p.field) + if word32_IsNil(v) { + return ErrNil + } + x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, uint64(x)) + return nil +} + +func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error { + v := structPointer_Word32Val(base, p.field) + x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range + if x == 0 { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, uint64(x)) + return nil +} + +func size_int32(p *Properties, base structPointer) (n int) { + v := structPointer_Word32(base, p.field) + if word32_IsNil(v) { + return 0 + } + x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range + n += len(p.tagcode) + n += p.valSize(uint64(x)) + return +} + +func size_proto3_int32(p *Properties, base structPointer) (n int) { + v := structPointer_Word32Val(base, p.field) + x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range + if x == 0 { + return 0 + } + n += len(p.tagcode) + n += p.valSize(uint64(x)) + return +} + +// Encode a uint32. +// Exactly the same as int32, except for no sign extension. +func (o *Buffer) enc_uint32(p *Properties, base structPointer) error { + v := structPointer_Word32(base, p.field) + if word32_IsNil(v) { + return ErrNil + } + x := word32_Get(v) + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, uint64(x)) + return nil +} + +func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error { + v := structPointer_Word32Val(base, p.field) + x := word32Val_Get(v) + if x == 0 { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, uint64(x)) + return nil +} + +func size_uint32(p *Properties, base structPointer) (n int) { + v := structPointer_Word32(base, p.field) + if word32_IsNil(v) { + return 0 + } + x := word32_Get(v) + n += len(p.tagcode) + n += p.valSize(uint64(x)) + return +} + +func size_proto3_uint32(p *Properties, base structPointer) (n int) { + v := structPointer_Word32Val(base, p.field) + x := word32Val_Get(v) + if x == 0 { + return 0 + } + n += len(p.tagcode) + n += p.valSize(uint64(x)) + return +} + +// Encode an int64. +func (o *Buffer) enc_int64(p *Properties, base structPointer) error { + v := structPointer_Word64(base, p.field) + if word64_IsNil(v) { + return ErrNil + } + x := word64_Get(v) + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, x) + return nil +} + +func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error { + v := structPointer_Word64Val(base, p.field) + x := word64Val_Get(v) + if x == 0 { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, x) + return nil +} + +func size_int64(p *Properties, base structPointer) (n int) { + v := structPointer_Word64(base, p.field) + if word64_IsNil(v) { + return 0 + } + x := word64_Get(v) + n += len(p.tagcode) + n += p.valSize(x) + return +} + +func size_proto3_int64(p *Properties, base structPointer) (n int) { + v := structPointer_Word64Val(base, p.field) + x := word64Val_Get(v) + if x == 0 { + return 0 + } + n += len(p.tagcode) + n += p.valSize(x) + return +} + +// Encode a string. +func (o *Buffer) enc_string(p *Properties, base structPointer) error { + v := *structPointer_String(base, p.field) + if v == nil { + return ErrNil + } + x := *v + o.buf = append(o.buf, p.tagcode...) + o.EncodeStringBytes(x) + return nil +} + +func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error { + v := *structPointer_StringVal(base, p.field) + if v == "" { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeStringBytes(v) + return nil +} + +func size_string(p *Properties, base structPointer) (n int) { + v := *structPointer_String(base, p.field) + if v == nil { + return 0 + } + x := *v + n += len(p.tagcode) + n += sizeStringBytes(x) + return +} + +func size_proto3_string(p *Properties, base structPointer) (n int) { + v := *structPointer_StringVal(base, p.field) + if v == "" { + return 0 + } + n += len(p.tagcode) + n += sizeStringBytes(v) + return +} + +// All protocol buffer fields are nillable, but be careful. +func isNil(v reflect.Value) bool { + switch v.Kind() { + case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return v.IsNil() + } + return false +} + +// Encode a message struct. +func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { + var state errorState + structp := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(structp) { + return ErrNil + } + + // Can the object marshal itself? + if p.isMarshaler { + m := structPointer_Interface(structp, p.stype).(Marshaler) + data, err := m.Marshal() + if err != nil && !state.shouldContinue(err, nil) { + return err + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeRawBytes(data) + return nil + } + + o.buf = append(o.buf, p.tagcode...) + return o.enc_len_struct(p.sprop, structp, &state) +} + +func size_struct_message(p *Properties, base structPointer) int { + structp := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(structp) { + return 0 + } + + // Can the object marshal itself? + if p.isMarshaler { + m := structPointer_Interface(structp, p.stype).(Marshaler) + data, _ := m.Marshal() + n0 := len(p.tagcode) + n1 := sizeRawBytes(data) + return n0 + n1 + } + + n0 := len(p.tagcode) + n1 := size_struct(p.sprop, structp) + n2 := sizeVarint(uint64(n1)) // size of encoded length + return n0 + n1 + n2 +} + +// Encode a group struct. +func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error { + var state errorState + b := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(b) { + return ErrNil + } + + o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) + err := o.enc_struct(p.sprop, b) + if err != nil && !state.shouldContinue(err, nil) { + return err + } + o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) + return state.err +} + +func size_struct_group(p *Properties, base structPointer) (n int) { + b := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(b) { + return 0 + } + + n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup)) + n += size_struct(p.sprop, b) + n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup)) + return +} + +// Encode a slice of bools ([]bool). +func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error { + s := *structPointer_BoolSlice(base, p.field) + l := len(s) + if l == 0 { + return ErrNil + } + for _, x := range s { + o.buf = append(o.buf, p.tagcode...) + v := uint64(0) + if x { + v = 1 + } + p.valEnc(o, v) + } + return nil +} + +func size_slice_bool(p *Properties, base structPointer) int { + s := *structPointer_BoolSlice(base, p.field) + l := len(s) + if l == 0 { + return 0 + } + return l * (len(p.tagcode) + 1) // each bool takes exactly one byte +} + +// Encode a slice of bools ([]bool) in packed format. +func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error { + s := *structPointer_BoolSlice(base, p.field) + l := len(s) + if l == 0 { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeVarint(uint64(l)) // each bool takes exactly one byte + for _, x := range s { + v := uint64(0) + if x { + v = 1 + } + p.valEnc(o, v) + } + return nil +} + +func size_slice_packed_bool(p *Properties, base structPointer) (n int) { + s := *structPointer_BoolSlice(base, p.field) + l := len(s) + if l == 0 { + return 0 + } + n += len(p.tagcode) + n += sizeVarint(uint64(l)) + n += l // each bool takes exactly one byte + return +} + +// Encode a slice of bytes ([]byte). +func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error { + s := *structPointer_Bytes(base, p.field) + if s == nil { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeRawBytes(s) + return nil +} + +func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error { + s := *structPointer_Bytes(base, p.field) + if len(s) == 0 { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeRawBytes(s) + return nil +} + +func size_slice_byte(p *Properties, base structPointer) (n int) { + s := *structPointer_Bytes(base, p.field) + if s == nil { + return 0 + } + n += len(p.tagcode) + n += sizeRawBytes(s) + return +} + +func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { + s := *structPointer_Bytes(base, p.field) + if len(s) == 0 { + return 0 + } + n += len(p.tagcode) + n += sizeRawBytes(s) + return +} + +// Encode a slice of int32s ([]int32). +func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + for i := 0; i < l; i++ { + o.buf = append(o.buf, p.tagcode...) + x := int32(s.Index(i)) // permit sign extension to use full 64-bit range + p.valEnc(o, uint64(x)) + } + return nil +} + +func size_slice_int32(p *Properties, base structPointer) (n int) { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + for i := 0; i < l; i++ { + n += len(p.tagcode) + x := int32(s.Index(i)) // permit sign extension to use full 64-bit range + n += p.valSize(uint64(x)) + } + return +} + +// Encode a slice of int32s ([]int32) in packed format. +func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + // TODO: Reuse a Buffer. + buf := NewBuffer(nil) + for i := 0; i < l; i++ { + x := int32(s.Index(i)) // permit sign extension to use full 64-bit range + p.valEnc(buf, uint64(x)) + } + + o.buf = append(o.buf, p.tagcode...) + o.EncodeVarint(uint64(len(buf.buf))) + o.buf = append(o.buf, buf.buf...) + return nil +} + +func size_slice_packed_int32(p *Properties, base structPointer) (n int) { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + var bufSize int + for i := 0; i < l; i++ { + x := int32(s.Index(i)) // permit sign extension to use full 64-bit range + bufSize += p.valSize(uint64(x)) + } + + n += len(p.tagcode) + n += sizeVarint(uint64(bufSize)) + n += bufSize + return +} + +// Encode a slice of uint32s ([]uint32). +// Exactly the same as int32, except for no sign extension. +func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + for i := 0; i < l; i++ { + o.buf = append(o.buf, p.tagcode...) + x := s.Index(i) + p.valEnc(o, uint64(x)) + } + return nil +} + +func size_slice_uint32(p *Properties, base structPointer) (n int) { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + for i := 0; i < l; i++ { + n += len(p.tagcode) + x := s.Index(i) + n += p.valSize(uint64(x)) + } + return +} + +// Encode a slice of uint32s ([]uint32) in packed format. +// Exactly the same as int32, except for no sign extension. +func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + // TODO: Reuse a Buffer. + buf := NewBuffer(nil) + for i := 0; i < l; i++ { + p.valEnc(buf, uint64(s.Index(i))) + } + + o.buf = append(o.buf, p.tagcode...) + o.EncodeVarint(uint64(len(buf.buf))) + o.buf = append(o.buf, buf.buf...) + return nil +} + +func size_slice_packed_uint32(p *Properties, base structPointer) (n int) { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + var bufSize int + for i := 0; i < l; i++ { + bufSize += p.valSize(uint64(s.Index(i))) + } + + n += len(p.tagcode) + n += sizeVarint(uint64(bufSize)) + n += bufSize + return +} + +// Encode a slice of int64s ([]int64). +func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error { + s := structPointer_Word64Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + for i := 0; i < l; i++ { + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, s.Index(i)) + } + return nil +} + +func size_slice_int64(p *Properties, base structPointer) (n int) { + s := structPointer_Word64Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + for i := 0; i < l; i++ { + n += len(p.tagcode) + n += p.valSize(s.Index(i)) + } + return +} + +// Encode a slice of int64s ([]int64) in packed format. +func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error { + s := structPointer_Word64Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + // TODO: Reuse a Buffer. + buf := NewBuffer(nil) + for i := 0; i < l; i++ { + p.valEnc(buf, s.Index(i)) + } + + o.buf = append(o.buf, p.tagcode...) + o.EncodeVarint(uint64(len(buf.buf))) + o.buf = append(o.buf, buf.buf...) + return nil +} + +func size_slice_packed_int64(p *Properties, base structPointer) (n int) { + s := structPointer_Word64Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + var bufSize int + for i := 0; i < l; i++ { + bufSize += p.valSize(s.Index(i)) + } + + n += len(p.tagcode) + n += sizeVarint(uint64(bufSize)) + n += bufSize + return +} + +// Encode a slice of slice of bytes ([][]byte). +func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error { + ss := *structPointer_BytesSlice(base, p.field) + l := len(ss) + if l == 0 { + return ErrNil + } + for i := 0; i < l; i++ { + o.buf = append(o.buf, p.tagcode...) + o.EncodeRawBytes(ss[i]) + } + return nil +} + +func size_slice_slice_byte(p *Properties, base structPointer) (n int) { + ss := *structPointer_BytesSlice(base, p.field) + l := len(ss) + if l == 0 { + return 0 + } + n += l * len(p.tagcode) + for i := 0; i < l; i++ { + n += sizeRawBytes(ss[i]) + } + return +} + +// Encode a slice of strings ([]string). +func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error { + ss := *structPointer_StringSlice(base, p.field) + l := len(ss) + for i := 0; i < l; i++ { + o.buf = append(o.buf, p.tagcode...) + o.EncodeStringBytes(ss[i]) + } + return nil +} + +func size_slice_string(p *Properties, base structPointer) (n int) { + ss := *structPointer_StringSlice(base, p.field) + l := len(ss) + n += l * len(p.tagcode) + for i := 0; i < l; i++ { + n += sizeStringBytes(ss[i]) + } + return +} + +// Encode a slice of message structs ([]*struct). +func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error { + var state errorState + s := structPointer_StructPointerSlice(base, p.field) + l := s.Len() + + for i := 0; i < l; i++ { + structp := s.Index(i) + if structPointer_IsNil(structp) { + return errRepeatedHasNil + } + + // Can the object marshal itself? + if p.isMarshaler { + m := structPointer_Interface(structp, p.stype).(Marshaler) + data, err := m.Marshal() + if err != nil && !state.shouldContinue(err, nil) { + return err + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeRawBytes(data) + continue + } + + o.buf = append(o.buf, p.tagcode...) + err := o.enc_len_struct(p.sprop, structp, &state) + if err != nil && !state.shouldContinue(err, nil) { + if err == ErrNil { + return errRepeatedHasNil + } + return err + } + } + return state.err +} + +func size_slice_struct_message(p *Properties, base structPointer) (n int) { + s := structPointer_StructPointerSlice(base, p.field) + l := s.Len() + n += l * len(p.tagcode) + for i := 0; i < l; i++ { + structp := s.Index(i) + if structPointer_IsNil(structp) { + return // return the size up to this point + } + + // Can the object marshal itself? + if p.isMarshaler { + m := structPointer_Interface(structp, p.stype).(Marshaler) + data, _ := m.Marshal() + n += len(p.tagcode) + n += sizeRawBytes(data) + continue + } + + n0 := size_struct(p.sprop, structp) + n1 := sizeVarint(uint64(n0)) // size of encoded length + n += n0 + n1 + } + return +} + +// Encode a slice of group structs ([]*struct). +func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error { + var state errorState + s := structPointer_StructPointerSlice(base, p.field) + l := s.Len() + + for i := 0; i < l; i++ { + b := s.Index(i) + if structPointer_IsNil(b) { + return errRepeatedHasNil + } + + o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) + + err := o.enc_struct(p.sprop, b) + + if err != nil && !state.shouldContinue(err, nil) { + if err == ErrNil { + return errRepeatedHasNil + } + return err + } + + o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) + } + return state.err +} + +func size_slice_struct_group(p *Properties, base structPointer) (n int) { + s := structPointer_StructPointerSlice(base, p.field) + l := s.Len() + + n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup)) + n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup)) + for i := 0; i < l; i++ { + b := s.Index(i) + if structPointer_IsNil(b) { + return // return size up to this point + } + + n += size_struct(p.sprop, b) + } + return +} + +// Encode an extension map. +func (o *Buffer) enc_map(p *Properties, base structPointer) error { + v := *structPointer_ExtMap(base, p.field) + if err := encodeExtensionMap(v); err != nil { + return err + } + // Fast-path for common cases: zero or one extensions. + if len(v) <= 1 { + for _, e := range v { + o.buf = append(o.buf, e.enc...) + } + return nil + } + + // Sort keys to provide a deterministic encoding. + keys := make([]int, 0, len(v)) + for k := range v { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + for _, k := range keys { + o.buf = append(o.buf, v[int32(k)].enc...) + } + return nil +} + +func size_map(p *Properties, base structPointer) int { + v := *structPointer_ExtMap(base, p.field) + return sizeExtensionMap(v) +} + +// Encode a map field. +func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { + var state errorState // XXX: or do we need to plumb this through? + + /* + A map defined as + map map_field = N; + is encoded in the same way as + message MapFieldEntry { + key_type key = 1; + value_type value = 2; + } + repeated MapFieldEntry map_field = N; + */ + + v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V + if v.Len() == 0 { + return nil + } + + keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) + + enc := func() error { + if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil { + return err + } + if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil { + return err + } + return nil + } + + keys := v.MapKeys() + sort.Sort(mapKeys(keys)) + for _, key := range keys { + val := v.MapIndex(key) + + // The only illegal map entry values are nil message pointers. + if val.Kind() == reflect.Ptr && val.IsNil() { + return errors.New("proto: map has nil element") + } + + keycopy.Set(key) + valcopy.Set(val) + + o.buf = append(o.buf, p.tagcode...) + if err := o.enc_len_thing(enc, &state); err != nil { + return err + } + } + return nil +} + +func size_new_map(p *Properties, base structPointer) int { + v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V + + keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) + + n := 0 + for _, key := range v.MapKeys() { + val := v.MapIndex(key) + keycopy.Set(key) + valcopy.Set(val) + + // Tag codes for key and val are the responsibility of the sub-sizer. + keysize := p.mkeyprop.size(p.mkeyprop, keybase) + valsize := p.mvalprop.size(p.mvalprop, valbase) + entry := keysize + valsize + // Add on tag code and length of map entry itself. + n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry + } + return n +} + +// mapEncodeScratch returns a new reflect.Value matching the map's value type, +// and a structPointer suitable for passing to an encoder or sizer. +func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { + // Prepare addressable doubly-indirect placeholders for the key and value types. + // This is needed because the element-type encoders expect **T, but the map iteration produces T. + + keycopy = reflect.New(mapType.Key()).Elem() // addressable K + keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K + keyptr.Set(keycopy.Addr()) // + keybase = toStructPointer(keyptr.Addr()) // **K + + // Value types are more varied and require special handling. + switch mapType.Elem().Kind() { + case reflect.Slice: + // []byte + var dummy []byte + valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte + valbase = toStructPointer(valcopy.Addr()) + case reflect.Ptr: + // message; the generated field type is map[K]*Msg (so V is *Msg), + // so we only need one level of indirection. + valcopy = reflect.New(mapType.Elem()).Elem() // addressable V + valbase = toStructPointer(valcopy.Addr()) + default: + // everything else + valcopy = reflect.New(mapType.Elem()).Elem() // addressable V + valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V + valptr.Set(valcopy.Addr()) // + valbase = toStructPointer(valptr.Addr()) // **V + } + return +} + +// Encode a struct. +func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { + var state errorState + // Encode fields in tag order so that decoders may use optimizations + // that depend on the ordering. + // https://developers.google.com/protocol-buffers/docs/encoding#order + for _, i := range prop.order { + p := prop.Prop[i] + if p.enc != nil { + err := p.enc(o, p, base) + if err != nil { + if err == ErrNil { + if p.Required && state.err == nil { + state.err = &RequiredNotSetError{p.Name} + } + } else if err == errRepeatedHasNil { + // Give more context to nil values in repeated fields. + return errors.New("repeated field " + p.OrigName + " has nil element") + } else if !state.shouldContinue(err, p) { + return err + } + } + } + } + + // Add unrecognized fields at the end. + if prop.unrecField.IsValid() { + v := *structPointer_Bytes(base, prop.unrecField) + if len(v) > 0 { + o.buf = append(o.buf, v...) + } + } + + return state.err +} + +func size_struct(prop *StructProperties, base structPointer) (n int) { + for _, i := range prop.order { + p := prop.Prop[i] + if p.size != nil { + n += p.size(p, base) + } + } + + // Add unrecognized fields at the end. + if prop.unrecField.IsValid() { + v := *structPointer_Bytes(base, prop.unrecField) + n += len(v) + } + + return +} + +var zeroes [20]byte // longer than any conceivable sizeVarint + +// Encode a struct, preceded by its encoded length (as a varint). +func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error { + return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state) +} + +// Encode something, preceded by its encoded length (as a varint). +func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error { + iLen := len(o.buf) + o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length + iMsg := len(o.buf) + err := enc() + if err != nil && !state.shouldContinue(err, nil) { + return err + } + lMsg := len(o.buf) - iMsg + lLen := sizeVarint(uint64(lMsg)) + switch x := lLen - (iMsg - iLen); { + case x > 0: // actual length is x bytes larger than the space we reserved + // Move msg x bytes right. + o.buf = append(o.buf, zeroes[:x]...) + copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) + case x < 0: // actual length is x bytes smaller than the space we reserved + // Move msg x bytes left. + copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) + o.buf = o.buf[:len(o.buf)+x] // x is negative + } + // Encode the length in the reserved space. + o.buf = o.buf[:iLen] + o.EncodeVarint(uint64(lMsg)) + o.buf = o.buf[:len(o.buf)+lMsg] + return state.err +} + +// errorState maintains the first error that occurs and updates that error +// with additional context. +type errorState struct { + err error +} + +// shouldContinue reports whether encoding should continue upon encountering the +// given error. If the error is RequiredNotSetError, shouldContinue returns true +// and, if this is the first appearance of that error, remembers it for future +// reporting. +// +// If prop is not nil, it may update any error with additional context about the +// field with the error. +func (s *errorState) shouldContinue(err error, prop *Properties) bool { + // Ignore unset required fields. + reqNotSet, ok := err.(*RequiredNotSetError) + if !ok { + return false + } + if s.err == nil { + if prop != nil { + err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field} + } + s.err = err + } + return true +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go new file mode 100644 index 0000000..d8673a3 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go @@ -0,0 +1,256 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2011 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Protocol buffer comparison. +// TODO: MessageSet. + +package proto + +import ( + "bytes" + "log" + "reflect" + "strings" +) + +/* +Equal returns true iff protocol buffers a and b are equal. +The arguments must both be pointers to protocol buffer structs. + +Equality is defined in this way: + - Two messages are equal iff they are the same type, + corresponding fields are equal, unknown field sets + are equal, and extensions sets are equal. + - Two set scalar fields are equal iff their values are equal. + If the fields are of a floating-point type, remember that + NaN != x for all x, including NaN. + - Two repeated fields are equal iff their lengths are the same, + and their corresponding elements are equal (a "bytes" field, + although represented by []byte, is not a repeated field) + - Two unset fields are equal. + - Two unknown field sets are equal if their current + encoded state is equal. + - Two extension sets are equal iff they have corresponding + elements that are pairwise equal. + - Every other combination of things are not equal. + +The return value is undefined if a and b are not protocol buffers. +*/ +func Equal(a, b Message) bool { + if a == nil || b == nil { + return a == b + } + v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) + if v1.Type() != v2.Type() { + return false + } + if v1.Kind() == reflect.Ptr { + if v1.IsNil() { + return v2.IsNil() + } + if v2.IsNil() { + return false + } + v1, v2 = v1.Elem(), v2.Elem() + } + if v1.Kind() != reflect.Struct { + return false + } + return equalStruct(v1, v2) +} + +// v1 and v2 are known to have the same type. +func equalStruct(v1, v2 reflect.Value) bool { + for i := 0; i < v1.NumField(); i++ { + f := v1.Type().Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + f1, f2 := v1.Field(i), v2.Field(i) + if f.Type.Kind() == reflect.Ptr { + if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { + // both unset + continue + } else if n1 != n2 { + // set/unset mismatch + return false + } + b1, ok := f1.Interface().(raw) + if ok { + b2 := f2.Interface().(raw) + // RawMessage + if !bytes.Equal(b1.Bytes(), b2.Bytes()) { + return false + } + continue + } + f1, f2 = f1.Elem(), f2.Elem() + } + if !equalAny(f1, f2) { + return false + } + } + + if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { + em2 := v2.FieldByName("XXX_extensions") + if !equalExtensions(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { + return false + } + } + + uf := v1.FieldByName("XXX_unrecognized") + if !uf.IsValid() { + return true + } + + u1 := uf.Bytes() + u2 := v2.FieldByName("XXX_unrecognized").Bytes() + if !bytes.Equal(u1, u2) { + return false + } + + return true +} + +// v1 and v2 are known to have the same type. +func equalAny(v1, v2 reflect.Value) bool { + if v1.Type() == protoMessageType { + m1, _ := v1.Interface().(Message) + m2, _ := v2.Interface().(Message) + return Equal(m1, m2) + } + switch v1.Kind() { + case reflect.Bool: + return v1.Bool() == v2.Bool() + case reflect.Float32, reflect.Float64: + return v1.Float() == v2.Float() + case reflect.Int32, reflect.Int64: + return v1.Int() == v2.Int() + case reflect.Map: + if v1.Len() != v2.Len() { + return false + } + for _, key := range v1.MapKeys() { + val2 := v2.MapIndex(key) + if !val2.IsValid() { + // This key was not found in the second map. + return false + } + if !equalAny(v1.MapIndex(key), val2) { + return false + } + } + return true + case reflect.Ptr: + return equalAny(v1.Elem(), v2.Elem()) + case reflect.Slice: + if v1.Type().Elem().Kind() == reflect.Uint8 { + // short circuit: []byte + if v1.IsNil() != v2.IsNil() { + return false + } + return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) + } + + if v1.Len() != v2.Len() { + return false + } + for i := 0; i < v1.Len(); i++ { + if !equalAny(v1.Index(i), v2.Index(i)) { + return false + } + } + return true + case reflect.String: + return v1.Interface().(string) == v2.Interface().(string) + case reflect.Struct: + return equalStruct(v1, v2) + case reflect.Uint32, reflect.Uint64: + return v1.Uint() == v2.Uint() + } + + // unknown type, so not a protocol buffer + log.Printf("proto: don't know how to compare %v", v1) + return false +} + +// base is the struct type that the extensions are based on. +// em1 and em2 are extension maps. +func equalExtensions(base reflect.Type, em1, em2 map[int32]Extension) bool { + if len(em1) != len(em2) { + return false + } + + for extNum, e1 := range em1 { + e2, ok := em2[extNum] + if !ok { + return false + } + + m1, m2 := e1.value, e2.value + + if m1 != nil && m2 != nil { + // Both are unencoded. + if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) { + return false + } + continue + } + + // At least one is encoded. To do a semantically correct comparison + // we need to unmarshal them first. + var desc *ExtensionDesc + if m := extensionMaps[base]; m != nil { + desc = m[extNum] + } + if desc == nil { + log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) + continue + } + var err error + if m1 == nil { + m1, err = decodeExtension(e1.enc, desc) + } + if m2 == nil && err == nil { + m2, err = decodeExtension(e2.enc, desc) + } + if err != nil { + // The encoded form is invalid. + log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) + return false + } + if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) { + return false + } + } + + return true +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go new file mode 100644 index 0000000..b322f65 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go @@ -0,0 +1,191 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2011 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto_test + +import ( + "testing" + + . "github.com/golang/protobuf/proto" + pb "github.com/golang/protobuf/proto/testdata" +) + +// Four identical base messages. +// The init function adds extensions to some of them. +var messageWithoutExtension = &pb.MyMessage{Count: Int32(7)} +var messageWithExtension1a = &pb.MyMessage{Count: Int32(7)} +var messageWithExtension1b = &pb.MyMessage{Count: Int32(7)} +var messageWithExtension2 = &pb.MyMessage{Count: Int32(7)} + +// Two messages with non-message extensions. +var messageWithInt32Extension1 = &pb.MyMessage{Count: Int32(8)} +var messageWithInt32Extension2 = &pb.MyMessage{Count: Int32(8)} + +func init() { + ext1 := &pb.Ext{Data: String("Kirk")} + ext2 := &pb.Ext{Data: String("Picard")} + + // messageWithExtension1a has ext1, but never marshals it. + if err := SetExtension(messageWithExtension1a, pb.E_Ext_More, ext1); err != nil { + panic("SetExtension on 1a failed: " + err.Error()) + } + + // messageWithExtension1b is the unmarshaled form of messageWithExtension1a. + if err := SetExtension(messageWithExtension1b, pb.E_Ext_More, ext1); err != nil { + panic("SetExtension on 1b failed: " + err.Error()) + } + buf, err := Marshal(messageWithExtension1b) + if err != nil { + panic("Marshal of 1b failed: " + err.Error()) + } + messageWithExtension1b.Reset() + if err := Unmarshal(buf, messageWithExtension1b); err != nil { + panic("Unmarshal of 1b failed: " + err.Error()) + } + + // messageWithExtension2 has ext2. + if err := SetExtension(messageWithExtension2, pb.E_Ext_More, ext2); err != nil { + panic("SetExtension on 2 failed: " + err.Error()) + } + + if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(23)); err != nil { + panic("SetExtension on Int32-1 failed: " + err.Error()) + } + if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(24)); err != nil { + panic("SetExtension on Int32-2 failed: " + err.Error()) + } +} + +var EqualTests = []struct { + desc string + a, b Message + exp bool +}{ + {"different types", &pb.GoEnum{}, &pb.GoTestField{}, false}, + {"equal empty", &pb.GoEnum{}, &pb.GoEnum{}, true}, + {"nil vs nil", nil, nil, true}, + {"typed nil vs typed nil", (*pb.GoEnum)(nil), (*pb.GoEnum)(nil), true}, + {"typed nil vs empty", (*pb.GoEnum)(nil), &pb.GoEnum{}, false}, + {"different typed nil", (*pb.GoEnum)(nil), (*pb.GoTestField)(nil), false}, + + {"one set field, one unset field", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{}, false}, + {"one set field zero, one unset field", &pb.GoTest{Param: Int32(0)}, &pb.GoTest{}, false}, + {"different set fields", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("bar")}, false}, + {"equal set", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("foo")}, true}, + + {"repeated, one set", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{}, false}, + {"repeated, different length", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{F_Int32Repeated: []int32{2}}, false}, + {"repeated, different value", &pb.GoTest{F_Int32Repeated: []int32{2}}, &pb.GoTest{F_Int32Repeated: []int32{3}}, false}, + {"repeated, equal", &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, true}, + {"repeated, nil equal nil", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: nil}, true}, + {"repeated, nil equal empty", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: []int32{}}, true}, + {"repeated, empty equal nil", &pb.GoTest{F_Int32Repeated: []int32{}}, &pb.GoTest{F_Int32Repeated: nil}, true}, + + { + "nested, different", + &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("foo")}}, + &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("bar")}}, + false, + }, + { + "nested, equal", + &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, + &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, + true, + }, + + {"bytes", &pb.OtherMessage{Value: []byte("foo")}, &pb.OtherMessage{Value: []byte("foo")}, true}, + {"bytes, empty", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: []byte{}}, true}, + {"bytes, empty vs nil", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: nil}, false}, + { + "repeated bytes", + &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, + &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, + true, + }, + + {"extension vs. no extension", messageWithoutExtension, messageWithExtension1a, false}, + {"extension vs. same extension", messageWithExtension1a, messageWithExtension1b, true}, + {"extension vs. different extension", messageWithExtension1a, messageWithExtension2, false}, + + {"int32 extension vs. itself", messageWithInt32Extension1, messageWithInt32Extension1, true}, + {"int32 extension vs. a different int32", messageWithInt32Extension1, messageWithInt32Extension2, false}, + + { + "message with group", + &pb.MyMessage{ + Count: Int32(1), + Somegroup: &pb.MyMessage_SomeGroup{ + GroupField: Int32(5), + }, + }, + &pb.MyMessage{ + Count: Int32(1), + Somegroup: &pb.MyMessage_SomeGroup{ + GroupField: Int32(5), + }, + }, + true, + }, + + { + "map same", + &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, + &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, + true, + }, + { + "map different entry", + &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, + &pb.MessageWithMap{NameMapping: map[int32]string{2: "Rob"}}, + false, + }, + { + "map different key only", + &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, + &pb.MessageWithMap{NameMapping: map[int32]string{2: "Ken"}}, + false, + }, + { + "map different value only", + &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, + &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob"}}, + false, + }, +} + +func TestEqual(t *testing.T) { + for _, tc := range EqualTests { + if res := Equal(tc.a, tc.b); res != tc.exp { + t.Errorf("%v: Equal(%v, %v) = %v, want %v", tc.desc, tc.a, tc.b, res, tc.exp) + } + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go new file mode 100644 index 0000000..e591cce --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go @@ -0,0 +1,400 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Types and routines for supporting protocol buffer extensions. + */ + +import ( + "errors" + "fmt" + "reflect" + "strconv" + "sync" +) + +// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. +var ErrMissingExtension = errors.New("proto: missing extension") + +// ExtensionRange represents a range of message extensions for a protocol buffer. +// Used in code generated by the protocol compiler. +type ExtensionRange struct { + Start, End int32 // both inclusive +} + +// extendableProto is an interface implemented by any protocol buffer that may be extended. +type extendableProto interface { + Message + ExtensionRangeArray() []ExtensionRange + ExtensionMap() map[int32]Extension +} + +var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem() + +// ExtensionDesc represents an extension specification. +// Used in generated code from the protocol compiler. +type ExtensionDesc struct { + ExtendedType Message // nil pointer to the type that is being extended + ExtensionType interface{} // nil pointer to the extension type + Field int32 // field number + Name string // fully-qualified name of extension, for text formatting + Tag string // protobuf tag style +} + +func (ed *ExtensionDesc) repeated() bool { + t := reflect.TypeOf(ed.ExtensionType) + return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 +} + +// Extension represents an extension in a message. +type Extension struct { + // When an extension is stored in a message using SetExtension + // only desc and value are set. When the message is marshaled + // enc will be set to the encoded form of the message. + // + // When a message is unmarshaled and contains extensions, each + // extension will have only enc set. When such an extension is + // accessed using GetExtension (or GetExtensions) desc and value + // will be set. + desc *ExtensionDesc + value interface{} + enc []byte +} + +// SetRawExtension is for testing only. +func SetRawExtension(base extendableProto, id int32, b []byte) { + base.ExtensionMap()[id] = Extension{enc: b} +} + +// isExtensionField returns true iff the given field number is in an extension range. +func isExtensionField(pb extendableProto, field int32) bool { + for _, er := range pb.ExtensionRangeArray() { + if er.Start <= field && field <= er.End { + return true + } + } + return false +} + +// checkExtensionTypes checks that the given extension is valid for pb. +func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { + // Check the extended type. + if a, b := reflect.TypeOf(pb), reflect.TypeOf(extension.ExtendedType); a != b { + return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String()) + } + // Check the range. + if !isExtensionField(pb, extension.Field) { + return errors.New("proto: bad extension number; not in declared ranges") + } + return nil +} + +// extPropKey is sufficient to uniquely identify an extension. +type extPropKey struct { + base reflect.Type + field int32 +} + +var extProp = struct { + sync.RWMutex + m map[extPropKey]*Properties +}{ + m: make(map[extPropKey]*Properties), +} + +func extensionProperties(ed *ExtensionDesc) *Properties { + key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} + + extProp.RLock() + if prop, ok := extProp.m[key]; ok { + extProp.RUnlock() + return prop + } + extProp.RUnlock() + + extProp.Lock() + defer extProp.Unlock() + // Check again. + if prop, ok := extProp.m[key]; ok { + return prop + } + + prop := new(Properties) + prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) + extProp.m[key] = prop + return prop +} + +// encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m. +func encodeExtensionMap(m map[int32]Extension) error { + for k, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + et := reflect.TypeOf(e.desc.ExtensionType) + props := extensionProperties(e.desc) + + p := NewBuffer(nil) + // If e.value has type T, the encoder expects a *struct{ X T }. + // Pass a *T with a zero field and hope it all works out. + x := reflect.New(et) + x.Elem().Set(reflect.ValueOf(e.value)) + if err := props.enc(p, props, toStructPointer(x)); err != nil { + return err + } + e.enc = p.buf + m[k] = e + } + return nil +} + +func sizeExtensionMap(m map[int32]Extension) (n int) { + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + n += len(e.enc) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + et := reflect.TypeOf(e.desc.ExtensionType) + props := extensionProperties(e.desc) + + // If e.value has type T, the encoder expects a *struct{ X T }. + // Pass a *T with a zero field and hope it all works out. + x := reflect.New(et) + x.Elem().Set(reflect.ValueOf(e.value)) + n += props.size(props, toStructPointer(x)) + } + return +} + +// HasExtension returns whether the given extension is present in pb. +func HasExtension(pb extendableProto, extension *ExtensionDesc) bool { + // TODO: Check types, field numbers, etc.? + _, ok := pb.ExtensionMap()[extension.Field] + return ok +} + +// ClearExtension removes the given extension from pb. +func ClearExtension(pb extendableProto, extension *ExtensionDesc) { + // TODO: Check types, field numbers, etc.? + delete(pb.ExtensionMap(), extension.Field) +} + +// GetExtension parses and returns the given extension of pb. +// If the extension is not present and has no default value it returns ErrMissingExtension. +func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, error) { + if err := checkExtensionTypes(pb, extension); err != nil { + return nil, err + } + + emap := pb.ExtensionMap() + e, ok := emap[extension.Field] + if !ok { + // defaultExtensionValue returns the default value or + // ErrMissingExtension if there is no default. + return defaultExtensionValue(extension) + } + + if e.value != nil { + // Already decoded. Check the descriptor, though. + if e.desc != extension { + // This shouldn't happen. If it does, it means that + // GetExtension was called twice with two different + // descriptors with the same field number. + return nil, errors.New("proto: descriptor conflict") + } + return e.value, nil + } + + v, err := decodeExtension(e.enc, extension) + if err != nil { + return nil, err + } + + // Remember the decoded version and drop the encoded version. + // That way it is safe to mutate what we return. + e.value = v + e.desc = extension + e.enc = nil + emap[extension.Field] = e + return e.value, nil +} + +// defaultExtensionValue returns the default value for extension. +// If no default for an extension is defined ErrMissingExtension is returned. +func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { + t := reflect.TypeOf(extension.ExtensionType) + props := extensionProperties(extension) + + sf, _, err := fieldDefault(t, props) + if err != nil { + return nil, err + } + + if sf == nil || sf.value == nil { + // There is no default value. + return nil, ErrMissingExtension + } + + if t.Kind() != reflect.Ptr { + // We do not need to return a Ptr, we can directly return sf.value. + return sf.value, nil + } + + // We need to return an interface{} that is a pointer to sf.value. + value := reflect.New(t).Elem() + value.Set(reflect.New(value.Type().Elem())) + if sf.kind == reflect.Int32 { + // We may have an int32 or an enum, but the underlying data is int32. + // Since we can't set an int32 into a non int32 reflect.value directly + // set it as a int32. + value.Elem().SetInt(int64(sf.value.(int32))) + } else { + value.Elem().Set(reflect.ValueOf(sf.value)) + } + return value.Interface(), nil +} + +// decodeExtension decodes an extension encoded in b. +func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { + o := NewBuffer(b) + + t := reflect.TypeOf(extension.ExtensionType) + rep := extension.repeated() + + props := extensionProperties(extension) + + // t is a pointer to a struct, pointer to basic type or a slice. + // Allocate a "field" to store the pointer/slice itself; the + // pointer/slice will be stored here. We pass + // the address of this field to props.dec. + // This passes a zero field and a *t and lets props.dec + // interpret it as a *struct{ x t }. + value := reflect.New(t).Elem() + + for { + // Discard wire type and field number varint. It isn't needed. + if _, err := o.DecodeVarint(); err != nil { + return nil, err + } + + if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil { + return nil, err + } + + if !rep || o.index >= len(o.buf) { + break + } + } + return value.Interface(), nil +} + +// GetExtensions returns a slice of the extensions present in pb that are also listed in es. +// The returned slice has the same length as es; missing extensions will appear as nil elements. +func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { + epb, ok := pb.(extendableProto) + if !ok { + err = errors.New("proto: not an extendable proto") + return + } + extensions = make([]interface{}, len(es)) + for i, e := range es { + extensions[i], err = GetExtension(epb, e) + if err == ErrMissingExtension { + err = nil + } + if err != nil { + return + } + } + return +} + +// SetExtension sets the specified extension of pb to the specified value. +func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error { + if err := checkExtensionTypes(pb, extension); err != nil { + return err + } + typ := reflect.TypeOf(extension.ExtensionType) + if typ != reflect.TypeOf(value) { + return errors.New("proto: bad extension value type") + } + // nil extension values need to be caught early, because the + // encoder can't distinguish an ErrNil due to a nil extension + // from an ErrNil due to a missing field. Extensions are + // always optional, so the encoder would just swallow the error + // and drop all the extensions from the encoded message. + if reflect.ValueOf(value).IsNil() { + return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) + } + + pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value} + return nil +} + +// A global registry of extensions. +// The generated code will register the generated descriptors by calling RegisterExtension. + +var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) + +// RegisterExtension is called from the generated code. +func RegisterExtension(desc *ExtensionDesc) { + st := reflect.TypeOf(desc.ExtendedType).Elem() + m := extensionMaps[st] + if m == nil { + m = make(map[int32]*ExtensionDesc) + extensionMaps[st] = m + } + if _, ok := m[desc.Field]; ok { + panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) + } + m[desc.Field] = desc +} + +// RegisteredExtensions returns a map of the registered extensions of a +// protocol buffer struct, indexed by the extension number. +// The argument pb should be a nil pointer to the struct type. +func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { + return extensionMaps[reflect.TypeOf(pb).Elem()] +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go new file mode 100644 index 0000000..7255276 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go @@ -0,0 +1,292 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2014 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto_test + +import ( + "fmt" + "reflect" + "testing" + + "github.com/golang/protobuf/proto" + pb "github.com/golang/protobuf/proto/testdata" +) + +func TestGetExtensionsWithMissingExtensions(t *testing.T) { + msg := &pb.MyMessage{} + ext1 := &pb.Ext{} + if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { + t.Fatalf("Could not set ext1: %s", ext1) + } + exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{ + pb.E_Ext_More, + pb.E_Ext_Text, + }) + if err != nil { + t.Fatalf("GetExtensions() failed: %s", err) + } + if exts[0] != ext1 { + t.Errorf("ext1 not in returned extensions: %T %v", exts[0], exts[0]) + } + if exts[1] != nil { + t.Errorf("ext2 in returned extensions: %T %v", exts[1], exts[1]) + } +} + +func TestGetExtensionStability(t *testing.T) { + check := func(m *pb.MyMessage) bool { + ext1, err := proto.GetExtension(m, pb.E_Ext_More) + if err != nil { + t.Fatalf("GetExtension() failed: %s", err) + } + ext2, err := proto.GetExtension(m, pb.E_Ext_More) + if err != nil { + t.Fatalf("GetExtension() failed: %s", err) + } + return ext1 == ext2 + } + msg := &pb.MyMessage{Count: proto.Int32(4)} + ext0 := &pb.Ext{} + if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil { + t.Fatalf("Could not set ext1: %s", ext0) + } + if !check(msg) { + t.Errorf("GetExtension() not stable before marshaling") + } + bb, err := proto.Marshal(msg) + if err != nil { + t.Fatalf("Marshal() failed: %s", err) + } + msg1 := &pb.MyMessage{} + err = proto.Unmarshal(bb, msg1) + if err != nil { + t.Fatalf("Unmarshal() failed: %s", err) + } + if !check(msg1) { + t.Errorf("GetExtension() not stable after unmarshaling") + } +} + +func TestGetExtensionDefaults(t *testing.T) { + var setFloat64 float64 = 1 + var setFloat32 float32 = 2 + var setInt32 int32 = 3 + var setInt64 int64 = 4 + var setUint32 uint32 = 5 + var setUint64 uint64 = 6 + var setBool = true + var setBool2 = false + var setString = "Goodnight string" + var setBytes = []byte("Goodnight bytes") + var setEnum = pb.DefaultsMessage_TWO + + type testcase struct { + ext *proto.ExtensionDesc // Extension we are testing. + want interface{} // Expected value of extension, or nil (meaning that GetExtension will fail). + def interface{} // Expected value of extension after ClearExtension(). + } + tests := []testcase{ + {pb.E_NoDefaultDouble, setFloat64, nil}, + {pb.E_NoDefaultFloat, setFloat32, nil}, + {pb.E_NoDefaultInt32, setInt32, nil}, + {pb.E_NoDefaultInt64, setInt64, nil}, + {pb.E_NoDefaultUint32, setUint32, nil}, + {pb.E_NoDefaultUint64, setUint64, nil}, + {pb.E_NoDefaultSint32, setInt32, nil}, + {pb.E_NoDefaultSint64, setInt64, nil}, + {pb.E_NoDefaultFixed32, setUint32, nil}, + {pb.E_NoDefaultFixed64, setUint64, nil}, + {pb.E_NoDefaultSfixed32, setInt32, nil}, + {pb.E_NoDefaultSfixed64, setInt64, nil}, + {pb.E_NoDefaultBool, setBool, nil}, + {pb.E_NoDefaultBool, setBool2, nil}, + {pb.E_NoDefaultString, setString, nil}, + {pb.E_NoDefaultBytes, setBytes, nil}, + {pb.E_NoDefaultEnum, setEnum, nil}, + {pb.E_DefaultDouble, setFloat64, float64(3.1415)}, + {pb.E_DefaultFloat, setFloat32, float32(3.14)}, + {pb.E_DefaultInt32, setInt32, int32(42)}, + {pb.E_DefaultInt64, setInt64, int64(43)}, + {pb.E_DefaultUint32, setUint32, uint32(44)}, + {pb.E_DefaultUint64, setUint64, uint64(45)}, + {pb.E_DefaultSint32, setInt32, int32(46)}, + {pb.E_DefaultSint64, setInt64, int64(47)}, + {pb.E_DefaultFixed32, setUint32, uint32(48)}, + {pb.E_DefaultFixed64, setUint64, uint64(49)}, + {pb.E_DefaultSfixed32, setInt32, int32(50)}, + {pb.E_DefaultSfixed64, setInt64, int64(51)}, + {pb.E_DefaultBool, setBool, true}, + {pb.E_DefaultBool, setBool2, true}, + {pb.E_DefaultString, setString, "Hello, string"}, + {pb.E_DefaultBytes, setBytes, []byte("Hello, bytes")}, + {pb.E_DefaultEnum, setEnum, pb.DefaultsMessage_ONE}, + } + + checkVal := func(test testcase, msg *pb.DefaultsMessage, valWant interface{}) error { + val, err := proto.GetExtension(msg, test.ext) + if err != nil { + if valWant != nil { + return fmt.Errorf("GetExtension(): %s", err) + } + if want := proto.ErrMissingExtension; err != want { + return fmt.Errorf("Unexpected error: got %v, want %v", err, want) + } + return nil + } + + // All proto2 extension values are either a pointer to a value or a slice of values. + ty := reflect.TypeOf(val) + tyWant := reflect.TypeOf(test.ext.ExtensionType) + if got, want := ty, tyWant; got != want { + return fmt.Errorf("unexpected reflect.TypeOf(): got %v want %v", got, want) + } + tye := ty.Elem() + tyeWant := tyWant.Elem() + if got, want := tye, tyeWant; got != want { + return fmt.Errorf("unexpected reflect.TypeOf().Elem(): got %v want %v", got, want) + } + + // Check the name of the type of the value. + // If it is an enum it will be type int32 with the name of the enum. + if got, want := tye.Name(), tye.Name(); got != want { + return fmt.Errorf("unexpected reflect.TypeOf().Elem().Name(): got %v want %v", got, want) + } + + // Check that value is what we expect. + // If we have a pointer in val, get the value it points to. + valExp := val + if ty.Kind() == reflect.Ptr { + valExp = reflect.ValueOf(val).Elem().Interface() + } + if got, want := valExp, valWant; !reflect.DeepEqual(got, want) { + return fmt.Errorf("unexpected reflect.DeepEqual(): got %v want %v", got, want) + } + + return nil + } + + setTo := func(test testcase) interface{} { + setTo := reflect.ValueOf(test.want) + if typ := reflect.TypeOf(test.ext.ExtensionType); typ.Kind() == reflect.Ptr { + setTo = reflect.New(typ).Elem() + setTo.Set(reflect.New(setTo.Type().Elem())) + setTo.Elem().Set(reflect.ValueOf(test.want)) + } + return setTo.Interface() + } + + for _, test := range tests { + msg := &pb.DefaultsMessage{} + name := test.ext.Name + + // Check the initial value. + if err := checkVal(test, msg, test.def); err != nil { + t.Errorf("%s: %v", name, err) + } + + // Set the per-type value and check value. + name = fmt.Sprintf("%s (set to %T %v)", name, test.want, test.want) + if err := proto.SetExtension(msg, test.ext, setTo(test)); err != nil { + t.Errorf("%s: SetExtension(): %v", name, err) + continue + } + if err := checkVal(test, msg, test.want); err != nil { + t.Errorf("%s: %v", name, err) + continue + } + + // Set and check the value. + name += " (cleared)" + proto.ClearExtension(msg, test.ext) + if err := checkVal(test, msg, test.def); err != nil { + t.Errorf("%s: %v", name, err) + } + } +} + +func TestExtensionsRoundTrip(t *testing.T) { + msg := &pb.MyMessage{} + ext1 := &pb.Ext{ + Data: proto.String("hi"), + } + ext2 := &pb.Ext{ + Data: proto.String("there"), + } + exists := proto.HasExtension(msg, pb.E_Ext_More) + if exists { + t.Error("Extension More present unexpectedly") + } + if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { + t.Error(err) + } + if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil { + t.Error(err) + } + e, err := proto.GetExtension(msg, pb.E_Ext_More) + if err != nil { + t.Error(err) + } + x, ok := e.(*pb.Ext) + if !ok { + t.Errorf("e has type %T, expected testdata.Ext", e) + } else if *x.Data != "there" { + t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x) + } + proto.ClearExtension(msg, pb.E_Ext_More) + if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension { + t.Errorf("got %v, expected ErrMissingExtension", e) + } + if _, err := proto.GetExtension(msg, pb.E_X215); err == nil { + t.Error("expected bad extension error, got nil") + } + if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil { + t.Error("expected extension err") + } + if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil { + t.Error("expected some sort of type mismatch error, got nil") + } +} + +func TestNilExtension(t *testing.T) { + msg := &pb.MyMessage{ + Count: proto.Int32(1), + } + if err := proto.SetExtension(msg, pb.E_Ext_Text, proto.String("hello")); err != nil { + t.Fatal(err) + } + if err := proto.SetExtension(msg, pb.E_Ext_More, (*pb.Ext)(nil)); err == nil { + t.Error("expected SetExtension to fail due to a nil extension") + } else if want := "proto: SetExtension called with nil value of type *testdata.Ext"; err.Error() != want { + t.Errorf("expected error %v, got %v", want, err) + } + // Note: if the behavior of Marshal is ever changed to ignore nil extensions, update + // this test to verify that E_Ext_Text is properly propagated through marshal->unmarshal. +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go new file mode 100644 index 0000000..0b28b08 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go @@ -0,0 +1,813 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +/* +Package proto converts data structures to and from the wire format of +protocol buffers. It works in concert with the Go source code generated +for .proto files by the protocol compiler. + +A summary of the properties of the protocol buffer interface +for a protocol buffer variable v: + + - Names are turned from camel_case to CamelCase for export. + - There are no methods on v to set fields; just treat + them as structure fields. + - There are getters that return a field's value if set, + and return the field's default value if unset. + The getters work even if the receiver is a nil message. + - The zero value for a struct is its correct initialization state. + All desired fields must be set before marshaling. + - A Reset() method will restore a protobuf struct to its zero state. + - Non-repeated fields are pointers to the values; nil means unset. + That is, optional or required field int32 f becomes F *int32. + - Repeated fields are slices. + - Helper functions are available to aid the setting of fields. + msg.Foo = proto.String("hello") // set field + - Constants are defined to hold the default values of all fields that + have them. They have the form Default_StructName_FieldName. + Because the getter methods handle defaulted values, + direct use of these constants should be rare. + - Enums are given type names and maps from names to values. + Enum values are prefixed by the enclosing message's name, or by the + enum's type name if it is a top-level enum. Enum types have a String + method, and a Enum method to assist in message construction. + - Nested messages, groups and enums have type names prefixed with the name of + the surrounding message type. + - Extensions are given descriptor names that start with E_, + followed by an underscore-delimited list of the nested messages + that contain it (if any) followed by the CamelCased name of the + extension field itself. HasExtension, ClearExtension, GetExtension + and SetExtension are functions for manipulating extensions. + - Marshal and Unmarshal are functions to encode and decode the wire format. + +The simplest way to describe this is to see an example. +Given file test.proto, containing + + package example; + + enum FOO { X = 17; } + + message Test { + required string label = 1; + optional int32 type = 2 [default=77]; + repeated int64 reps = 3; + optional group OptionalGroup = 4 { + required string RequiredField = 5; + } + } + +The resulting file, test.pb.go, is: + + package example + + import proto "github.com/golang/protobuf/proto" + import math "math" + + type FOO int32 + const ( + FOO_X FOO = 17 + ) + var FOO_name = map[int32]string{ + 17: "X", + } + var FOO_value = map[string]int32{ + "X": 17, + } + + func (x FOO) Enum() *FOO { + p := new(FOO) + *p = x + return p + } + func (x FOO) String() string { + return proto.EnumName(FOO_name, int32(x)) + } + func (x *FOO) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(FOO_value, data) + if err != nil { + return err + } + *x = FOO(value) + return nil + } + + type Test struct { + Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` + Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` + Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` + Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` + XXX_unrecognized []byte `json:"-"` + } + func (m *Test) Reset() { *m = Test{} } + func (m *Test) String() string { return proto.CompactTextString(m) } + func (*Test) ProtoMessage() {} + const Default_Test_Type int32 = 77 + + func (m *Test) GetLabel() string { + if m != nil && m.Label != nil { + return *m.Label + } + return "" + } + + func (m *Test) GetType() int32 { + if m != nil && m.Type != nil { + return *m.Type + } + return Default_Test_Type + } + + func (m *Test) GetOptionalgroup() *Test_OptionalGroup { + if m != nil { + return m.Optionalgroup + } + return nil + } + + type Test_OptionalGroup struct { + RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` + } + func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } + func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } + + func (m *Test_OptionalGroup) GetRequiredField() string { + if m != nil && m.RequiredField != nil { + return *m.RequiredField + } + return "" + } + + func init() { + proto.RegisterEnum("example.FOO", FOO_name, FOO_value) + } + +To create and play with a Test object: + +package main + + import ( + "log" + + "github.com/golang/protobuf/proto" + pb "./example.pb" + ) + + func main() { + test := &pb.Test{ + Label: proto.String("hello"), + Type: proto.Int32(17), + Optionalgroup: &pb.Test_OptionalGroup{ + RequiredField: proto.String("good bye"), + }, + } + data, err := proto.Marshal(test) + if err != nil { + log.Fatal("marshaling error: ", err) + } + newTest := &pb.Test{} + err = proto.Unmarshal(data, newTest) + if err != nil { + log.Fatal("unmarshaling error: ", err) + } + // Now test and newTest contain the same data. + if test.GetLabel() != newTest.GetLabel() { + log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) + } + // etc. + } +*/ +package proto + +import ( + "encoding/json" + "fmt" + "log" + "reflect" + "strconv" + "sync" +) + +// Message is implemented by generated protocol buffer messages. +type Message interface { + Reset() + String() string + ProtoMessage() +} + +// Stats records allocation details about the protocol buffer encoders +// and decoders. Useful for tuning the library itself. +type Stats struct { + Emalloc uint64 // mallocs in encode + Dmalloc uint64 // mallocs in decode + Encode uint64 // number of encodes + Decode uint64 // number of decodes + Chit uint64 // number of cache hits + Cmiss uint64 // number of cache misses + Size uint64 // number of sizes +} + +// Set to true to enable stats collection. +const collectStats = false + +var stats Stats + +// GetStats returns a copy of the global Stats structure. +func GetStats() Stats { return stats } + +// A Buffer is a buffer manager for marshaling and unmarshaling +// protocol buffers. It may be reused between invocations to +// reduce memory usage. It is not necessary to use a Buffer; +// the global functions Marshal and Unmarshal create a +// temporary Buffer and are fine for most applications. +type Buffer struct { + buf []byte // encode/decode byte stream + index int // write point + + // pools of basic types to amortize allocation. + bools []bool + uint32s []uint32 + uint64s []uint64 + + // extra pools, only used with pointer_reflect.go + int32s []int32 + int64s []int64 + float32s []float32 + float64s []float64 +} + +// NewBuffer allocates a new Buffer and initializes its internal data to +// the contents of the argument slice. +func NewBuffer(e []byte) *Buffer { + return &Buffer{buf: e} +} + +// Reset resets the Buffer, ready for marshaling a new protocol buffer. +func (p *Buffer) Reset() { + p.buf = p.buf[0:0] // for reading/writing + p.index = 0 // for reading +} + +// SetBuf replaces the internal buffer with the slice, +// ready for unmarshaling the contents of the slice. +func (p *Buffer) SetBuf(s []byte) { + p.buf = s + p.index = 0 +} + +// Bytes returns the contents of the Buffer. +func (p *Buffer) Bytes() []byte { return p.buf } + +/* + * Helper routines for simplifying the creation of optional fields of basic type. + */ + +// Bool is a helper routine that allocates a new bool value +// to store v and returns a pointer to it. +func Bool(v bool) *bool { + return &v +} + +// Int32 is a helper routine that allocates a new int32 value +// to store v and returns a pointer to it. +func Int32(v int32) *int32 { + return &v +} + +// Int is a helper routine that allocates a new int32 value +// to store v and returns a pointer to it, but unlike Int32 +// its argument value is an int. +func Int(v int) *int32 { + p := new(int32) + *p = int32(v) + return p +} + +// Int64 is a helper routine that allocates a new int64 value +// to store v and returns a pointer to it. +func Int64(v int64) *int64 { + return &v +} + +// Float32 is a helper routine that allocates a new float32 value +// to store v and returns a pointer to it. +func Float32(v float32) *float32 { + return &v +} + +// Float64 is a helper routine that allocates a new float64 value +// to store v and returns a pointer to it. +func Float64(v float64) *float64 { + return &v +} + +// Uint32 is a helper routine that allocates a new uint32 value +// to store v and returns a pointer to it. +func Uint32(v uint32) *uint32 { + return &v +} + +// Uint64 is a helper routine that allocates a new uint64 value +// to store v and returns a pointer to it. +func Uint64(v uint64) *uint64 { + return &v +} + +// String is a helper routine that allocates a new string value +// to store v and returns a pointer to it. +func String(v string) *string { + return &v +} + +// EnumName is a helper function to simplify printing protocol buffer enums +// by name. Given an enum map and a value, it returns a useful string. +func EnumName(m map[int32]string, v int32) string { + s, ok := m[v] + if ok { + return s + } + return strconv.Itoa(int(v)) +} + +// UnmarshalJSONEnum is a helper function to simplify recovering enum int values +// from their JSON-encoded representation. Given a map from the enum's symbolic +// names to its int values, and a byte buffer containing the JSON-encoded +// value, it returns an int32 that can be cast to the enum type by the caller. +// +// The function can deal with both JSON representations, numeric and symbolic. +func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { + if data[0] == '"' { + // New style: enums are strings. + var repr string + if err := json.Unmarshal(data, &repr); err != nil { + return -1, err + } + val, ok := m[repr] + if !ok { + return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) + } + return val, nil + } + // Old style: enums are ints. + var val int32 + if err := json.Unmarshal(data, &val); err != nil { + return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) + } + return val, nil +} + +// DebugPrint dumps the encoded data in b in a debugging format with a header +// including the string s. Used in testing but made available for general debugging. +func (p *Buffer) DebugPrint(s string, b []byte) { + var u uint64 + + obuf := p.buf + index := p.index + p.buf = b + p.index = 0 + depth := 0 + + fmt.Printf("\n--- %s ---\n", s) + +out: + for { + for i := 0; i < depth; i++ { + fmt.Print(" ") + } + + index := p.index + if index == len(p.buf) { + break + } + + op, err := p.DecodeVarint() + if err != nil { + fmt.Printf("%3d: fetching op err %v\n", index, err) + break out + } + tag := op >> 3 + wire := op & 7 + + switch wire { + default: + fmt.Printf("%3d: t=%3d unknown wire=%d\n", + index, tag, wire) + break out + + case WireBytes: + var r []byte + + r, err = p.DecodeRawBytes(false) + if err != nil { + break out + } + fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) + if len(r) <= 6 { + for i := 0; i < len(r); i++ { + fmt.Printf(" %.2x", r[i]) + } + } else { + for i := 0; i < 3; i++ { + fmt.Printf(" %.2x", r[i]) + } + fmt.Printf(" ..") + for i := len(r) - 3; i < len(r); i++ { + fmt.Printf(" %.2x", r[i]) + } + } + fmt.Printf("\n") + + case WireFixed32: + u, err = p.DecodeFixed32() + if err != nil { + fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) + + case WireFixed64: + u, err = p.DecodeFixed64() + if err != nil { + fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) + break + + case WireVarint: + u, err = p.DecodeVarint() + if err != nil { + fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) + + case WireStartGroup: + if err != nil { + fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d start\n", index, tag) + depth++ + + case WireEndGroup: + depth-- + if err != nil { + fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d end\n", index, tag) + } + } + + if depth != 0 { + fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) + } + fmt.Printf("\n") + + p.buf = obuf + p.index = index +} + +// SetDefaults sets unset protocol buffer fields to their default values. +// It only modifies fields that are both unset and have defined defaults. +// It recursively sets default values in any non-nil sub-messages. +func SetDefaults(pb Message) { + setDefaults(reflect.ValueOf(pb), true, false) +} + +// v is a pointer to a struct. +func setDefaults(v reflect.Value, recur, zeros bool) { + v = v.Elem() + + defaultMu.RLock() + dm, ok := defaults[v.Type()] + defaultMu.RUnlock() + if !ok { + dm = buildDefaultMessage(v.Type()) + defaultMu.Lock() + defaults[v.Type()] = dm + defaultMu.Unlock() + } + + for _, sf := range dm.scalars { + f := v.Field(sf.index) + if !f.IsNil() { + // field already set + continue + } + dv := sf.value + if dv == nil && !zeros { + // no explicit default, and don't want to set zeros + continue + } + fptr := f.Addr().Interface() // **T + // TODO: Consider batching the allocations we do here. + switch sf.kind { + case reflect.Bool: + b := new(bool) + if dv != nil { + *b = dv.(bool) + } + *(fptr.(**bool)) = b + case reflect.Float32: + f := new(float32) + if dv != nil { + *f = dv.(float32) + } + *(fptr.(**float32)) = f + case reflect.Float64: + f := new(float64) + if dv != nil { + *f = dv.(float64) + } + *(fptr.(**float64)) = f + case reflect.Int32: + // might be an enum + if ft := f.Type(); ft != int32PtrType { + // enum + f.Set(reflect.New(ft.Elem())) + if dv != nil { + f.Elem().SetInt(int64(dv.(int32))) + } + } else { + // int32 field + i := new(int32) + if dv != nil { + *i = dv.(int32) + } + *(fptr.(**int32)) = i + } + case reflect.Int64: + i := new(int64) + if dv != nil { + *i = dv.(int64) + } + *(fptr.(**int64)) = i + case reflect.String: + s := new(string) + if dv != nil { + *s = dv.(string) + } + *(fptr.(**string)) = s + case reflect.Uint8: + // exceptional case: []byte + var b []byte + if dv != nil { + db := dv.([]byte) + b = make([]byte, len(db)) + copy(b, db) + } else { + b = []byte{} + } + *(fptr.(*[]byte)) = b + case reflect.Uint32: + u := new(uint32) + if dv != nil { + *u = dv.(uint32) + } + *(fptr.(**uint32)) = u + case reflect.Uint64: + u := new(uint64) + if dv != nil { + *u = dv.(uint64) + } + *(fptr.(**uint64)) = u + default: + log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) + } + } + + for _, ni := range dm.nested { + f := v.Field(ni) + // f is *T or []*T or map[T]*T + switch f.Kind() { + case reflect.Ptr: + if f.IsNil() { + continue + } + setDefaults(f, recur, zeros) + + case reflect.Slice: + for i := 0; i < f.Len(); i++ { + e := f.Index(i) + if e.IsNil() { + continue + } + setDefaults(e, recur, zeros) + } + + case reflect.Map: + for _, k := range f.MapKeys() { + e := f.MapIndex(k) + if e.IsNil() { + continue + } + setDefaults(e, recur, zeros) + } + } + } +} + +var ( + // defaults maps a protocol buffer struct type to a slice of the fields, + // with its scalar fields set to their proto-declared non-zero default values. + defaultMu sync.RWMutex + defaults = make(map[reflect.Type]defaultMessage) + + int32PtrType = reflect.TypeOf((*int32)(nil)) +) + +// defaultMessage represents information about the default values of a message. +type defaultMessage struct { + scalars []scalarField + nested []int // struct field index of nested messages +} + +type scalarField struct { + index int // struct field index + kind reflect.Kind // element type (the T in *T or []T) + value interface{} // the proto-declared default value, or nil +} + +// t is a struct type. +func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { + sprop := GetProperties(t) + for _, prop := range sprop.Prop { + fi, ok := sprop.decoderTags.get(prop.Tag) + if !ok { + // XXX_unrecognized + continue + } + ft := t.Field(fi).Type + + sf, nested, err := fieldDefault(ft, prop) + switch { + case err != nil: + log.Print(err) + case nested: + dm.nested = append(dm.nested, fi) + case sf != nil: + sf.index = fi + dm.scalars = append(dm.scalars, *sf) + } + } + + return dm +} + +// fieldDefault returns the scalarField for field type ft. +// sf will be nil if the field can not have a default. +// nestedMessage will be true if this is a nested message. +// Note that sf.index is not set on return. +func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { + var canHaveDefault bool + switch ft.Kind() { + case reflect.Ptr: + if ft.Elem().Kind() == reflect.Struct { + nestedMessage = true + } else { + canHaveDefault = true // proto2 scalar field + } + + case reflect.Slice: + switch ft.Elem().Kind() { + case reflect.Ptr: + nestedMessage = true // repeated message + case reflect.Uint8: + canHaveDefault = true // bytes field + } + + case reflect.Map: + if ft.Elem().Kind() == reflect.Ptr { + nestedMessage = true // map with message values + } + } + + if !canHaveDefault { + if nestedMessage { + return nil, true, nil + } + return nil, false, nil + } + + // We now know that ft is a pointer or slice. + sf = &scalarField{kind: ft.Elem().Kind()} + + // scalar fields without defaults + if !prop.HasDefault { + return sf, false, nil + } + + // a scalar field: either *T or []byte + switch ft.Elem().Kind() { + case reflect.Bool: + x, err := strconv.ParseBool(prop.Default) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) + } + sf.value = x + case reflect.Float32: + x, err := strconv.ParseFloat(prop.Default, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) + } + sf.value = float32(x) + case reflect.Float64: + x, err := strconv.ParseFloat(prop.Default, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) + } + sf.value = x + case reflect.Int32: + x, err := strconv.ParseInt(prop.Default, 10, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) + } + sf.value = int32(x) + case reflect.Int64: + x, err := strconv.ParseInt(prop.Default, 10, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) + } + sf.value = x + case reflect.String: + sf.value = prop.Default + case reflect.Uint8: + // []byte (not *uint8) + sf.value = []byte(prop.Default) + case reflect.Uint32: + x, err := strconv.ParseUint(prop.Default, 10, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) + } + sf.value = uint32(x) + case reflect.Uint64: + x, err := strconv.ParseUint(prop.Default, 10, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) + } + sf.value = x + default: + return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) + } + + return sf, false, nil +} + +// Map fields may have key types of non-float scalars, strings and enums. +// The easiest way to sort them in some deterministic order is to use fmt. +// If this turns out to be inefficient we can always consider other options, +// such as doing a Schwartzian transform. + +type mapKeys []reflect.Value + +func (s mapKeys) Len() int { return len(s) } +func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s mapKeys) Less(i, j int) bool { + return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) +} + +// isProto3Zero reports whether v is a zero proto3 value. +func isProto3Zero(v reflect.Value) bool { + switch v.Kind() { + case reflect.Bool: + return !v.Bool() + case reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint32, reflect.Uint64: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.String: + return v.String() == "" + } + return false +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go new file mode 100644 index 0000000..9d912bc --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go @@ -0,0 +1,287 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Support for message sets. + */ + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "reflect" + "sort" +) + +// ErrNoMessageTypeId occurs when a protocol buffer does not have a message type ID. +// A message type ID is required for storing a protocol buffer in a message set. +var ErrNoMessageTypeId = errors.New("proto does not have a message type ID") + +// The first two types (_MessageSet_Item and MessageSet) +// model what the protocol compiler produces for the following protocol message: +// message MessageSet { +// repeated group Item = 1 { +// required int32 type_id = 2; +// required string message = 3; +// }; +// } +// That is the MessageSet wire format. We can't use a proto to generate these +// because that would introduce a circular dependency between it and this package. +// +// When a proto1 proto has a field that looks like: +// optional message info = 3; +// the protocol compiler produces a field in the generated struct that looks like: +// Info *_proto_.MessageSet `protobuf:"bytes,3,opt,name=info"` +// The package is automatically inserted so there is no need for that proto file to +// import this package. + +type _MessageSet_Item struct { + TypeId *int32 `protobuf:"varint,2,req,name=type_id"` + Message []byte `protobuf:"bytes,3,req,name=message"` +} + +type MessageSet struct { + Item []*_MessageSet_Item `protobuf:"group,1,rep"` + XXX_unrecognized []byte + // TODO: caching? +} + +// Make sure MessageSet is a Message. +var _ Message = (*MessageSet)(nil) + +// messageTypeIder is an interface satisfied by a protocol buffer type +// that may be stored in a MessageSet. +type messageTypeIder interface { + MessageTypeId() int32 +} + +func (ms *MessageSet) find(pb Message) *_MessageSet_Item { + mti, ok := pb.(messageTypeIder) + if !ok { + return nil + } + id := mti.MessageTypeId() + for _, item := range ms.Item { + if *item.TypeId == id { + return item + } + } + return nil +} + +func (ms *MessageSet) Has(pb Message) bool { + if ms.find(pb) != nil { + return true + } + return false +} + +func (ms *MessageSet) Unmarshal(pb Message) error { + if item := ms.find(pb); item != nil { + return Unmarshal(item.Message, pb) + } + if _, ok := pb.(messageTypeIder); !ok { + return ErrNoMessageTypeId + } + return nil // TODO: return error instead? +} + +func (ms *MessageSet) Marshal(pb Message) error { + msg, err := Marshal(pb) + if err != nil { + return err + } + if item := ms.find(pb); item != nil { + // reuse existing item + item.Message = msg + return nil + } + + mti, ok := pb.(messageTypeIder) + if !ok { + return ErrNoMessageTypeId + } + + mtid := mti.MessageTypeId() + ms.Item = append(ms.Item, &_MessageSet_Item{ + TypeId: &mtid, + Message: msg, + }) + return nil +} + +func (ms *MessageSet) Reset() { *ms = MessageSet{} } +func (ms *MessageSet) String() string { return CompactTextString(ms) } +func (*MessageSet) ProtoMessage() {} + +// Support for the message_set_wire_format message option. + +func skipVarint(buf []byte) []byte { + i := 0 + for ; buf[i]&0x80 != 0; i++ { + } + return buf[i+1:] +} + +// MarshalMessageSet encodes the extension map represented by m in the message set wire format. +// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. +func MarshalMessageSet(m map[int32]Extension) ([]byte, error) { + if err := encodeExtensionMap(m); err != nil { + return nil, err + } + + // Sort extension IDs to provide a deterministic encoding. + // See also enc_map in encode.go. + ids := make([]int, 0, len(m)) + for id := range m { + ids = append(ids, int(id)) + } + sort.Ints(ids) + + ms := &MessageSet{Item: make([]*_MessageSet_Item, 0, len(m))} + for _, id := range ids { + e := m[int32(id)] + // Remove the wire type and field number varint, as well as the length varint. + msg := skipVarint(skipVarint(e.enc)) + + ms.Item = append(ms.Item, &_MessageSet_Item{ + TypeId: Int32(int32(id)), + Message: msg, + }) + } + return Marshal(ms) +} + +// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. +// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. +func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error { + ms := new(MessageSet) + if err := Unmarshal(buf, ms); err != nil { + return err + } + for _, item := range ms.Item { + id := *item.TypeId + msg := item.Message + + // Restore wire type and field number varint, plus length varint. + // Be careful to preserve duplicate items. + b := EncodeVarint(uint64(id)<<3 | WireBytes) + if ext, ok := m[id]; ok { + // Existing data; rip off the tag and length varint + // so we join the new data correctly. + // We can assume that ext.enc is set because we are unmarshaling. + o := ext.enc[len(b):] // skip wire type and field number + _, n := DecodeVarint(o) // calculate length of length varint + o = o[n:] // skip length varint + msg = append(o, msg...) // join old data and new data + } + b = append(b, EncodeVarint(uint64(len(msg)))...) + b = append(b, msg...) + + m[id] = Extension{enc: b} + } + return nil +} + +// MarshalMessageSetJSON encodes the extension map represented by m in JSON format. +// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. +func MarshalMessageSetJSON(m map[int32]Extension) ([]byte, error) { + var b bytes.Buffer + b.WriteByte('{') + + // Process the map in key order for deterministic output. + ids := make([]int32, 0, len(m)) + for id := range m { + ids = append(ids, id) + } + sort.Sort(int32Slice(ids)) // int32Slice defined in text.go + + for i, id := range ids { + ext := m[id] + if i > 0 { + b.WriteByte(',') + } + + msd, ok := messageSetMap[id] + if !ok { + // Unknown type; we can't render it, so skip it. + continue + } + fmt.Fprintf(&b, `"[%s]":`, msd.name) + + x := ext.value + if x == nil { + x = reflect.New(msd.t.Elem()).Interface() + if err := Unmarshal(ext.enc, x.(Message)); err != nil { + return nil, err + } + } + d, err := json.Marshal(x) + if err != nil { + return nil, err + } + b.Write(d) + } + b.WriteByte('}') + return b.Bytes(), nil +} + +// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. +// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. +func UnmarshalMessageSetJSON(buf []byte, m map[int32]Extension) error { + // Common-case fast path. + if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { + return nil + } + + // This is fairly tricky, and it's not clear that it is needed. + return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") +} + +// A global registry of types that can be used in a MessageSet. + +var messageSetMap = make(map[int32]messageSetDesc) + +type messageSetDesc struct { + t reflect.Type // pointer to struct + name string +} + +// RegisterMessageSetType is called from the generated code. +func RegisterMessageSetType(m Message, fieldNum int32, name string) { + messageSetMap[fieldNum] = messageSetDesc{ + t: reflect.TypeOf(m), + name: name, + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go new file mode 100644 index 0000000..7c29bcc --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go @@ -0,0 +1,66 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2014 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "bytes" + "testing" +) + +func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { + // Check that a repeated message set entry will be concatenated. + in := &MessageSet{ + Item: []*_MessageSet_Item{ + {TypeId: Int32(12345), Message: []byte("hoo")}, + {TypeId: Int32(12345), Message: []byte("hah")}, + }, + } + b, err := Marshal(in) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + t.Logf("Marshaled bytes: %q", b) + + m := make(map[int32]Extension) + if err := UnmarshalMessageSet(b, m); err != nil { + t.Fatalf("UnmarshalMessageSet: %v", err) + } + ext, ok := m[12345] + if !ok { + t.Fatalf("Didn't retrieve extension 12345; map is %v", m) + } + // Skip wire type/field number and length varints. + got := skipVarint(skipVarint(ext.enc)) + if want := []byte("hoohah"); !bytes.Equal(got, want) { + t.Errorf("Combined extension is %q, want %q", got, want) + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go new file mode 100644 index 0000000..749919d --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go @@ -0,0 +1,479 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2012 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// +build appengine + +// This file contains an implementation of proto field accesses using package reflect. +// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can +// be used on App Engine. + +package proto + +import ( + "math" + "reflect" +) + +// A structPointer is a pointer to a struct. +type structPointer struct { + v reflect.Value +} + +// toStructPointer returns a structPointer equivalent to the given reflect value. +// The reflect value must itself be a pointer to a struct. +func toStructPointer(v reflect.Value) structPointer { + return structPointer{v} +} + +// IsNil reports whether p is nil. +func structPointer_IsNil(p structPointer) bool { + return p.v.IsNil() +} + +// Interface returns the struct pointer as an interface value. +func structPointer_Interface(p structPointer, _ reflect.Type) interface{} { + return p.v.Interface() +} + +// A field identifies a field in a struct, accessible from a structPointer. +// In this implementation, a field is identified by the sequence of field indices +// passed to reflect's FieldByIndex. +type field []int + +// toField returns a field equivalent to the given reflect field. +func toField(f *reflect.StructField) field { + return f.Index +} + +// invalidField is an invalid field identifier. +var invalidField = field(nil) + +// IsValid reports whether the field identifier is valid. +func (f field) IsValid() bool { return f != nil } + +// field returns the given field in the struct as a reflect value. +func structPointer_field(p structPointer, f field) reflect.Value { + // Special case: an extension map entry with a value of type T + // passes a *T to the struct-handling code with a zero field, + // expecting that it will be treated as equivalent to *struct{ X T }, + // which has the same memory layout. We have to handle that case + // specially, because reflect will panic if we call FieldByIndex on a + // non-struct. + if f == nil { + return p.v.Elem() + } + + return p.v.Elem().FieldByIndex(f) +} + +// ifield returns the given field in the struct as an interface value. +func structPointer_ifield(p structPointer, f field) interface{} { + return structPointer_field(p, f).Addr().Interface() +} + +// Bytes returns the address of a []byte field in the struct. +func structPointer_Bytes(p structPointer, f field) *[]byte { + return structPointer_ifield(p, f).(*[]byte) +} + +// BytesSlice returns the address of a [][]byte field in the struct. +func structPointer_BytesSlice(p structPointer, f field) *[][]byte { + return structPointer_ifield(p, f).(*[][]byte) +} + +// Bool returns the address of a *bool field in the struct. +func structPointer_Bool(p structPointer, f field) **bool { + return structPointer_ifield(p, f).(**bool) +} + +// BoolVal returns the address of a bool field in the struct. +func structPointer_BoolVal(p structPointer, f field) *bool { + return structPointer_ifield(p, f).(*bool) +} + +// BoolSlice returns the address of a []bool field in the struct. +func structPointer_BoolSlice(p structPointer, f field) *[]bool { + return structPointer_ifield(p, f).(*[]bool) +} + +// String returns the address of a *string field in the struct. +func structPointer_String(p structPointer, f field) **string { + return structPointer_ifield(p, f).(**string) +} + +// StringVal returns the address of a string field in the struct. +func structPointer_StringVal(p structPointer, f field) *string { + return structPointer_ifield(p, f).(*string) +} + +// StringSlice returns the address of a []string field in the struct. +func structPointer_StringSlice(p structPointer, f field) *[]string { + return structPointer_ifield(p, f).(*[]string) +} + +// ExtMap returns the address of an extension map field in the struct. +func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { + return structPointer_ifield(p, f).(*map[int32]Extension) +} + +// NewAt returns the reflect.Value for a pointer to a field in the struct. +func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { + return structPointer_field(p, f).Addr() +} + +// SetStructPointer writes a *struct field in the struct. +func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { + structPointer_field(p, f).Set(q.v) +} + +// GetStructPointer reads a *struct field in the struct. +func structPointer_GetStructPointer(p structPointer, f field) structPointer { + return structPointer{structPointer_field(p, f)} +} + +// StructPointerSlice the address of a []*struct field in the struct. +func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice { + return structPointerSlice{structPointer_field(p, f)} +} + +// A structPointerSlice represents the address of a slice of pointers to structs +// (themselves messages or groups). That is, v.Type() is *[]*struct{...}. +type structPointerSlice struct { + v reflect.Value +} + +func (p structPointerSlice) Len() int { return p.v.Len() } +func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} } +func (p structPointerSlice) Append(q structPointer) { + p.v.Set(reflect.Append(p.v, q.v)) +} + +var ( + int32Type = reflect.TypeOf(int32(0)) + uint32Type = reflect.TypeOf(uint32(0)) + float32Type = reflect.TypeOf(float32(0)) + int64Type = reflect.TypeOf(int64(0)) + uint64Type = reflect.TypeOf(uint64(0)) + float64Type = reflect.TypeOf(float64(0)) +) + +// A word32 represents a field of type *int32, *uint32, *float32, or *enum. +// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable. +type word32 struct { + v reflect.Value +} + +// IsNil reports whether p is nil. +func word32_IsNil(p word32) bool { + return p.v.IsNil() +} + +// Set sets p to point at a newly allocated word with bits set to x. +func word32_Set(p word32, o *Buffer, x uint32) { + t := p.v.Type().Elem() + switch t { + case int32Type: + if len(o.int32s) == 0 { + o.int32s = make([]int32, uint32PoolSize) + } + o.int32s[0] = int32(x) + p.v.Set(reflect.ValueOf(&o.int32s[0])) + o.int32s = o.int32s[1:] + return + case uint32Type: + if len(o.uint32s) == 0 { + o.uint32s = make([]uint32, uint32PoolSize) + } + o.uint32s[0] = x + p.v.Set(reflect.ValueOf(&o.uint32s[0])) + o.uint32s = o.uint32s[1:] + return + case float32Type: + if len(o.float32s) == 0 { + o.float32s = make([]float32, uint32PoolSize) + } + o.float32s[0] = math.Float32frombits(x) + p.v.Set(reflect.ValueOf(&o.float32s[0])) + o.float32s = o.float32s[1:] + return + } + + // must be enum + p.v.Set(reflect.New(t)) + p.v.Elem().SetInt(int64(int32(x))) +} + +// Get gets the bits pointed at by p, as a uint32. +func word32_Get(p word32) uint32 { + elem := p.v.Elem() + switch elem.Kind() { + case reflect.Int32: + return uint32(elem.Int()) + case reflect.Uint32: + return uint32(elem.Uint()) + case reflect.Float32: + return math.Float32bits(float32(elem.Float())) + } + panic("unreachable") +} + +// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct. +func structPointer_Word32(p structPointer, f field) word32 { + return word32{structPointer_field(p, f)} +} + +// A word32Val represents a field of type int32, uint32, float32, or enum. +// That is, v.Type() is int32, uint32, float32, or enum and v is assignable. +type word32Val struct { + v reflect.Value +} + +// Set sets *p to x. +func word32Val_Set(p word32Val, x uint32) { + switch p.v.Type() { + case int32Type: + p.v.SetInt(int64(x)) + return + case uint32Type: + p.v.SetUint(uint64(x)) + return + case float32Type: + p.v.SetFloat(float64(math.Float32frombits(x))) + return + } + + // must be enum + p.v.SetInt(int64(int32(x))) +} + +// Get gets the bits pointed at by p, as a uint32. +func word32Val_Get(p word32Val) uint32 { + elem := p.v + switch elem.Kind() { + case reflect.Int32: + return uint32(elem.Int()) + case reflect.Uint32: + return uint32(elem.Uint()) + case reflect.Float32: + return math.Float32bits(float32(elem.Float())) + } + panic("unreachable") +} + +// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct. +func structPointer_Word32Val(p structPointer, f field) word32Val { + return word32Val{structPointer_field(p, f)} +} + +// A word32Slice is a slice of 32-bit values. +// That is, v.Type() is []int32, []uint32, []float32, or []enum. +type word32Slice struct { + v reflect.Value +} + +func (p word32Slice) Append(x uint32) { + n, m := p.v.Len(), p.v.Cap() + if n < m { + p.v.SetLen(n + 1) + } else { + t := p.v.Type().Elem() + p.v.Set(reflect.Append(p.v, reflect.Zero(t))) + } + elem := p.v.Index(n) + switch elem.Kind() { + case reflect.Int32: + elem.SetInt(int64(int32(x))) + case reflect.Uint32: + elem.SetUint(uint64(x)) + case reflect.Float32: + elem.SetFloat(float64(math.Float32frombits(x))) + } +} + +func (p word32Slice) Len() int { + return p.v.Len() +} + +func (p word32Slice) Index(i int) uint32 { + elem := p.v.Index(i) + switch elem.Kind() { + case reflect.Int32: + return uint32(elem.Int()) + case reflect.Uint32: + return uint32(elem.Uint()) + case reflect.Float32: + return math.Float32bits(float32(elem.Float())) + } + panic("unreachable") +} + +// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct. +func structPointer_Word32Slice(p structPointer, f field) word32Slice { + return word32Slice{structPointer_field(p, f)} +} + +// word64 is like word32 but for 64-bit values. +type word64 struct { + v reflect.Value +} + +func word64_Set(p word64, o *Buffer, x uint64) { + t := p.v.Type().Elem() + switch t { + case int64Type: + if len(o.int64s) == 0 { + o.int64s = make([]int64, uint64PoolSize) + } + o.int64s[0] = int64(x) + p.v.Set(reflect.ValueOf(&o.int64s[0])) + o.int64s = o.int64s[1:] + return + case uint64Type: + if len(o.uint64s) == 0 { + o.uint64s = make([]uint64, uint64PoolSize) + } + o.uint64s[0] = x + p.v.Set(reflect.ValueOf(&o.uint64s[0])) + o.uint64s = o.uint64s[1:] + return + case float64Type: + if len(o.float64s) == 0 { + o.float64s = make([]float64, uint64PoolSize) + } + o.float64s[0] = math.Float64frombits(x) + p.v.Set(reflect.ValueOf(&o.float64s[0])) + o.float64s = o.float64s[1:] + return + } + panic("unreachable") +} + +func word64_IsNil(p word64) bool { + return p.v.IsNil() +} + +func word64_Get(p word64) uint64 { + elem := p.v.Elem() + switch elem.Kind() { + case reflect.Int64: + return uint64(elem.Int()) + case reflect.Uint64: + return elem.Uint() + case reflect.Float64: + return math.Float64bits(elem.Float()) + } + panic("unreachable") +} + +func structPointer_Word64(p structPointer, f field) word64 { + return word64{structPointer_field(p, f)} +} + +// word64Val is like word32Val but for 64-bit values. +type word64Val struct { + v reflect.Value +} + +func word64Val_Set(p word64Val, o *Buffer, x uint64) { + switch p.v.Type() { + case int64Type: + p.v.SetInt(int64(x)) + return + case uint64Type: + p.v.SetUint(x) + return + case float64Type: + p.v.SetFloat(math.Float64frombits(x)) + return + } + panic("unreachable") +} + +func word64Val_Get(p word64Val) uint64 { + elem := p.v + switch elem.Kind() { + case reflect.Int64: + return uint64(elem.Int()) + case reflect.Uint64: + return elem.Uint() + case reflect.Float64: + return math.Float64bits(elem.Float()) + } + panic("unreachable") +} + +func structPointer_Word64Val(p structPointer, f field) word64Val { + return word64Val{structPointer_field(p, f)} +} + +type word64Slice struct { + v reflect.Value +} + +func (p word64Slice) Append(x uint64) { + n, m := p.v.Len(), p.v.Cap() + if n < m { + p.v.SetLen(n + 1) + } else { + t := p.v.Type().Elem() + p.v.Set(reflect.Append(p.v, reflect.Zero(t))) + } + elem := p.v.Index(n) + switch elem.Kind() { + case reflect.Int64: + elem.SetInt(int64(int64(x))) + case reflect.Uint64: + elem.SetUint(uint64(x)) + case reflect.Float64: + elem.SetFloat(float64(math.Float64frombits(x))) + } +} + +func (p word64Slice) Len() int { + return p.v.Len() +} + +func (p word64Slice) Index(i int) uint64 { + elem := p.v.Index(i) + switch elem.Kind() { + case reflect.Int64: + return uint64(elem.Int()) + case reflect.Uint64: + return uint64(elem.Uint()) + case reflect.Float64: + return math.Float64bits(float64(elem.Float())) + } + panic("unreachable") +} + +func structPointer_Word64Slice(p structPointer, f field) word64Slice { + return word64Slice{structPointer_field(p, f)} +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go new file mode 100644 index 0000000..e9be0fe --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go @@ -0,0 +1,266 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2012 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// +build !appengine + +// This file contains the implementation of the proto field accesses using package unsafe. + +package proto + +import ( + "reflect" + "unsafe" +) + +// NOTE: These type_Foo functions would more idiomatically be methods, +// but Go does not allow methods on pointer types, and we must preserve +// some pointer type for the garbage collector. We use these +// funcs with clunky names as our poor approximation to methods. +// +// An alternative would be +// type structPointer struct { p unsafe.Pointer } +// but that does not registerize as well. + +// A structPointer is a pointer to a struct. +type structPointer unsafe.Pointer + +// toStructPointer returns a structPointer equivalent to the given reflect value. +func toStructPointer(v reflect.Value) structPointer { + return structPointer(unsafe.Pointer(v.Pointer())) +} + +// IsNil reports whether p is nil. +func structPointer_IsNil(p structPointer) bool { + return p == nil +} + +// Interface returns the struct pointer, assumed to have element type t, +// as an interface value. +func structPointer_Interface(p structPointer, t reflect.Type) interface{} { + return reflect.NewAt(t, unsafe.Pointer(p)).Interface() +} + +// A field identifies a field in a struct, accessible from a structPointer. +// In this implementation, a field is identified by its byte offset from the start of the struct. +type field uintptr + +// toField returns a field equivalent to the given reflect field. +func toField(f *reflect.StructField) field { + return field(f.Offset) +} + +// invalidField is an invalid field identifier. +const invalidField = ^field(0) + +// IsValid reports whether the field identifier is valid. +func (f field) IsValid() bool { + return f != ^field(0) +} + +// Bytes returns the address of a []byte field in the struct. +func structPointer_Bytes(p structPointer, f field) *[]byte { + return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// BytesSlice returns the address of a [][]byte field in the struct. +func structPointer_BytesSlice(p structPointer, f field) *[][]byte { + return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// Bool returns the address of a *bool field in the struct. +func structPointer_Bool(p structPointer, f field) **bool { + return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// BoolVal returns the address of a bool field in the struct. +func structPointer_BoolVal(p structPointer, f field) *bool { + return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// BoolSlice returns the address of a []bool field in the struct. +func structPointer_BoolSlice(p structPointer, f field) *[]bool { + return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// String returns the address of a *string field in the struct. +func structPointer_String(p structPointer, f field) **string { + return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// StringVal returns the address of a string field in the struct. +func structPointer_StringVal(p structPointer, f field) *string { + return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// StringSlice returns the address of a []string field in the struct. +func structPointer_StringSlice(p structPointer, f field) *[]string { + return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// ExtMap returns the address of an extension map field in the struct. +func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { + return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// NewAt returns the reflect.Value for a pointer to a field in the struct. +func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { + return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f))) +} + +// SetStructPointer writes a *struct field in the struct. +func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { + *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q +} + +// GetStructPointer reads a *struct field in the struct. +func structPointer_GetStructPointer(p structPointer, f field) structPointer { + return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// StructPointerSlice the address of a []*struct field in the struct. +func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice { + return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups). +type structPointerSlice []structPointer + +func (v *structPointerSlice) Len() int { return len(*v) } +func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] } +func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) } + +// A word32 is the address of a "pointer to 32-bit value" field. +type word32 **uint32 + +// IsNil reports whether *v is nil. +func word32_IsNil(p word32) bool { + return *p == nil +} + +// Set sets *v to point at a newly allocated word set to x. +func word32_Set(p word32, o *Buffer, x uint32) { + if len(o.uint32s) == 0 { + o.uint32s = make([]uint32, uint32PoolSize) + } + o.uint32s[0] = x + *p = &o.uint32s[0] + o.uint32s = o.uint32s[1:] +} + +// Get gets the value pointed at by *v. +func word32_Get(p word32) uint32 { + return **p +} + +// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct. +func structPointer_Word32(p structPointer, f field) word32 { + return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +} + +// A word32Val is the address of a 32-bit value field. +type word32Val *uint32 + +// Set sets *p to x. +func word32Val_Set(p word32Val, x uint32) { + *p = x +} + +// Get gets the value pointed at by p. +func word32Val_Get(p word32Val) uint32 { + return *p +} + +// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct. +func structPointer_Word32Val(p structPointer, f field) word32Val { + return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +} + +// A word32Slice is a slice of 32-bit values. +type word32Slice []uint32 + +func (v *word32Slice) Append(x uint32) { *v = append(*v, x) } +func (v *word32Slice) Len() int { return len(*v) } +func (v *word32Slice) Index(i int) uint32 { return (*v)[i] } + +// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct. +func structPointer_Word32Slice(p structPointer, f field) *word32Slice { + return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// word64 is like word32 but for 64-bit values. +type word64 **uint64 + +func word64_Set(p word64, o *Buffer, x uint64) { + if len(o.uint64s) == 0 { + o.uint64s = make([]uint64, uint64PoolSize) + } + o.uint64s[0] = x + *p = &o.uint64s[0] + o.uint64s = o.uint64s[1:] +} + +func word64_IsNil(p word64) bool { + return *p == nil +} + +func word64_Get(p word64) uint64 { + return **p +} + +func structPointer_Word64(p structPointer, f field) word64 { + return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +} + +// word64Val is like word32Val but for 64-bit values. +type word64Val *uint64 + +func word64Val_Set(p word64Val, o *Buffer, x uint64) { + *p = x +} + +func word64Val_Get(p word64Val) uint64 { + return *p +} + +func structPointer_Word64Val(p structPointer, f field) word64Val { + return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +} + +// word64Slice is like word32Slice but for 64-bit values. +type word64Slice []uint64 + +func (v *word64Slice) Append(x uint64) { *v = append(*v, x) } +func (v *word64Slice) Len() int { return len(*v) } +func (v *word64Slice) Index(i int) uint64 { return (*v)[i] } + +func structPointer_Word64Slice(p structPointer, f field) *word64Slice { + return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go new file mode 100644 index 0000000..d74844a --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go @@ -0,0 +1,742 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Routines for encoding data into the wire format for protocol buffers. + */ + +import ( + "fmt" + "os" + "reflect" + "sort" + "strconv" + "strings" + "sync" +) + +const debug bool = false + +// Constants that identify the encoding of a value on the wire. +const ( + WireVarint = 0 + WireFixed64 = 1 + WireBytes = 2 + WireStartGroup = 3 + WireEndGroup = 4 + WireFixed32 = 5 +) + +const startSize = 10 // initial slice/string sizes + +// Encoders are defined in encode.go +// An encoder outputs the full representation of a field, including its +// tag and encoder type. +type encoder func(p *Buffer, prop *Properties, base structPointer) error + +// A valueEncoder encodes a single integer in a particular encoding. +type valueEncoder func(o *Buffer, x uint64) error + +// Sizers are defined in encode.go +// A sizer returns the encoded size of a field, including its tag and encoder +// type. +type sizer func(prop *Properties, base structPointer) int + +// A valueSizer returns the encoded size of a single integer in a particular +// encoding. +type valueSizer func(x uint64) int + +// Decoders are defined in decode.go +// A decoder creates a value from its wire representation. +// Unrecognized subelements are saved in unrec. +type decoder func(p *Buffer, prop *Properties, base structPointer) error + +// A valueDecoder decodes a single integer in a particular encoding. +type valueDecoder func(o *Buffer) (x uint64, err error) + +// tagMap is an optimization over map[int]int for typical protocol buffer +// use-cases. Encoded protocol buffers are often in tag order with small tag +// numbers. +type tagMap struct { + fastTags []int + slowTags map[int]int +} + +// tagMapFastLimit is the upper bound on the tag number that will be stored in +// the tagMap slice rather than its map. +const tagMapFastLimit = 1024 + +func (p *tagMap) get(t int) (int, bool) { + if t > 0 && t < tagMapFastLimit { + if t >= len(p.fastTags) { + return 0, false + } + fi := p.fastTags[t] + return fi, fi >= 0 + } + fi, ok := p.slowTags[t] + return fi, ok +} + +func (p *tagMap) put(t int, fi int) { + if t > 0 && t < tagMapFastLimit { + for len(p.fastTags) < t+1 { + p.fastTags = append(p.fastTags, -1) + } + p.fastTags[t] = fi + return + } + if p.slowTags == nil { + p.slowTags = make(map[int]int) + } + p.slowTags[t] = fi +} + +// StructProperties represents properties for all the fields of a struct. +// decoderTags and decoderOrigNames should only be used by the decoder. +type StructProperties struct { + Prop []*Properties // properties for each field + reqCount int // required count + decoderTags tagMap // map from proto tag to struct field number + decoderOrigNames map[string]int // map from original name to struct field number + order []int // list of struct field numbers in tag order + unrecField field // field id of the XXX_unrecognized []byte field + extendable bool // is this an extendable proto +} + +// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. +// See encode.go, (*Buffer).enc_struct. + +func (sp *StructProperties) Len() int { return len(sp.order) } +func (sp *StructProperties) Less(i, j int) bool { + return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag +} +func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } + +// Properties represents the protocol-specific behavior of a single struct field. +type Properties struct { + Name string // name of the field, for error messages + OrigName string // original name before protocol compiler (always set) + Wire string + WireType int + Tag int + Required bool + Optional bool + Repeated bool + Packed bool // relevant for repeated primitives only + Enum string // set for enum types only + proto3 bool // whether this is known to be a proto3 field; set for []byte only + + Default string // default value + HasDefault bool // whether an explicit default was provided + def_uint64 uint64 + + enc encoder + valEnc valueEncoder // set for bool and numeric types only + field field + tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType) + tagbuf [8]byte + stype reflect.Type // set for struct types only + sprop *StructProperties // set for struct types only + isMarshaler bool + isUnmarshaler bool + + mtype reflect.Type // set for map types only + mkeyprop *Properties // set for map types only + mvalprop *Properties // set for map types only + + size sizer + valSize valueSizer // set for bool and numeric types only + + dec decoder + valDec valueDecoder // set for bool and numeric types only + + // If this is a packable field, this will be the decoder for the packed version of the field. + packedDec decoder +} + +// String formats the properties in the protobuf struct field tag style. +func (p *Properties) String() string { + s := p.Wire + s = "," + s += strconv.Itoa(p.Tag) + if p.Required { + s += ",req" + } + if p.Optional { + s += ",opt" + } + if p.Repeated { + s += ",rep" + } + if p.Packed { + s += ",packed" + } + if p.OrigName != p.Name { + s += ",name=" + p.OrigName + } + if p.proto3 { + s += ",proto3" + } + if len(p.Enum) > 0 { + s += ",enum=" + p.Enum + } + if p.HasDefault { + s += ",def=" + p.Default + } + return s +} + +// Parse populates p by parsing a string in the protobuf struct field tag style. +func (p *Properties) Parse(s string) { + // "bytes,49,opt,name=foo,def=hello!" + fields := strings.Split(s, ",") // breaks def=, but handled below. + if len(fields) < 2 { + fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) + return + } + + p.Wire = fields[0] + switch p.Wire { + case "varint": + p.WireType = WireVarint + p.valEnc = (*Buffer).EncodeVarint + p.valDec = (*Buffer).DecodeVarint + p.valSize = sizeVarint + case "fixed32": + p.WireType = WireFixed32 + p.valEnc = (*Buffer).EncodeFixed32 + p.valDec = (*Buffer).DecodeFixed32 + p.valSize = sizeFixed32 + case "fixed64": + p.WireType = WireFixed64 + p.valEnc = (*Buffer).EncodeFixed64 + p.valDec = (*Buffer).DecodeFixed64 + p.valSize = sizeFixed64 + case "zigzag32": + p.WireType = WireVarint + p.valEnc = (*Buffer).EncodeZigzag32 + p.valDec = (*Buffer).DecodeZigzag32 + p.valSize = sizeZigzag32 + case "zigzag64": + p.WireType = WireVarint + p.valEnc = (*Buffer).EncodeZigzag64 + p.valDec = (*Buffer).DecodeZigzag64 + p.valSize = sizeZigzag64 + case "bytes", "group": + p.WireType = WireBytes + // no numeric converter for non-numeric types + default: + fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) + return + } + + var err error + p.Tag, err = strconv.Atoi(fields[1]) + if err != nil { + return + } + + for i := 2; i < len(fields); i++ { + f := fields[i] + switch { + case f == "req": + p.Required = true + case f == "opt": + p.Optional = true + case f == "rep": + p.Repeated = true + case f == "packed": + p.Packed = true + case strings.HasPrefix(f, "name="): + p.OrigName = f[5:] + case strings.HasPrefix(f, "enum="): + p.Enum = f[5:] + case f == "proto3": + p.proto3 = true + case strings.HasPrefix(f, "def="): + p.HasDefault = true + p.Default = f[4:] // rest of string + if i+1 < len(fields) { + // Commas aren't escaped, and def is always last. + p.Default += "," + strings.Join(fields[i+1:], ",") + break + } + } + } +} + +func logNoSliceEnc(t1, t2 reflect.Type) { + fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2) +} + +var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() + +// Initialize the fields for encoding and decoding. +func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { + p.enc = nil + p.dec = nil + p.size = nil + + switch t1 := typ; t1.Kind() { + default: + fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1) + + // proto3 scalar types + + case reflect.Bool: + p.enc = (*Buffer).enc_proto3_bool + p.dec = (*Buffer).dec_proto3_bool + p.size = size_proto3_bool + case reflect.Int32: + p.enc = (*Buffer).enc_proto3_int32 + p.dec = (*Buffer).dec_proto3_int32 + p.size = size_proto3_int32 + case reflect.Uint32: + p.enc = (*Buffer).enc_proto3_uint32 + p.dec = (*Buffer).dec_proto3_int32 // can reuse + p.size = size_proto3_uint32 + case reflect.Int64, reflect.Uint64: + p.enc = (*Buffer).enc_proto3_int64 + p.dec = (*Buffer).dec_proto3_int64 + p.size = size_proto3_int64 + case reflect.Float32: + p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits + p.dec = (*Buffer).dec_proto3_int32 + p.size = size_proto3_uint32 + case reflect.Float64: + p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits + p.dec = (*Buffer).dec_proto3_int64 + p.size = size_proto3_int64 + case reflect.String: + p.enc = (*Buffer).enc_proto3_string + p.dec = (*Buffer).dec_proto3_string + p.size = size_proto3_string + + case reflect.Ptr: + switch t2 := t1.Elem(); t2.Kind() { + default: + fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2) + break + case reflect.Bool: + p.enc = (*Buffer).enc_bool + p.dec = (*Buffer).dec_bool + p.size = size_bool + case reflect.Int32: + p.enc = (*Buffer).enc_int32 + p.dec = (*Buffer).dec_int32 + p.size = size_int32 + case reflect.Uint32: + p.enc = (*Buffer).enc_uint32 + p.dec = (*Buffer).dec_int32 // can reuse + p.size = size_uint32 + case reflect.Int64, reflect.Uint64: + p.enc = (*Buffer).enc_int64 + p.dec = (*Buffer).dec_int64 + p.size = size_int64 + case reflect.Float32: + p.enc = (*Buffer).enc_uint32 // can just treat them as bits + p.dec = (*Buffer).dec_int32 + p.size = size_uint32 + case reflect.Float64: + p.enc = (*Buffer).enc_int64 // can just treat them as bits + p.dec = (*Buffer).dec_int64 + p.size = size_int64 + case reflect.String: + p.enc = (*Buffer).enc_string + p.dec = (*Buffer).dec_string + p.size = size_string + case reflect.Struct: + p.stype = t1.Elem() + p.isMarshaler = isMarshaler(t1) + p.isUnmarshaler = isUnmarshaler(t1) + if p.Wire == "bytes" { + p.enc = (*Buffer).enc_struct_message + p.dec = (*Buffer).dec_struct_message + p.size = size_struct_message + } else { + p.enc = (*Buffer).enc_struct_group + p.dec = (*Buffer).dec_struct_group + p.size = size_struct_group + } + } + + case reflect.Slice: + switch t2 := t1.Elem(); t2.Kind() { + default: + logNoSliceEnc(t1, t2) + break + case reflect.Bool: + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_bool + p.size = size_slice_packed_bool + } else { + p.enc = (*Buffer).enc_slice_bool + p.size = size_slice_bool + } + p.dec = (*Buffer).dec_slice_bool + p.packedDec = (*Buffer).dec_slice_packed_bool + case reflect.Int32: + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_int32 + p.size = size_slice_packed_int32 + } else { + p.enc = (*Buffer).enc_slice_int32 + p.size = size_slice_int32 + } + p.dec = (*Buffer).dec_slice_int32 + p.packedDec = (*Buffer).dec_slice_packed_int32 + case reflect.Uint32: + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_uint32 + p.size = size_slice_packed_uint32 + } else { + p.enc = (*Buffer).enc_slice_uint32 + p.size = size_slice_uint32 + } + p.dec = (*Buffer).dec_slice_int32 + p.packedDec = (*Buffer).dec_slice_packed_int32 + case reflect.Int64, reflect.Uint64: + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_int64 + p.size = size_slice_packed_int64 + } else { + p.enc = (*Buffer).enc_slice_int64 + p.size = size_slice_int64 + } + p.dec = (*Buffer).dec_slice_int64 + p.packedDec = (*Buffer).dec_slice_packed_int64 + case reflect.Uint8: + p.enc = (*Buffer).enc_slice_byte + p.dec = (*Buffer).dec_slice_byte + p.size = size_slice_byte + // This is a []byte, which is either a bytes field, + // or the value of a map field. In the latter case, + // we always encode an empty []byte, so we should not + // use the proto3 enc/size funcs. + // f == nil iff this is the key/value of a map field. + if p.proto3 && f != nil { + p.enc = (*Buffer).enc_proto3_slice_byte + p.size = size_proto3_slice_byte + } + case reflect.Float32, reflect.Float64: + switch t2.Bits() { + case 32: + // can just treat them as bits + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_uint32 + p.size = size_slice_packed_uint32 + } else { + p.enc = (*Buffer).enc_slice_uint32 + p.size = size_slice_uint32 + } + p.dec = (*Buffer).dec_slice_int32 + p.packedDec = (*Buffer).dec_slice_packed_int32 + case 64: + // can just treat them as bits + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_int64 + p.size = size_slice_packed_int64 + } else { + p.enc = (*Buffer).enc_slice_int64 + p.size = size_slice_int64 + } + p.dec = (*Buffer).dec_slice_int64 + p.packedDec = (*Buffer).dec_slice_packed_int64 + default: + logNoSliceEnc(t1, t2) + break + } + case reflect.String: + p.enc = (*Buffer).enc_slice_string + p.dec = (*Buffer).dec_slice_string + p.size = size_slice_string + case reflect.Ptr: + switch t3 := t2.Elem(); t3.Kind() { + default: + fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3) + break + case reflect.Struct: + p.stype = t2.Elem() + p.isMarshaler = isMarshaler(t2) + p.isUnmarshaler = isUnmarshaler(t2) + if p.Wire == "bytes" { + p.enc = (*Buffer).enc_slice_struct_message + p.dec = (*Buffer).dec_slice_struct_message + p.size = size_slice_struct_message + } else { + p.enc = (*Buffer).enc_slice_struct_group + p.dec = (*Buffer).dec_slice_struct_group + p.size = size_slice_struct_group + } + } + case reflect.Slice: + switch t2.Elem().Kind() { + default: + fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem()) + break + case reflect.Uint8: + p.enc = (*Buffer).enc_slice_slice_byte + p.dec = (*Buffer).dec_slice_slice_byte + p.size = size_slice_slice_byte + } + } + + case reflect.Map: + p.enc = (*Buffer).enc_new_map + p.dec = (*Buffer).dec_new_map + p.size = size_new_map + + p.mtype = t1 + p.mkeyprop = &Properties{} + p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) + p.mvalprop = &Properties{} + vtype := p.mtype.Elem() + if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { + // The value type is not a message (*T) or bytes ([]byte), + // so we need encoders for the pointer to this type. + vtype = reflect.PtrTo(vtype) + } + p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) + } + + // precalculate tag code + wire := p.WireType + if p.Packed { + wire = WireBytes + } + x := uint32(p.Tag)<<3 | uint32(wire) + i := 0 + for i = 0; x > 127; i++ { + p.tagbuf[i] = 0x80 | uint8(x&0x7F) + x >>= 7 + } + p.tagbuf[i] = uint8(x) + p.tagcode = p.tagbuf[0 : i+1] + + if p.stype != nil { + if lockGetProp { + p.sprop = GetProperties(p.stype) + } else { + p.sprop = getPropertiesLocked(p.stype) + } + } +} + +var ( + marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() + unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() +) + +// isMarshaler reports whether type t implements Marshaler. +func isMarshaler(t reflect.Type) bool { + // We're checking for (likely) pointer-receiver methods + // so if t is not a pointer, something is very wrong. + // The calls above only invoke isMarshaler on pointer types. + if t.Kind() != reflect.Ptr { + panic("proto: misuse of isMarshaler") + } + return t.Implements(marshalerType) +} + +// isUnmarshaler reports whether type t implements Unmarshaler. +func isUnmarshaler(t reflect.Type) bool { + // We're checking for (likely) pointer-receiver methods + // so if t is not a pointer, something is very wrong. + // The calls above only invoke isUnmarshaler on pointer types. + if t.Kind() != reflect.Ptr { + panic("proto: misuse of isUnmarshaler") + } + return t.Implements(unmarshalerType) +} + +// Init populates the properties from a protocol buffer struct tag. +func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { + p.init(typ, name, tag, f, true) +} + +func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { + // "bytes,49,opt,def=hello!" + p.Name = name + p.OrigName = name + if f != nil { + p.field = toField(f) + } + if tag == "" { + return + } + p.Parse(tag) + p.setEncAndDec(typ, f, lockGetProp) +} + +var ( + propertiesMu sync.RWMutex + propertiesMap = make(map[reflect.Type]*StructProperties) +) + +// GetProperties returns the list of properties for the type represented by t. +// t must represent a generated struct type of a protocol message. +func GetProperties(t reflect.Type) *StructProperties { + if t.Kind() != reflect.Struct { + panic("proto: type must have kind struct") + } + + // Most calls to GetProperties in a long-running program will be + // retrieving details for types we have seen before. + propertiesMu.RLock() + sprop, ok := propertiesMap[t] + propertiesMu.RUnlock() + if ok { + if collectStats { + stats.Chit++ + } + return sprop + } + + propertiesMu.Lock() + sprop = getPropertiesLocked(t) + propertiesMu.Unlock() + return sprop +} + +// getPropertiesLocked requires that propertiesMu is held. +func getPropertiesLocked(t reflect.Type) *StructProperties { + if prop, ok := propertiesMap[t]; ok { + if collectStats { + stats.Chit++ + } + return prop + } + if collectStats { + stats.Cmiss++ + } + + prop := new(StructProperties) + // in case of recursive protos, fill this in now. + propertiesMap[t] = prop + + // build properties + prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) + prop.unrecField = invalidField + prop.Prop = make([]*Properties, t.NumField()) + prop.order = make([]int, t.NumField()) + + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + p := new(Properties) + name := f.Name + p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) + + if f.Name == "XXX_extensions" { // special case + p.enc = (*Buffer).enc_map + p.dec = nil // not needed + p.size = size_map + } + if f.Name == "XXX_unrecognized" { // special case + prop.unrecField = toField(&f) + } + prop.Prop[i] = p + prop.order[i] = i + if debug { + print(i, " ", f.Name, " ", t.String(), " ") + if p.Tag > 0 { + print(p.String()) + } + print("\n") + } + if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") { + fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") + } + } + + // Re-order prop.order. + sort.Sort(prop) + + // build required counts + // build tags + reqCount := 0 + prop.decoderOrigNames = make(map[string]int) + for i, p := range prop.Prop { + if strings.HasPrefix(p.Name, "XXX_") { + // Internal fields should not appear in tags/origNames maps. + // They are handled specially when encoding and decoding. + continue + } + if p.Required { + reqCount++ + } + prop.decoderTags.put(p.Tag, i) + prop.decoderOrigNames[p.OrigName] = i + } + prop.reqCount = reqCount + + return prop +} + +// Return the Properties object for the x[0]'th field of the structure. +func propByIndex(t reflect.Type, x []int) *Properties { + if len(x) != 1 { + fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t) + return nil + } + prop := GetProperties(t) + return prop.Prop[x[0]] +} + +// Get the address and type of a pointer to a struct from an interface. +func getbase(pb Message) (t reflect.Type, b structPointer, err error) { + if pb == nil { + err = ErrNil + return + } + // get the reflect type of the pointer to the struct. + t = reflect.TypeOf(pb) + // get the address of the struct. + value := reflect.ValueOf(pb) + b = toStructPointer(value) + return +} + +// A global registry of enum types. +// The generated code will register the generated maps by calling RegisterEnum. + +var enumValueMaps = make(map[string]map[string]int32) + +// RegisterEnum is called from the generated code to install the enum descriptor +// maps into the global table to aid parsing text format protocol buffers. +func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { + if _, ok := enumValueMaps[typeName]; ok { + panic("proto: duplicate enum registered: " + typeName) + } + enumValueMaps[typeName] = valueMap +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go new file mode 100644 index 0000000..37c7782 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go @@ -0,0 +1,122 @@ +// Code generated by protoc-gen-go. +// source: proto3_proto/proto3.proto +// DO NOT EDIT! + +/* +Package proto3_proto is a generated protocol buffer package. + +It is generated from these files: + proto3_proto/proto3.proto + +It has these top-level messages: + Message + Nested + MessageWithMap +*/ +package proto3_proto + +import proto "github.com/golang/protobuf/proto" +import testdata "github.com/golang/protobuf/proto/testdata" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal + +type Message_Humour int32 + +const ( + Message_UNKNOWN Message_Humour = 0 + Message_PUNS Message_Humour = 1 + Message_SLAPSTICK Message_Humour = 2 + Message_BILL_BAILEY Message_Humour = 3 +) + +var Message_Humour_name = map[int32]string{ + 0: "UNKNOWN", + 1: "PUNS", + 2: "SLAPSTICK", + 3: "BILL_BAILEY", +} +var Message_Humour_value = map[string]int32{ + "UNKNOWN": 0, + "PUNS": 1, + "SLAPSTICK": 2, + "BILL_BAILEY": 3, +} + +func (x Message_Humour) String() string { + return proto.EnumName(Message_Humour_name, int32(x)) +} + +type Message struct { + Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"` + HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm" json:"height_in_cm,omitempty"` + Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` + ResultCount int64 `protobuf:"varint,7,opt,name=result_count" json:"result_count,omitempty"` + TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman" json:"true_scotsman,omitempty"` + Score float32 `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"` + Key []uint64 `protobuf:"varint,5,rep,name=key" json:"key,omitempty"` + Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"` + Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + Proto2Field *testdata.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field" json:"proto2_field,omitempty"` + Proto2Value map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` +} + +func (m *Message) Reset() { *m = Message{} } +func (m *Message) String() string { return proto.CompactTextString(m) } +func (*Message) ProtoMessage() {} + +func (m *Message) GetNested() *Nested { + if m != nil { + return m.Nested + } + return nil +} + +func (m *Message) GetTerrain() map[string]*Nested { + if m != nil { + return m.Terrain + } + return nil +} + +func (m *Message) GetProto2Field() *testdata.SubDefaults { + if m != nil { + return m.Proto2Field + } + return nil +} + +func (m *Message) GetProto2Value() map[string]*testdata.SubDefaults { + if m != nil { + return m.Proto2Value + } + return nil +} + +type Nested struct { + Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"` +} + +func (m *Nested) Reset() { *m = Nested{} } +func (m *Nested) String() string { return proto.CompactTextString(m) } +func (*Nested) ProtoMessage() {} + +type MessageWithMap struct { + ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"` +} + +func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } +func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } +func (*MessageWithMap) ProtoMessage() {} + +func (m *MessageWithMap) GetByteMapping() map[bool][]byte { + if m != nil { + return m.ByteMapping + } + return nil +} + +func init() { + proto.RegisterEnum("proto3_proto.Message_Humour", Message_Humour_name, Message_Humour_value) +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto new file mode 100644 index 0000000..e2311d9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto @@ -0,0 +1,68 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2014 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +import "testdata/test.proto"; + +package proto3_proto; + +message Message { + enum Humour { + UNKNOWN = 0; + PUNS = 1; + SLAPSTICK = 2; + BILL_BAILEY = 3; + } + + string name = 1; + Humour hilarity = 2; + uint32 height_in_cm = 3; + bytes data = 4; + int64 result_count = 7; + bool true_scotsman = 8; + float score = 9; + + repeated uint64 key = 5; + Nested nested = 6; + + map terrain = 10; + testdata.SubDefaults proto2_field = 11; + map proto2_value = 13; +} + +message Nested { + string bunny = 1; +} + +message MessageWithMap { + map byte_mapping = 1; +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go new file mode 100644 index 0000000..462f805 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go @@ -0,0 +1,125 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2014 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto_test + +import ( + "testing" + + "github.com/golang/protobuf/proto" + pb "github.com/golang/protobuf/proto/proto3_proto" + tpb "github.com/golang/protobuf/proto/testdata" +) + +func TestProto3ZeroValues(t *testing.T) { + tests := []struct { + desc string + m proto.Message + }{ + {"zero message", &pb.Message{}}, + {"empty bytes field", &pb.Message{Data: []byte{}}}, + } + for _, test := range tests { + b, err := proto.Marshal(test.m) + if err != nil { + t.Errorf("%s: proto.Marshal: %v", test.desc, err) + continue + } + if len(b) > 0 { + t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) + } + } +} + +func TestRoundTripProto3(t *testing.T) { + m := &pb.Message{ + Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" + Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 + HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 + Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" + ResultCount: 47, // (0 | 7<<3): 0x38 0x2f + TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 + Score: 8.1, // (5 | 9<<3): 0x4d <8.1> + + Key: []uint64{1, 0xdeadbeef}, + Nested: &pb.Nested{ + Bunny: "Monty", + }, + } + t.Logf(" m: %v", m) + + b, err := proto.Marshal(m) + if err != nil { + t.Fatalf("proto.Marshal: %v", err) + } + t.Logf(" b: %q", b) + + m2 := new(pb.Message) + if err := proto.Unmarshal(b, m2); err != nil { + t.Fatalf("proto.Unmarshal: %v", err) + } + t.Logf("m2: %v", m2) + + if !proto.Equal(m, m2) { + t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) + } +} + +func TestProto3SetDefaults(t *testing.T) { + in := &pb.Message{ + Terrain: map[string]*pb.Nested{ + "meadow": new(pb.Nested), + }, + Proto2Field: new(tpb.SubDefaults), + Proto2Value: map[string]*tpb.SubDefaults{ + "badlands": new(tpb.SubDefaults), + }, + } + + got := proto.Clone(in).(*pb.Message) + proto.SetDefaults(got) + + // There are no defaults in proto3. Everything should be the zero value, but + // we need to remember to set defaults for nested proto2 messages. + want := &pb.Message{ + Terrain: map[string]*pb.Nested{ + "meadow": new(pb.Nested), + }, + Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, + Proto2Value: map[string]*tpb.SubDefaults{ + "badlands": &tpb.SubDefaults{N: proto.Int64(7)}, + }, + } + + if !proto.Equal(got, want) { + t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go new file mode 100644 index 0000000..a2729c3 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go @@ -0,0 +1,63 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2012 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "testing" +) + +// This is a separate file and package from size_test.go because that one uses +// generated messages and thus may not be in package proto without having a circular +// dependency, whereas this file tests unexported details of size.go. + +func TestVarintSize(t *testing.T) { + // Check the edge cases carefully. + testCases := []struct { + n uint64 + size int + }{ + {0, 1}, + {1, 1}, + {127, 1}, + {128, 2}, + {16383, 2}, + {16384, 3}, + {1<<63 - 1, 9}, + {1 << 63, 10}, + } + for _, tc := range testCases { + size := sizeVarint(tc.n) + if size != tc.size { + t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) + } + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go new file mode 100644 index 0000000..db5614f --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go @@ -0,0 +1,142 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2012 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto_test + +import ( + "log" + "strings" + "testing" + + . "github.com/golang/protobuf/proto" + proto3pb "github.com/golang/protobuf/proto/proto3_proto" + pb "github.com/golang/protobuf/proto/testdata" +) + +var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} + +// messageWithExtension2 is in equal_test.go. +var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} + +func init() { + if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { + log.Panicf("SetExtension: %v", err) + } + if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { + log.Panicf("SetExtension: %v", err) + } + + // Force messageWithExtension3 to have the extension encoded. + Marshal(messageWithExtension3) + +} + +var SizeTests = []struct { + desc string + pb Message +}{ + {"empty", &pb.OtherMessage{}}, + // Basic types. + {"bool", &pb.Defaults{F_Bool: Bool(true)}}, + {"int32", &pb.Defaults{F_Int32: Int32(12)}}, + {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, + {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, + {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, + {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, + {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, + {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, + {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, + {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, + {"float", &pb.Defaults{F_Float: Float32(12.6)}}, + {"double", &pb.Defaults{F_Double: Float64(13.9)}}, + {"string", &pb.Defaults{F_String: String("niles")}}, + {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, + {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, + {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, + {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, + {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, + // Repeated. + {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, + {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, + {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, + {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, + {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, + {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ + // Need enough large numbers to verify that the header is counting the number of bytes + // for the field, not the number of elements. + 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, + 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, + }}}, + {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, + {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, + // Nested. + {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, + {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, + // Other things. + {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, + {"extension (unencoded)", messageWithExtension1}, + {"extension (encoded)", messageWithExtension3}, + // proto3 message + {"proto3 empty", &proto3pb.Message{}}, + {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, + {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, + {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, + {"proto3 float", &proto3pb.Message{Score: 12.6}}, + {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, + {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, + {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, + {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, + {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}}, + + {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, + {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, + {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, + {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}}, + + {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, + {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, + {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, +} + +func TestSize(t *testing.T) { + for _, tc := range SizeTests { + size := Size(tc.pb) + b, err := Marshal(tc.pb) + if err != nil { + t.Errorf("%v: Marshal failed: %v", tc.desc, err) + continue + } + if size != len(b) { + t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) + t.Logf("%v: bytes: %#v", tc.desc, b) + } + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile new file mode 100644 index 0000000..fc28862 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile @@ -0,0 +1,50 @@ +# Go support for Protocol Buffers - Google's data interchange format +# +# Copyright 2010 The Go Authors. All rights reserved. +# https://github.com/golang/protobuf +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +include ../../Make.protobuf + +all: regenerate + +regenerate: + rm -f test.pb.go + make test.pb.go + +# The following rules are just aids to development. Not needed for typical testing. + +diff: regenerate + git diff test.pb.go + +restore: + cp test.pb.go.golden test.pb.go + +preserve: + cp test.pb.go test.pb.go.golden diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go new file mode 100644 index 0000000..7172d0e --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go @@ -0,0 +1,86 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2012 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Verify that the compiler output for test.proto is unchanged. + +package testdata + +import ( + "crypto/sha1" + "fmt" + "io/ioutil" + "os" + "os/exec" + "path/filepath" + "testing" +) + +// sum returns in string form (for easy comparison) the SHA-1 hash of the named file. +func sum(t *testing.T, name string) string { + data, err := ioutil.ReadFile(name) + if err != nil { + t.Fatal(err) + } + t.Logf("sum(%q): length is %d", name, len(data)) + hash := sha1.New() + _, err = hash.Write(data) + if err != nil { + t.Fatal(err) + } + return fmt.Sprintf("% x", hash.Sum(nil)) +} + +func run(t *testing.T, name string, args ...string) { + cmd := exec.Command(name, args...) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + err := cmd.Run() + if err != nil { + t.Fatal(err) + } +} + +func TestGolden(t *testing.T) { + // Compute the original checksum. + goldenSum := sum(t, "test.pb.go") + // Run the proto compiler. + run(t, "protoc", "--go_out="+os.TempDir(), "test.proto") + newFile := filepath.Join(os.TempDir(), "test.pb.go") + defer os.Remove(newFile) + // Compute the new checksum. + newSum := sum(t, newFile) + // Verify + if newSum != goldenSum { + run(t, "diff", "-u", "test.pb.go", newFile) + t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go") + } +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go new file mode 100644 index 0000000..13674a4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go @@ -0,0 +1,2746 @@ +// Code generated by protoc-gen-go. +// source: test.proto +// DO NOT EDIT! + +/* +Package testdata is a generated protocol buffer package. + +It is generated from these files: + test.proto + +It has these top-level messages: + GoEnum + GoTestField + GoTest + GoSkipTest + NonPackedTest + PackedTest + MaxTag + OldMessage + NewMessage + InnerMessage + OtherMessage + MyMessage + Ext + DefaultsMessage + MyMessageSet + Empty + MessageList + Strings + Defaults + SubDefaults + RepeatedEnum + MoreRepeated + GroupOld + GroupNew + FloatingPoint + MessageWithMap +*/ +package testdata + +import proto "github.com/golang/protobuf/proto" +import math "math" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = math.Inf + +type FOO int32 + +const ( + FOO_FOO1 FOO = 1 +) + +var FOO_name = map[int32]string{ + 1: "FOO1", +} +var FOO_value = map[string]int32{ + "FOO1": 1, +} + +func (x FOO) Enum() *FOO { + p := new(FOO) + *p = x + return p +} +func (x FOO) String() string { + return proto.EnumName(FOO_name, int32(x)) +} +func (x *FOO) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO") + if err != nil { + return err + } + *x = FOO(value) + return nil +} + +// An enum, for completeness. +type GoTest_KIND int32 + +const ( + GoTest_VOID GoTest_KIND = 0 + // Basic types + GoTest_BOOL GoTest_KIND = 1 + GoTest_BYTES GoTest_KIND = 2 + GoTest_FINGERPRINT GoTest_KIND = 3 + GoTest_FLOAT GoTest_KIND = 4 + GoTest_INT GoTest_KIND = 5 + GoTest_STRING GoTest_KIND = 6 + GoTest_TIME GoTest_KIND = 7 + // Groupings + GoTest_TUPLE GoTest_KIND = 8 + GoTest_ARRAY GoTest_KIND = 9 + GoTest_MAP GoTest_KIND = 10 + // Table types + GoTest_TABLE GoTest_KIND = 11 + // Functions + GoTest_FUNCTION GoTest_KIND = 12 +) + +var GoTest_KIND_name = map[int32]string{ + 0: "VOID", + 1: "BOOL", + 2: "BYTES", + 3: "FINGERPRINT", + 4: "FLOAT", + 5: "INT", + 6: "STRING", + 7: "TIME", + 8: "TUPLE", + 9: "ARRAY", + 10: "MAP", + 11: "TABLE", + 12: "FUNCTION", +} +var GoTest_KIND_value = map[string]int32{ + "VOID": 0, + "BOOL": 1, + "BYTES": 2, + "FINGERPRINT": 3, + "FLOAT": 4, + "INT": 5, + "STRING": 6, + "TIME": 7, + "TUPLE": 8, + "ARRAY": 9, + "MAP": 10, + "TABLE": 11, + "FUNCTION": 12, +} + +func (x GoTest_KIND) Enum() *GoTest_KIND { + p := new(GoTest_KIND) + *p = x + return p +} +func (x GoTest_KIND) String() string { + return proto.EnumName(GoTest_KIND_name, int32(x)) +} +func (x *GoTest_KIND) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND") + if err != nil { + return err + } + *x = GoTest_KIND(value) + return nil +} + +type MyMessage_Color int32 + +const ( + MyMessage_RED MyMessage_Color = 0 + MyMessage_GREEN MyMessage_Color = 1 + MyMessage_BLUE MyMessage_Color = 2 +) + +var MyMessage_Color_name = map[int32]string{ + 0: "RED", + 1: "GREEN", + 2: "BLUE", +} +var MyMessage_Color_value = map[string]int32{ + "RED": 0, + "GREEN": 1, + "BLUE": 2, +} + +func (x MyMessage_Color) Enum() *MyMessage_Color { + p := new(MyMessage_Color) + *p = x + return p +} +func (x MyMessage_Color) String() string { + return proto.EnumName(MyMessage_Color_name, int32(x)) +} +func (x *MyMessage_Color) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color") + if err != nil { + return err + } + *x = MyMessage_Color(value) + return nil +} + +type DefaultsMessage_DefaultsEnum int32 + +const ( + DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0 + DefaultsMessage_ONE DefaultsMessage_DefaultsEnum = 1 + DefaultsMessage_TWO DefaultsMessage_DefaultsEnum = 2 +) + +var DefaultsMessage_DefaultsEnum_name = map[int32]string{ + 0: "ZERO", + 1: "ONE", + 2: "TWO", +} +var DefaultsMessage_DefaultsEnum_value = map[string]int32{ + "ZERO": 0, + "ONE": 1, + "TWO": 2, +} + +func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum { + p := new(DefaultsMessage_DefaultsEnum) + *p = x + return p +} +func (x DefaultsMessage_DefaultsEnum) String() string { + return proto.EnumName(DefaultsMessage_DefaultsEnum_name, int32(x)) +} +func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(DefaultsMessage_DefaultsEnum_value, data, "DefaultsMessage_DefaultsEnum") + if err != nil { + return err + } + *x = DefaultsMessage_DefaultsEnum(value) + return nil +} + +type Defaults_Color int32 + +const ( + Defaults_RED Defaults_Color = 0 + Defaults_GREEN Defaults_Color = 1 + Defaults_BLUE Defaults_Color = 2 +) + +var Defaults_Color_name = map[int32]string{ + 0: "RED", + 1: "GREEN", + 2: "BLUE", +} +var Defaults_Color_value = map[string]int32{ + "RED": 0, + "GREEN": 1, + "BLUE": 2, +} + +func (x Defaults_Color) Enum() *Defaults_Color { + p := new(Defaults_Color) + *p = x + return p +} +func (x Defaults_Color) String() string { + return proto.EnumName(Defaults_Color_name, int32(x)) +} +func (x *Defaults_Color) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color") + if err != nil { + return err + } + *x = Defaults_Color(value) + return nil +} + +type RepeatedEnum_Color int32 + +const ( + RepeatedEnum_RED RepeatedEnum_Color = 1 +) + +var RepeatedEnum_Color_name = map[int32]string{ + 1: "RED", +} +var RepeatedEnum_Color_value = map[string]int32{ + "RED": 1, +} + +func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color { + p := new(RepeatedEnum_Color) + *p = x + return p +} +func (x RepeatedEnum_Color) String() string { + return proto.EnumName(RepeatedEnum_Color_name, int32(x)) +} +func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color") + if err != nil { + return err + } + *x = RepeatedEnum_Color(value) + return nil +} + +type GoEnum struct { + Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GoEnum) Reset() { *m = GoEnum{} } +func (m *GoEnum) String() string { return proto.CompactTextString(m) } +func (*GoEnum) ProtoMessage() {} + +func (m *GoEnum) GetFoo() FOO { + if m != nil && m.Foo != nil { + return *m.Foo + } + return FOO_FOO1 +} + +type GoTestField struct { + Label *string `protobuf:"bytes,1,req" json:"Label,omitempty"` + Type *string `protobuf:"bytes,2,req" json:"Type,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GoTestField) Reset() { *m = GoTestField{} } +func (m *GoTestField) String() string { return proto.CompactTextString(m) } +func (*GoTestField) ProtoMessage() {} + +func (m *GoTestField) GetLabel() string { + if m != nil && m.Label != nil { + return *m.Label + } + return "" +} + +func (m *GoTestField) GetType() string { + if m != nil && m.Type != nil { + return *m.Type + } + return "" +} + +type GoTest struct { + // Some typical parameters + Kind *GoTest_KIND `protobuf:"varint,1,req,enum=testdata.GoTest_KIND" json:"Kind,omitempty"` + Table *string `protobuf:"bytes,2,opt" json:"Table,omitempty"` + Param *int32 `protobuf:"varint,3,opt" json:"Param,omitempty"` + // Required, repeated and optional foreign fields. + RequiredField *GoTestField `protobuf:"bytes,4,req" json:"RequiredField,omitempty"` + RepeatedField []*GoTestField `protobuf:"bytes,5,rep" json:"RepeatedField,omitempty"` + OptionalField *GoTestField `protobuf:"bytes,6,opt" json:"OptionalField,omitempty"` + // Required fields of all basic types + F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required" json:"F_Bool_required,omitempty"` + F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required" json:"F_Int32_required,omitempty"` + F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required" json:"F_Int64_required,omitempty"` + F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required" json:"F_Fixed32_required,omitempty"` + F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required" json:"F_Fixed64_required,omitempty"` + F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required" json:"F_Uint32_required,omitempty"` + F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required" json:"F_Uint64_required,omitempty"` + F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required" json:"F_Float_required,omitempty"` + F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required" json:"F_Double_required,omitempty"` + F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required" json:"F_String_required,omitempty"` + F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required" json:"F_Bytes_required,omitempty"` + F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required" json:"F_Sint32_required,omitempty"` + F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required" json:"F_Sint64_required,omitempty"` + // Repeated fields of all basic types + F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated" json:"F_Bool_repeated,omitempty"` + F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated" json:"F_Int32_repeated,omitempty"` + F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated" json:"F_Int64_repeated,omitempty"` + F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated" json:"F_Fixed32_repeated,omitempty"` + F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated" json:"F_Fixed64_repeated,omitempty"` + F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated" json:"F_Uint32_repeated,omitempty"` + F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated" json:"F_Uint64_repeated,omitempty"` + F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated" json:"F_Float_repeated,omitempty"` + F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated" json:"F_Double_repeated,omitempty"` + F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated" json:"F_String_repeated,omitempty"` + F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated" json:"F_Bytes_repeated,omitempty"` + F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated" json:"F_Sint32_repeated,omitempty"` + F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated" json:"F_Sint64_repeated,omitempty"` + // Optional fields of all basic types + F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional" json:"F_Bool_optional,omitempty"` + F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional" json:"F_Int32_optional,omitempty"` + F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional" json:"F_Int64_optional,omitempty"` + F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional" json:"F_Fixed32_optional,omitempty"` + F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional" json:"F_Fixed64_optional,omitempty"` + F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional" json:"F_Uint32_optional,omitempty"` + F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional" json:"F_Uint64_optional,omitempty"` + F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional" json:"F_Float_optional,omitempty"` + F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional" json:"F_Double_optional,omitempty"` + F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional" json:"F_String_optional,omitempty"` + F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional" json:"F_Bytes_optional,omitempty"` + F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional" json:"F_Sint32_optional,omitempty"` + F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional" json:"F_Sint64_optional,omitempty"` + // Default-valued fields of all basic types + F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,def=1" json:"F_Bool_defaulted,omitempty"` + F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,def=32" json:"F_Int32_defaulted,omitempty"` + F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,def=64" json:"F_Int64_defaulted,omitempty"` + F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"` + F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"` + F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"` + F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"` + F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,def=314159" json:"F_Float_defaulted,omitempty"` + F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,def=271828" json:"F_Double_defaulted,omitempty"` + F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"` + F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"` + F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"` + F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"` + // Packed repeated fields (no string or bytes). + F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed" json:"F_Bool_repeated_packed,omitempty"` + F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed" json:"F_Int32_repeated_packed,omitempty"` + F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed" json:"F_Int64_repeated_packed,omitempty"` + F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed" json:"F_Fixed32_repeated_packed,omitempty"` + F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed" json:"F_Fixed64_repeated_packed,omitempty"` + F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed" json:"F_Uint32_repeated_packed,omitempty"` + F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed" json:"F_Uint64_repeated_packed,omitempty"` + F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed" json:"F_Float_repeated_packed,omitempty"` + F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed" json:"F_Double_repeated_packed,omitempty"` + F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed" json:"F_Sint32_repeated_packed,omitempty"` + F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed" json:"F_Sint64_repeated_packed,omitempty"` + Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup" json:"requiredgroup,omitempty"` + Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup" json:"repeatedgroup,omitempty"` + Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GoTest) Reset() { *m = GoTest{} } +func (m *GoTest) String() string { return proto.CompactTextString(m) } +func (*GoTest) ProtoMessage() {} + +const Default_GoTest_F_BoolDefaulted bool = true +const Default_GoTest_F_Int32Defaulted int32 = 32 +const Default_GoTest_F_Int64Defaulted int64 = 64 +const Default_GoTest_F_Fixed32Defaulted uint32 = 320 +const Default_GoTest_F_Fixed64Defaulted uint64 = 640 +const Default_GoTest_F_Uint32Defaulted uint32 = 3200 +const Default_GoTest_F_Uint64Defaulted uint64 = 6400 +const Default_GoTest_F_FloatDefaulted float32 = 314159 +const Default_GoTest_F_DoubleDefaulted float64 = 271828 +const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n" + +var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose") + +const Default_GoTest_F_Sint32Defaulted int32 = -32 +const Default_GoTest_F_Sint64Defaulted int64 = -64 + +func (m *GoTest) GetKind() GoTest_KIND { + if m != nil && m.Kind != nil { + return *m.Kind + } + return GoTest_VOID +} + +func (m *GoTest) GetTable() string { + if m != nil && m.Table != nil { + return *m.Table + } + return "" +} + +func (m *GoTest) GetParam() int32 { + if m != nil && m.Param != nil { + return *m.Param + } + return 0 +} + +func (m *GoTest) GetRequiredField() *GoTestField { + if m != nil { + return m.RequiredField + } + return nil +} + +func (m *GoTest) GetRepeatedField() []*GoTestField { + if m != nil { + return m.RepeatedField + } + return nil +} + +func (m *GoTest) GetOptionalField() *GoTestField { + if m != nil { + return m.OptionalField + } + return nil +} + +func (m *GoTest) GetF_BoolRequired() bool { + if m != nil && m.F_BoolRequired != nil { + return *m.F_BoolRequired + } + return false +} + +func (m *GoTest) GetF_Int32Required() int32 { + if m != nil && m.F_Int32Required != nil { + return *m.F_Int32Required + } + return 0 +} + +func (m *GoTest) GetF_Int64Required() int64 { + if m != nil && m.F_Int64Required != nil { + return *m.F_Int64Required + } + return 0 +} + +func (m *GoTest) GetF_Fixed32Required() uint32 { + if m != nil && m.F_Fixed32Required != nil { + return *m.F_Fixed32Required + } + return 0 +} + +func (m *GoTest) GetF_Fixed64Required() uint64 { + if m != nil && m.F_Fixed64Required != nil { + return *m.F_Fixed64Required + } + return 0 +} + +func (m *GoTest) GetF_Uint32Required() uint32 { + if m != nil && m.F_Uint32Required != nil { + return *m.F_Uint32Required + } + return 0 +} + +func (m *GoTest) GetF_Uint64Required() uint64 { + if m != nil && m.F_Uint64Required != nil { + return *m.F_Uint64Required + } + return 0 +} + +func (m *GoTest) GetF_FloatRequired() float32 { + if m != nil && m.F_FloatRequired != nil { + return *m.F_FloatRequired + } + return 0 +} + +func (m *GoTest) GetF_DoubleRequired() float64 { + if m != nil && m.F_DoubleRequired != nil { + return *m.F_DoubleRequired + } + return 0 +} + +func (m *GoTest) GetF_StringRequired() string { + if m != nil && m.F_StringRequired != nil { + return *m.F_StringRequired + } + return "" +} + +func (m *GoTest) GetF_BytesRequired() []byte { + if m != nil { + return m.F_BytesRequired + } + return nil +} + +func (m *GoTest) GetF_Sint32Required() int32 { + if m != nil && m.F_Sint32Required != nil { + return *m.F_Sint32Required + } + return 0 +} + +func (m *GoTest) GetF_Sint64Required() int64 { + if m != nil && m.F_Sint64Required != nil { + return *m.F_Sint64Required + } + return 0 +} + +func (m *GoTest) GetF_BoolRepeated() []bool { + if m != nil { + return m.F_BoolRepeated + } + return nil +} + +func (m *GoTest) GetF_Int32Repeated() []int32 { + if m != nil { + return m.F_Int32Repeated + } + return nil +} + +func (m *GoTest) GetF_Int64Repeated() []int64 { + if m != nil { + return m.F_Int64Repeated + } + return nil +} + +func (m *GoTest) GetF_Fixed32Repeated() []uint32 { + if m != nil { + return m.F_Fixed32Repeated + } + return nil +} + +func (m *GoTest) GetF_Fixed64Repeated() []uint64 { + if m != nil { + return m.F_Fixed64Repeated + } + return nil +} + +func (m *GoTest) GetF_Uint32Repeated() []uint32 { + if m != nil { + return m.F_Uint32Repeated + } + return nil +} + +func (m *GoTest) GetF_Uint64Repeated() []uint64 { + if m != nil { + return m.F_Uint64Repeated + } + return nil +} + +func (m *GoTest) GetF_FloatRepeated() []float32 { + if m != nil { + return m.F_FloatRepeated + } + return nil +} + +func (m *GoTest) GetF_DoubleRepeated() []float64 { + if m != nil { + return m.F_DoubleRepeated + } + return nil +} + +func (m *GoTest) GetF_StringRepeated() []string { + if m != nil { + return m.F_StringRepeated + } + return nil +} + +func (m *GoTest) GetF_BytesRepeated() [][]byte { + if m != nil { + return m.F_BytesRepeated + } + return nil +} + +func (m *GoTest) GetF_Sint32Repeated() []int32 { + if m != nil { + return m.F_Sint32Repeated + } + return nil +} + +func (m *GoTest) GetF_Sint64Repeated() []int64 { + if m != nil { + return m.F_Sint64Repeated + } + return nil +} + +func (m *GoTest) GetF_BoolOptional() bool { + if m != nil && m.F_BoolOptional != nil { + return *m.F_BoolOptional + } + return false +} + +func (m *GoTest) GetF_Int32Optional() int32 { + if m != nil && m.F_Int32Optional != nil { + return *m.F_Int32Optional + } + return 0 +} + +func (m *GoTest) GetF_Int64Optional() int64 { + if m != nil && m.F_Int64Optional != nil { + return *m.F_Int64Optional + } + return 0 +} + +func (m *GoTest) GetF_Fixed32Optional() uint32 { + if m != nil && m.F_Fixed32Optional != nil { + return *m.F_Fixed32Optional + } + return 0 +} + +func (m *GoTest) GetF_Fixed64Optional() uint64 { + if m != nil && m.F_Fixed64Optional != nil { + return *m.F_Fixed64Optional + } + return 0 +} + +func (m *GoTest) GetF_Uint32Optional() uint32 { + if m != nil && m.F_Uint32Optional != nil { + return *m.F_Uint32Optional + } + return 0 +} + +func (m *GoTest) GetF_Uint64Optional() uint64 { + if m != nil && m.F_Uint64Optional != nil { + return *m.F_Uint64Optional + } + return 0 +} + +func (m *GoTest) GetF_FloatOptional() float32 { + if m != nil && m.F_FloatOptional != nil { + return *m.F_FloatOptional + } + return 0 +} + +func (m *GoTest) GetF_DoubleOptional() float64 { + if m != nil && m.F_DoubleOptional != nil { + return *m.F_DoubleOptional + } + return 0 +} + +func (m *GoTest) GetF_StringOptional() string { + if m != nil && m.F_StringOptional != nil { + return *m.F_StringOptional + } + return "" +} + +func (m *GoTest) GetF_BytesOptional() []byte { + if m != nil { + return m.F_BytesOptional + } + return nil +} + +func (m *GoTest) GetF_Sint32Optional() int32 { + if m != nil && m.F_Sint32Optional != nil { + return *m.F_Sint32Optional + } + return 0 +} + +func (m *GoTest) GetF_Sint64Optional() int64 { + if m != nil && m.F_Sint64Optional != nil { + return *m.F_Sint64Optional + } + return 0 +} + +func (m *GoTest) GetF_BoolDefaulted() bool { + if m != nil && m.F_BoolDefaulted != nil { + return *m.F_BoolDefaulted + } + return Default_GoTest_F_BoolDefaulted +} + +func (m *GoTest) GetF_Int32Defaulted() int32 { + if m != nil && m.F_Int32Defaulted != nil { + return *m.F_Int32Defaulted + } + return Default_GoTest_F_Int32Defaulted +} + +func (m *GoTest) GetF_Int64Defaulted() int64 { + if m != nil && m.F_Int64Defaulted != nil { + return *m.F_Int64Defaulted + } + return Default_GoTest_F_Int64Defaulted +} + +func (m *GoTest) GetF_Fixed32Defaulted() uint32 { + if m != nil && m.F_Fixed32Defaulted != nil { + return *m.F_Fixed32Defaulted + } + return Default_GoTest_F_Fixed32Defaulted +} + +func (m *GoTest) GetF_Fixed64Defaulted() uint64 { + if m != nil && m.F_Fixed64Defaulted != nil { + return *m.F_Fixed64Defaulted + } + return Default_GoTest_F_Fixed64Defaulted +} + +func (m *GoTest) GetF_Uint32Defaulted() uint32 { + if m != nil && m.F_Uint32Defaulted != nil { + return *m.F_Uint32Defaulted + } + return Default_GoTest_F_Uint32Defaulted +} + +func (m *GoTest) GetF_Uint64Defaulted() uint64 { + if m != nil && m.F_Uint64Defaulted != nil { + return *m.F_Uint64Defaulted + } + return Default_GoTest_F_Uint64Defaulted +} + +func (m *GoTest) GetF_FloatDefaulted() float32 { + if m != nil && m.F_FloatDefaulted != nil { + return *m.F_FloatDefaulted + } + return Default_GoTest_F_FloatDefaulted +} + +func (m *GoTest) GetF_DoubleDefaulted() float64 { + if m != nil && m.F_DoubleDefaulted != nil { + return *m.F_DoubleDefaulted + } + return Default_GoTest_F_DoubleDefaulted +} + +func (m *GoTest) GetF_StringDefaulted() string { + if m != nil && m.F_StringDefaulted != nil { + return *m.F_StringDefaulted + } + return Default_GoTest_F_StringDefaulted +} + +func (m *GoTest) GetF_BytesDefaulted() []byte { + if m != nil && m.F_BytesDefaulted != nil { + return m.F_BytesDefaulted + } + return append([]byte(nil), Default_GoTest_F_BytesDefaulted...) +} + +func (m *GoTest) GetF_Sint32Defaulted() int32 { + if m != nil && m.F_Sint32Defaulted != nil { + return *m.F_Sint32Defaulted + } + return Default_GoTest_F_Sint32Defaulted +} + +func (m *GoTest) GetF_Sint64Defaulted() int64 { + if m != nil && m.F_Sint64Defaulted != nil { + return *m.F_Sint64Defaulted + } + return Default_GoTest_F_Sint64Defaulted +} + +func (m *GoTest) GetF_BoolRepeatedPacked() []bool { + if m != nil { + return m.F_BoolRepeatedPacked + } + return nil +} + +func (m *GoTest) GetF_Int32RepeatedPacked() []int32 { + if m != nil { + return m.F_Int32RepeatedPacked + } + return nil +} + +func (m *GoTest) GetF_Int64RepeatedPacked() []int64 { + if m != nil { + return m.F_Int64RepeatedPacked + } + return nil +} + +func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 { + if m != nil { + return m.F_Fixed32RepeatedPacked + } + return nil +} + +func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 { + if m != nil { + return m.F_Fixed64RepeatedPacked + } + return nil +} + +func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 { + if m != nil { + return m.F_Uint32RepeatedPacked + } + return nil +} + +func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 { + if m != nil { + return m.F_Uint64RepeatedPacked + } + return nil +} + +func (m *GoTest) GetF_FloatRepeatedPacked() []float32 { + if m != nil { + return m.F_FloatRepeatedPacked + } + return nil +} + +func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 { + if m != nil { + return m.F_DoubleRepeatedPacked + } + return nil +} + +func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 { + if m != nil { + return m.F_Sint32RepeatedPacked + } + return nil +} + +func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 { + if m != nil { + return m.F_Sint64RepeatedPacked + } + return nil +} + +func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup { + if m != nil { + return m.Requiredgroup + } + return nil +} + +func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup { + if m != nil { + return m.Repeatedgroup + } + return nil +} + +func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup { + if m != nil { + return m.Optionalgroup + } + return nil +} + +// Required, repeated, and optional groups. +type GoTest_RequiredGroup struct { + RequiredField *string `protobuf:"bytes,71,req" json:"RequiredField,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} } +func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) } +func (*GoTest_RequiredGroup) ProtoMessage() {} + +func (m *GoTest_RequiredGroup) GetRequiredField() string { + if m != nil && m.RequiredField != nil { + return *m.RequiredField + } + return "" +} + +type GoTest_RepeatedGroup struct { + RequiredField *string `protobuf:"bytes,81,req" json:"RequiredField,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} } +func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) } +func (*GoTest_RepeatedGroup) ProtoMessage() {} + +func (m *GoTest_RepeatedGroup) GetRequiredField() string { + if m != nil && m.RequiredField != nil { + return *m.RequiredField + } + return "" +} + +type GoTest_OptionalGroup struct { + RequiredField *string `protobuf:"bytes,91,req" json:"RequiredField,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} } +func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) } +func (*GoTest_OptionalGroup) ProtoMessage() {} + +func (m *GoTest_OptionalGroup) GetRequiredField() string { + if m != nil && m.RequiredField != nil { + return *m.RequiredField + } + return "" +} + +// For testing skipping of unrecognized fields. +// Numbers are all big, larger than tag numbers in GoTestField, +// the message used in the corresponding test. +type GoSkipTest struct { + SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32" json:"skip_int32,omitempty"` + SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32" json:"skip_fixed32,omitempty"` + SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64" json:"skip_fixed64,omitempty"` + SkipString *string `protobuf:"bytes,14,req,name=skip_string" json:"skip_string,omitempty"` + Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup" json:"skipgroup,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GoSkipTest) Reset() { *m = GoSkipTest{} } +func (m *GoSkipTest) String() string { return proto.CompactTextString(m) } +func (*GoSkipTest) ProtoMessage() {} + +func (m *GoSkipTest) GetSkipInt32() int32 { + if m != nil && m.SkipInt32 != nil { + return *m.SkipInt32 + } + return 0 +} + +func (m *GoSkipTest) GetSkipFixed32() uint32 { + if m != nil && m.SkipFixed32 != nil { + return *m.SkipFixed32 + } + return 0 +} + +func (m *GoSkipTest) GetSkipFixed64() uint64 { + if m != nil && m.SkipFixed64 != nil { + return *m.SkipFixed64 + } + return 0 +} + +func (m *GoSkipTest) GetSkipString() string { + if m != nil && m.SkipString != nil { + return *m.SkipString + } + return "" +} + +func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup { + if m != nil { + return m.Skipgroup + } + return nil +} + +type GoSkipTest_SkipGroup struct { + GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32" json:"group_int32,omitempty"` + GroupString *string `protobuf:"bytes,17,req,name=group_string" json:"group_string,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} } +func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) } +func (*GoSkipTest_SkipGroup) ProtoMessage() {} + +func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 { + if m != nil && m.GroupInt32 != nil { + return *m.GroupInt32 + } + return 0 +} + +func (m *GoSkipTest_SkipGroup) GetGroupString() string { + if m != nil && m.GroupString != nil { + return *m.GroupString + } + return "" +} + +// For testing packed/non-packed decoder switching. +// A serialized instance of one should be deserializable as the other. +type NonPackedTest struct { + A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *NonPackedTest) Reset() { *m = NonPackedTest{} } +func (m *NonPackedTest) String() string { return proto.CompactTextString(m) } +func (*NonPackedTest) ProtoMessage() {} + +func (m *NonPackedTest) GetA() []int32 { + if m != nil { + return m.A + } + return nil +} + +type PackedTest struct { + B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PackedTest) Reset() { *m = PackedTest{} } +func (m *PackedTest) String() string { return proto.CompactTextString(m) } +func (*PackedTest) ProtoMessage() {} + +func (m *PackedTest) GetB() []int32 { + if m != nil { + return m.B + } + return nil +} + +type MaxTag struct { + // Maximum possible tag number. + LastField *string `protobuf:"bytes,536870911,opt,name=last_field" json:"last_field,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MaxTag) Reset() { *m = MaxTag{} } +func (m *MaxTag) String() string { return proto.CompactTextString(m) } +func (*MaxTag) ProtoMessage() {} + +func (m *MaxTag) GetLastField() string { + if m != nil && m.LastField != nil { + return *m.LastField + } + return "" +} + +type OldMessage struct { + Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` + Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *OldMessage) Reset() { *m = OldMessage{} } +func (m *OldMessage) String() string { return proto.CompactTextString(m) } +func (*OldMessage) ProtoMessage() {} + +func (m *OldMessage) GetNested() *OldMessage_Nested { + if m != nil { + return m.Nested + } + return nil +} + +func (m *OldMessage) GetNum() int32 { + if m != nil && m.Num != nil { + return *m.Num + } + return 0 +} + +type OldMessage_Nested struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} } +func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) } +func (*OldMessage_Nested) ProtoMessage() {} + +func (m *OldMessage_Nested) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +// NewMessage is wire compatible with OldMessage; +// imagine it as a future version. +type NewMessage struct { + Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` + // This is an int32 in OldMessage. + Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *NewMessage) Reset() { *m = NewMessage{} } +func (m *NewMessage) String() string { return proto.CompactTextString(m) } +func (*NewMessage) ProtoMessage() {} + +func (m *NewMessage) GetNested() *NewMessage_Nested { + if m != nil { + return m.Nested + } + return nil +} + +func (m *NewMessage) GetNum() int64 { + if m != nil && m.Num != nil { + return *m.Num + } + return 0 +} + +type NewMessage_Nested struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + FoodGroup *string `protobuf:"bytes,2,opt,name=food_group" json:"food_group,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} } +func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) } +func (*NewMessage_Nested) ProtoMessage() {} + +func (m *NewMessage_Nested) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *NewMessage_Nested) GetFoodGroup() string { + if m != nil && m.FoodGroup != nil { + return *m.FoodGroup + } + return "" +} + +type InnerMessage struct { + Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"` + Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"` + Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *InnerMessage) Reset() { *m = InnerMessage{} } +func (m *InnerMessage) String() string { return proto.CompactTextString(m) } +func (*InnerMessage) ProtoMessage() {} + +const Default_InnerMessage_Port int32 = 4000 + +func (m *InnerMessage) GetHost() string { + if m != nil && m.Host != nil { + return *m.Host + } + return "" +} + +func (m *InnerMessage) GetPort() int32 { + if m != nil && m.Port != nil { + return *m.Port + } + return Default_InnerMessage_Port +} + +func (m *InnerMessage) GetConnected() bool { + if m != nil && m.Connected != nil { + return *m.Connected + } + return false +} + +type OtherMessage struct { + Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` + Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` + Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"` + Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *OtherMessage) Reset() { *m = OtherMessage{} } +func (m *OtherMessage) String() string { return proto.CompactTextString(m) } +func (*OtherMessage) ProtoMessage() {} + +func (m *OtherMessage) GetKey() int64 { + if m != nil && m.Key != nil { + return *m.Key + } + return 0 +} + +func (m *OtherMessage) GetValue() []byte { + if m != nil { + return m.Value + } + return nil +} + +func (m *OtherMessage) GetWeight() float32 { + if m != nil && m.Weight != nil { + return *m.Weight + } + return 0 +} + +func (m *OtherMessage) GetInner() *InnerMessage { + if m != nil { + return m.Inner + } + return nil +} + +type MyMessage struct { + Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"` + Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` + Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"` + Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"` + Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"` + Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"` + RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner" json:"rep_inner,omitempty"` + Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"` + Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup" json:"somegroup,omitempty"` + // This field becomes [][]byte in the generated code. + RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes" json:"rep_bytes,omitempty"` + Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"` + XXX_extensions map[int32]proto.Extension `json:"-"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MyMessage) Reset() { *m = MyMessage{} } +func (m *MyMessage) String() string { return proto.CompactTextString(m) } +func (*MyMessage) ProtoMessage() {} + +var extRange_MyMessage = []proto.ExtensionRange{ + {100, 536870911}, +} + +func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange { + return extRange_MyMessage +} +func (m *MyMessage) ExtensionMap() map[int32]proto.Extension { + if m.XXX_extensions == nil { + m.XXX_extensions = make(map[int32]proto.Extension) + } + return m.XXX_extensions +} + +func (m *MyMessage) GetCount() int32 { + if m != nil && m.Count != nil { + return *m.Count + } + return 0 +} + +func (m *MyMessage) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *MyMessage) GetQuote() string { + if m != nil && m.Quote != nil { + return *m.Quote + } + return "" +} + +func (m *MyMessage) GetPet() []string { + if m != nil { + return m.Pet + } + return nil +} + +func (m *MyMessage) GetInner() *InnerMessage { + if m != nil { + return m.Inner + } + return nil +} + +func (m *MyMessage) GetOthers() []*OtherMessage { + if m != nil { + return m.Others + } + return nil +} + +func (m *MyMessage) GetRepInner() []*InnerMessage { + if m != nil { + return m.RepInner + } + return nil +} + +func (m *MyMessage) GetBikeshed() MyMessage_Color { + if m != nil && m.Bikeshed != nil { + return *m.Bikeshed + } + return MyMessage_RED +} + +func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup { + if m != nil { + return m.Somegroup + } + return nil +} + +func (m *MyMessage) GetRepBytes() [][]byte { + if m != nil { + return m.RepBytes + } + return nil +} + +func (m *MyMessage) GetBigfloat() float64 { + if m != nil && m.Bigfloat != nil { + return *m.Bigfloat + } + return 0 +} + +type MyMessage_SomeGroup struct { + GroupField *int32 `protobuf:"varint,9,opt,name=group_field" json:"group_field,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} } +func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) } +func (*MyMessage_SomeGroup) ProtoMessage() {} + +func (m *MyMessage_SomeGroup) GetGroupField() int32 { + if m != nil && m.GroupField != nil { + return *m.GroupField + } + return 0 +} + +type Ext struct { + Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Ext) Reset() { *m = Ext{} } +func (m *Ext) String() string { return proto.CompactTextString(m) } +func (*Ext) ProtoMessage() {} + +func (m *Ext) GetData() string { + if m != nil && m.Data != nil { + return *m.Data + } + return "" +} + +var E_Ext_More = &proto.ExtensionDesc{ + ExtendedType: (*MyMessage)(nil), + ExtensionType: (*Ext)(nil), + Field: 103, + Name: "testdata.Ext.more", + Tag: "bytes,103,opt,name=more", +} + +var E_Ext_Text = &proto.ExtensionDesc{ + ExtendedType: (*MyMessage)(nil), + ExtensionType: (*string)(nil), + Field: 104, + Name: "testdata.Ext.text", + Tag: "bytes,104,opt,name=text", +} + +var E_Ext_Number = &proto.ExtensionDesc{ + ExtendedType: (*MyMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 105, + Name: "testdata.Ext.number", + Tag: "varint,105,opt,name=number", +} + +type DefaultsMessage struct { + XXX_extensions map[int32]proto.Extension `json:"-"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *DefaultsMessage) Reset() { *m = DefaultsMessage{} } +func (m *DefaultsMessage) String() string { return proto.CompactTextString(m) } +func (*DefaultsMessage) ProtoMessage() {} + +var extRange_DefaultsMessage = []proto.ExtensionRange{ + {100, 536870911}, +} + +func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange { + return extRange_DefaultsMessage +} +func (m *DefaultsMessage) ExtensionMap() map[int32]proto.Extension { + if m.XXX_extensions == nil { + m.XXX_extensions = make(map[int32]proto.Extension) + } + return m.XXX_extensions +} + +type MyMessageSet struct { + XXX_extensions map[int32]proto.Extension `json:"-"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MyMessageSet) Reset() { *m = MyMessageSet{} } +func (m *MyMessageSet) String() string { return proto.CompactTextString(m) } +func (*MyMessageSet) ProtoMessage() {} + +func (m *MyMessageSet) Marshal() ([]byte, error) { + return proto.MarshalMessageSet(m.ExtensionMap()) +} +func (m *MyMessageSet) Unmarshal(buf []byte) error { + return proto.UnmarshalMessageSet(buf, m.ExtensionMap()) +} +func (m *MyMessageSet) MarshalJSON() ([]byte, error) { + return proto.MarshalMessageSetJSON(m.XXX_extensions) +} +func (m *MyMessageSet) UnmarshalJSON(buf []byte) error { + return proto.UnmarshalMessageSetJSON(buf, m.XXX_extensions) +} + +// ensure MyMessageSet satisfies proto.Marshaler and proto.Unmarshaler +var _ proto.Marshaler = (*MyMessageSet)(nil) +var _ proto.Unmarshaler = (*MyMessageSet)(nil) + +var extRange_MyMessageSet = []proto.ExtensionRange{ + {100, 2147483646}, +} + +func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange { + return extRange_MyMessageSet +} +func (m *MyMessageSet) ExtensionMap() map[int32]proto.Extension { + if m.XXX_extensions == nil { + m.XXX_extensions = make(map[int32]proto.Extension) + } + return m.XXX_extensions +} + +type Empty struct { + XXX_unrecognized []byte `json:"-"` +} + +func (m *Empty) Reset() { *m = Empty{} } +func (m *Empty) String() string { return proto.CompactTextString(m) } +func (*Empty) ProtoMessage() {} + +type MessageList struct { + Message []*MessageList_Message `protobuf:"group,1,rep" json:"message,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MessageList) Reset() { *m = MessageList{} } +func (m *MessageList) String() string { return proto.CompactTextString(m) } +func (*MessageList) ProtoMessage() {} + +func (m *MessageList) GetMessage() []*MessageList_Message { + if m != nil { + return m.Message + } + return nil +} + +type MessageList_Message struct { + Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` + Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MessageList_Message) Reset() { *m = MessageList_Message{} } +func (m *MessageList_Message) String() string { return proto.CompactTextString(m) } +func (*MessageList_Message) ProtoMessage() {} + +func (m *MessageList_Message) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *MessageList_Message) GetCount() int32 { + if m != nil && m.Count != nil { + return *m.Count + } + return 0 +} + +type Strings struct { + StringField *string `protobuf:"bytes,1,opt,name=string_field" json:"string_field,omitempty"` + BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field" json:"bytes_field,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Strings) Reset() { *m = Strings{} } +func (m *Strings) String() string { return proto.CompactTextString(m) } +func (*Strings) ProtoMessage() {} + +func (m *Strings) GetStringField() string { + if m != nil && m.StringField != nil { + return *m.StringField + } + return "" +} + +func (m *Strings) GetBytesField() []byte { + if m != nil { + return m.BytesField + } + return nil +} + +type Defaults struct { + // Default-valued fields of all basic types. + // Same as GoTest, but copied here to make testing easier. + F_Bool *bool `protobuf:"varint,1,opt,def=1" json:"F_Bool,omitempty"` + F_Int32 *int32 `protobuf:"varint,2,opt,def=32" json:"F_Int32,omitempty"` + F_Int64 *int64 `protobuf:"varint,3,opt,def=64" json:"F_Int64,omitempty"` + F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,def=320" json:"F_Fixed32,omitempty"` + F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,def=640" json:"F_Fixed64,omitempty"` + F_Uint32 *uint32 `protobuf:"varint,6,opt,def=3200" json:"F_Uint32,omitempty"` + F_Uint64 *uint64 `protobuf:"varint,7,opt,def=6400" json:"F_Uint64,omitempty"` + F_Float *float32 `protobuf:"fixed32,8,opt,def=314159" json:"F_Float,omitempty"` + F_Double *float64 `protobuf:"fixed64,9,opt,def=271828" json:"F_Double,omitempty"` + F_String *string `protobuf:"bytes,10,opt,def=hello, \"world!\"\n" json:"F_String,omitempty"` + F_Bytes []byte `protobuf:"bytes,11,opt,def=Bignose" json:"F_Bytes,omitempty"` + F_Sint32 *int32 `protobuf:"zigzag32,12,opt,def=-32" json:"F_Sint32,omitempty"` + F_Sint64 *int64 `protobuf:"zigzag64,13,opt,def=-64" json:"F_Sint64,omitempty"` + F_Enum *Defaults_Color `protobuf:"varint,14,opt,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"` + // More fields with crazy defaults. + F_Pinf *float32 `protobuf:"fixed32,15,opt,def=inf" json:"F_Pinf,omitempty"` + F_Ninf *float32 `protobuf:"fixed32,16,opt,def=-inf" json:"F_Ninf,omitempty"` + F_Nan *float32 `protobuf:"fixed32,17,opt,def=nan" json:"F_Nan,omitempty"` + // Sub-message. + Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"` + // Redundant but explicit defaults. + StrZero *string `protobuf:"bytes,19,opt,name=str_zero,def=" json:"str_zero,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Defaults) Reset() { *m = Defaults{} } +func (m *Defaults) String() string { return proto.CompactTextString(m) } +func (*Defaults) ProtoMessage() {} + +const Default_Defaults_F_Bool bool = true +const Default_Defaults_F_Int32 int32 = 32 +const Default_Defaults_F_Int64 int64 = 64 +const Default_Defaults_F_Fixed32 uint32 = 320 +const Default_Defaults_F_Fixed64 uint64 = 640 +const Default_Defaults_F_Uint32 uint32 = 3200 +const Default_Defaults_F_Uint64 uint64 = 6400 +const Default_Defaults_F_Float float32 = 314159 +const Default_Defaults_F_Double float64 = 271828 +const Default_Defaults_F_String string = "hello, \"world!\"\n" + +var Default_Defaults_F_Bytes []byte = []byte("Bignose") + +const Default_Defaults_F_Sint32 int32 = -32 +const Default_Defaults_F_Sint64 int64 = -64 +const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN + +var Default_Defaults_F_Pinf float32 = float32(math.Inf(1)) +var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1)) +var Default_Defaults_F_Nan float32 = float32(math.NaN()) + +func (m *Defaults) GetF_Bool() bool { + if m != nil && m.F_Bool != nil { + return *m.F_Bool + } + return Default_Defaults_F_Bool +} + +func (m *Defaults) GetF_Int32() int32 { + if m != nil && m.F_Int32 != nil { + return *m.F_Int32 + } + return Default_Defaults_F_Int32 +} + +func (m *Defaults) GetF_Int64() int64 { + if m != nil && m.F_Int64 != nil { + return *m.F_Int64 + } + return Default_Defaults_F_Int64 +} + +func (m *Defaults) GetF_Fixed32() uint32 { + if m != nil && m.F_Fixed32 != nil { + return *m.F_Fixed32 + } + return Default_Defaults_F_Fixed32 +} + +func (m *Defaults) GetF_Fixed64() uint64 { + if m != nil && m.F_Fixed64 != nil { + return *m.F_Fixed64 + } + return Default_Defaults_F_Fixed64 +} + +func (m *Defaults) GetF_Uint32() uint32 { + if m != nil && m.F_Uint32 != nil { + return *m.F_Uint32 + } + return Default_Defaults_F_Uint32 +} + +func (m *Defaults) GetF_Uint64() uint64 { + if m != nil && m.F_Uint64 != nil { + return *m.F_Uint64 + } + return Default_Defaults_F_Uint64 +} + +func (m *Defaults) GetF_Float() float32 { + if m != nil && m.F_Float != nil { + return *m.F_Float + } + return Default_Defaults_F_Float +} + +func (m *Defaults) GetF_Double() float64 { + if m != nil && m.F_Double != nil { + return *m.F_Double + } + return Default_Defaults_F_Double +} + +func (m *Defaults) GetF_String() string { + if m != nil && m.F_String != nil { + return *m.F_String + } + return Default_Defaults_F_String +} + +func (m *Defaults) GetF_Bytes() []byte { + if m != nil && m.F_Bytes != nil { + return m.F_Bytes + } + return append([]byte(nil), Default_Defaults_F_Bytes...) +} + +func (m *Defaults) GetF_Sint32() int32 { + if m != nil && m.F_Sint32 != nil { + return *m.F_Sint32 + } + return Default_Defaults_F_Sint32 +} + +func (m *Defaults) GetF_Sint64() int64 { + if m != nil && m.F_Sint64 != nil { + return *m.F_Sint64 + } + return Default_Defaults_F_Sint64 +} + +func (m *Defaults) GetF_Enum() Defaults_Color { + if m != nil && m.F_Enum != nil { + return *m.F_Enum + } + return Default_Defaults_F_Enum +} + +func (m *Defaults) GetF_Pinf() float32 { + if m != nil && m.F_Pinf != nil { + return *m.F_Pinf + } + return Default_Defaults_F_Pinf +} + +func (m *Defaults) GetF_Ninf() float32 { + if m != nil && m.F_Ninf != nil { + return *m.F_Ninf + } + return Default_Defaults_F_Ninf +} + +func (m *Defaults) GetF_Nan() float32 { + if m != nil && m.F_Nan != nil { + return *m.F_Nan + } + return Default_Defaults_F_Nan +} + +func (m *Defaults) GetSub() *SubDefaults { + if m != nil { + return m.Sub + } + return nil +} + +func (m *Defaults) GetStrZero() string { + if m != nil && m.StrZero != nil { + return *m.StrZero + } + return "" +} + +type SubDefaults struct { + N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *SubDefaults) Reset() { *m = SubDefaults{} } +func (m *SubDefaults) String() string { return proto.CompactTextString(m) } +func (*SubDefaults) ProtoMessage() {} + +const Default_SubDefaults_N int64 = 7 + +func (m *SubDefaults) GetN() int64 { + if m != nil && m.N != nil { + return *m.N + } + return Default_SubDefaults_N +} + +type RepeatedEnum struct { + Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} } +func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) } +func (*RepeatedEnum) ProtoMessage() {} + +func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color { + if m != nil { + return m.Color + } + return nil +} + +type MoreRepeated struct { + Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"` + BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed" json:"bools_packed,omitempty"` + Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"` + IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed" json:"ints_packed,omitempty"` + Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed" json:"int64s_packed,omitempty"` + Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"` + Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MoreRepeated) Reset() { *m = MoreRepeated{} } +func (m *MoreRepeated) String() string { return proto.CompactTextString(m) } +func (*MoreRepeated) ProtoMessage() {} + +func (m *MoreRepeated) GetBools() []bool { + if m != nil { + return m.Bools + } + return nil +} + +func (m *MoreRepeated) GetBoolsPacked() []bool { + if m != nil { + return m.BoolsPacked + } + return nil +} + +func (m *MoreRepeated) GetInts() []int32 { + if m != nil { + return m.Ints + } + return nil +} + +func (m *MoreRepeated) GetIntsPacked() []int32 { + if m != nil { + return m.IntsPacked + } + return nil +} + +func (m *MoreRepeated) GetInt64SPacked() []int64 { + if m != nil { + return m.Int64SPacked + } + return nil +} + +func (m *MoreRepeated) GetStrings() []string { + if m != nil { + return m.Strings + } + return nil +} + +func (m *MoreRepeated) GetFixeds() []uint32 { + if m != nil { + return m.Fixeds + } + return nil +} + +type GroupOld struct { + G *GroupOld_G `protobuf:"group,101,opt" json:"g,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GroupOld) Reset() { *m = GroupOld{} } +func (m *GroupOld) String() string { return proto.CompactTextString(m) } +func (*GroupOld) ProtoMessage() {} + +func (m *GroupOld) GetG() *GroupOld_G { + if m != nil { + return m.G + } + return nil +} + +type GroupOld_G struct { + X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GroupOld_G) Reset() { *m = GroupOld_G{} } +func (m *GroupOld_G) String() string { return proto.CompactTextString(m) } +func (*GroupOld_G) ProtoMessage() {} + +func (m *GroupOld_G) GetX() int32 { + if m != nil && m.X != nil { + return *m.X + } + return 0 +} + +type GroupNew struct { + G *GroupNew_G `protobuf:"group,101,opt" json:"g,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GroupNew) Reset() { *m = GroupNew{} } +func (m *GroupNew) String() string { return proto.CompactTextString(m) } +func (*GroupNew) ProtoMessage() {} + +func (m *GroupNew) GetG() *GroupNew_G { + if m != nil { + return m.G + } + return nil +} + +type GroupNew_G struct { + X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` + Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *GroupNew_G) Reset() { *m = GroupNew_G{} } +func (m *GroupNew_G) String() string { return proto.CompactTextString(m) } +func (*GroupNew_G) ProtoMessage() {} + +func (m *GroupNew_G) GetX() int32 { + if m != nil && m.X != nil { + return *m.X + } + return 0 +} + +func (m *GroupNew_G) GetY() int32 { + if m != nil && m.Y != nil { + return *m.Y + } + return 0 +} + +type FloatingPoint struct { + F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *FloatingPoint) Reset() { *m = FloatingPoint{} } +func (m *FloatingPoint) String() string { return proto.CompactTextString(m) } +func (*FloatingPoint) ProtoMessage() {} + +func (m *FloatingPoint) GetF() float64 { + if m != nil && m.F != nil { + return *m.F + } + return 0 +} + +type MessageWithMap struct { + NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + StrToStr map[string]string `protobuf:"bytes,4,rep,name=str_to_str" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } +func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } +func (*MessageWithMap) ProtoMessage() {} + +func (m *MessageWithMap) GetNameMapping() map[int32]string { + if m != nil { + return m.NameMapping + } + return nil +} + +func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint { + if m != nil { + return m.MsgMapping + } + return nil +} + +func (m *MessageWithMap) GetByteMapping() map[bool][]byte { + if m != nil { + return m.ByteMapping + } + return nil +} + +func (m *MessageWithMap) GetStrToStr() map[string]string { + if m != nil { + return m.StrToStr + } + return nil +} + +var E_Greeting = &proto.ExtensionDesc{ + ExtendedType: (*MyMessage)(nil), + ExtensionType: ([]string)(nil), + Field: 106, + Name: "testdata.greeting", + Tag: "bytes,106,rep,name=greeting", +} + +var E_NoDefaultDouble = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*float64)(nil), + Field: 101, + Name: "testdata.no_default_double", + Tag: "fixed64,101,opt,name=no_default_double", +} + +var E_NoDefaultFloat = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*float32)(nil), + Field: 102, + Name: "testdata.no_default_float", + Tag: "fixed32,102,opt,name=no_default_float", +} + +var E_NoDefaultInt32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 103, + Name: "testdata.no_default_int32", + Tag: "varint,103,opt,name=no_default_int32", +} + +var E_NoDefaultInt64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 104, + Name: "testdata.no_default_int64", + Tag: "varint,104,opt,name=no_default_int64", +} + +var E_NoDefaultUint32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint32)(nil), + Field: 105, + Name: "testdata.no_default_uint32", + Tag: "varint,105,opt,name=no_default_uint32", +} + +var E_NoDefaultUint64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint64)(nil), + Field: 106, + Name: "testdata.no_default_uint64", + Tag: "varint,106,opt,name=no_default_uint64", +} + +var E_NoDefaultSint32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 107, + Name: "testdata.no_default_sint32", + Tag: "zigzag32,107,opt,name=no_default_sint32", +} + +var E_NoDefaultSint64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 108, + Name: "testdata.no_default_sint64", + Tag: "zigzag64,108,opt,name=no_default_sint64", +} + +var E_NoDefaultFixed32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint32)(nil), + Field: 109, + Name: "testdata.no_default_fixed32", + Tag: "fixed32,109,opt,name=no_default_fixed32", +} + +var E_NoDefaultFixed64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint64)(nil), + Field: 110, + Name: "testdata.no_default_fixed64", + Tag: "fixed64,110,opt,name=no_default_fixed64", +} + +var E_NoDefaultSfixed32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 111, + Name: "testdata.no_default_sfixed32", + Tag: "fixed32,111,opt,name=no_default_sfixed32", +} + +var E_NoDefaultSfixed64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 112, + Name: "testdata.no_default_sfixed64", + Tag: "fixed64,112,opt,name=no_default_sfixed64", +} + +var E_NoDefaultBool = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*bool)(nil), + Field: 113, + Name: "testdata.no_default_bool", + Tag: "varint,113,opt,name=no_default_bool", +} + +var E_NoDefaultString = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*string)(nil), + Field: 114, + Name: "testdata.no_default_string", + Tag: "bytes,114,opt,name=no_default_string", +} + +var E_NoDefaultBytes = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: ([]byte)(nil), + Field: 115, + Name: "testdata.no_default_bytes", + Tag: "bytes,115,opt,name=no_default_bytes", +} + +var E_NoDefaultEnum = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), + Field: 116, + Name: "testdata.no_default_enum", + Tag: "varint,116,opt,name=no_default_enum,enum=testdata.DefaultsMessage_DefaultsEnum", +} + +var E_DefaultDouble = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*float64)(nil), + Field: 201, + Name: "testdata.default_double", + Tag: "fixed64,201,opt,name=default_double,def=3.1415", +} + +var E_DefaultFloat = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*float32)(nil), + Field: 202, + Name: "testdata.default_float", + Tag: "fixed32,202,opt,name=default_float,def=3.14", +} + +var E_DefaultInt32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 203, + Name: "testdata.default_int32", + Tag: "varint,203,opt,name=default_int32,def=42", +} + +var E_DefaultInt64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 204, + Name: "testdata.default_int64", + Tag: "varint,204,opt,name=default_int64,def=43", +} + +var E_DefaultUint32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint32)(nil), + Field: 205, + Name: "testdata.default_uint32", + Tag: "varint,205,opt,name=default_uint32,def=44", +} + +var E_DefaultUint64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint64)(nil), + Field: 206, + Name: "testdata.default_uint64", + Tag: "varint,206,opt,name=default_uint64,def=45", +} + +var E_DefaultSint32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 207, + Name: "testdata.default_sint32", + Tag: "zigzag32,207,opt,name=default_sint32,def=46", +} + +var E_DefaultSint64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 208, + Name: "testdata.default_sint64", + Tag: "zigzag64,208,opt,name=default_sint64,def=47", +} + +var E_DefaultFixed32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint32)(nil), + Field: 209, + Name: "testdata.default_fixed32", + Tag: "fixed32,209,opt,name=default_fixed32,def=48", +} + +var E_DefaultFixed64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*uint64)(nil), + Field: 210, + Name: "testdata.default_fixed64", + Tag: "fixed64,210,opt,name=default_fixed64,def=49", +} + +var E_DefaultSfixed32 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int32)(nil), + Field: 211, + Name: "testdata.default_sfixed32", + Tag: "fixed32,211,opt,name=default_sfixed32,def=50", +} + +var E_DefaultSfixed64 = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*int64)(nil), + Field: 212, + Name: "testdata.default_sfixed64", + Tag: "fixed64,212,opt,name=default_sfixed64,def=51", +} + +var E_DefaultBool = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*bool)(nil), + Field: 213, + Name: "testdata.default_bool", + Tag: "varint,213,opt,name=default_bool,def=1", +} + +var E_DefaultString = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*string)(nil), + Field: 214, + Name: "testdata.default_string", + Tag: "bytes,214,opt,name=default_string,def=Hello, string", +} + +var E_DefaultBytes = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: ([]byte)(nil), + Field: 215, + Name: "testdata.default_bytes", + Tag: "bytes,215,opt,name=default_bytes,def=Hello, bytes", +} + +var E_DefaultEnum = &proto.ExtensionDesc{ + ExtendedType: (*DefaultsMessage)(nil), + ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), + Field: 216, + Name: "testdata.default_enum", + Tag: "varint,216,opt,name=default_enum,enum=testdata.DefaultsMessage_DefaultsEnum,def=1", +} + +var E_X201 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 201, + Name: "testdata.x201", + Tag: "bytes,201,opt,name=x201", +} + +var E_X202 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 202, + Name: "testdata.x202", + Tag: "bytes,202,opt,name=x202", +} + +var E_X203 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 203, + Name: "testdata.x203", + Tag: "bytes,203,opt,name=x203", +} + +var E_X204 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 204, + Name: "testdata.x204", + Tag: "bytes,204,opt,name=x204", +} + +var E_X205 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 205, + Name: "testdata.x205", + Tag: "bytes,205,opt,name=x205", +} + +var E_X206 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 206, + Name: "testdata.x206", + Tag: "bytes,206,opt,name=x206", +} + +var E_X207 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 207, + Name: "testdata.x207", + Tag: "bytes,207,opt,name=x207", +} + +var E_X208 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 208, + Name: "testdata.x208", + Tag: "bytes,208,opt,name=x208", +} + +var E_X209 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 209, + Name: "testdata.x209", + Tag: "bytes,209,opt,name=x209", +} + +var E_X210 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 210, + Name: "testdata.x210", + Tag: "bytes,210,opt,name=x210", +} + +var E_X211 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 211, + Name: "testdata.x211", + Tag: "bytes,211,opt,name=x211", +} + +var E_X212 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 212, + Name: "testdata.x212", + Tag: "bytes,212,opt,name=x212", +} + +var E_X213 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 213, + Name: "testdata.x213", + Tag: "bytes,213,opt,name=x213", +} + +var E_X214 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 214, + Name: "testdata.x214", + Tag: "bytes,214,opt,name=x214", +} + +var E_X215 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 215, + Name: "testdata.x215", + Tag: "bytes,215,opt,name=x215", +} + +var E_X216 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 216, + Name: "testdata.x216", + Tag: "bytes,216,opt,name=x216", +} + +var E_X217 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 217, + Name: "testdata.x217", + Tag: "bytes,217,opt,name=x217", +} + +var E_X218 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 218, + Name: "testdata.x218", + Tag: "bytes,218,opt,name=x218", +} + +var E_X219 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 219, + Name: "testdata.x219", + Tag: "bytes,219,opt,name=x219", +} + +var E_X220 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 220, + Name: "testdata.x220", + Tag: "bytes,220,opt,name=x220", +} + +var E_X221 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 221, + Name: "testdata.x221", + Tag: "bytes,221,opt,name=x221", +} + +var E_X222 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 222, + Name: "testdata.x222", + Tag: "bytes,222,opt,name=x222", +} + +var E_X223 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 223, + Name: "testdata.x223", + Tag: "bytes,223,opt,name=x223", +} + +var E_X224 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 224, + Name: "testdata.x224", + Tag: "bytes,224,opt,name=x224", +} + +var E_X225 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 225, + Name: "testdata.x225", + Tag: "bytes,225,opt,name=x225", +} + +var E_X226 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 226, + Name: "testdata.x226", + Tag: "bytes,226,opt,name=x226", +} + +var E_X227 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 227, + Name: "testdata.x227", + Tag: "bytes,227,opt,name=x227", +} + +var E_X228 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 228, + Name: "testdata.x228", + Tag: "bytes,228,opt,name=x228", +} + +var E_X229 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 229, + Name: "testdata.x229", + Tag: "bytes,229,opt,name=x229", +} + +var E_X230 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 230, + Name: "testdata.x230", + Tag: "bytes,230,opt,name=x230", +} + +var E_X231 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 231, + Name: "testdata.x231", + Tag: "bytes,231,opt,name=x231", +} + +var E_X232 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 232, + Name: "testdata.x232", + Tag: "bytes,232,opt,name=x232", +} + +var E_X233 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 233, + Name: "testdata.x233", + Tag: "bytes,233,opt,name=x233", +} + +var E_X234 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 234, + Name: "testdata.x234", + Tag: "bytes,234,opt,name=x234", +} + +var E_X235 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 235, + Name: "testdata.x235", + Tag: "bytes,235,opt,name=x235", +} + +var E_X236 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 236, + Name: "testdata.x236", + Tag: "bytes,236,opt,name=x236", +} + +var E_X237 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 237, + Name: "testdata.x237", + Tag: "bytes,237,opt,name=x237", +} + +var E_X238 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 238, + Name: "testdata.x238", + Tag: "bytes,238,opt,name=x238", +} + +var E_X239 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 239, + Name: "testdata.x239", + Tag: "bytes,239,opt,name=x239", +} + +var E_X240 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 240, + Name: "testdata.x240", + Tag: "bytes,240,opt,name=x240", +} + +var E_X241 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 241, + Name: "testdata.x241", + Tag: "bytes,241,opt,name=x241", +} + +var E_X242 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 242, + Name: "testdata.x242", + Tag: "bytes,242,opt,name=x242", +} + +var E_X243 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 243, + Name: "testdata.x243", + Tag: "bytes,243,opt,name=x243", +} + +var E_X244 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 244, + Name: "testdata.x244", + Tag: "bytes,244,opt,name=x244", +} + +var E_X245 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 245, + Name: "testdata.x245", + Tag: "bytes,245,opt,name=x245", +} + +var E_X246 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 246, + Name: "testdata.x246", + Tag: "bytes,246,opt,name=x246", +} + +var E_X247 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 247, + Name: "testdata.x247", + Tag: "bytes,247,opt,name=x247", +} + +var E_X248 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 248, + Name: "testdata.x248", + Tag: "bytes,248,opt,name=x248", +} + +var E_X249 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 249, + Name: "testdata.x249", + Tag: "bytes,249,opt,name=x249", +} + +var E_X250 = &proto.ExtensionDesc{ + ExtendedType: (*MyMessageSet)(nil), + ExtensionType: (*Empty)(nil), + Field: 250, + Name: "testdata.x250", + Tag: "bytes,250,opt,name=x250", +} + +func init() { + proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value) + proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value) + proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value) + proto.RegisterEnum("testdata.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value) + proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value) + proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value) + proto.RegisterExtension(E_Ext_More) + proto.RegisterExtension(E_Ext_Text) + proto.RegisterExtension(E_Ext_Number) + proto.RegisterExtension(E_Greeting) + proto.RegisterExtension(E_NoDefaultDouble) + proto.RegisterExtension(E_NoDefaultFloat) + proto.RegisterExtension(E_NoDefaultInt32) + proto.RegisterExtension(E_NoDefaultInt64) + proto.RegisterExtension(E_NoDefaultUint32) + proto.RegisterExtension(E_NoDefaultUint64) + proto.RegisterExtension(E_NoDefaultSint32) + proto.RegisterExtension(E_NoDefaultSint64) + proto.RegisterExtension(E_NoDefaultFixed32) + proto.RegisterExtension(E_NoDefaultFixed64) + proto.RegisterExtension(E_NoDefaultSfixed32) + proto.RegisterExtension(E_NoDefaultSfixed64) + proto.RegisterExtension(E_NoDefaultBool) + proto.RegisterExtension(E_NoDefaultString) + proto.RegisterExtension(E_NoDefaultBytes) + proto.RegisterExtension(E_NoDefaultEnum) + proto.RegisterExtension(E_DefaultDouble) + proto.RegisterExtension(E_DefaultFloat) + proto.RegisterExtension(E_DefaultInt32) + proto.RegisterExtension(E_DefaultInt64) + proto.RegisterExtension(E_DefaultUint32) + proto.RegisterExtension(E_DefaultUint64) + proto.RegisterExtension(E_DefaultSint32) + proto.RegisterExtension(E_DefaultSint64) + proto.RegisterExtension(E_DefaultFixed32) + proto.RegisterExtension(E_DefaultFixed64) + proto.RegisterExtension(E_DefaultSfixed32) + proto.RegisterExtension(E_DefaultSfixed64) + proto.RegisterExtension(E_DefaultBool) + proto.RegisterExtension(E_DefaultString) + proto.RegisterExtension(E_DefaultBytes) + proto.RegisterExtension(E_DefaultEnum) + proto.RegisterExtension(E_X201) + proto.RegisterExtension(E_X202) + proto.RegisterExtension(E_X203) + proto.RegisterExtension(E_X204) + proto.RegisterExtension(E_X205) + proto.RegisterExtension(E_X206) + proto.RegisterExtension(E_X207) + proto.RegisterExtension(E_X208) + proto.RegisterExtension(E_X209) + proto.RegisterExtension(E_X210) + proto.RegisterExtension(E_X211) + proto.RegisterExtension(E_X212) + proto.RegisterExtension(E_X213) + proto.RegisterExtension(E_X214) + proto.RegisterExtension(E_X215) + proto.RegisterExtension(E_X216) + proto.RegisterExtension(E_X217) + proto.RegisterExtension(E_X218) + proto.RegisterExtension(E_X219) + proto.RegisterExtension(E_X220) + proto.RegisterExtension(E_X221) + proto.RegisterExtension(E_X222) + proto.RegisterExtension(E_X223) + proto.RegisterExtension(E_X224) + proto.RegisterExtension(E_X225) + proto.RegisterExtension(E_X226) + proto.RegisterExtension(E_X227) + proto.RegisterExtension(E_X228) + proto.RegisterExtension(E_X229) + proto.RegisterExtension(E_X230) + proto.RegisterExtension(E_X231) + proto.RegisterExtension(E_X232) + proto.RegisterExtension(E_X233) + proto.RegisterExtension(E_X234) + proto.RegisterExtension(E_X235) + proto.RegisterExtension(E_X236) + proto.RegisterExtension(E_X237) + proto.RegisterExtension(E_X238) + proto.RegisterExtension(E_X239) + proto.RegisterExtension(E_X240) + proto.RegisterExtension(E_X241) + proto.RegisterExtension(E_X242) + proto.RegisterExtension(E_X243) + proto.RegisterExtension(E_X244) + proto.RegisterExtension(E_X245) + proto.RegisterExtension(E_X246) + proto.RegisterExtension(E_X247) + proto.RegisterExtension(E_X248) + proto.RegisterExtension(E_X249) + proto.RegisterExtension(E_X250) +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto new file mode 100644 index 0000000..440dba3 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto @@ -0,0 +1,480 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// A feature-rich test file for the protocol compiler and libraries. + +syntax = "proto2"; + +package testdata; + +enum FOO { FOO1 = 1; }; + +message GoEnum { + required FOO foo = 1; +} + +message GoTestField { + required string Label = 1; + required string Type = 2; +} + +message GoTest { + // An enum, for completeness. + enum KIND { + VOID = 0; + + // Basic types + BOOL = 1; + BYTES = 2; + FINGERPRINT = 3; + FLOAT = 4; + INT = 5; + STRING = 6; + TIME = 7; + + // Groupings + TUPLE = 8; + ARRAY = 9; + MAP = 10; + + // Table types + TABLE = 11; + + // Functions + FUNCTION = 12; // last tag + }; + + // Some typical parameters + required KIND Kind = 1; + optional string Table = 2; + optional int32 Param = 3; + + // Required, repeated and optional foreign fields. + required GoTestField RequiredField = 4; + repeated GoTestField RepeatedField = 5; + optional GoTestField OptionalField = 6; + + // Required fields of all basic types + required bool F_Bool_required = 10; + required int32 F_Int32_required = 11; + required int64 F_Int64_required = 12; + required fixed32 F_Fixed32_required = 13; + required fixed64 F_Fixed64_required = 14; + required uint32 F_Uint32_required = 15; + required uint64 F_Uint64_required = 16; + required float F_Float_required = 17; + required double F_Double_required = 18; + required string F_String_required = 19; + required bytes F_Bytes_required = 101; + required sint32 F_Sint32_required = 102; + required sint64 F_Sint64_required = 103; + + // Repeated fields of all basic types + repeated bool F_Bool_repeated = 20; + repeated int32 F_Int32_repeated = 21; + repeated int64 F_Int64_repeated = 22; + repeated fixed32 F_Fixed32_repeated = 23; + repeated fixed64 F_Fixed64_repeated = 24; + repeated uint32 F_Uint32_repeated = 25; + repeated uint64 F_Uint64_repeated = 26; + repeated float F_Float_repeated = 27; + repeated double F_Double_repeated = 28; + repeated string F_String_repeated = 29; + repeated bytes F_Bytes_repeated = 201; + repeated sint32 F_Sint32_repeated = 202; + repeated sint64 F_Sint64_repeated = 203; + + // Optional fields of all basic types + optional bool F_Bool_optional = 30; + optional int32 F_Int32_optional = 31; + optional int64 F_Int64_optional = 32; + optional fixed32 F_Fixed32_optional = 33; + optional fixed64 F_Fixed64_optional = 34; + optional uint32 F_Uint32_optional = 35; + optional uint64 F_Uint64_optional = 36; + optional float F_Float_optional = 37; + optional double F_Double_optional = 38; + optional string F_String_optional = 39; + optional bytes F_Bytes_optional = 301; + optional sint32 F_Sint32_optional = 302; + optional sint64 F_Sint64_optional = 303; + + // Default-valued fields of all basic types + optional bool F_Bool_defaulted = 40 [default=true]; + optional int32 F_Int32_defaulted = 41 [default=32]; + optional int64 F_Int64_defaulted = 42 [default=64]; + optional fixed32 F_Fixed32_defaulted = 43 [default=320]; + optional fixed64 F_Fixed64_defaulted = 44 [default=640]; + optional uint32 F_Uint32_defaulted = 45 [default=3200]; + optional uint64 F_Uint64_defaulted = 46 [default=6400]; + optional float F_Float_defaulted = 47 [default=314159.]; + optional double F_Double_defaulted = 48 [default=271828.]; + optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"]; + optional bytes F_Bytes_defaulted = 401 [default="Bignose"]; + optional sint32 F_Sint32_defaulted = 402 [default = -32]; + optional sint64 F_Sint64_defaulted = 403 [default = -64]; + + // Packed repeated fields (no string or bytes). + repeated bool F_Bool_repeated_packed = 50 [packed=true]; + repeated int32 F_Int32_repeated_packed = 51 [packed=true]; + repeated int64 F_Int64_repeated_packed = 52 [packed=true]; + repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true]; + repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true]; + repeated uint32 F_Uint32_repeated_packed = 55 [packed=true]; + repeated uint64 F_Uint64_repeated_packed = 56 [packed=true]; + repeated float F_Float_repeated_packed = 57 [packed=true]; + repeated double F_Double_repeated_packed = 58 [packed=true]; + repeated sint32 F_Sint32_repeated_packed = 502 [packed=true]; + repeated sint64 F_Sint64_repeated_packed = 503 [packed=true]; + + // Required, repeated, and optional groups. + required group RequiredGroup = 70 { + required string RequiredField = 71; + }; + + repeated group RepeatedGroup = 80 { + required string RequiredField = 81; + }; + + optional group OptionalGroup = 90 { + required string RequiredField = 91; + }; +} + +// For testing skipping of unrecognized fields. +// Numbers are all big, larger than tag numbers in GoTestField, +// the message used in the corresponding test. +message GoSkipTest { + required int32 skip_int32 = 11; + required fixed32 skip_fixed32 = 12; + required fixed64 skip_fixed64 = 13; + required string skip_string = 14; + required group SkipGroup = 15 { + required int32 group_int32 = 16; + required string group_string = 17; + } +} + +// For testing packed/non-packed decoder switching. +// A serialized instance of one should be deserializable as the other. +message NonPackedTest { + repeated int32 a = 1; +} + +message PackedTest { + repeated int32 b = 1 [packed=true]; +} + +message MaxTag { + // Maximum possible tag number. + optional string last_field = 536870911; +} + +message OldMessage { + message Nested { + optional string name = 1; + } + optional Nested nested = 1; + + optional int32 num = 2; +} + +// NewMessage is wire compatible with OldMessage; +// imagine it as a future version. +message NewMessage { + message Nested { + optional string name = 1; + optional string food_group = 2; + } + optional Nested nested = 1; + + // This is an int32 in OldMessage. + optional int64 num = 2; +} + +// Smaller tests for ASCII formatting. + +message InnerMessage { + required string host = 1; + optional int32 port = 2 [default=4000]; + optional bool connected = 3; +} + +message OtherMessage { + optional int64 key = 1; + optional bytes value = 2; + optional float weight = 3; + optional InnerMessage inner = 4; +} + +message MyMessage { + required int32 count = 1; + optional string name = 2; + optional string quote = 3; + repeated string pet = 4; + optional InnerMessage inner = 5; + repeated OtherMessage others = 6; + repeated InnerMessage rep_inner = 12; + + enum Color { + RED = 0; + GREEN = 1; + BLUE = 2; + }; + optional Color bikeshed = 7; + + optional group SomeGroup = 8 { + optional int32 group_field = 9; + } + + // This field becomes [][]byte in the generated code. + repeated bytes rep_bytes = 10; + + optional double bigfloat = 11; + + extensions 100 to max; +} + +message Ext { + extend MyMessage { + optional Ext more = 103; + optional string text = 104; + optional int32 number = 105; + } + + optional string data = 1; +} + +extend MyMessage { + repeated string greeting = 106; +} + +message DefaultsMessage { + enum DefaultsEnum { + ZERO = 0; + ONE = 1; + TWO = 2; + }; + extensions 100 to max; +} + +extend DefaultsMessage { + optional double no_default_double = 101; + optional float no_default_float = 102; + optional int32 no_default_int32 = 103; + optional int64 no_default_int64 = 104; + optional uint32 no_default_uint32 = 105; + optional uint64 no_default_uint64 = 106; + optional sint32 no_default_sint32 = 107; + optional sint64 no_default_sint64 = 108; + optional fixed32 no_default_fixed32 = 109; + optional fixed64 no_default_fixed64 = 110; + optional sfixed32 no_default_sfixed32 = 111; + optional sfixed64 no_default_sfixed64 = 112; + optional bool no_default_bool = 113; + optional string no_default_string = 114; + optional bytes no_default_bytes = 115; + optional DefaultsMessage.DefaultsEnum no_default_enum = 116; + + optional double default_double = 201 [default = 3.1415]; + optional float default_float = 202 [default = 3.14]; + optional int32 default_int32 = 203 [default = 42]; + optional int64 default_int64 = 204 [default = 43]; + optional uint32 default_uint32 = 205 [default = 44]; + optional uint64 default_uint64 = 206 [default = 45]; + optional sint32 default_sint32 = 207 [default = 46]; + optional sint64 default_sint64 = 208 [default = 47]; + optional fixed32 default_fixed32 = 209 [default = 48]; + optional fixed64 default_fixed64 = 210 [default = 49]; + optional sfixed32 default_sfixed32 = 211 [default = 50]; + optional sfixed64 default_sfixed64 = 212 [default = 51]; + optional bool default_bool = 213 [default = true]; + optional string default_string = 214 [default = "Hello, string"]; + optional bytes default_bytes = 215 [default = "Hello, bytes"]; + optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE]; +} + +message MyMessageSet { + option message_set_wire_format = true; + extensions 100 to max; +} + +message Empty { +} + +extend MyMessageSet { + optional Empty x201 = 201; + optional Empty x202 = 202; + optional Empty x203 = 203; + optional Empty x204 = 204; + optional Empty x205 = 205; + optional Empty x206 = 206; + optional Empty x207 = 207; + optional Empty x208 = 208; + optional Empty x209 = 209; + optional Empty x210 = 210; + optional Empty x211 = 211; + optional Empty x212 = 212; + optional Empty x213 = 213; + optional Empty x214 = 214; + optional Empty x215 = 215; + optional Empty x216 = 216; + optional Empty x217 = 217; + optional Empty x218 = 218; + optional Empty x219 = 219; + optional Empty x220 = 220; + optional Empty x221 = 221; + optional Empty x222 = 222; + optional Empty x223 = 223; + optional Empty x224 = 224; + optional Empty x225 = 225; + optional Empty x226 = 226; + optional Empty x227 = 227; + optional Empty x228 = 228; + optional Empty x229 = 229; + optional Empty x230 = 230; + optional Empty x231 = 231; + optional Empty x232 = 232; + optional Empty x233 = 233; + optional Empty x234 = 234; + optional Empty x235 = 235; + optional Empty x236 = 236; + optional Empty x237 = 237; + optional Empty x238 = 238; + optional Empty x239 = 239; + optional Empty x240 = 240; + optional Empty x241 = 241; + optional Empty x242 = 242; + optional Empty x243 = 243; + optional Empty x244 = 244; + optional Empty x245 = 245; + optional Empty x246 = 246; + optional Empty x247 = 247; + optional Empty x248 = 248; + optional Empty x249 = 249; + optional Empty x250 = 250; +} + +message MessageList { + repeated group Message = 1 { + required string name = 2; + required int32 count = 3; + } +} + +message Strings { + optional string string_field = 1; + optional bytes bytes_field = 2; +} + +message Defaults { + enum Color { + RED = 0; + GREEN = 1; + BLUE = 2; + } + + // Default-valued fields of all basic types. + // Same as GoTest, but copied here to make testing easier. + optional bool F_Bool = 1 [default=true]; + optional int32 F_Int32 = 2 [default=32]; + optional int64 F_Int64 = 3 [default=64]; + optional fixed32 F_Fixed32 = 4 [default=320]; + optional fixed64 F_Fixed64 = 5 [default=640]; + optional uint32 F_Uint32 = 6 [default=3200]; + optional uint64 F_Uint64 = 7 [default=6400]; + optional float F_Float = 8 [default=314159.]; + optional double F_Double = 9 [default=271828.]; + optional string F_String = 10 [default="hello, \"world!\"\n"]; + optional bytes F_Bytes = 11 [default="Bignose"]; + optional sint32 F_Sint32 = 12 [default=-32]; + optional sint64 F_Sint64 = 13 [default=-64]; + optional Color F_Enum = 14 [default=GREEN]; + + // More fields with crazy defaults. + optional float F_Pinf = 15 [default=inf]; + optional float F_Ninf = 16 [default=-inf]; + optional float F_Nan = 17 [default=nan]; + + // Sub-message. + optional SubDefaults sub = 18; + + // Redundant but explicit defaults. + optional string str_zero = 19 [default=""]; +} + +message SubDefaults { + optional int64 n = 1 [default=7]; +} + +message RepeatedEnum { + enum Color { + RED = 1; + } + repeated Color color = 1; +} + +message MoreRepeated { + repeated bool bools = 1; + repeated bool bools_packed = 2 [packed=true]; + repeated int32 ints = 3; + repeated int32 ints_packed = 4 [packed=true]; + repeated int64 int64s_packed = 7 [packed=true]; + repeated string strings = 5; + repeated fixed32 fixeds = 6; +} + +// GroupOld and GroupNew have the same wire format. +// GroupNew has a new field inside a group. + +message GroupOld { + optional group G = 101 { + optional int32 x = 2; + } +} + +message GroupNew { + optional group G = 101 { + optional int32 x = 2; + optional int32 y = 3; + } +} + +message FloatingPoint { + required double f = 1; +} + +message MessageWithMap { + map name_mapping = 1; + map msg_mapping = 2; + map byte_mapping = 3; + map str_to_str = 4; +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go new file mode 100644 index 0000000..f7dc58a --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go @@ -0,0 +1,769 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +// Functions for writing the text protocol buffer format. + +import ( + "bufio" + "bytes" + "encoding" + "fmt" + "io" + "log" + "math" + "reflect" + "sort" + "strings" +) + +var ( + newline = []byte("\n") + spaces = []byte(" ") + gtNewline = []byte(">\n") + endBraceNewline = []byte("}\n") + backslashN = []byte{'\\', 'n'} + backslashR = []byte{'\\', 'r'} + backslashT = []byte{'\\', 't'} + backslashDQ = []byte{'\\', '"'} + backslashBS = []byte{'\\', '\\'} + posInf = []byte("inf") + negInf = []byte("-inf") + nan = []byte("nan") +) + +type writer interface { + io.Writer + WriteByte(byte) error +} + +// textWriter is an io.Writer that tracks its indentation level. +type textWriter struct { + ind int + complete bool // if the current position is a complete line + compact bool // whether to write out as a one-liner + w writer +} + +func (w *textWriter) WriteString(s string) (n int, err error) { + if !strings.Contains(s, "\n") { + if !w.compact && w.complete { + w.writeIndent() + } + w.complete = false + return io.WriteString(w.w, s) + } + // WriteString is typically called without newlines, so this + // codepath and its copy are rare. We copy to avoid + // duplicating all of Write's logic here. + return w.Write([]byte(s)) +} + +func (w *textWriter) Write(p []byte) (n int, err error) { + newlines := bytes.Count(p, newline) + if newlines == 0 { + if !w.compact && w.complete { + w.writeIndent() + } + n, err = w.w.Write(p) + w.complete = false + return n, err + } + + frags := bytes.SplitN(p, newline, newlines+1) + if w.compact { + for i, frag := range frags { + if i > 0 { + if err := w.w.WriteByte(' '); err != nil { + return n, err + } + n++ + } + nn, err := w.w.Write(frag) + n += nn + if err != nil { + return n, err + } + } + return n, nil + } + + for i, frag := range frags { + if w.complete { + w.writeIndent() + } + nn, err := w.w.Write(frag) + n += nn + if err != nil { + return n, err + } + if i+1 < len(frags) { + if err := w.w.WriteByte('\n'); err != nil { + return n, err + } + n++ + } + } + w.complete = len(frags[len(frags)-1]) == 0 + return n, nil +} + +func (w *textWriter) WriteByte(c byte) error { + if w.compact && c == '\n' { + c = ' ' + } + if !w.compact && w.complete { + w.writeIndent() + } + err := w.w.WriteByte(c) + w.complete = c == '\n' + return err +} + +func (w *textWriter) indent() { w.ind++ } + +func (w *textWriter) unindent() { + if w.ind == 0 { + log.Printf("proto: textWriter unindented too far") + return + } + w.ind-- +} + +func writeName(w *textWriter, props *Properties) error { + if _, err := w.WriteString(props.OrigName); err != nil { + return err + } + if props.Wire != "group" { + return w.WriteByte(':') + } + return nil +} + +var ( + messageSetType = reflect.TypeOf((*MessageSet)(nil)).Elem() +) + +// raw is the interface satisfied by RawMessage. +type raw interface { + Bytes() []byte +} + +func writeStruct(w *textWriter, sv reflect.Value) error { + if sv.Type() == messageSetType { + return writeMessageSet(w, sv.Addr().Interface().(*MessageSet)) + } + + st := sv.Type() + sprops := GetProperties(st) + for i := 0; i < sv.NumField(); i++ { + fv := sv.Field(i) + props := sprops.Prop[i] + name := st.Field(i).Name + + if strings.HasPrefix(name, "XXX_") { + // There are two XXX_ fields: + // XXX_unrecognized []byte + // XXX_extensions map[int32]proto.Extension + // The first is handled here; + // the second is handled at the bottom of this function. + if name == "XXX_unrecognized" && !fv.IsNil() { + if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { + return err + } + } + continue + } + if fv.Kind() == reflect.Ptr && fv.IsNil() { + // Field not filled in. This could be an optional field or + // a required field that wasn't filled in. Either way, there + // isn't anything we can show for it. + continue + } + if fv.Kind() == reflect.Slice && fv.IsNil() { + // Repeated field that is empty, or a bytes field that is unused. + continue + } + + if props.Repeated && fv.Kind() == reflect.Slice { + // Repeated field. + for j := 0; j < fv.Len(); j++ { + if err := writeName(w, props); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + v := fv.Index(j) + if v.Kind() == reflect.Ptr && v.IsNil() { + // A nil message in a repeated field is not valid, + // but we can handle that more gracefully than panicking. + if _, err := w.Write([]byte("\n")); err != nil { + return err + } + continue + } + if err := writeAny(w, v, props); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + } + continue + } + if fv.Kind() == reflect.Map { + // Map fields are rendered as a repeated struct with key/value fields. + keys := fv.MapKeys() // TODO: should we sort these for deterministic output? + sort.Sort(mapKeys(keys)) + for _, key := range keys { + val := fv.MapIndex(key) + if err := writeName(w, props); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + // open struct + if err := w.WriteByte('<'); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte('\n'); err != nil { + return err + } + } + w.indent() + // key + if _, err := w.WriteString("key:"); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if err := writeAny(w, key, props.mkeyprop); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + // nil values aren't legal, but we can avoid panicking because of them. + if val.Kind() != reflect.Ptr || !val.IsNil() { + // value + if _, err := w.WriteString("value:"); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if err := writeAny(w, val, props.mvalprop); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + } + // close struct + w.unindent() + if err := w.WriteByte('>'); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + } + continue + } + if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { + // empty bytes field + continue + } + if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { + // proto3 non-repeated scalar field; skip if zero value + if isProto3Zero(fv) { + continue + } + } + + if err := writeName(w, props); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if b, ok := fv.Interface().(raw); ok { + if err := writeRaw(w, b.Bytes()); err != nil { + return err + } + continue + } + + // Enums have a String method, so writeAny will work fine. + if err := writeAny(w, fv, props); err != nil { + return err + } + + if err := w.WriteByte('\n'); err != nil { + return err + } + } + + // Extensions (the XXX_extensions field). + pv := sv.Addr() + if pv.Type().Implements(extendableProtoType) { + if err := writeExtensions(w, pv); err != nil { + return err + } + } + + return nil +} + +// writeRaw writes an uninterpreted raw message. +func writeRaw(w *textWriter, b []byte) error { + if err := w.WriteByte('<'); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte('\n'); err != nil { + return err + } + } + w.indent() + if err := writeUnknownStruct(w, b); err != nil { + return err + } + w.unindent() + if err := w.WriteByte('>'); err != nil { + return err + } + return nil +} + +// writeAny writes an arbitrary field. +func writeAny(w *textWriter, v reflect.Value, props *Properties) error { + v = reflect.Indirect(v) + + // Floats have special cases. + if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { + x := v.Float() + var b []byte + switch { + case math.IsInf(x, 1): + b = posInf + case math.IsInf(x, -1): + b = negInf + case math.IsNaN(x): + b = nan + } + if b != nil { + _, err := w.Write(b) + return err + } + // Other values are handled below. + } + + // We don't attempt to serialise every possible value type; only those + // that can occur in protocol buffers. + switch v.Kind() { + case reflect.Slice: + // Should only be a []byte; repeated fields are handled in writeStruct. + if err := writeString(w, string(v.Interface().([]byte))); err != nil { + return err + } + case reflect.String: + if err := writeString(w, v.String()); err != nil { + return err + } + case reflect.Struct: + // Required/optional group/message. + var bra, ket byte = '<', '>' + if props != nil && props.Wire == "group" { + bra, ket = '{', '}' + } + if err := w.WriteByte(bra); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte('\n'); err != nil { + return err + } + } + w.indent() + if tm, ok := v.Interface().(encoding.TextMarshaler); ok { + text, err := tm.MarshalText() + if err != nil { + return err + } + if _, err = w.Write(text); err != nil { + return err + } + } else if err := writeStruct(w, v); err != nil { + return err + } + w.unindent() + if err := w.WriteByte(ket); err != nil { + return err + } + default: + _, err := fmt.Fprint(w, v.Interface()) + return err + } + return nil +} + +// equivalent to C's isprint. +func isprint(c byte) bool { + return c >= 0x20 && c < 0x7f +} + +// writeString writes a string in the protocol buffer text format. +// It is similar to strconv.Quote except we don't use Go escape sequences, +// we treat the string as a byte sequence, and we use octal escapes. +// These differences are to maintain interoperability with the other +// languages' implementations of the text format. +func writeString(w *textWriter, s string) error { + // use WriteByte here to get any needed indent + if err := w.WriteByte('"'); err != nil { + return err + } + // Loop over the bytes, not the runes. + for i := 0; i < len(s); i++ { + var err error + // Divergence from C++: we don't escape apostrophes. + // There's no need to escape them, and the C++ parser + // copes with a naked apostrophe. + switch c := s[i]; c { + case '\n': + _, err = w.w.Write(backslashN) + case '\r': + _, err = w.w.Write(backslashR) + case '\t': + _, err = w.w.Write(backslashT) + case '"': + _, err = w.w.Write(backslashDQ) + case '\\': + _, err = w.w.Write(backslashBS) + default: + if isprint(c) { + err = w.w.WriteByte(c) + } else { + _, err = fmt.Fprintf(w.w, "\\%03o", c) + } + } + if err != nil { + return err + } + } + return w.WriteByte('"') +} + +func writeMessageSet(w *textWriter, ms *MessageSet) error { + for _, item := range ms.Item { + id := *item.TypeId + if msd, ok := messageSetMap[id]; ok { + // Known message set type. + if _, err := fmt.Fprintf(w, "[%s]: <\n", msd.name); err != nil { + return err + } + w.indent() + + pb := reflect.New(msd.t.Elem()) + if err := Unmarshal(item.Message, pb.Interface().(Message)); err != nil { + if _, err := fmt.Fprintf(w, "/* bad message: %v */\n", err); err != nil { + return err + } + } else { + if err := writeStruct(w, pb.Elem()); err != nil { + return err + } + } + } else { + // Unknown type. + if _, err := fmt.Fprintf(w, "[%d]: <\n", id); err != nil { + return err + } + w.indent() + if err := writeUnknownStruct(w, item.Message); err != nil { + return err + } + } + w.unindent() + if _, err := w.Write(gtNewline); err != nil { + return err + } + } + return nil +} + +func writeUnknownStruct(w *textWriter, data []byte) (err error) { + if !w.compact { + if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { + return err + } + } + b := NewBuffer(data) + for b.index < len(b.buf) { + x, err := b.DecodeVarint() + if err != nil { + _, err := fmt.Fprintf(w, "/* %v */\n", err) + return err + } + wire, tag := x&7, x>>3 + if wire == WireEndGroup { + w.unindent() + if _, err := w.Write(endBraceNewline); err != nil { + return err + } + continue + } + if _, err := fmt.Fprint(w, tag); err != nil { + return err + } + if wire != WireStartGroup { + if err := w.WriteByte(':'); err != nil { + return err + } + } + if !w.compact || wire == WireStartGroup { + if err := w.WriteByte(' '); err != nil { + return err + } + } + switch wire { + case WireBytes: + buf, e := b.DecodeRawBytes(false) + if e == nil { + _, err = fmt.Fprintf(w, "%q", buf) + } else { + _, err = fmt.Fprintf(w, "/* %v */", e) + } + case WireFixed32: + x, err = b.DecodeFixed32() + err = writeUnknownInt(w, x, err) + case WireFixed64: + x, err = b.DecodeFixed64() + err = writeUnknownInt(w, x, err) + case WireStartGroup: + err = w.WriteByte('{') + w.indent() + case WireVarint: + x, err = b.DecodeVarint() + err = writeUnknownInt(w, x, err) + default: + _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) + } + if err != nil { + return err + } + if err = w.WriteByte('\n'); err != nil { + return err + } + } + return nil +} + +func writeUnknownInt(w *textWriter, x uint64, err error) error { + if err == nil { + _, err = fmt.Fprint(w, x) + } else { + _, err = fmt.Fprintf(w, "/* %v */", err) + } + return err +} + +type int32Slice []int32 + +func (s int32Slice) Len() int { return len(s) } +func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } +func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + +// writeExtensions writes all the extensions in pv. +// pv is assumed to be a pointer to a protocol message struct that is extendable. +func writeExtensions(w *textWriter, pv reflect.Value) error { + emap := extensionMaps[pv.Type().Elem()] + ep := pv.Interface().(extendableProto) + + // Order the extensions by ID. + // This isn't strictly necessary, but it will give us + // canonical output, which will also make testing easier. + m := ep.ExtensionMap() + ids := make([]int32, 0, len(m)) + for id := range m { + ids = append(ids, id) + } + sort.Sort(int32Slice(ids)) + + for _, extNum := range ids { + ext := m[extNum] + var desc *ExtensionDesc + if emap != nil { + desc = emap[extNum] + } + if desc == nil { + // Unknown extension. + if err := writeUnknownStruct(w, ext.enc); err != nil { + return err + } + continue + } + + pb, err := GetExtension(ep, desc) + if err != nil { + return fmt.Errorf("failed getting extension: %v", err) + } + + // Repeated extensions will appear as a slice. + if !desc.repeated() { + if err := writeExtension(w, desc.Name, pb); err != nil { + return err + } + } else { + v := reflect.ValueOf(pb) + for i := 0; i < v.Len(); i++ { + if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { + return err + } + } + } + } + return nil +} + +func writeExtension(w *textWriter, name string, pb interface{}) error { + if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if err := writeAny(w, reflect.ValueOf(pb), nil); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + return nil +} + +func (w *textWriter) writeIndent() { + if !w.complete { + return + } + remain := w.ind * 2 + for remain > 0 { + n := remain + if n > len(spaces) { + n = len(spaces) + } + w.w.Write(spaces[:n]) + remain -= n + } + w.complete = false +} + +func marshalText(w io.Writer, pb Message, compact bool) error { + val := reflect.ValueOf(pb) + if pb == nil || val.IsNil() { + w.Write([]byte("")) + return nil + } + var bw *bufio.Writer + ww, ok := w.(writer) + if !ok { + bw = bufio.NewWriter(w) + ww = bw + } + aw := &textWriter{ + w: ww, + complete: true, + compact: compact, + } + + if tm, ok := pb.(encoding.TextMarshaler); ok { + text, err := tm.MarshalText() + if err != nil { + return err + } + if _, err = aw.Write(text); err != nil { + return err + } + if bw != nil { + return bw.Flush() + } + return nil + } + // Dereference the received pointer so we don't have outer < and >. + v := reflect.Indirect(val) + if err := writeStruct(aw, v); err != nil { + return err + } + if bw != nil { + return bw.Flush() + } + return nil +} + +// MarshalText writes a given protocol buffer in text format. +// The only errors returned are from w. +func MarshalText(w io.Writer, pb Message) error { + return marshalText(w, pb, false) +} + +// MarshalTextString is the same as MarshalText, but returns the string directly. +func MarshalTextString(pb Message) string { + var buf bytes.Buffer + marshalText(&buf, pb, false) + return buf.String() +} + +// CompactText writes a given protocol buffer in compact text format (one line). +func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) } + +// CompactTextString is the same as CompactText, but returns the string directly. +func CompactTextString(pb Message) string { + var buf bytes.Buffer + marshalText(&buf, pb, true) + return buf.String() +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go new file mode 100644 index 0000000..7d0c757 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go @@ -0,0 +1,772 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +// Functions for parsing the Text protocol buffer format. +// TODO: message sets. + +import ( + "encoding" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "unicode/utf8" +) + +type ParseError struct { + Message string + Line int // 1-based line number + Offset int // 0-based byte offset from start of input +} + +func (p *ParseError) Error() string { + if p.Line == 1 { + // show offset only for first line + return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) + } + return fmt.Sprintf("line %d: %v", p.Line, p.Message) +} + +type token struct { + value string + err *ParseError + line int // line number + offset int // byte number from start of input, not start of line + unquoted string // the unquoted version of value, if it was a quoted string +} + +func (t *token) String() string { + if t.err == nil { + return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) + } + return fmt.Sprintf("parse error: %v", t.err) +} + +type textParser struct { + s string // remaining input + done bool // whether the parsing is finished (success or error) + backed bool // whether back() was called + offset, line int + cur token +} + +func newTextParser(s string) *textParser { + p := new(textParser) + p.s = s + p.line = 1 + p.cur.line = 1 + return p +} + +func (p *textParser) errorf(format string, a ...interface{}) *ParseError { + pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} + p.cur.err = pe + p.done = true + return pe +} + +// Numbers and identifiers are matched by [-+._A-Za-z0-9] +func isIdentOrNumberChar(c byte) bool { + switch { + case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': + return true + case '0' <= c && c <= '9': + return true + } + switch c { + case '-', '+', '.', '_': + return true + } + return false +} + +func isWhitespace(c byte) bool { + switch c { + case ' ', '\t', '\n', '\r': + return true + } + return false +} + +func (p *textParser) skipWhitespace() { + i := 0 + for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { + if p.s[i] == '#' { + // comment; skip to end of line or input + for i < len(p.s) && p.s[i] != '\n' { + i++ + } + if i == len(p.s) { + break + } + } + if p.s[i] == '\n' { + p.line++ + } + i++ + } + p.offset += i + p.s = p.s[i:len(p.s)] + if len(p.s) == 0 { + p.done = true + } +} + +func (p *textParser) advance() { + // Skip whitespace + p.skipWhitespace() + if p.done { + return + } + + // Start of non-whitespace + p.cur.err = nil + p.cur.offset, p.cur.line = p.offset, p.line + p.cur.unquoted = "" + switch p.s[0] { + case '<', '>', '{', '}', ':', '[', ']', ';', ',': + // Single symbol + p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] + case '"', '\'': + // Quoted string + i := 1 + for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { + if p.s[i] == '\\' && i+1 < len(p.s) { + // skip escaped char + i++ + } + i++ + } + if i >= len(p.s) || p.s[i] != p.s[0] { + p.errorf("unmatched quote") + return + } + unq, err := unquoteC(p.s[1:i], rune(p.s[0])) + if err != nil { + p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) + return + } + p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] + p.cur.unquoted = unq + default: + i := 0 + for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { + i++ + } + if i == 0 { + p.errorf("unexpected byte %#x", p.s[0]) + return + } + p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] + } + p.offset += len(p.cur.value) +} + +var ( + errBadUTF8 = errors.New("proto: bad UTF-8") + errBadHex = errors.New("proto: bad hexadecimal") +) + +func unquoteC(s string, quote rune) (string, error) { + // This is based on C++'s tokenizer.cc. + // Despite its name, this is *not* parsing C syntax. + // For instance, "\0" is an invalid quoted string. + + // Avoid allocation in trivial cases. + simple := true + for _, r := range s { + if r == '\\' || r == quote { + simple = false + break + } + } + if simple { + return s, nil + } + + buf := make([]byte, 0, 3*len(s)/2) + for len(s) > 0 { + r, n := utf8.DecodeRuneInString(s) + if r == utf8.RuneError && n == 1 { + return "", errBadUTF8 + } + s = s[n:] + if r != '\\' { + if r < utf8.RuneSelf { + buf = append(buf, byte(r)) + } else { + buf = append(buf, string(r)...) + } + continue + } + + ch, tail, err := unescape(s) + if err != nil { + return "", err + } + buf = append(buf, ch...) + s = tail + } + return string(buf), nil +} + +func unescape(s string) (ch string, tail string, err error) { + r, n := utf8.DecodeRuneInString(s) + if r == utf8.RuneError && n == 1 { + return "", "", errBadUTF8 + } + s = s[n:] + switch r { + case 'a': + return "\a", s, nil + case 'b': + return "\b", s, nil + case 'f': + return "\f", s, nil + case 'n': + return "\n", s, nil + case 'r': + return "\r", s, nil + case 't': + return "\t", s, nil + case 'v': + return "\v", s, nil + case '?': + return "?", s, nil // trigraph workaround + case '\'', '"', '\\': + return string(r), s, nil + case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X': + if len(s) < 2 { + return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) + } + base := 8 + ss := s[:2] + s = s[2:] + if r == 'x' || r == 'X' { + base = 16 + } else { + ss = string(r) + ss + } + i, err := strconv.ParseUint(ss, base, 8) + if err != nil { + return "", "", err + } + return string([]byte{byte(i)}), s, nil + case 'u', 'U': + n := 4 + if r == 'U' { + n = 8 + } + if len(s) < n { + return "", "", fmt.Errorf(`\%c requires %d digits`, r, n) + } + + bs := make([]byte, n/2) + for i := 0; i < n; i += 2 { + a, ok1 := unhex(s[i]) + b, ok2 := unhex(s[i+1]) + if !ok1 || !ok2 { + return "", "", errBadHex + } + bs[i/2] = a<<4 | b + } + s = s[n:] + return string(bs), s, nil + } + return "", "", fmt.Errorf(`unknown escape \%c`, r) +} + +// Adapted from src/pkg/strconv/quote.go. +func unhex(b byte) (v byte, ok bool) { + switch { + case '0' <= b && b <= '9': + return b - '0', true + case 'a' <= b && b <= 'f': + return b - 'a' + 10, true + case 'A' <= b && b <= 'F': + return b - 'A' + 10, true + } + return 0, false +} + +// Back off the parser by one token. Can only be done between calls to next(). +// It makes the next advance() a no-op. +func (p *textParser) back() { p.backed = true } + +// Advances the parser and returns the new current token. +func (p *textParser) next() *token { + if p.backed || p.done { + p.backed = false + return &p.cur + } + p.advance() + if p.done { + p.cur.value = "" + } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' { + // Look for multiple quoted strings separated by whitespace, + // and concatenate them. + cat := p.cur + for { + p.skipWhitespace() + if p.done || p.s[0] != '"' { + break + } + p.advance() + if p.cur.err != nil { + return &p.cur + } + cat.value += " " + p.cur.value + cat.unquoted += p.cur.unquoted + } + p.done = false // parser may have seen EOF, but we want to return cat + p.cur = cat + } + return &p.cur +} + +func (p *textParser) consumeToken(s string) error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != s { + p.back() + return p.errorf("expected %q, found %q", s, tok.value) + } + return nil +} + +// Return a RequiredNotSetError indicating which required field was not set. +func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { + st := sv.Type() + sprops := GetProperties(st) + for i := 0; i < st.NumField(); i++ { + if !isNil(sv.Field(i)) { + continue + } + + props := sprops.Prop[i] + if props.Required { + return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} + } + } + return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen +} + +// Returns the index in the struct for the named field, as well as the parsed tag properties. +func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) { + sprops := GetProperties(st) + i, ok := sprops.decoderOrigNames[name] + if ok { + return i, sprops.Prop[i], true + } + return -1, nil, false +} + +// Consume a ':' from the input stream (if the next token is a colon), +// returning an error if a colon is needed but not present. +func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != ":" { + // Colon is optional when the field is a group or message. + needColon := true + switch props.Wire { + case "group": + needColon = false + case "bytes": + // A "bytes" field is either a message, a string, or a repeated field; + // those three become *T, *string and []T respectively, so we can check for + // this field being a pointer to a non-string. + if typ.Kind() == reflect.Ptr { + // *T or *string + if typ.Elem().Kind() == reflect.String { + break + } + } else if typ.Kind() == reflect.Slice { + // []T or []*T + if typ.Elem().Kind() != reflect.Ptr { + break + } + } else if typ.Kind() == reflect.String { + // The proto3 exception is for a string field, + // which requires a colon. + break + } + needColon = false + } + if needColon { + return p.errorf("expected ':', found %q", tok.value) + } + p.back() + } + return nil +} + +func (p *textParser) readStruct(sv reflect.Value, terminator string) error { + st := sv.Type() + reqCount := GetProperties(st).reqCount + var reqFieldErr error + fieldSet := make(map[string]bool) + // A struct is a sequence of "name: value", terminated by one of + // '>' or '}', or the end of the input. A name may also be + // "[extension]". + for { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == terminator { + break + } + if tok.value == "[" { + // Looks like an extension. + // + // TODO: Check whether we need to handle + // namespace rooted names (e.g. ".something.Foo"). + tok = p.next() + if tok.err != nil { + return tok.err + } + var desc *ExtensionDesc + // This could be faster, but it's functional. + // TODO: Do something smarter than a linear scan. + for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { + if d.Name == tok.value { + desc = d + break + } + } + if desc == nil { + return p.errorf("unrecognized extension %q", tok.value) + } + // Check the extension terminator. + tok = p.next() + if tok.err != nil { + return tok.err + } + if tok.value != "]" { + return p.errorf("unrecognized extension terminator %q", tok.value) + } + + props := &Properties{} + props.Parse(desc.Tag) + + typ := reflect.TypeOf(desc.ExtensionType) + if err := p.checkForColon(props, typ); err != nil { + return err + } + + rep := desc.repeated() + + // Read the extension structure, and set it in + // the value we're constructing. + var ext reflect.Value + if !rep { + ext = reflect.New(typ).Elem() + } else { + ext = reflect.New(typ.Elem()).Elem() + } + if err := p.readAny(ext, props); err != nil { + if _, ok := err.(*RequiredNotSetError); !ok { + return err + } + reqFieldErr = err + } + ep := sv.Addr().Interface().(extendableProto) + if !rep { + SetExtension(ep, desc, ext.Interface()) + } else { + old, err := GetExtension(ep, desc) + var sl reflect.Value + if err == nil { + sl = reflect.ValueOf(old) // existing slice + } else { + sl = reflect.MakeSlice(typ, 0, 1) + } + sl = reflect.Append(sl, ext) + SetExtension(ep, desc, sl.Interface()) + } + } else { + // This is a normal, non-extension field. + name := tok.value + fi, props, ok := structFieldByName(st, name) + if !ok { + return p.errorf("unknown field name %q in %v", name, st) + } + + dst := sv.Field(fi) + + if dst.Kind() == reflect.Map { + // Consume any colon. + if err := p.checkForColon(props, dst.Type()); err != nil { + return err + } + + // Construct the map if it doesn't already exist. + if dst.IsNil() { + dst.Set(reflect.MakeMap(dst.Type())) + } + key := reflect.New(dst.Type().Key()).Elem() + val := reflect.New(dst.Type().Elem()).Elem() + + // The map entry should be this sequence of tokens: + // < key : KEY value : VALUE > + // Technically the "key" and "value" could come in any order, + // but in practice they won't. + + tok := p.next() + var terminator string + switch tok.value { + case "<": + terminator = ">" + case "{": + terminator = "}" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + if err := p.consumeToken("key"); err != nil { + return err + } + if err := p.consumeToken(":"); err != nil { + return err + } + if err := p.readAny(key, props.mkeyprop); err != nil { + return err + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + if err := p.consumeToken("value"); err != nil { + return err + } + if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { + return err + } + if err := p.readAny(val, props.mvalprop); err != nil { + return err + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + if err := p.consumeToken(terminator); err != nil { + return err + } + + dst.SetMapIndex(key, val) + continue + } + + // Check that it's not already set if it's not a repeated field. + if !props.Repeated && fieldSet[name] { + return p.errorf("non-repeated field %q was repeated", name) + } + + if err := p.checkForColon(props, st.Field(fi).Type); err != nil { + return err + } + + // Parse into the field. + fieldSet[name] = true + if err := p.readAny(dst, props); err != nil { + if _, ok := err.(*RequiredNotSetError); !ok { + return err + } + reqFieldErr = err + } else if props.Required { + reqCount-- + } + } + + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + + } + + if reqCount > 0 { + return p.missingRequiredFieldError(sv) + } + return reqFieldErr +} + +// consumeOptionalSeparator consumes an optional semicolon or comma. +// It is used in readStruct to provide backward compatibility. +func (p *textParser) consumeOptionalSeparator() error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != ";" && tok.value != "," { + p.back() + } + return nil +} + +func (p *textParser) readAny(v reflect.Value, props *Properties) error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == "" { + return p.errorf("unexpected EOF") + } + + switch fv := v; fv.Kind() { + case reflect.Slice: + at := v.Type() + if at.Elem().Kind() == reflect.Uint8 { + // Special case for []byte + if tok.value[0] != '"' && tok.value[0] != '\'' { + // Deliberately written out here, as the error after + // this switch statement would write "invalid []byte: ...", + // which is not as user-friendly. + return p.errorf("invalid string: %v", tok.value) + } + bytes := []byte(tok.unquoted) + fv.Set(reflect.ValueOf(bytes)) + return nil + } + // Repeated field. May already exist. + flen := fv.Len() + if flen == fv.Cap() { + nav := reflect.MakeSlice(at, flen, 2*flen+1) + reflect.Copy(nav, fv) + fv.Set(nav) + } + fv.SetLen(flen + 1) + + // Read one. + p.back() + return p.readAny(fv.Index(flen), props) + case reflect.Bool: + // Either "true", "false", 1 or 0. + switch tok.value { + case "true", "1": + fv.SetBool(true) + return nil + case "false", "0": + fv.SetBool(false) + return nil + } + case reflect.Float32, reflect.Float64: + v := tok.value + // Ignore 'f' for compatibility with output generated by C++, but don't + // remove 'f' when the value is "-inf" or "inf". + if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { + v = v[:len(v)-1] + } + if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { + fv.SetFloat(f) + return nil + } + case reflect.Int32: + if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { + fv.SetInt(x) + return nil + } + + if len(props.Enum) == 0 { + break + } + m, ok := enumValueMaps[props.Enum] + if !ok { + break + } + x, ok := m[tok.value] + if !ok { + break + } + fv.SetInt(int64(x)) + return nil + case reflect.Int64: + if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { + fv.SetInt(x) + return nil + } + + case reflect.Ptr: + // A basic field (indirected through pointer), or a repeated message/group + p.back() + fv.Set(reflect.New(fv.Type().Elem())) + return p.readAny(fv.Elem(), props) + case reflect.String: + if tok.value[0] == '"' || tok.value[0] == '\'' { + fv.SetString(tok.unquoted) + return nil + } + case reflect.Struct: + var terminator string + switch tok.value { + case "{": + terminator = "}" + case "<": + terminator = ">" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + // TODO: Handle nested messages which implement encoding.TextUnmarshaler. + return p.readStruct(fv, terminator) + case reflect.Uint32: + if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { + fv.SetUint(uint64(x)) + return nil + } + case reflect.Uint64: + if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { + fv.SetUint(x) + return nil + } + } + return p.errorf("invalid %v: %v", v.Type(), tok.value) +} + +// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb +// before starting to unmarshal, so any existing data in pb is always removed. +// If a required field is not set and no other error occurs, +// UnmarshalText returns *RequiredNotSetError. +func UnmarshalText(s string, pb Message) error { + if um, ok := pb.(encoding.TextUnmarshaler); ok { + err := um.UnmarshalText([]byte(s)) + return err + } + pb.Reset() + v := reflect.ValueOf(pb) + if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil { + return pe + } + return nil +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go new file mode 100644 index 0000000..0754b26 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go @@ -0,0 +1,511 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto_test + +import ( + "math" + "reflect" + "testing" + + . "github.com/golang/protobuf/proto" + proto3pb "github.com/golang/protobuf/proto/proto3_proto" + . "github.com/golang/protobuf/proto/testdata" +) + +type UnmarshalTextTest struct { + in string + err string // if "", no error expected + out *MyMessage +} + +func buildExtStructTest(text string) UnmarshalTextTest { + msg := &MyMessage{ + Count: Int32(42), + } + SetExtension(msg, E_Ext_More, &Ext{ + Data: String("Hello, world!"), + }) + return UnmarshalTextTest{in: text, out: msg} +} + +func buildExtDataTest(text string) UnmarshalTextTest { + msg := &MyMessage{ + Count: Int32(42), + } + SetExtension(msg, E_Ext_Text, String("Hello, world!")) + SetExtension(msg, E_Ext_Number, Int32(1729)) + return UnmarshalTextTest{in: text, out: msg} +} + +func buildExtRepStringTest(text string) UnmarshalTextTest { + msg := &MyMessage{ + Count: Int32(42), + } + if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { + panic(err) + } + return UnmarshalTextTest{in: text, out: msg} +} + +var unMarshalTextTests = []UnmarshalTextTest{ + // Basic + { + in: " count:42\n name:\"Dave\" ", + out: &MyMessage{ + Count: Int32(42), + Name: String("Dave"), + }, + }, + + // Empty quoted string + { + in: `count:42 name:""`, + out: &MyMessage{ + Count: Int32(42), + Name: String(""), + }, + }, + + // Quoted string concatenation + { + in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, + out: &MyMessage{ + Count: Int32(42), + Name: String("My name is elsewhere"), + }, + }, + + // Quoted string with escaped apostrophe + { + in: `count:42 name: "HOLIDAY - New Year\'s Day"`, + out: &MyMessage{ + Count: Int32(42), + Name: String("HOLIDAY - New Year's Day"), + }, + }, + + // Quoted string with single quote + { + in: `count:42 name: 'Roger "The Ramster" Ramjet'`, + out: &MyMessage{ + Count: Int32(42), + Name: String(`Roger "The Ramster" Ramjet`), + }, + }, + + // Quoted string with all the accepted special characters from the C++ test + { + in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", + out: &MyMessage{ + Count: Int32(42), + Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), + }, + }, + + // Quoted string with quoted backslash + { + in: `count:42 name: "\\'xyz"`, + out: &MyMessage{ + Count: Int32(42), + Name: String(`\'xyz`), + }, + }, + + // Quoted string with UTF-8 bytes. + { + in: "count:42 name: '\303\277\302\201\xAB'", + out: &MyMessage{ + Count: Int32(42), + Name: String("\303\277\302\201\xAB"), + }, + }, + + // Bad quoted string + { + in: `inner: < host: "\0" >` + "\n", + err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, + }, + + // Number too large for int64 + { + in: "count: 1 others { key: 123456789012345678901 }", + err: "line 1.23: invalid int64: 123456789012345678901", + }, + + // Number too large for int32 + { + in: "count: 1234567890123", + err: "line 1.7: invalid int32: 1234567890123", + }, + + // Number in hexadecimal + { + in: "count: 0x2beef", + out: &MyMessage{ + Count: Int32(0x2beef), + }, + }, + + // Number in octal + { + in: "count: 024601", + out: &MyMessage{ + Count: Int32(024601), + }, + }, + + // Floating point number with "f" suffix + { + in: "count: 4 others:< weight: 17.0f >", + out: &MyMessage{ + Count: Int32(4), + Others: []*OtherMessage{ + { + Weight: Float32(17), + }, + }, + }, + }, + + // Floating point positive infinity + { + in: "count: 4 bigfloat: inf", + out: &MyMessage{ + Count: Int32(4), + Bigfloat: Float64(math.Inf(1)), + }, + }, + + // Floating point negative infinity + { + in: "count: 4 bigfloat: -inf", + out: &MyMessage{ + Count: Int32(4), + Bigfloat: Float64(math.Inf(-1)), + }, + }, + + // Number too large for float32 + { + in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", + err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", + }, + + // Number posing as a quoted string + { + in: `inner: < host: 12 >` + "\n", + err: `line 1.15: invalid string: 12`, + }, + + // Quoted string posing as int32 + { + in: `count: "12"`, + err: `line 1.7: invalid int32: "12"`, + }, + + // Quoted string posing a float32 + { + in: `others:< weight: "17.4" >`, + err: `line 1.17: invalid float32: "17.4"`, + }, + + // Enum + { + in: `count:42 bikeshed: BLUE`, + out: &MyMessage{ + Count: Int32(42), + Bikeshed: MyMessage_BLUE.Enum(), + }, + }, + + // Repeated field + { + in: `count:42 pet: "horsey" pet:"bunny"`, + out: &MyMessage{ + Count: Int32(42), + Pet: []string{"horsey", "bunny"}, + }, + }, + + // Repeated message with/without colon and <>/{} + { + in: `count:42 others:{} others{} others:<> others:{}`, + out: &MyMessage{ + Count: Int32(42), + Others: []*OtherMessage{ + {}, + {}, + {}, + {}, + }, + }, + }, + + // Missing colon for inner message + { + in: `count:42 inner < host: "cauchy.syd" >`, + out: &MyMessage{ + Count: Int32(42), + Inner: &InnerMessage{ + Host: String("cauchy.syd"), + }, + }, + }, + + // Missing colon for string field + { + in: `name "Dave"`, + err: `line 1.5: expected ':', found "\"Dave\""`, + }, + + // Missing colon for int32 field + { + in: `count 42`, + err: `line 1.6: expected ':', found "42"`, + }, + + // Missing required field + { + in: `name: "Pawel"`, + err: `proto: required field "testdata.MyMessage.count" not set`, + out: &MyMessage{ + Name: String("Pawel"), + }, + }, + + // Repeated non-repeated field + { + in: `name: "Rob" name: "Russ"`, + err: `line 1.12: non-repeated field "name" was repeated`, + }, + + // Group + { + in: `count: 17 SomeGroup { group_field: 12 }`, + out: &MyMessage{ + Count: Int32(17), + Somegroup: &MyMessage_SomeGroup{ + GroupField: Int32(12), + }, + }, + }, + + // Semicolon between fields + { + in: `count:3;name:"Calvin"`, + out: &MyMessage{ + Count: Int32(3), + Name: String("Calvin"), + }, + }, + // Comma between fields + { + in: `count:4,name:"Ezekiel"`, + out: &MyMessage{ + Count: Int32(4), + Name: String("Ezekiel"), + }, + }, + + // Extension + buildExtStructTest(`count: 42 [testdata.Ext.more]:`), + buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), + buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), + buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), + + // Big all-in-one + { + in: "count:42 # Meaning\n" + + `name:"Dave" ` + + `quote:"\"I didn't want to go.\"" ` + + `pet:"bunny" ` + + `pet:"kitty" ` + + `pet:"horsey" ` + + `inner:<` + + ` host:"footrest.syd" ` + + ` port:7001 ` + + ` connected:true ` + + `> ` + + `others:<` + + ` key:3735928559 ` + + ` value:"\x01A\a\f" ` + + `> ` + + `others:<` + + " weight:58.9 # Atomic weight of Co\n" + + ` inner:<` + + ` host:"lesha.mtv" ` + + ` port:8002 ` + + ` >` + + `>`, + out: &MyMessage{ + Count: Int32(42), + Name: String("Dave"), + Quote: String(`"I didn't want to go."`), + Pet: []string{"bunny", "kitty", "horsey"}, + Inner: &InnerMessage{ + Host: String("footrest.syd"), + Port: Int32(7001), + Connected: Bool(true), + }, + Others: []*OtherMessage{ + { + Key: Int64(3735928559), + Value: []byte{0x1, 'A', '\a', '\f'}, + }, + { + Weight: Float32(58.9), + Inner: &InnerMessage{ + Host: String("lesha.mtv"), + Port: Int32(8002), + }, + }, + }, + }, + }, +} + +func TestUnmarshalText(t *testing.T) { + for i, test := range unMarshalTextTests { + pb := new(MyMessage) + err := UnmarshalText(test.in, pb) + if test.err == "" { + // We don't expect failure. + if err != nil { + t.Errorf("Test %d: Unexpected error: %v", i, err) + } else if !reflect.DeepEqual(pb, test.out) { + t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", + i, pb, test.out) + } + } else { + // We do expect failure. + if err == nil { + t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) + } else if err.Error() != test.err { + t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", + i, err.Error(), test.err) + } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { + t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", + i, pb, test.out) + } + } + } +} + +func TestUnmarshalTextCustomMessage(t *testing.T) { + msg := &textMessage{} + if err := UnmarshalText("custom", msg); err != nil { + t.Errorf("Unexpected error from custom unmarshal: %v", err) + } + if UnmarshalText("not custom", msg) == nil { + t.Errorf("Didn't get expected error from custom unmarshal") + } +} + +// Regression test; this caused a panic. +func TestRepeatedEnum(t *testing.T) { + pb := new(RepeatedEnum) + if err := UnmarshalText("color: RED", pb); err != nil { + t.Fatal(err) + } + exp := &RepeatedEnum{ + Color: []RepeatedEnum_Color{RepeatedEnum_RED}, + } + if !Equal(pb, exp) { + t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) + } +} + +func TestProto3TextParsing(t *testing.T) { + m := new(proto3pb.Message) + const in = `name: "Wallace" true_scotsman: true` + want := &proto3pb.Message{ + Name: "Wallace", + TrueScotsman: true, + } + if err := UnmarshalText(in, m); err != nil { + t.Fatal(err) + } + if !Equal(m, want) { + t.Errorf("\n got %v\nwant %v", m, want) + } +} + +func TestMapParsing(t *testing.T) { + m := new(MessageWithMap) + const in = `name_mapping: name_mapping:` + + `msg_mapping:,>` + // separating commas are okay + `msg_mapping>` + // no colon after "value" + `byte_mapping:` + want := &MessageWithMap{ + NameMapping: map[int32]string{ + 1: "Beatles", + 1234: "Feist", + }, + MsgMapping: map[int64]*FloatingPoint{ + -4: {F: Float64(2.0)}, + -2: {F: Float64(4.0)}, + }, + ByteMapping: map[bool][]byte{ + true: []byte("so be it"), + }, + } + if err := UnmarshalText(in, m); err != nil { + t.Fatal(err) + } + if !Equal(m, want) { + t.Errorf("\n got %v\nwant %v", m, want) + } +} + +var benchInput string + +func init() { + benchInput = "count: 4\n" + for i := 0; i < 1000; i++ { + benchInput += "pet: \"fido\"\n" + } + + // Check it is valid input. + pb := new(MyMessage) + err := UnmarshalText(benchInput, pb) + if err != nil { + panic("Bad benchmark input: " + err.Error()) + } +} + +func BenchmarkUnmarshalText(b *testing.B) { + pb := new(MyMessage) + for i := 0; i < b.N; i++ { + UnmarshalText(benchInput, pb) + } + b.SetBytes(int64(len(benchInput))) +} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go new file mode 100644 index 0000000..39861d1 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go @@ -0,0 +1,441 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto_test + +import ( + "bytes" + "errors" + "io/ioutil" + "math" + "strings" + "testing" + + "github.com/golang/protobuf/proto" + + proto3pb "github.com/golang/protobuf/proto/proto3_proto" + pb "github.com/golang/protobuf/proto/testdata" +) + +// textMessage implements the methods that allow it to marshal and unmarshal +// itself as text. +type textMessage struct { +} + +func (*textMessage) MarshalText() ([]byte, error) { + return []byte("custom"), nil +} + +func (*textMessage) UnmarshalText(bytes []byte) error { + if string(bytes) != "custom" { + return errors.New("expected 'custom'") + } + return nil +} + +func (*textMessage) Reset() {} +func (*textMessage) String() string { return "" } +func (*textMessage) ProtoMessage() {} + +func newTestMessage() *pb.MyMessage { + msg := &pb.MyMessage{ + Count: proto.Int32(42), + Name: proto.String("Dave"), + Quote: proto.String(`"I didn't want to go."`), + Pet: []string{"bunny", "kitty", "horsey"}, + Inner: &pb.InnerMessage{ + Host: proto.String("footrest.syd"), + Port: proto.Int32(7001), + Connected: proto.Bool(true), + }, + Others: []*pb.OtherMessage{ + { + Key: proto.Int64(0xdeadbeef), + Value: []byte{1, 65, 7, 12}, + }, + { + Weight: proto.Float32(6.022), + Inner: &pb.InnerMessage{ + Host: proto.String("lesha.mtv"), + Port: proto.Int32(8002), + }, + }, + }, + Bikeshed: pb.MyMessage_BLUE.Enum(), + Somegroup: &pb.MyMessage_SomeGroup{ + GroupField: proto.Int32(8), + }, + // One normally wouldn't do this. + // This is an undeclared tag 13, as a varint (wire type 0) with value 4. + XXX_unrecognized: []byte{13<<3 | 0, 4}, + } + ext := &pb.Ext{ + Data: proto.String("Big gobs for big rats"), + } + if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { + panic(err) + } + greetings := []string{"adg", "easy", "cow"} + if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { + panic(err) + } + + // Add an unknown extension. We marshal a pb.Ext, and fake the ID. + b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) + if err != nil { + panic(err) + } + b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) + proto.SetRawExtension(msg, 201, b) + + // Extensions can be plain fields, too, so let's test that. + b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) + proto.SetRawExtension(msg, 202, b) + + return msg +} + +const text = `count: 42 +name: "Dave" +quote: "\"I didn't want to go.\"" +pet: "bunny" +pet: "kitty" +pet: "horsey" +inner: < + host: "footrest.syd" + port: 7001 + connected: true +> +others: < + key: 3735928559 + value: "\001A\007\014" +> +others: < + weight: 6.022 + inner: < + host: "lesha.mtv" + port: 8002 + > +> +bikeshed: BLUE +SomeGroup { + group_field: 8 +} +/* 2 unknown bytes */ +13: 4 +[testdata.Ext.more]: < + data: "Big gobs for big rats" +> +[testdata.greeting]: "adg" +[testdata.greeting]: "easy" +[testdata.greeting]: "cow" +/* 13 unknown bytes */ +201: "\t3G skiing" +/* 3 unknown bytes */ +202: 19 +` + +func TestMarshalText(t *testing.T) { + buf := new(bytes.Buffer) + if err := proto.MarshalText(buf, newTestMessage()); err != nil { + t.Fatalf("proto.MarshalText: %v", err) + } + s := buf.String() + if s != text { + t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) + } +} + +func TestMarshalTextCustomMessage(t *testing.T) { + buf := new(bytes.Buffer) + if err := proto.MarshalText(buf, &textMessage{}); err != nil { + t.Fatalf("proto.MarshalText: %v", err) + } + s := buf.String() + if s != "custom" { + t.Errorf("Got %q, expected %q", s, "custom") + } +} +func TestMarshalTextNil(t *testing.T) { + want := "" + tests := []proto.Message{nil, (*pb.MyMessage)(nil)} + for i, test := range tests { + buf := new(bytes.Buffer) + if err := proto.MarshalText(buf, test); err != nil { + t.Fatal(err) + } + if got := buf.String(); got != want { + t.Errorf("%d: got %q want %q", i, got, want) + } + } +} + +func TestMarshalTextUnknownEnum(t *testing.T) { + // The Color enum only specifies values 0-2. + m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} + got := m.String() + const want = `bikeshed:3 ` + if got != want { + t.Errorf("\n got %q\nwant %q", got, want) + } +} + +func BenchmarkMarshalTextBuffered(b *testing.B) { + buf := new(bytes.Buffer) + m := newTestMessage() + for i := 0; i < b.N; i++ { + buf.Reset() + proto.MarshalText(buf, m) + } +} + +func BenchmarkMarshalTextUnbuffered(b *testing.B) { + w := ioutil.Discard + m := newTestMessage() + for i := 0; i < b.N; i++ { + proto.MarshalText(w, m) + } +} + +func compact(src string) string { + // s/[ \n]+/ /g; s/ $//; + dst := make([]byte, len(src)) + space, comment := false, false + j := 0 + for i := 0; i < len(src); i++ { + if strings.HasPrefix(src[i:], "/*") { + comment = true + i++ + continue + } + if comment && strings.HasPrefix(src[i:], "*/") { + comment = false + i++ + continue + } + if comment { + continue + } + c := src[i] + if c == ' ' || c == '\n' { + space = true + continue + } + if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { + space = false + } + if c == '{' { + space = false + } + if space { + dst[j] = ' ' + j++ + space = false + } + dst[j] = c + j++ + } + if space { + dst[j] = ' ' + j++ + } + return string(dst[0:j]) +} + +var compactText = compact(text) + +func TestCompactText(t *testing.T) { + s := proto.CompactTextString(newTestMessage()) + if s != compactText { + t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) + } +} + +func TestStringEscaping(t *testing.T) { + testCases := []struct { + in *pb.Strings + out string + }{ + { + // Test data from C++ test (TextFormatTest.StringEscape). + // Single divergence: we don't escape apostrophes. + &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, + "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", + }, + { + // Test data from the same C++ test. + &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, + "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", + }, + { + // Some UTF-8. + &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, + `string_field: "\000\001\377\201"` + "\n", + }, + } + + for i, tc := range testCases { + var buf bytes.Buffer + if err := proto.MarshalText(&buf, tc.in); err != nil { + t.Errorf("proto.MarsalText: %v", err) + continue + } + s := buf.String() + if s != tc.out { + t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) + continue + } + + // Check round-trip. + pb := new(pb.Strings) + if err := proto.UnmarshalText(s, pb); err != nil { + t.Errorf("#%d: UnmarshalText: %v", i, err) + continue + } + if !proto.Equal(pb, tc.in) { + t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) + } + } +} + +// A limitedWriter accepts some output before it fails. +// This is a proxy for something like a nearly-full or imminently-failing disk, +// or a network connection that is about to die. +type limitedWriter struct { + b bytes.Buffer + limit int +} + +var outOfSpace = errors.New("proto: insufficient space") + +func (w *limitedWriter) Write(p []byte) (n int, err error) { + var avail = w.limit - w.b.Len() + if avail <= 0 { + return 0, outOfSpace + } + if len(p) <= avail { + return w.b.Write(p) + } + n, _ = w.b.Write(p[:avail]) + return n, outOfSpace +} + +func TestMarshalTextFailing(t *testing.T) { + // Try lots of different sizes to exercise more error code-paths. + for lim := 0; lim < len(text); lim++ { + buf := new(limitedWriter) + buf.limit = lim + err := proto.MarshalText(buf, newTestMessage()) + // We expect a certain error, but also some partial results in the buffer. + if err != outOfSpace { + t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) + } + s := buf.b.String() + x := text[:buf.limit] + if s != x { + t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) + } + } +} + +func TestFloats(t *testing.T) { + tests := []struct { + f float64 + want string + }{ + {0, "0"}, + {4.7, "4.7"}, + {math.Inf(1), "inf"}, + {math.Inf(-1), "-inf"}, + {math.NaN(), "nan"}, + } + for _, test := range tests { + msg := &pb.FloatingPoint{F: &test.f} + got := strings.TrimSpace(msg.String()) + want := `f:` + test.want + if got != want { + t.Errorf("f=%f: got %q, want %q", test.f, got, want) + } + } +} + +func TestRepeatedNilText(t *testing.T) { + m := &pb.MessageList{ + Message: []*pb.MessageList_Message{ + nil, + &pb.MessageList_Message{ + Name: proto.String("Horse"), + }, + nil, + }, + } + want := `Message +Message { + name: "Horse" +} +Message +` + if s := proto.MarshalTextString(m); s != want { + t.Errorf(" got: %s\nwant: %s", s, want) + } +} + +func TestProto3Text(t *testing.T) { + tests := []struct { + m proto.Message + want string + }{ + // zero message + {&proto3pb.Message{}, ``}, + // zero message except for an empty byte slice + {&proto3pb.Message{Data: []byte{}}, ``}, + // trivial case + {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, + // empty map + {&pb.MessageWithMap{}, ``}, + // non-empty map; current map format is the same as a repeated struct + { + &pb.MessageWithMap{NameMapping: map[int32]string{1234: "Feist"}}, + `name_mapping:`, + }, + // map with nil value; not well-defined, but we shouldn't crash + { + &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, + `msg_mapping:`, + }, + } + for _, test := range tests { + got := strings.TrimSpace(test.m.String()) + if got != test.want { + t.Errorf("\n got %s\nwant %s", got, test.want) + } + } +} diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/.gitignore b/Godeps/_workspace/src/github.com/jmoiron/jsonq/.gitignore new file mode 100644 index 0000000..dbec55f --- /dev/null +++ b/Godeps/_workspace/src/github.com/jmoiron/jsonq/.gitignore @@ -0,0 +1 @@ +*.sw[op] diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/LICENSE b/Godeps/_workspace/src/github.com/jmoiron/jsonq/LICENSE new file mode 100644 index 0000000..88b577e --- /dev/null +++ b/Godeps/_workspace/src/github.com/jmoiron/jsonq/LICENSE @@ -0,0 +1,23 @@ + Copyright (c) 2012, Jason Moiron + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/README.md b/Godeps/_workspace/src/github.com/jmoiron/jsonq/README.md new file mode 100644 index 0000000..4fba5ed --- /dev/null +++ b/Godeps/_workspace/src/github.com/jmoiron/jsonq/README.md @@ -0,0 +1,83 @@ +# jsonq + +[![Build Status](https://drone.io/github.com/jmoiron/jsonq/status.png)](https://drone.io/github.com/jmoiron/jsonq/latest) [![Godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/jmoiron/jsonq) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/jmoiron/jsonq/master/LICENSE) + + +Simplify your golang json usage by extracting fields or items from arrays and objects with a simple, hierarchical query. [API Documentation](http://godoc.org/github.com/jmoiron/jsonq) on godoc.org. + +This package is meant to make working with complex feeds a bit more easy. If you have simple feeds you want to model with struct types, check out [jflect](http://github.com/str1ngs/jflect), which will create struct definitions given a json document. + +# installing + +``` +go get github.com/jmoiron/jsonq +``` + +# usage + +Given some json data like: + +```javascript +{ + "foo": 1, + "bar": 2, + "test": "Hello, world!", + "baz": 123.1, + "array": [ + {"foo": 1}, + {"bar": 2}, + {"baz": 3} + ], + "subobj": { + "foo": 1, + "subarray": [1,2,3], + "subsubobj": { + "bar": 2, + "baz": 3, + "array": ["hello", "world"] + } + }, + "bool": true +} +``` + +Decode it into a `map[string]interface{}`: + +```go +import ( + "strings" + "encoding/json" + "github.com/jmoiron/jsonq" +) + +data := map[string]interface{}{} +dec := json.NewDecoder(strings.NewReader(jsonstring)) +dec.Decode(&data) +jq := jsonq.NewQuery(data) +``` + +From here, you can query along different keys and indexes: + +```go +// data["foo"] -> 1 +jq.Int("foo") + +// data["subobj"]["subarray"][1] -> 2 +jq.Int("subobj", "subarray", "1") + +// data["subobj"]["subarray"]["array"][0] -> "hello" +jq.String("subobj", "subsubobj", "array", "0") + +// data["subobj"] -> map[string]interface{}{"subobj": ...} +obj, err := jq.Object("subobj") +``` + +Missing keys, out of bounds indexes, and type failures will return errors. +For simplicity, integer keys (ie, {"0": "zero"}) are inaccessible +by `jsonq` as integer strings are assumed to be array indexes. + +The `Int` and `Float` methods will attempt to parse numbers from string +values to ease the use of many real world feeds which deliver numbers as strings. + +Suggestions/comments please tweet [@jmoiron](http://twitter.com/jmoiron) + diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/autotest.sh b/Godeps/_workspace/src/github.com/jmoiron/jsonq/autotest.sh new file mode 100644 index 0000000..b154ad3 --- /dev/null +++ b/Godeps/_workspace/src/github.com/jmoiron/jsonq/autotest.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +cur=`pwd` + +inotifywait -mqr --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' \ + -e modify ./ | while read date time dir file; do + ext="${file##*.}" + if [[ "$ext" = "go" ]]; then + echo "$file changed @ $time $date, rebuilding..." + go test + fi +done + diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/doc.go b/Godeps/_workspace/src/github.com/jmoiron/jsonq/doc.go new file mode 100644 index 0000000..eb6918c --- /dev/null +++ b/Godeps/_workspace/src/github.com/jmoiron/jsonq/doc.go @@ -0,0 +1,68 @@ +/* +Simplify your golang json usage with a simple hierarchical query. + +Installing + + go get github.com/jmoiron/jsonq + +Examples + +Given some json data like: + + { + "foo": 1, + "bar": 2, + "test": "Hello, world!", + "baz": 123.1, + "array": [ + {"foo": 1}, + {"bar": 2}, + {"baz": 3} + ], + "subobj": { + "foo": 1, + "subarray": [1,2,3], + "subsubobj": { + "bar": 2, + "baz": 3, + "array": ["hello", "world"] + } + }, + "bool": true + } + +Decode it into a map[string]interrface{}: + + import ( + "strings" + "encoding/json" + "github.com/jmoiron/jsonq" + ) + + data := map[string]interface{}{} + dec := json.NewDecoder(strings.NewReader(jsonstring)) + dec.Decode(&data) + jq := jsonq.NewQuery(data) + +From here, you can query along different keys and indexes: + + // data["foo"] -> 1 + jq.Int("foo") + + // data["subobj"]["subarray"][1] -> 2 + jq.Int("subobj", "subarray", "1") + + // data["subobj"]["subarray"]["array"][0] -> "hello" + jq.String("subobj", "subsubobj", "array", "0") + + // data["subobj"] -> map[string]interface{}{"subobj": ...} + obj, err := jq.Object("subobj") + +Notes + +Missing keys, out of bounds indexes, and type failures will return errors. +For simplicity, integer keys (ie, {"0": "zero"}) are inaccessible by `jsonq` +as integer strings are assumed to be array indexes. + +*/ +package jsonq diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq.go b/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq.go new file mode 100644 index 0000000..e7880ce --- /dev/null +++ b/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq.go @@ -0,0 +1,311 @@ +package jsonq + +import ( + "fmt" + "strconv" +) + +type JsonQuery struct { + blob map[string]interface{} +} + +/* +The following methods are identical to the routines that were originally embedded in the realted query methods. +They are seperated out here to keep the code as dry as possible. +*/ + +//stringFromInterface converts an interface{} to a string and returns an error if types don't match. +func stringFromInterface(val interface{}) (string, error) { + switch val.(type) { + case string: + return val.(string), nil + } + return "", fmt.Errorf("Expected string value for String, got \"%v\"\n", val) +} + +//boolFromInterface converts an interface{} to a bool and returns an error if types don't match. +func boolFromInterface(val interface{}) (bool, error) { + switch val.(type) { + case bool: + return val.(bool), nil + } + return false, fmt.Errorf("Expected boolean value for Bool, got \"%v\"\n", val) +} + +//floatFromInterface converts an interface{} to a float64 and returns an error if types don't match. +func floatFromInterface(val interface{}) (float64, error) { + switch val.(type) { + case float64: + return val.(float64), nil + case int: + return float64(val.(int)), nil + case string: + fval, err := strconv.ParseFloat(val.(string), 64) + if err == nil { + return fval, nil + } + } + return 0.0, fmt.Errorf("Expected numeric value for Float, got \"%v\"\n", val) +} + +//intFromInterface converts an interface{} to an int and returns an error if types don't match. +func intFromInterface(val interface{}) (int, error) { + switch val.(type) { + case float64: + return int(val.(float64)), nil + case string: + ival, err := strconv.ParseFloat(val.(string), 64) + if err == nil { + return int(ival), nil + } + case int: + return val.(int), nil + } + return 0, fmt.Errorf("Expected numeric value for Int, got \"%v\"\n", val) +} + +//objectFromInterface converts an interface{} to a map[string]interface{} and returns an error if types don't match. +func objectFromInterface(val interface{}) (map[string]interface{}, error) { + switch val.(type) { + case map[string]interface{}: + return val.(map[string]interface{}), nil + } + return map[string]interface{}{}, fmt.Errorf("Expected json object for Object, got \"%v\"\n", val) +} + +//arrayFromInterface converts an interface{} to an []interface{} and returns an error if types don't match. +func arrayFromInterface(val interface{}) ([]interface{}, error) { + switch val.(type) { + case []interface{}: + return val.([]interface{}), nil + } + return []interface{}{}, fmt.Errorf("Expected json array for Array, got \"%v\"\n", val) +} + +// Create a new JsonQuery obj from a json-decoded interface{} +func NewQuery(data interface{}) *JsonQuery { + j := new(JsonQuery) + j.blob = data.(map[string]interface{}) + return j +} + +// Extract a Bool from some json +func (j *JsonQuery) Bool(s ...string) (bool, error) { + val, err := rquery(j.blob, s...) + if err != nil { + return false, err + } + return boolFromInterface(val) +} + +// Extract a float from some json +func (j *JsonQuery) Float(s ...string) (float64, error) { + val, err := rquery(j.blob, s...) + if err != nil { + return 0.0, err + } + return floatFromInterface(val) +} + +// Extract an int from some json +func (j *JsonQuery) Int(s ...string) (int, error) { + val, err := rquery(j.blob, s...) + if err != nil { + return 0, err + } + return intFromInterface(val) +} + +// Extract a string from some json +func (j *JsonQuery) String(s ...string) (string, error) { + val, err := rquery(j.blob, s...) + if err != nil { + return "", err + } + return stringFromInterface(val) +} + +// Extract an object from some json +func (j *JsonQuery) Object(s ...string) (map[string]interface{}, error) { + val, err := rquery(j.blob, s...) + if err != nil { + return map[string]interface{}{}, err + } + return objectFromInterface(val) +} + +// Extract an array from some json +func (j *JsonQuery) Array(s ...string) ([]interface{}, error) { + val, err := rquery(j.blob, s...) + if err != nil { + return []interface{}{}, err + } + return arrayFromInterface(val) +} + +// Extract interface from some json +func (j *JsonQuery) Interface(s ...string) (interface{}, error) { + val, err := rquery(j.blob, s...) + if err != nil { + return nil, err + } + return val, nil +} + +/* +Extract typed slices. +*/ + +//ArrayOfStrings extracts an array of strings from some json +func (j *JsonQuery) ArrayOfStrings(s ...string) ([]string, error) { + array, err := j.Array(s...) + if err != nil { + return []string{}, err + } + toReturn := make([]string, len(array)) + for index, val := range array { + toReturn[index], err = stringFromInterface(val) + if err != nil { + return toReturn, err + } + } + return toReturn, nil +} + +//ArrayOfInts extracts an array of ints from some json +func (j *JsonQuery) ArrayOfInts(s ...string) ([]int, error) { + array, err := j.Array(s...) + if err != nil { + return []int{}, err + } + toReturn := make([]int, len(array)) + for index, val := range array { + toReturn[index], err = intFromInterface(val) + if err != nil { + return toReturn, err + } + } + return toReturn, nil +} + +//ArrayOfFloats extracts an array of float64s from some json +func (j *JsonQuery) ArrayOfFloats(s ...string) ([]float64, error) { + array, err := j.Array(s...) + if err != nil { + return []float64{}, err + } + toReturn := make([]float64, len(array)) + for index, val := range array { + toReturn[index], err = floatFromInterface(val) + if err != nil { + return toReturn, err + } + } + return toReturn, nil +} + +//ArrayOfBools extracts an array of bools from some json +func (j *JsonQuery) ArrayOfBools(s ...string) ([]bool, error) { + array, err := j.Array(s...) + if err != nil { + return []bool{}, err + } + toReturn := make([]bool, len(array)) + for index, val := range array { + toReturn[index], err = boolFromInterface(val) + if err != nil { + return toReturn, err + } + } + return toReturn, nil +} + +//ArrayOfObjects extracts an array of map[string]interface{} (objects) from some json +func (j *JsonQuery) ArrayOfObjects(s ...string) ([]map[string]interface{}, error) { + array, err := j.Array(s...) + if err != nil { + return []map[string]interface{}{}, err + } + toReturn := make([]map[string]interface{}, len(array)) + for index, val := range array { + toReturn[index], err = objectFromInterface(val) + if err != nil { + return toReturn, err + } + } + return toReturn, nil +} + +//ArrayOfArrays extracts an array of []interface{} (arrays) from some json +func (j *JsonQuery) ArrayOfArrays(s ...string) ([][]interface{}, error) { + array, err := j.Array(s...) + if err != nil { + return [][]interface{}{}, err + } + toReturn := make([][]interface{}, len(array)) + for index, val := range array { + toReturn[index], err = arrayFromInterface(val) + if err != nil { + return toReturn, err + } + } + return toReturn, nil +} + +//Matrix2D is an alias for ArrayOfArrays +func (j *JsonQuery) Matrix2D(s ...string) ([][]interface{}, error) { + return j.ArrayOfArrays(s...) +} + +// Recursively query a decoded json blob +func rquery(blob interface{}, s ...string) (interface{}, error) { + var ( + val interface{} + err error + ) + val = blob + for _, q := range s { + val, err = query(val, q) + if err != nil { + return nil, err + } + } + switch val.(type) { + case nil: + return nil, fmt.Errorf("Nil value found at %s\n", s[len(s)-1]) + } + return val, nil +} + +// Query a json blob for a single field or index. If query is a string, then +// the blob is treated as a json object (map[string]interface{}). If query is +// an integer, the blob is treated as a json array ([]interface{}). Any kind +// of key or index error will result in a nil return value with an error set. +func query(blob interface{}, query string) (interface{}, error) { + index, err := strconv.Atoi(query) + // if it's an integer, then we treat the current interface as an array + if err == nil { + switch blob.(type) { + case []interface{}: + default: + return nil, fmt.Errorf("Array index on non-array %v\n", blob) + } + if len(blob.([]interface{})) > index { + return blob.([]interface{})[index], nil + } + return nil, fmt.Errorf("Array index %d on array %v out of bounds\n", index, blob) + } + + // blob is likely an object, but verify first + switch blob.(type) { + case map[string]interface{}: + default: + return nil, fmt.Errorf("Object lookup \"%s\" on non-object %v\n", query, blob) + } + + val, ok := blob.(map[string]interface{})[query] + if !ok { + return nil, fmt.Errorf("Object %v does not contain field %s\n", blob, query) + } + return val, nil +} diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq_test.go b/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq_test.go new file mode 100644 index 0000000..9b1835b --- /dev/null +++ b/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq_test.go @@ -0,0 +1,186 @@ +package jsonq + +import ( + "encoding/json" + "fmt" + "strings" + "testing" +) + +const TestData = `{ + "foo": 1, + "bar": 2, + "test": "Hello, world!", + "baz": 123.1, + "numstring": "42", + "floatstring": "42.1", + "array": [ + {"foo": 1}, + {"bar": 2}, + {"baz": 3} + ], + "subobj": { + "foo": 1, + "subarray": [1,2,3], + "subsubobj": { + "bar": 2, + "baz": 3, + "array": ["hello", "world"] + } + }, + "collections": { + "bools": [false, true, false], + "strings": ["hello", "strings"], + "numbers": [1,2,3,4], + "arrays": [[1.0,2.0],[2.0,3.0],[4.0,3.0]], + "objects": [ + {"obj1": 1}, + {"obj2": 2} + ] + }, + "bool": true +}` + +func tErr(t *testing.T, err error) { + if err != nil { + t.Errorf("Error: %v\n", err) + } +} + +func TestQuery(t *testing.T) { + data := map[string]interface{}{} + dec := json.NewDecoder(strings.NewReader(TestData)) + err := dec.Decode(&data) + tErr(t, err) + q := NewQuery(data) + + ival, err := q.Int("foo") + if ival != 1 { + t.Errorf("Expecting 1, got %v\n", ival) + } + tErr(t, err) + ival, err = q.Int("bar") + if ival != 2 { + t.Errorf("Expecting 2, got %v\n", ival) + } + tErr(t, err) + + ival, err = q.Int("subobj", "foo") + if ival != 1 { + t.Errorf("Expecting 1, got %v\n", ival) + } + tErr(t, err) + + // test that strings can get int-ed + ival, err = q.Int("numstring") + if ival != 42 { + t.Errorf("Expecting 42, got %v\n", ival) + } + tErr(t, err) + + for i := 0; i < 3; i++ { + ival, err := q.Int("subobj", "subarray", fmt.Sprintf("%d", i)) + if ival != i+1 { + t.Errorf("Expecting %d, got %v\n", i+1, ival) + } + tErr(t, err) + } + + fval, err := q.Float("baz") + if fval != 123.1 { + t.Errorf("Expecting 123.1, got %f\n", fval) + } + tErr(t, err) + + // test that strings can get float-ed + fval, err = q.Float("floatstring") + if fval != 42.1 { + t.Errorf("Expecting 42.1, got %v\n", fval) + } + tErr(t, err) + + sval, err := q.String("test") + if sval != "Hello, world!" { + t.Errorf("Expecting \"Hello, World!\", got \"%v\"\n", sval) + } + + sval, err = q.String("subobj", "subsubobj", "array", "0") + if sval != "hello" { + t.Errorf("Expecting \"hello\", got \"%s\"\n", sval) + } + tErr(t, err) + + bval, err := q.Bool("bool") + if !bval { + t.Errorf("Expecting true, got %v\n", bval) + } + tErr(t, err) + + obj, err := q.Object("subobj", "subsubobj") + tErr(t, err) + q2 := NewQuery(obj) + sval, err = q2.String("array", "1") + if sval != "world" { + t.Errorf("Expecting \"world\", got \"%s\"\n", sval) + } + tErr(t, err) + + aobj, err := q.Array("subobj", "subarray") + tErr(t, err) + if aobj[0].(float64) != 1 { + t.Errorf("Expecting 1, got %v\n", aobj[0]) + } + + iobj, err := q.Interface("numstring") + tErr(t, err) + if _, ok := iobj.(string); !ok { + t.Errorf("Expecting type string got: %s", iobj) + } + + /* + Test Extraction of typed slices + */ + + //test array of strings + astrings, err := q.ArrayOfStrings("collections", "strings") + tErr(t, err) + if astrings[0] != "hello" { + t.Errorf("Expecting hello, got %v\n", astrings[0]) + } + + //test array of ints + aints, err := q.ArrayOfInts("collections", "numbers") + tErr(t, err) + if aints[0] != 1 { + t.Errorf("Expecting 1, got %v\n", aints[0]) + } + + //test array of floats + afloats, err := q.ArrayOfFloats("collections", "numbers") + tErr(t, err) + if afloats[0] != 1.0 { + t.Errorf("Expecting 1.0, got %v\n", afloats[0]) + } + + //test array of bools + abools, err := q.ArrayOfBools("collections", "bools") + tErr(t, err) + if abools[0] { + t.Errorf("Expecting true, got %v\n", abools[0]) + } + + //test array of arrays + aa, err := q.ArrayOfArrays("collections", "arrays") + tErr(t, err) + if aa[0][0].(float64) != 1 { + t.Errorf("Expecting 1, got %v\n", aa[0][0]) + } + + //test array of objs + aobjs, err := q.ArrayOfObjects("collections", "objects") + tErr(t, err) + if aobjs[0]["obj1"].(float64) != 1 { + t.Errorf("Expecting 1, got %v\n", aobjs[0]["obj1"]) + } + +} diff --git a/Godeps/_workspace/src/github.com/layeh/gopus/LICENSE b/Godeps/_workspace/src/github.com/layeh/gopus/LICENSE new file mode 100644 index 0000000..45385d1 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gopus/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Tim Cooper + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Godeps/_workspace/src/github.com/layeh/gopus/README.md b/Godeps/_workspace/src/github.com/layeh/gopus/README.md new file mode 100644 index 0000000..99ec9e9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gopus/README.md @@ -0,0 +1,20 @@ +# gopus + +gopus is a Go binding for the [Opus](http://www.opus-codec.org/) audio codec. + +## Documentation + +- [API Reference](https://godoc.org/github.com/layeh/gopus) + +## Requirements + +- cgo +- [opus](http://www.opus-codec.org/) + +## License + +MIT + +## Author + +Tim Cooper () diff --git a/Godeps/_workspace/src/github.com/layeh/gopus/decoder.go b/Godeps/_workspace/src/github.com/layeh/gopus/decoder.go new file mode 100644 index 0000000..76ce8d5 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gopus/decoder.go @@ -0,0 +1,71 @@ +package gopus + +// #cgo !nopkgconfig pkg-config: opus +// #include +// +// void gopus_decoder_resetstate(OpusDecoder *decoder) { +// opus_decoder_ctl(decoder, OPUS_RESET_STATE); +// } +import "C" + +import ( + "unsafe" +) + +type Decoder struct { + data []byte + cDecoder *C.struct_OpusDecoder + channels int +} + +func NewDecoder(sampleRate, channels int) (*Decoder, error) { + decoder := &Decoder{} + decoder.data = make([]byte, int(C.opus_decoder_get_size(C.int(channels)))) + decoder.cDecoder = (*C.struct_OpusDecoder)(unsafe.Pointer(&decoder.data[0])) + + ret := C.opus_decoder_init(decoder.cDecoder, C.opus_int32(sampleRate), C.int(channels)) + if err := getErr(ret); err != nil { + return nil, err + } + decoder.channels = channels + + return decoder, nil +} + +func (d *Decoder) Decode(data []byte, frameSize int, fec bool) ([]int16, error) { + dataPtr := (*C.uchar)(unsafe.Pointer(&data[0])) + dataLen := C.opus_int32(len(data)) + + output := make([]int16, d.channels * frameSize) + outputPtr := (*C.opus_int16)(unsafe.Pointer(&output[0])) + + var cFec C.int + if fec { + cFec = 1 + } else { + cFec = 0 + } + + cRet := C.opus_decode(d.cDecoder, dataPtr, dataLen, outputPtr, C.int(frameSize), cFec) + ret := int(cRet) + + if ret < 0 { + return nil, getErr(cRet) + } + return output[:ret], nil +} + +func (d *Decoder) ResetState() { + C.gopus_decoder_resetstate(d.cDecoder) +} + +func CountFrames(data []byte) (int, error) { + dataPtr := (*C.uchar)(unsafe.Pointer(&data[0])) + cLen := C.opus_int32(len(data)) + + cRet := C.opus_packet_get_nb_frames(dataPtr, cLen) + if err := getErr(cRet); err != nil { + return 0, err + } + return int(cRet), nil +} diff --git a/Godeps/_workspace/src/github.com/layeh/gopus/encoder.go b/Godeps/_workspace/src/github.com/layeh/gopus/encoder.go new file mode 100644 index 0000000..d39b36c --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gopus/encoder.go @@ -0,0 +1,119 @@ +package gopus + +// #cgo !nopkgconfig pkg-config: opus +// #include +// +// enum { +// gopus_application_voip = OPUS_APPLICATION_VOIP, +// gopus_application_audio = OPUS_APPLICATION_AUDIO, +// gopus_restricted_lowdelay = OPUS_APPLICATION_RESTRICTED_LOWDELAY, +// gopus_bitrate_max = OPUS_BITRATE_MAX, +// }; +// +// +// void gopus_setvbr(OpusEncoder *encoder, int vbr) { +// opus_encoder_ctl(encoder, OPUS_SET_VBR(vbr)); +// } +// +// void gopus_setbitrate(OpusEncoder *encoder, int bitrate) { +// opus_encoder_ctl(encoder, OPUS_SET_BITRATE(bitrate)); +// } +// +// opus_int32 gopus_bitrate(OpusEncoder *encoder) { +// opus_int32 bitrate; +// opus_encoder_ctl(encoder, OPUS_GET_BITRATE(&bitrate)); +// return bitrate; +// } +// +// void gopus_setapplication(OpusEncoder *encoder, int application) { +// opus_encoder_ctl(encoder, OPUS_SET_APPLICATION(application)); +// } +// +// opus_int32 gopus_application(OpusEncoder *encoder) { +// opus_int32 application; +// opus_encoder_ctl(encoder, OPUS_GET_APPLICATION(&application)); +// return application; +// } +// +// void gopus_encoder_resetstate(OpusEncoder *encoder) { +// opus_encoder_ctl(encoder, OPUS_RESET_STATE); +// } +import "C" + +import ( + "unsafe" +) + +type Application int + +const ( + Voip Application = C.gopus_application_voip + Audio Application = C.gopus_application_audio + RestrictedLowDelay Application = C.gopus_restricted_lowdelay +) + +const ( + BitrateMaximum = C.gopus_bitrate_max +) + +type Encoder struct { + data []byte + cEncoder *C.struct_OpusEncoder +} + +func NewEncoder(sampleRate, channels int, application Application) (*Encoder, error) { + encoder := &Encoder{} + encoder.data = make([]byte, int(C.opus_encoder_get_size(C.int(channels)))) + encoder.cEncoder = (*C.struct_OpusEncoder)(unsafe.Pointer(&encoder.data[0])) + + ret := C.opus_encoder_init(encoder.cEncoder, C.opus_int32(sampleRate), C.int(channels), C.int(application)) + if err := getErr(ret); err != nil { + return nil, err + } + return encoder, nil +} + +func (e *Encoder) Encode(pcm []int16, frameSize, maxDataBytes int) ([]byte, error) { + pcmPtr := (*C.opus_int16)(unsafe.Pointer(&pcm[0])) + + data := make([]byte, maxDataBytes) + dataPtr := (*C.uchar)(unsafe.Pointer(&data[0])) + + encodedC := C.opus_encode(e.cEncoder, pcmPtr, C.int(frameSize), dataPtr, C.opus_int32(len(data))) + encoded := int(encodedC) + + if encoded < 0 { + return nil, getErr(C.int(encodedC)) + } + return data[0:encoded], nil +} + +func (e *Encoder) SetVbr(vbr bool) { + var cVbr C.int + if vbr { + cVbr = 1 + } else { + cVbr = 0 + } + C.gopus_setvbr(e.cEncoder, cVbr) +} + +func (e *Encoder) SetBitrate(bitrate int) { + C.gopus_setbitrate(e.cEncoder, C.int(bitrate)) +} + +func (e *Encoder) Bitrate() int { + return int(C.gopus_bitrate(e.cEncoder)) +} + +func (e *Encoder) SetApplication(application Application) { + C.gopus_setapplication(e.cEncoder, C.int(application)) +} + +func (e *Encoder) Application() Application { + return Application(C.gopus_application(e.cEncoder)) +} + +func (e *Encoder) ResetState() { + C.gopus_encoder_resetstate(e.cEncoder) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gopus/gopus.go b/Godeps/_workspace/src/github.com/layeh/gopus/gopus.go new file mode 100644 index 0000000..9fde581 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gopus/gopus.go @@ -0,0 +1,53 @@ +package gopus + +// #include +// +// enum { +// gopus_ok = OPUS_OK, +// gopus_bad_arg = OPUS_BAD_ARG, +// gopus_small_buffer = OPUS_BUFFER_TOO_SMALL, +// gopus_internal = OPUS_INTERNAL_ERROR, +// gopus_invalid_packet = OPUS_INVALID_PACKET, +// gopus_unimplemented = OPUS_UNIMPLEMENTED, +// gopus_invalid_state = OPUS_INVALID_STATE, +// gopus_alloc_fail = OPUS_ALLOC_FAIL, +// }; +import "C" + +import ( + "errors" +) + +var ( + ErrBadArgument = errors.New("bad argument") + ErrSmallBuffer = errors.New("buffer is too small") + ErrInternal = errors.New("internal error") + ErrInvalidPacket = errors.New("invalid packet") + ErrUnimplemented = errors.New("unimplemented") + ErrInvalidState = errors.New("invalid state") + ErrAllocFail = errors.New("allocation failed") + ErrUnknown = errors.New("unknown error") +) + +func getErr(code C.int) error { + switch code { + case C.gopus_ok: + return nil + case C.gopus_bad_arg: + return ErrBadArgument + case C.gopus_small_buffer: + return ErrSmallBuffer + case C.gopus_internal: + return ErrInternal + case C.gopus_invalid_packet: + return ErrInvalidPacket + case C.gopus_unimplemented: + return ErrUnimplemented + case C.gopus_invalid_state: + return ErrInvalidState + case C.gopus_alloc_fail: + return ErrAllocFail + default: + return ErrUnknown + } +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/LICENSE b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/LICENSE new file mode 100644 index 0000000..c3ffe8f --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/LICENSE @@ -0,0 +1,37 @@ +Copyright (C) 2005-2013, Thorvald Natvig +Copyright (C) 2007, Stefan Gehn +Copyright (C) 2007, Sebastian Schlingmann +Copyright (C) 2008-2013, Mikkel Krautz +Copyright (C) 2008, Andreas Messer +Copyright (C) 2007, Trenton Schulz +Copyright (C) 2008-2013, Stefan Hacker +Copyright (C) 2008-2011, Snares +Copyright (C) 2009-2013, Benjamin Jemlich +Copyright (C) 2009-2013, Kissaki + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +- Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +- Neither the name of the Mumble Developers nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +`AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.pb.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.pb.go new file mode 100644 index 0000000..a9f4ad9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.pb.go @@ -0,0 +1,2092 @@ +// Code generated by protoc-gen-go. +// source: Mumble.proto +// DO NOT EDIT! + +/* +Package MumbleProto is a generated protocol buffer package. + +It is generated from these files: + Mumble.proto + +It has these top-level messages: + Version + UDPTunnel + Authenticate + Ping + Reject + ServerSync + ChannelRemove + ChannelState + UserRemove + UserState + BanList + TextMessage + PermissionDenied + ACL + QueryUsers + CryptSetup + ContextActionModify + ContextAction + UserList + VoiceTarget + PermissionQuery + CodecVersion + UserStats + RequestBlob + ServerConfig + SuggestConfig +*/ +package MumbleProto + +import proto "github.com/golang/protobuf/proto" +import math "math" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = math.Inf + +type Reject_RejectType int32 + +const ( + // TODO ?? + Reject_None Reject_RejectType = 0 + // The client attempted to connect with an incompatible version. + Reject_WrongVersion Reject_RejectType = 1 + // The user name supplied by the client was invalid. + Reject_InvalidUsername Reject_RejectType = 2 + // The client attempted to authenticate as a user with a password but it + // was wrong. + Reject_WrongUserPW Reject_RejectType = 3 + // The client attempted to connect to a passworded server but the password + // was wrong. + Reject_WrongServerPW Reject_RejectType = 4 + // Supplied username is already in use. + Reject_UsernameInUse Reject_RejectType = 5 + // Server is currently full and cannot accept more users. + Reject_ServerFull Reject_RejectType = 6 + // The user did not provide a certificate but one is required. + Reject_NoCertificate Reject_RejectType = 7 + Reject_AuthenticatorFail Reject_RejectType = 8 +) + +var Reject_RejectType_name = map[int32]string{ + 0: "None", + 1: "WrongVersion", + 2: "InvalidUsername", + 3: "WrongUserPW", + 4: "WrongServerPW", + 5: "UsernameInUse", + 6: "ServerFull", + 7: "NoCertificate", + 8: "AuthenticatorFail", +} +var Reject_RejectType_value = map[string]int32{ + "None": 0, + "WrongVersion": 1, + "InvalidUsername": 2, + "WrongUserPW": 3, + "WrongServerPW": 4, + "UsernameInUse": 5, + "ServerFull": 6, + "NoCertificate": 7, + "AuthenticatorFail": 8, +} + +func (x Reject_RejectType) Enum() *Reject_RejectType { + p := new(Reject_RejectType) + *p = x + return p +} +func (x Reject_RejectType) String() string { + return proto.EnumName(Reject_RejectType_name, int32(x)) +} +func (x *Reject_RejectType) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(Reject_RejectType_value, data, "Reject_RejectType") + if err != nil { + return err + } + *x = Reject_RejectType(value) + return nil +} + +type PermissionDenied_DenyType int32 + +const ( + // Operation denied for other reason, see reason field. + PermissionDenied_Text PermissionDenied_DenyType = 0 + // Permissions were denied. + PermissionDenied_Permission PermissionDenied_DenyType = 1 + // Cannot modify SuperUser. + PermissionDenied_SuperUser PermissionDenied_DenyType = 2 + // Invalid channel name. + PermissionDenied_ChannelName PermissionDenied_DenyType = 3 + // Text message too long. + PermissionDenied_TextTooLong PermissionDenied_DenyType = 4 + // The flux capacitor was spelled wrong. + PermissionDenied_H9K PermissionDenied_DenyType = 5 + // Operation not permitted in temporary channel. + PermissionDenied_TemporaryChannel PermissionDenied_DenyType = 6 + // Operation requires certificate. + PermissionDenied_MissingCertificate PermissionDenied_DenyType = 7 + // Invalid username. + PermissionDenied_UserName PermissionDenied_DenyType = 8 + // Channel is full. + PermissionDenied_ChannelFull PermissionDenied_DenyType = 9 + PermissionDenied_NestingLimit PermissionDenied_DenyType = 10 +) + +var PermissionDenied_DenyType_name = map[int32]string{ + 0: "Text", + 1: "Permission", + 2: "SuperUser", + 3: "ChannelName", + 4: "TextTooLong", + 5: "H9K", + 6: "TemporaryChannel", + 7: "MissingCertificate", + 8: "UserName", + 9: "ChannelFull", + 10: "NestingLimit", +} +var PermissionDenied_DenyType_value = map[string]int32{ + "Text": 0, + "Permission": 1, + "SuperUser": 2, + "ChannelName": 3, + "TextTooLong": 4, + "H9K": 5, + "TemporaryChannel": 6, + "MissingCertificate": 7, + "UserName": 8, + "ChannelFull": 9, + "NestingLimit": 10, +} + +func (x PermissionDenied_DenyType) Enum() *PermissionDenied_DenyType { + p := new(PermissionDenied_DenyType) + *p = x + return p +} +func (x PermissionDenied_DenyType) String() string { + return proto.EnumName(PermissionDenied_DenyType_name, int32(x)) +} +func (x *PermissionDenied_DenyType) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(PermissionDenied_DenyType_value, data, "PermissionDenied_DenyType") + if err != nil { + return err + } + *x = PermissionDenied_DenyType(value) + return nil +} + +type ContextActionModify_Context int32 + +const ( + // Action is applicable to the server. + ContextActionModify_Server ContextActionModify_Context = 1 + // Action can target a Channel. + ContextActionModify_Channel ContextActionModify_Context = 2 + // Action can target a User. + ContextActionModify_User ContextActionModify_Context = 4 +) + +var ContextActionModify_Context_name = map[int32]string{ + 1: "Server", + 2: "Channel", + 4: "User", +} +var ContextActionModify_Context_value = map[string]int32{ + "Server": 1, + "Channel": 2, + "User": 4, +} + +func (x ContextActionModify_Context) Enum() *ContextActionModify_Context { + p := new(ContextActionModify_Context) + *p = x + return p +} +func (x ContextActionModify_Context) String() string { + return proto.EnumName(ContextActionModify_Context_name, int32(x)) +} +func (x *ContextActionModify_Context) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(ContextActionModify_Context_value, data, "ContextActionModify_Context") + if err != nil { + return err + } + *x = ContextActionModify_Context(value) + return nil +} + +type ContextActionModify_Operation int32 + +const ( + ContextActionModify_Add ContextActionModify_Operation = 0 + ContextActionModify_Remove ContextActionModify_Operation = 1 +) + +var ContextActionModify_Operation_name = map[int32]string{ + 0: "Add", + 1: "Remove", +} +var ContextActionModify_Operation_value = map[string]int32{ + "Add": 0, + "Remove": 1, +} + +func (x ContextActionModify_Operation) Enum() *ContextActionModify_Operation { + p := new(ContextActionModify_Operation) + *p = x + return p +} +func (x ContextActionModify_Operation) String() string { + return proto.EnumName(ContextActionModify_Operation_name, int32(x)) +} +func (x *ContextActionModify_Operation) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(ContextActionModify_Operation_value, data, "ContextActionModify_Operation") + if err != nil { + return err + } + *x = ContextActionModify_Operation(value) + return nil +} + +type Version struct { + // 2-byte Major, 1-byte Minor and 1-byte Patch version number. + Version *uint32 `protobuf:"varint,1,opt,name=version" json:"version,omitempty"` + // Client release name. + Release *string `protobuf:"bytes,2,opt,name=release" json:"release,omitempty"` + // Client OS name. + Os *string `protobuf:"bytes,3,opt,name=os" json:"os,omitempty"` + // Client OS version. + OsVersion *string `protobuf:"bytes,4,opt,name=os_version" json:"os_version,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Version) Reset() { *m = Version{} } +func (m *Version) String() string { return proto.CompactTextString(m) } +func (*Version) ProtoMessage() {} + +func (m *Version) GetVersion() uint32 { + if m != nil && m.Version != nil { + return *m.Version + } + return 0 +} + +func (m *Version) GetRelease() string { + if m != nil && m.Release != nil { + return *m.Release + } + return "" +} + +func (m *Version) GetOs() string { + if m != nil && m.Os != nil { + return *m.Os + } + return "" +} + +func (m *Version) GetOsVersion() string { + if m != nil && m.OsVersion != nil { + return *m.OsVersion + } + return "" +} + +// Not used. Not even for tunneling UDP through TCP. +type UDPTunnel struct { + // Not used. + Packet []byte `protobuf:"bytes,1,req,name=packet" json:"packet,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *UDPTunnel) Reset() { *m = UDPTunnel{} } +func (m *UDPTunnel) String() string { return proto.CompactTextString(m) } +func (*UDPTunnel) ProtoMessage() {} + +func (m *UDPTunnel) GetPacket() []byte { + if m != nil { + return m.Packet + } + return nil +} + +// Used by the client to send the authentication credentials to the server. +type Authenticate struct { + // UTF-8 encoded username. + Username *string `protobuf:"bytes,1,opt,name=username" json:"username,omitempty"` + // Server or user password. + Password *string `protobuf:"bytes,2,opt,name=password" json:"password,omitempty"` + // Additional access tokens for server ACL groups. + Tokens []string `protobuf:"bytes,3,rep,name=tokens" json:"tokens,omitempty"` + // A list of CELT bitstream version constants supported by the client. + CeltVersions []int32 `protobuf:"varint,4,rep,name=celt_versions" json:"celt_versions,omitempty"` + Opus *bool `protobuf:"varint,5,opt,name=opus,def=0" json:"opus,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Authenticate) Reset() { *m = Authenticate{} } +func (m *Authenticate) String() string { return proto.CompactTextString(m) } +func (*Authenticate) ProtoMessage() {} + +const Default_Authenticate_Opus bool = false + +func (m *Authenticate) GetUsername() string { + if m != nil && m.Username != nil { + return *m.Username + } + return "" +} + +func (m *Authenticate) GetPassword() string { + if m != nil && m.Password != nil { + return *m.Password + } + return "" +} + +func (m *Authenticate) GetTokens() []string { + if m != nil { + return m.Tokens + } + return nil +} + +func (m *Authenticate) GetCeltVersions() []int32 { + if m != nil { + return m.CeltVersions + } + return nil +} + +func (m *Authenticate) GetOpus() bool { + if m != nil && m.Opus != nil { + return *m.Opus + } + return Default_Authenticate_Opus +} + +// Sent by the client to notify the server that the client is still alive. +// Server must reply to the packet with the same timestamp and its own +// good/late/lost/resync numbers. None of the fields is strictly required. +type Ping struct { + // Client timestamp. Server should not attempt to decode. + Timestamp *uint64 `protobuf:"varint,1,opt,name=timestamp" json:"timestamp,omitempty"` + // The amount of good packets received. + Good *uint32 `protobuf:"varint,2,opt,name=good" json:"good,omitempty"` + // The amount of late packets received. + Late *uint32 `protobuf:"varint,3,opt,name=late" json:"late,omitempty"` + // The amount of packets never received. + Lost *uint32 `protobuf:"varint,4,opt,name=lost" json:"lost,omitempty"` + // The amount of nonce resyncs. + Resync *uint32 `protobuf:"varint,5,opt,name=resync" json:"resync,omitempty"` + // The total amount of UDP packets received. + UdpPackets *uint32 `protobuf:"varint,6,opt,name=udp_packets" json:"udp_packets,omitempty"` + // The total amount of TCP packets received. + TcpPackets *uint32 `protobuf:"varint,7,opt,name=tcp_packets" json:"tcp_packets,omitempty"` + // UDP ping average. + UdpPingAvg *float32 `protobuf:"fixed32,8,opt,name=udp_ping_avg" json:"udp_ping_avg,omitempty"` + // UDP ping variance. + UdpPingVar *float32 `protobuf:"fixed32,9,opt,name=udp_ping_var" json:"udp_ping_var,omitempty"` + // TCP ping average. + TcpPingAvg *float32 `protobuf:"fixed32,10,opt,name=tcp_ping_avg" json:"tcp_ping_avg,omitempty"` + // TCP ping variance. + TcpPingVar *float32 `protobuf:"fixed32,11,opt,name=tcp_ping_var" json:"tcp_ping_var,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Ping) Reset() { *m = Ping{} } +func (m *Ping) String() string { return proto.CompactTextString(m) } +func (*Ping) ProtoMessage() {} + +func (m *Ping) GetTimestamp() uint64 { + if m != nil && m.Timestamp != nil { + return *m.Timestamp + } + return 0 +} + +func (m *Ping) GetGood() uint32 { + if m != nil && m.Good != nil { + return *m.Good + } + return 0 +} + +func (m *Ping) GetLate() uint32 { + if m != nil && m.Late != nil { + return *m.Late + } + return 0 +} + +func (m *Ping) GetLost() uint32 { + if m != nil && m.Lost != nil { + return *m.Lost + } + return 0 +} + +func (m *Ping) GetResync() uint32 { + if m != nil && m.Resync != nil { + return *m.Resync + } + return 0 +} + +func (m *Ping) GetUdpPackets() uint32 { + if m != nil && m.UdpPackets != nil { + return *m.UdpPackets + } + return 0 +} + +func (m *Ping) GetTcpPackets() uint32 { + if m != nil && m.TcpPackets != nil { + return *m.TcpPackets + } + return 0 +} + +func (m *Ping) GetUdpPingAvg() float32 { + if m != nil && m.UdpPingAvg != nil { + return *m.UdpPingAvg + } + return 0 +} + +func (m *Ping) GetUdpPingVar() float32 { + if m != nil && m.UdpPingVar != nil { + return *m.UdpPingVar + } + return 0 +} + +func (m *Ping) GetTcpPingAvg() float32 { + if m != nil && m.TcpPingAvg != nil { + return *m.TcpPingAvg + } + return 0 +} + +func (m *Ping) GetTcpPingVar() float32 { + if m != nil && m.TcpPingVar != nil { + return *m.TcpPingVar + } + return 0 +} + +// Sent by the server when it rejects the user connection. +type Reject struct { + // Rejection type. + Type *Reject_RejectType `protobuf:"varint,1,opt,name=type,enum=MumbleProto.Reject_RejectType" json:"type,omitempty"` + // Human readable rejection reason. + Reason *string `protobuf:"bytes,2,opt,name=reason" json:"reason,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Reject) Reset() { *m = Reject{} } +func (m *Reject) String() string { return proto.CompactTextString(m) } +func (*Reject) ProtoMessage() {} + +func (m *Reject) GetType() Reject_RejectType { + if m != nil && m.Type != nil { + return *m.Type + } + return Reject_None +} + +func (m *Reject) GetReason() string { + if m != nil && m.Reason != nil { + return *m.Reason + } + return "" +} + +// ServerSync message is sent by the server when it has authenticated the user +// and finished synchronizing the server state. +type ServerSync struct { + // The session of the current user. + Session *uint32 `protobuf:"varint,1,opt,name=session" json:"session,omitempty"` + // Maximum bandwidth that the user should use. + MaxBandwidth *uint32 `protobuf:"varint,2,opt,name=max_bandwidth" json:"max_bandwidth,omitempty"` + // Server welcome text. + WelcomeText *string `protobuf:"bytes,3,opt,name=welcome_text" json:"welcome_text,omitempty"` + // Current user permissions TODO: Confirm?? + Permissions *uint64 `protobuf:"varint,4,opt,name=permissions" json:"permissions,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ServerSync) Reset() { *m = ServerSync{} } +func (m *ServerSync) String() string { return proto.CompactTextString(m) } +func (*ServerSync) ProtoMessage() {} + +func (m *ServerSync) GetSession() uint32 { + if m != nil && m.Session != nil { + return *m.Session + } + return 0 +} + +func (m *ServerSync) GetMaxBandwidth() uint32 { + if m != nil && m.MaxBandwidth != nil { + return *m.MaxBandwidth + } + return 0 +} + +func (m *ServerSync) GetWelcomeText() string { + if m != nil && m.WelcomeText != nil { + return *m.WelcomeText + } + return "" +} + +func (m *ServerSync) GetPermissions() uint64 { + if m != nil && m.Permissions != nil { + return *m.Permissions + } + return 0 +} + +// Sent by the client when it wants a channel removed. Sent by the server when +// a channel has been removed and clients should be notified. +type ChannelRemove struct { + ChannelId *uint32 `protobuf:"varint,1,req,name=channel_id" json:"channel_id,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ChannelRemove) Reset() { *m = ChannelRemove{} } +func (m *ChannelRemove) String() string { return proto.CompactTextString(m) } +func (*ChannelRemove) ProtoMessage() {} + +func (m *ChannelRemove) GetChannelId() uint32 { + if m != nil && m.ChannelId != nil { + return *m.ChannelId + } + return 0 +} + +// Used to communicate channel properties between the client and the server. +// Sent by the server during the login process or when channel properties are +// updated. Client may use this message to update said channel properties. +type ChannelState struct { + // Unique ID for the channel within the server. + ChannelId *uint32 `protobuf:"varint,1,opt,name=channel_id" json:"channel_id,omitempty"` + // channel_id of the parent channel. + Parent *uint32 `protobuf:"varint,2,opt,name=parent" json:"parent,omitempty"` + // UTF-8 encoded channel name. + Name *string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"` + // A collection of channel id values of the linked channels. Absent during + // the first channel listing. + Links []uint32 `protobuf:"varint,4,rep,name=links" json:"links,omitempty"` + // UTF-8 encoded channel description. Only if the description is less than + // 128 bytes + Description *string `protobuf:"bytes,5,opt,name=description" json:"description,omitempty"` + // A collection of channel_id values that should be added to links. + LinksAdd []uint32 `protobuf:"varint,6,rep,name=links_add" json:"links_add,omitempty"` + // A collection of channel_id values that should be removed from links. + LinksRemove []uint32 `protobuf:"varint,7,rep,name=links_remove" json:"links_remove,omitempty"` + // True if the channel is temporary. + Temporary *bool `protobuf:"varint,8,opt,name=temporary,def=0" json:"temporary,omitempty"` + // Position weight to tweak the channel position in the channel list. + Position *int32 `protobuf:"varint,9,opt,name=position,def=0" json:"position,omitempty"` + // SHA1 hash of the description if the description is 128 bytes or more. + DescriptionHash []byte `protobuf:"bytes,10,opt,name=description_hash" json:"description_hash,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ChannelState) Reset() { *m = ChannelState{} } +func (m *ChannelState) String() string { return proto.CompactTextString(m) } +func (*ChannelState) ProtoMessage() {} + +const Default_ChannelState_Temporary bool = false +const Default_ChannelState_Position int32 = 0 + +func (m *ChannelState) GetChannelId() uint32 { + if m != nil && m.ChannelId != nil { + return *m.ChannelId + } + return 0 +} + +func (m *ChannelState) GetParent() uint32 { + if m != nil && m.Parent != nil { + return *m.Parent + } + return 0 +} + +func (m *ChannelState) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *ChannelState) GetLinks() []uint32 { + if m != nil { + return m.Links + } + return nil +} + +func (m *ChannelState) GetDescription() string { + if m != nil && m.Description != nil { + return *m.Description + } + return "" +} + +func (m *ChannelState) GetLinksAdd() []uint32 { + if m != nil { + return m.LinksAdd + } + return nil +} + +func (m *ChannelState) GetLinksRemove() []uint32 { + if m != nil { + return m.LinksRemove + } + return nil +} + +func (m *ChannelState) GetTemporary() bool { + if m != nil && m.Temporary != nil { + return *m.Temporary + } + return Default_ChannelState_Temporary +} + +func (m *ChannelState) GetPosition() int32 { + if m != nil && m.Position != nil { + return *m.Position + } + return Default_ChannelState_Position +} + +func (m *ChannelState) GetDescriptionHash() []byte { + if m != nil { + return m.DescriptionHash + } + return nil +} + +// Used to communicate user leaving or being kicked. May be sent by the client +// when it attempts to kick a user. Sent by the server when it informs the +// clients that a user is not present anymore. +type UserRemove struct { + // The user who is being kicked, identified by their session, not present + // when no one is being kicked. + Session *uint32 `protobuf:"varint,1,req,name=session" json:"session,omitempty"` + // The user who initiated the removal. Either the user who performs the kick + // or the user who is currently leaving. + Actor *uint32 `protobuf:"varint,2,opt,name=actor" json:"actor,omitempty"` + // Reason for the kick, stored as the ban reason if the user is banned. + Reason *string `protobuf:"bytes,3,opt,name=reason" json:"reason,omitempty"` + // True if the kick should result in a ban. + Ban *bool `protobuf:"varint,4,opt,name=ban" json:"ban,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *UserRemove) Reset() { *m = UserRemove{} } +func (m *UserRemove) String() string { return proto.CompactTextString(m) } +func (*UserRemove) ProtoMessage() {} + +func (m *UserRemove) GetSession() uint32 { + if m != nil && m.Session != nil { + return *m.Session + } + return 0 +} + +func (m *UserRemove) GetActor() uint32 { + if m != nil && m.Actor != nil { + return *m.Actor + } + return 0 +} + +func (m *UserRemove) GetReason() string { + if m != nil && m.Reason != nil { + return *m.Reason + } + return "" +} + +func (m *UserRemove) GetBan() bool { + if m != nil && m.Ban != nil { + return *m.Ban + } + return false +} + +// Sent by the server when it communicates new and changed users to client. +// First seen during login procedure. May be sent by the client when it wishes +// to alter its state. +type UserState struct { + // Unique user session ID of the user whose state this is, may change on + // reconnect. + Session *uint32 `protobuf:"varint,1,opt,name=session" json:"session,omitempty"` + // The session of the user who is updating this user. + Actor *uint32 `protobuf:"varint,2,opt,name=actor" json:"actor,omitempty"` + // User name, UTF-8 encoded. + Name *string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"` + // Registered user ID if the user is registered. + UserId *uint32 `protobuf:"varint,4,opt,name=user_id" json:"user_id,omitempty"` + // Channel on which the user is. + ChannelId *uint32 `protobuf:"varint,5,opt,name=channel_id" json:"channel_id,omitempty"` + // True if the user is muted by admin. + Mute *bool `protobuf:"varint,6,opt,name=mute" json:"mute,omitempty"` + // True if the user is deafened by admin. + Deaf *bool `protobuf:"varint,7,opt,name=deaf" json:"deaf,omitempty"` + // True if the user has been suppressed from talking by a reason other than + // being muted. + Suppress *bool `protobuf:"varint,8,opt,name=suppress" json:"suppress,omitempty"` + // True if the user has muted self. + SelfMute *bool `protobuf:"varint,9,opt,name=self_mute" json:"self_mute,omitempty"` + // True if the user has deafened self. + SelfDeaf *bool `protobuf:"varint,10,opt,name=self_deaf" json:"self_deaf,omitempty"` + // User image if it is less than 128 bytes. + Texture []byte `protobuf:"bytes,11,opt,name=texture" json:"texture,omitempty"` + // TODO ?? + PluginContext []byte `protobuf:"bytes,12,opt,name=plugin_context" json:"plugin_context,omitempty"` + // TODO ?? + PluginIdentity *string `protobuf:"bytes,13,opt,name=plugin_identity" json:"plugin_identity,omitempty"` + // User comment if it is less than 128 bytes. + Comment *string `protobuf:"bytes,14,opt,name=comment" json:"comment,omitempty"` + // The hash of the user certificate. + Hash *string `protobuf:"bytes,15,opt,name=hash" json:"hash,omitempty"` + // SHA1 hash of the user comment if it 128 bytes or more. + CommentHash []byte `protobuf:"bytes,16,opt,name=comment_hash" json:"comment_hash,omitempty"` + // SHA1 hash of the user picture if it 128 bytes or more. + TextureHash []byte `protobuf:"bytes,17,opt,name=texture_hash" json:"texture_hash,omitempty"` + // True if the user is a priority speaker. + PrioritySpeaker *bool `protobuf:"varint,18,opt,name=priority_speaker" json:"priority_speaker,omitempty"` + // True if the user is currently recording. + Recording *bool `protobuf:"varint,19,opt,name=recording" json:"recording,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *UserState) Reset() { *m = UserState{} } +func (m *UserState) String() string { return proto.CompactTextString(m) } +func (*UserState) ProtoMessage() {} + +func (m *UserState) GetSession() uint32 { + if m != nil && m.Session != nil { + return *m.Session + } + return 0 +} + +func (m *UserState) GetActor() uint32 { + if m != nil && m.Actor != nil { + return *m.Actor + } + return 0 +} + +func (m *UserState) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *UserState) GetUserId() uint32 { + if m != nil && m.UserId != nil { + return *m.UserId + } + return 0 +} + +func (m *UserState) GetChannelId() uint32 { + if m != nil && m.ChannelId != nil { + return *m.ChannelId + } + return 0 +} + +func (m *UserState) GetMute() bool { + if m != nil && m.Mute != nil { + return *m.Mute + } + return false +} + +func (m *UserState) GetDeaf() bool { + if m != nil && m.Deaf != nil { + return *m.Deaf + } + return false +} + +func (m *UserState) GetSuppress() bool { + if m != nil && m.Suppress != nil { + return *m.Suppress + } + return false +} + +func (m *UserState) GetSelfMute() bool { + if m != nil && m.SelfMute != nil { + return *m.SelfMute + } + return false +} + +func (m *UserState) GetSelfDeaf() bool { + if m != nil && m.SelfDeaf != nil { + return *m.SelfDeaf + } + return false +} + +func (m *UserState) GetTexture() []byte { + if m != nil { + return m.Texture + } + return nil +} + +func (m *UserState) GetPluginContext() []byte { + if m != nil { + return m.PluginContext + } + return nil +} + +func (m *UserState) GetPluginIdentity() string { + if m != nil && m.PluginIdentity != nil { + return *m.PluginIdentity + } + return "" +} + +func (m *UserState) GetComment() string { + if m != nil && m.Comment != nil { + return *m.Comment + } + return "" +} + +func (m *UserState) GetHash() string { + if m != nil && m.Hash != nil { + return *m.Hash + } + return "" +} + +func (m *UserState) GetCommentHash() []byte { + if m != nil { + return m.CommentHash + } + return nil +} + +func (m *UserState) GetTextureHash() []byte { + if m != nil { + return m.TextureHash + } + return nil +} + +func (m *UserState) GetPrioritySpeaker() bool { + if m != nil && m.PrioritySpeaker != nil { + return *m.PrioritySpeaker + } + return false +} + +func (m *UserState) GetRecording() bool { + if m != nil && m.Recording != nil { + return *m.Recording + } + return false +} + +// Relays information on the bans. The client may send the BanList message to +// either modify the list of bans or query them from the server. The server +// sends this list only after a client queries for it. +type BanList struct { + // List of ban entries currently in place. + Bans []*BanList_BanEntry `protobuf:"bytes,1,rep,name=bans" json:"bans,omitempty"` + // True if the server should return the list, false if it should replace old + // ban list with the one provided. + Query *bool `protobuf:"varint,2,opt,name=query,def=0" json:"query,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *BanList) Reset() { *m = BanList{} } +func (m *BanList) String() string { return proto.CompactTextString(m) } +func (*BanList) ProtoMessage() {} + +const Default_BanList_Query bool = false + +func (m *BanList) GetBans() []*BanList_BanEntry { + if m != nil { + return m.Bans + } + return nil +} + +func (m *BanList) GetQuery() bool { + if m != nil && m.Query != nil { + return *m.Query + } + return Default_BanList_Query +} + +type BanList_BanEntry struct { + // Banned IP address. + Address []byte `protobuf:"bytes,1,req,name=address" json:"address,omitempty"` + // The length of the subnet mask for the ban. + Mask *uint32 `protobuf:"varint,2,req,name=mask" json:"mask,omitempty"` + // User name for identification purposes (does not affect the ban). + Name *string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"` + // TODO ?? + Hash *string `protobuf:"bytes,4,opt,name=hash" json:"hash,omitempty"` + // Reason for the ban (does not affect the ban). + Reason *string `protobuf:"bytes,5,opt,name=reason" json:"reason,omitempty"` + // Ban start time. + Start *string `protobuf:"bytes,6,opt,name=start" json:"start,omitempty"` + // Ban duration in seconds. + Duration *uint32 `protobuf:"varint,7,opt,name=duration" json:"duration,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *BanList_BanEntry) Reset() { *m = BanList_BanEntry{} } +func (m *BanList_BanEntry) String() string { return proto.CompactTextString(m) } +func (*BanList_BanEntry) ProtoMessage() {} + +func (m *BanList_BanEntry) GetAddress() []byte { + if m != nil { + return m.Address + } + return nil +} + +func (m *BanList_BanEntry) GetMask() uint32 { + if m != nil && m.Mask != nil { + return *m.Mask + } + return 0 +} + +func (m *BanList_BanEntry) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *BanList_BanEntry) GetHash() string { + if m != nil && m.Hash != nil { + return *m.Hash + } + return "" +} + +func (m *BanList_BanEntry) GetReason() string { + if m != nil && m.Reason != nil { + return *m.Reason + } + return "" +} + +func (m *BanList_BanEntry) GetStart() string { + if m != nil && m.Start != nil { + return *m.Start + } + return "" +} + +func (m *BanList_BanEntry) GetDuration() uint32 { + if m != nil && m.Duration != nil { + return *m.Duration + } + return 0 +} + +// Used to send and broadcast text messages. +type TextMessage struct { + // The message sender, identified by its session. + Actor *uint32 `protobuf:"varint,1,opt,name=actor" json:"actor,omitempty"` + // Target users for the message, identified by their session. + Session []uint32 `protobuf:"varint,2,rep,name=session" json:"session,omitempty"` + // The channels to which the message is sent, identified by their + // channel_ids. + ChannelId []uint32 `protobuf:"varint,3,rep,name=channel_id" json:"channel_id,omitempty"` + // The root channels when sending message recursively to several channels, + // identified by their channel_ids. + TreeId []uint32 `protobuf:"varint,4,rep,name=tree_id" json:"tree_id,omitempty"` + // The UTF-8 encoded message. May be HTML if the server allows. + Message *string `protobuf:"bytes,5,req,name=message" json:"message,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *TextMessage) Reset() { *m = TextMessage{} } +func (m *TextMessage) String() string { return proto.CompactTextString(m) } +func (*TextMessage) ProtoMessage() {} + +func (m *TextMessage) GetActor() uint32 { + if m != nil && m.Actor != nil { + return *m.Actor + } + return 0 +} + +func (m *TextMessage) GetSession() []uint32 { + if m != nil { + return m.Session + } + return nil +} + +func (m *TextMessage) GetChannelId() []uint32 { + if m != nil { + return m.ChannelId + } + return nil +} + +func (m *TextMessage) GetTreeId() []uint32 { + if m != nil { + return m.TreeId + } + return nil +} + +func (m *TextMessage) GetMessage() string { + if m != nil && m.Message != nil { + return *m.Message + } + return "" +} + +type PermissionDenied struct { + // The denied permission when type is Permission. + Permission *uint32 `protobuf:"varint,1,opt,name=permission" json:"permission,omitempty"` + // channel_id for the channel where the permission was denied when type is + // Permission. + ChannelId *uint32 `protobuf:"varint,2,opt,name=channel_id" json:"channel_id,omitempty"` + // The user who was denied permissions, identified by session. + Session *uint32 `protobuf:"varint,3,opt,name=session" json:"session,omitempty"` + // Textual reason for the denial. + Reason *string `protobuf:"bytes,4,opt,name=reason" json:"reason,omitempty"` + // Type of the denial. + Type *PermissionDenied_DenyType `protobuf:"varint,5,opt,name=type,enum=MumbleProto.PermissionDenied_DenyType" json:"type,omitempty"` + // The name that is invalid when type is UserName. + Name *string `protobuf:"bytes,6,opt,name=name" json:"name,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PermissionDenied) Reset() { *m = PermissionDenied{} } +func (m *PermissionDenied) String() string { return proto.CompactTextString(m) } +func (*PermissionDenied) ProtoMessage() {} + +func (m *PermissionDenied) GetPermission() uint32 { + if m != nil && m.Permission != nil { + return *m.Permission + } + return 0 +} + +func (m *PermissionDenied) GetChannelId() uint32 { + if m != nil && m.ChannelId != nil { + return *m.ChannelId + } + return 0 +} + +func (m *PermissionDenied) GetSession() uint32 { + if m != nil && m.Session != nil { + return *m.Session + } + return 0 +} + +func (m *PermissionDenied) GetReason() string { + if m != nil && m.Reason != nil { + return *m.Reason + } + return "" +} + +func (m *PermissionDenied) GetType() PermissionDenied_DenyType { + if m != nil && m.Type != nil { + return *m.Type + } + return PermissionDenied_Text +} + +func (m *PermissionDenied) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +type ACL struct { + // Channel ID of the channel this message affects. + ChannelId *uint32 `protobuf:"varint,1,req,name=channel_id" json:"channel_id,omitempty"` + // True if the channel inherits its parent's ACLs. + InheritAcls *bool `protobuf:"varint,2,opt,name=inherit_acls,def=1" json:"inherit_acls,omitempty"` + // User group specifications. + Groups []*ACL_ChanGroup `protobuf:"bytes,3,rep,name=groups" json:"groups,omitempty"` + // ACL specifications. + Acls []*ACL_ChanACL `protobuf:"bytes,4,rep,name=acls" json:"acls,omitempty"` + // True if the message is a query for ACLs instead of setting them. + Query *bool `protobuf:"varint,5,opt,name=query,def=0" json:"query,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ACL) Reset() { *m = ACL{} } +func (m *ACL) String() string { return proto.CompactTextString(m) } +func (*ACL) ProtoMessage() {} + +const Default_ACL_InheritAcls bool = true +const Default_ACL_Query bool = false + +func (m *ACL) GetChannelId() uint32 { + if m != nil && m.ChannelId != nil { + return *m.ChannelId + } + return 0 +} + +func (m *ACL) GetInheritAcls() bool { + if m != nil && m.InheritAcls != nil { + return *m.InheritAcls + } + return Default_ACL_InheritAcls +} + +func (m *ACL) GetGroups() []*ACL_ChanGroup { + if m != nil { + return m.Groups + } + return nil +} + +func (m *ACL) GetAcls() []*ACL_ChanACL { + if m != nil { + return m.Acls + } + return nil +} + +func (m *ACL) GetQuery() bool { + if m != nil && m.Query != nil { + return *m.Query + } + return Default_ACL_Query +} + +type ACL_ChanGroup struct { + // Name of the channel group, UTF-8 encoded. + Name *string `protobuf:"bytes,1,req,name=name" json:"name,omitempty"` + // True if the group has been inherited from the parent (Read only). + Inherited *bool `protobuf:"varint,2,opt,name=inherited,def=1" json:"inherited,omitempty"` + // True if the group members are inherited. + Inherit *bool `protobuf:"varint,3,opt,name=inherit,def=1" json:"inherit,omitempty"` + // True if the group can be inherited by sub channels. + Inheritable *bool `protobuf:"varint,4,opt,name=inheritable,def=1" json:"inheritable,omitempty"` + // Users explicitly included in this group, identified by user_id. + Add []uint32 `protobuf:"varint,5,rep,name=add" json:"add,omitempty"` + // Users explicitly removed from this group in this channel if the group + // has been inherited, identified by user_id. + Remove []uint32 `protobuf:"varint,6,rep,name=remove" json:"remove,omitempty"` + // Users inherited, identified by user_id. + InheritedMembers []uint32 `protobuf:"varint,7,rep,name=inherited_members" json:"inherited_members,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ACL_ChanGroup) Reset() { *m = ACL_ChanGroup{} } +func (m *ACL_ChanGroup) String() string { return proto.CompactTextString(m) } +func (*ACL_ChanGroup) ProtoMessage() {} + +const Default_ACL_ChanGroup_Inherited bool = true +const Default_ACL_ChanGroup_Inherit bool = true +const Default_ACL_ChanGroup_Inheritable bool = true + +func (m *ACL_ChanGroup) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *ACL_ChanGroup) GetInherited() bool { + if m != nil && m.Inherited != nil { + return *m.Inherited + } + return Default_ACL_ChanGroup_Inherited +} + +func (m *ACL_ChanGroup) GetInherit() bool { + if m != nil && m.Inherit != nil { + return *m.Inherit + } + return Default_ACL_ChanGroup_Inherit +} + +func (m *ACL_ChanGroup) GetInheritable() bool { + if m != nil && m.Inheritable != nil { + return *m.Inheritable + } + return Default_ACL_ChanGroup_Inheritable +} + +func (m *ACL_ChanGroup) GetAdd() []uint32 { + if m != nil { + return m.Add + } + return nil +} + +func (m *ACL_ChanGroup) GetRemove() []uint32 { + if m != nil { + return m.Remove + } + return nil +} + +func (m *ACL_ChanGroup) GetInheritedMembers() []uint32 { + if m != nil { + return m.InheritedMembers + } + return nil +} + +type ACL_ChanACL struct { + // True if this ACL applies to the current channel. + ApplyHere *bool `protobuf:"varint,1,opt,name=apply_here,def=1" json:"apply_here,omitempty"` + // True if this ACL applies to the sub channels. + ApplySubs *bool `protobuf:"varint,2,opt,name=apply_subs,def=1" json:"apply_subs,omitempty"` + // True if the ACL has been inherited from the parent. + Inherited *bool `protobuf:"varint,3,opt,name=inherited,def=1" json:"inherited,omitempty"` + // ID of the user that is affected by this ACL. + UserId *uint32 `protobuf:"varint,4,opt,name=user_id" json:"user_id,omitempty"` + // ID of the group that is affected by this ACL. + Group *string `protobuf:"bytes,5,opt,name=group" json:"group,omitempty"` + // Bit flag field of the permissions granted by this ACL. + Grant *uint32 `protobuf:"varint,6,opt,name=grant" json:"grant,omitempty"` + // Bit flag field of the permissions denied by this ACL. + Deny *uint32 `protobuf:"varint,7,opt,name=deny" json:"deny,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ACL_ChanACL) Reset() { *m = ACL_ChanACL{} } +func (m *ACL_ChanACL) String() string { return proto.CompactTextString(m) } +func (*ACL_ChanACL) ProtoMessage() {} + +const Default_ACL_ChanACL_ApplyHere bool = true +const Default_ACL_ChanACL_ApplySubs bool = true +const Default_ACL_ChanACL_Inherited bool = true + +func (m *ACL_ChanACL) GetApplyHere() bool { + if m != nil && m.ApplyHere != nil { + return *m.ApplyHere + } + return Default_ACL_ChanACL_ApplyHere +} + +func (m *ACL_ChanACL) GetApplySubs() bool { + if m != nil && m.ApplySubs != nil { + return *m.ApplySubs + } + return Default_ACL_ChanACL_ApplySubs +} + +func (m *ACL_ChanACL) GetInherited() bool { + if m != nil && m.Inherited != nil { + return *m.Inherited + } + return Default_ACL_ChanACL_Inherited +} + +func (m *ACL_ChanACL) GetUserId() uint32 { + if m != nil && m.UserId != nil { + return *m.UserId + } + return 0 +} + +func (m *ACL_ChanACL) GetGroup() string { + if m != nil && m.Group != nil { + return *m.Group + } + return "" +} + +func (m *ACL_ChanACL) GetGrant() uint32 { + if m != nil && m.Grant != nil { + return *m.Grant + } + return 0 +} + +func (m *ACL_ChanACL) GetDeny() uint32 { + if m != nil && m.Deny != nil { + return *m.Deny + } + return 0 +} + +// Client may use this message to refresh its registered user information. The +// client should fill the IDs or Names of the users it wants to refresh. The +// server fills the missing parts and sends the message back. +type QueryUsers struct { + // user_ids. + Ids []uint32 `protobuf:"varint,1,rep,name=ids" json:"ids,omitempty"` + // User names in the same order as ids. + Names []string `protobuf:"bytes,2,rep,name=names" json:"names,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *QueryUsers) Reset() { *m = QueryUsers{} } +func (m *QueryUsers) String() string { return proto.CompactTextString(m) } +func (*QueryUsers) ProtoMessage() {} + +func (m *QueryUsers) GetIds() []uint32 { + if m != nil { + return m.Ids + } + return nil +} + +func (m *QueryUsers) GetNames() []string { + if m != nil { + return m.Names + } + return nil +} + +// Used to initialize and resync the UDP encryption. Either side may request a +// resync by sending the message without any values filled. The resync is +// performed by sending the message with only the client or server nonce +// filled. +type CryptSetup struct { + // Encryption key. + Key []byte `protobuf:"bytes,1,opt,name=key" json:"key,omitempty"` + // Client nonce. + ClientNonce []byte `protobuf:"bytes,2,opt,name=client_nonce" json:"client_nonce,omitempty"` + // Server nonce. + ServerNonce []byte `protobuf:"bytes,3,opt,name=server_nonce" json:"server_nonce,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *CryptSetup) Reset() { *m = CryptSetup{} } +func (m *CryptSetup) String() string { return proto.CompactTextString(m) } +func (*CryptSetup) ProtoMessage() {} + +func (m *CryptSetup) GetKey() []byte { + if m != nil { + return m.Key + } + return nil +} + +func (m *CryptSetup) GetClientNonce() []byte { + if m != nil { + return m.ClientNonce + } + return nil +} + +func (m *CryptSetup) GetServerNonce() []byte { + if m != nil { + return m.ServerNonce + } + return nil +} + +type ContextActionModify struct { + // The action name. + Action *string `protobuf:"bytes,1,req,name=action" json:"action,omitempty"` + // The display name of the action. + Text *string `protobuf:"bytes,2,opt,name=text" json:"text,omitempty"` + // Context bit flags defining where the action should be displayed. + Context *uint32 `protobuf:"varint,3,opt,name=context" json:"context,omitempty"` + Operation *ContextActionModify_Operation `protobuf:"varint,4,opt,name=operation,enum=MumbleProto.ContextActionModify_Operation" json:"operation,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ContextActionModify) Reset() { *m = ContextActionModify{} } +func (m *ContextActionModify) String() string { return proto.CompactTextString(m) } +func (*ContextActionModify) ProtoMessage() {} + +func (m *ContextActionModify) GetAction() string { + if m != nil && m.Action != nil { + return *m.Action + } + return "" +} + +func (m *ContextActionModify) GetText() string { + if m != nil && m.Text != nil { + return *m.Text + } + return "" +} + +func (m *ContextActionModify) GetContext() uint32 { + if m != nil && m.Context != nil { + return *m.Context + } + return 0 +} + +func (m *ContextActionModify) GetOperation() ContextActionModify_Operation { + if m != nil && m.Operation != nil { + return *m.Operation + } + return ContextActionModify_Add +} + +// Sent by the client when it wants to initiate a Context action. +type ContextAction struct { + // The target User for the action, identified by session. + Session *uint32 `protobuf:"varint,1,opt,name=session" json:"session,omitempty"` + // The target Channel for the action, identified by channel_id. + ChannelId *uint32 `protobuf:"varint,2,opt,name=channel_id" json:"channel_id,omitempty"` + // The action that should be executed. + Action *string `protobuf:"bytes,3,req,name=action" json:"action,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ContextAction) Reset() { *m = ContextAction{} } +func (m *ContextAction) String() string { return proto.CompactTextString(m) } +func (*ContextAction) ProtoMessage() {} + +func (m *ContextAction) GetSession() uint32 { + if m != nil && m.Session != nil { + return *m.Session + } + return 0 +} + +func (m *ContextAction) GetChannelId() uint32 { + if m != nil && m.ChannelId != nil { + return *m.ChannelId + } + return 0 +} + +func (m *ContextAction) GetAction() string { + if m != nil && m.Action != nil { + return *m.Action + } + return "" +} + +// Lists the registered users. +type UserList struct { + // A list of registered users. + Users []*UserList_User `protobuf:"bytes,1,rep,name=users" json:"users,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *UserList) Reset() { *m = UserList{} } +func (m *UserList) String() string { return proto.CompactTextString(m) } +func (*UserList) ProtoMessage() {} + +func (m *UserList) GetUsers() []*UserList_User { + if m != nil { + return m.Users + } + return nil +} + +type UserList_User struct { + // Registered user ID. + UserId *uint32 `protobuf:"varint,1,req,name=user_id" json:"user_id,omitempty"` + // Registered user name. + Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` + LastSeen *string `protobuf:"bytes,3,opt,name=last_seen" json:"last_seen,omitempty"` + LastChannel *uint32 `protobuf:"varint,4,opt,name=last_channel" json:"last_channel,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *UserList_User) Reset() { *m = UserList_User{} } +func (m *UserList_User) String() string { return proto.CompactTextString(m) } +func (*UserList_User) ProtoMessage() {} + +func (m *UserList_User) GetUserId() uint32 { + if m != nil && m.UserId != nil { + return *m.UserId + } + return 0 +} + +func (m *UserList_User) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *UserList_User) GetLastSeen() string { + if m != nil && m.LastSeen != nil { + return *m.LastSeen + } + return "" +} + +func (m *UserList_User) GetLastChannel() uint32 { + if m != nil && m.LastChannel != nil { + return *m.LastChannel + } + return 0 +} + +// Sent by the client when it wants to register or clear whisper targets. +// +// Note: The first available target ID is 1 as 0 is reserved for normal +// talking. Maximum target ID is 30. +type VoiceTarget struct { + // Voice target ID. + Id *uint32 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"` + // The receivers that this voice target includes. + Targets []*VoiceTarget_Target `protobuf:"bytes,2,rep,name=targets" json:"targets,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *VoiceTarget) Reset() { *m = VoiceTarget{} } +func (m *VoiceTarget) String() string { return proto.CompactTextString(m) } +func (*VoiceTarget) ProtoMessage() {} + +func (m *VoiceTarget) GetId() uint32 { + if m != nil && m.Id != nil { + return *m.Id + } + return 0 +} + +func (m *VoiceTarget) GetTargets() []*VoiceTarget_Target { + if m != nil { + return m.Targets + } + return nil +} + +type VoiceTarget_Target struct { + // Users that are included as targets. + Session []uint32 `protobuf:"varint,1,rep,name=session" json:"session,omitempty"` + // Channels that are included as targets. + ChannelId *uint32 `protobuf:"varint,2,opt,name=channel_id" json:"channel_id,omitempty"` + // TODO ?? + Group *string `protobuf:"bytes,3,opt,name=group" json:"group,omitempty"` + // True if the voice should follow links from the specified channel. + Links *bool `protobuf:"varint,4,opt,name=links,def=0" json:"links,omitempty"` + // True if the voice should also be sent to children of the specific + // channel. + Children *bool `protobuf:"varint,5,opt,name=children,def=0" json:"children,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *VoiceTarget_Target) Reset() { *m = VoiceTarget_Target{} } +func (m *VoiceTarget_Target) String() string { return proto.CompactTextString(m) } +func (*VoiceTarget_Target) ProtoMessage() {} + +const Default_VoiceTarget_Target_Links bool = false +const Default_VoiceTarget_Target_Children bool = false + +func (m *VoiceTarget_Target) GetSession() []uint32 { + if m != nil { + return m.Session + } + return nil +} + +func (m *VoiceTarget_Target) GetChannelId() uint32 { + if m != nil && m.ChannelId != nil { + return *m.ChannelId + } + return 0 +} + +func (m *VoiceTarget_Target) GetGroup() string { + if m != nil && m.Group != nil { + return *m.Group + } + return "" +} + +func (m *VoiceTarget_Target) GetLinks() bool { + if m != nil && m.Links != nil { + return *m.Links + } + return Default_VoiceTarget_Target_Links +} + +func (m *VoiceTarget_Target) GetChildren() bool { + if m != nil && m.Children != nil { + return *m.Children + } + return Default_VoiceTarget_Target_Children +} + +// Sent by the client when it wants permissions for a certain channel. Sent by +// the server when it replies to the query or wants the user to resync all +// channel permissions. +type PermissionQuery struct { + // channel_id of the channel for which the permissions are queried. + ChannelId *uint32 `protobuf:"varint,1,opt,name=channel_id" json:"channel_id,omitempty"` + // Channel permissions. + Permissions *uint32 `protobuf:"varint,2,opt,name=permissions" json:"permissions,omitempty"` + // True if the client should drop its current permission information for all + // channels. + Flush *bool `protobuf:"varint,3,opt,name=flush,def=0" json:"flush,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PermissionQuery) Reset() { *m = PermissionQuery{} } +func (m *PermissionQuery) String() string { return proto.CompactTextString(m) } +func (*PermissionQuery) ProtoMessage() {} + +const Default_PermissionQuery_Flush bool = false + +func (m *PermissionQuery) GetChannelId() uint32 { + if m != nil && m.ChannelId != nil { + return *m.ChannelId + } + return 0 +} + +func (m *PermissionQuery) GetPermissions() uint32 { + if m != nil && m.Permissions != nil { + return *m.Permissions + } + return 0 +} + +func (m *PermissionQuery) GetFlush() bool { + if m != nil && m.Flush != nil { + return *m.Flush + } + return Default_PermissionQuery_Flush +} + +// Sent by the server to notify the users of the version of the CELT codec they +// should use. This may change during the connection when new users join. +type CodecVersion struct { + // The version of the CELT Alpha codec. + Alpha *int32 `protobuf:"varint,1,req,name=alpha" json:"alpha,omitempty"` + // The version of the CELT Beta codec. + Beta *int32 `protobuf:"varint,2,req,name=beta" json:"beta,omitempty"` + // True if the user should prefer Alpha over Beta. + PreferAlpha *bool `protobuf:"varint,3,req,name=prefer_alpha,def=1" json:"prefer_alpha,omitempty"` + Opus *bool `protobuf:"varint,4,opt,name=opus,def=0" json:"opus,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *CodecVersion) Reset() { *m = CodecVersion{} } +func (m *CodecVersion) String() string { return proto.CompactTextString(m) } +func (*CodecVersion) ProtoMessage() {} + +const Default_CodecVersion_PreferAlpha bool = true +const Default_CodecVersion_Opus bool = false + +func (m *CodecVersion) GetAlpha() int32 { + if m != nil && m.Alpha != nil { + return *m.Alpha + } + return 0 +} + +func (m *CodecVersion) GetBeta() int32 { + if m != nil && m.Beta != nil { + return *m.Beta + } + return 0 +} + +func (m *CodecVersion) GetPreferAlpha() bool { + if m != nil && m.PreferAlpha != nil { + return *m.PreferAlpha + } + return Default_CodecVersion_PreferAlpha +} + +func (m *CodecVersion) GetOpus() bool { + if m != nil && m.Opus != nil { + return *m.Opus + } + return Default_CodecVersion_Opus +} + +// Used to communicate user stats between the server and clients. +type UserStats struct { + // User whose stats these are. + Session *uint32 `protobuf:"varint,1,opt,name=session" json:"session,omitempty"` + // True if the message contains only mutable stats (packets, ping). + StatsOnly *bool `protobuf:"varint,2,opt,name=stats_only,def=0" json:"stats_only,omitempty"` + // Full user certificate chain of the user certificate in DER format. + Certificates [][]byte `protobuf:"bytes,3,rep,name=certificates" json:"certificates,omitempty"` + // Packet statistics for packets received from the client. + FromClient *UserStats_Stats `protobuf:"bytes,4,opt,name=from_client" json:"from_client,omitempty"` + // Packet statistics for packets sent by the server. + FromServer *UserStats_Stats `protobuf:"bytes,5,opt,name=from_server" json:"from_server,omitempty"` + // Amount of UDP packets sent. + UdpPackets *uint32 `protobuf:"varint,6,opt,name=udp_packets" json:"udp_packets,omitempty"` + // Amount of TCP packets sent. + TcpPackets *uint32 `protobuf:"varint,7,opt,name=tcp_packets" json:"tcp_packets,omitempty"` + // UDP ping average. + UdpPingAvg *float32 `protobuf:"fixed32,8,opt,name=udp_ping_avg" json:"udp_ping_avg,omitempty"` + // UDP ping variance. + UdpPingVar *float32 `protobuf:"fixed32,9,opt,name=udp_ping_var" json:"udp_ping_var,omitempty"` + // TCP ping average. + TcpPingAvg *float32 `protobuf:"fixed32,10,opt,name=tcp_ping_avg" json:"tcp_ping_avg,omitempty"` + // TCP ping variance. + TcpPingVar *float32 `protobuf:"fixed32,11,opt,name=tcp_ping_var" json:"tcp_ping_var,omitempty"` + // Client version. + Version *Version `protobuf:"bytes,12,opt,name=version" json:"version,omitempty"` + // A list of CELT bitstream version constants supported by the client of this + // user. + CeltVersions []int32 `protobuf:"varint,13,rep,name=celt_versions" json:"celt_versions,omitempty"` + // Client IP address. + Address []byte `protobuf:"bytes,14,opt,name=address" json:"address,omitempty"` + // Bandwith used by this client. + Bandwidth *uint32 `protobuf:"varint,15,opt,name=bandwidth" json:"bandwidth,omitempty"` + // Connection duration. + Onlinesecs *uint32 `protobuf:"varint,16,opt,name=onlinesecs" json:"onlinesecs,omitempty"` + // Duration since last activity. + Idlesecs *uint32 `protobuf:"varint,17,opt,name=idlesecs" json:"idlesecs,omitempty"` + // True if the user has a strong certificate. + StrongCertificate *bool `protobuf:"varint,18,opt,name=strong_certificate,def=0" json:"strong_certificate,omitempty"` + Opus *bool `protobuf:"varint,19,opt,name=opus,def=0" json:"opus,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *UserStats) Reset() { *m = UserStats{} } +func (m *UserStats) String() string { return proto.CompactTextString(m) } +func (*UserStats) ProtoMessage() {} + +const Default_UserStats_StatsOnly bool = false +const Default_UserStats_StrongCertificate bool = false +const Default_UserStats_Opus bool = false + +func (m *UserStats) GetSession() uint32 { + if m != nil && m.Session != nil { + return *m.Session + } + return 0 +} + +func (m *UserStats) GetStatsOnly() bool { + if m != nil && m.StatsOnly != nil { + return *m.StatsOnly + } + return Default_UserStats_StatsOnly +} + +func (m *UserStats) GetCertificates() [][]byte { + if m != nil { + return m.Certificates + } + return nil +} + +func (m *UserStats) GetFromClient() *UserStats_Stats { + if m != nil { + return m.FromClient + } + return nil +} + +func (m *UserStats) GetFromServer() *UserStats_Stats { + if m != nil { + return m.FromServer + } + return nil +} + +func (m *UserStats) GetUdpPackets() uint32 { + if m != nil && m.UdpPackets != nil { + return *m.UdpPackets + } + return 0 +} + +func (m *UserStats) GetTcpPackets() uint32 { + if m != nil && m.TcpPackets != nil { + return *m.TcpPackets + } + return 0 +} + +func (m *UserStats) GetUdpPingAvg() float32 { + if m != nil && m.UdpPingAvg != nil { + return *m.UdpPingAvg + } + return 0 +} + +func (m *UserStats) GetUdpPingVar() float32 { + if m != nil && m.UdpPingVar != nil { + return *m.UdpPingVar + } + return 0 +} + +func (m *UserStats) GetTcpPingAvg() float32 { + if m != nil && m.TcpPingAvg != nil { + return *m.TcpPingAvg + } + return 0 +} + +func (m *UserStats) GetTcpPingVar() float32 { + if m != nil && m.TcpPingVar != nil { + return *m.TcpPingVar + } + return 0 +} + +func (m *UserStats) GetVersion() *Version { + if m != nil { + return m.Version + } + return nil +} + +func (m *UserStats) GetCeltVersions() []int32 { + if m != nil { + return m.CeltVersions + } + return nil +} + +func (m *UserStats) GetAddress() []byte { + if m != nil { + return m.Address + } + return nil +} + +func (m *UserStats) GetBandwidth() uint32 { + if m != nil && m.Bandwidth != nil { + return *m.Bandwidth + } + return 0 +} + +func (m *UserStats) GetOnlinesecs() uint32 { + if m != nil && m.Onlinesecs != nil { + return *m.Onlinesecs + } + return 0 +} + +func (m *UserStats) GetIdlesecs() uint32 { + if m != nil && m.Idlesecs != nil { + return *m.Idlesecs + } + return 0 +} + +func (m *UserStats) GetStrongCertificate() bool { + if m != nil && m.StrongCertificate != nil { + return *m.StrongCertificate + } + return Default_UserStats_StrongCertificate +} + +func (m *UserStats) GetOpus() bool { + if m != nil && m.Opus != nil { + return *m.Opus + } + return Default_UserStats_Opus +} + +type UserStats_Stats struct { + // The amount of good packets received. + Good *uint32 `protobuf:"varint,1,opt,name=good" json:"good,omitempty"` + // The amount of late packets received. + Late *uint32 `protobuf:"varint,2,opt,name=late" json:"late,omitempty"` + // The amount of packets never received. + Lost *uint32 `protobuf:"varint,3,opt,name=lost" json:"lost,omitempty"` + // The amount of nonce resyncs. + Resync *uint32 `protobuf:"varint,4,opt,name=resync" json:"resync,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *UserStats_Stats) Reset() { *m = UserStats_Stats{} } +func (m *UserStats_Stats) String() string { return proto.CompactTextString(m) } +func (*UserStats_Stats) ProtoMessage() {} + +func (m *UserStats_Stats) GetGood() uint32 { + if m != nil && m.Good != nil { + return *m.Good + } + return 0 +} + +func (m *UserStats_Stats) GetLate() uint32 { + if m != nil && m.Late != nil { + return *m.Late + } + return 0 +} + +func (m *UserStats_Stats) GetLost() uint32 { + if m != nil && m.Lost != nil { + return *m.Lost + } + return 0 +} + +func (m *UserStats_Stats) GetResync() uint32 { + if m != nil && m.Resync != nil { + return *m.Resync + } + return 0 +} + +// Used by the client to request binary data from the server. By default large +// comments or textures are not sent within standard messages but instead the +// hash is. If the client does not recognize the hash it may request the +// resource when it needs it. The client does so by sending a RequestBlob +// message with the correct fields filled with the user sessions or channel_ids +// it wants to receive. The server replies to this by sending a new +// UserState/ChannelState message with the resources filled even if they would +// normally be transmitted as hashes. +type RequestBlob struct { + // sessions of the requested UserState textures. + SessionTexture []uint32 `protobuf:"varint,1,rep,name=session_texture" json:"session_texture,omitempty"` + // sessions of the requested UserState comments. + SessionComment []uint32 `protobuf:"varint,2,rep,name=session_comment" json:"session_comment,omitempty"` + // channel_ids of the requested ChannelState descriptions. + ChannelDescription []uint32 `protobuf:"varint,3,rep,name=channel_description" json:"channel_description,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *RequestBlob) Reset() { *m = RequestBlob{} } +func (m *RequestBlob) String() string { return proto.CompactTextString(m) } +func (*RequestBlob) ProtoMessage() {} + +func (m *RequestBlob) GetSessionTexture() []uint32 { + if m != nil { + return m.SessionTexture + } + return nil +} + +func (m *RequestBlob) GetSessionComment() []uint32 { + if m != nil { + return m.SessionComment + } + return nil +} + +func (m *RequestBlob) GetChannelDescription() []uint32 { + if m != nil { + return m.ChannelDescription + } + return nil +} + +// Sent by the server when it informs the clients on server configuration +// details. +type ServerConfig struct { + // The maximum bandwidth the clients should use. + MaxBandwidth *uint32 `protobuf:"varint,1,opt,name=max_bandwidth" json:"max_bandwidth,omitempty"` + // Server welcome text. + WelcomeText *string `protobuf:"bytes,2,opt,name=welcome_text" json:"welcome_text,omitempty"` + // True if the server allows HTML. + AllowHtml *bool `protobuf:"varint,3,opt,name=allow_html" json:"allow_html,omitempty"` + // Maximum text message length. + MessageLength *uint32 `protobuf:"varint,4,opt,name=message_length" json:"message_length,omitempty"` + // Maximum image message length. + ImageMessageLength *uint32 `protobuf:"varint,5,opt,name=image_message_length" json:"image_message_length,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ServerConfig) Reset() { *m = ServerConfig{} } +func (m *ServerConfig) String() string { return proto.CompactTextString(m) } +func (*ServerConfig) ProtoMessage() {} + +func (m *ServerConfig) GetMaxBandwidth() uint32 { + if m != nil && m.MaxBandwidth != nil { + return *m.MaxBandwidth + } + return 0 +} + +func (m *ServerConfig) GetWelcomeText() string { + if m != nil && m.WelcomeText != nil { + return *m.WelcomeText + } + return "" +} + +func (m *ServerConfig) GetAllowHtml() bool { + if m != nil && m.AllowHtml != nil { + return *m.AllowHtml + } + return false +} + +func (m *ServerConfig) GetMessageLength() uint32 { + if m != nil && m.MessageLength != nil { + return *m.MessageLength + } + return 0 +} + +func (m *ServerConfig) GetImageMessageLength() uint32 { + if m != nil && m.ImageMessageLength != nil { + return *m.ImageMessageLength + } + return 0 +} + +// Sent by the server to inform the clients of suggested client configuration +// specified by the server administrator. +type SuggestConfig struct { + // Suggested client version. + Version *uint32 `protobuf:"varint,1,opt,name=version" json:"version,omitempty"` + // True if the administrator suggests positional audio to be used on this + // server. + Positional *bool `protobuf:"varint,2,opt,name=positional" json:"positional,omitempty"` + // True if the administrator suggests push to talk to be used on this server. + PushToTalk *bool `protobuf:"varint,3,opt,name=push_to_talk" json:"push_to_talk,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *SuggestConfig) Reset() { *m = SuggestConfig{} } +func (m *SuggestConfig) String() string { return proto.CompactTextString(m) } +func (*SuggestConfig) ProtoMessage() {} + +func (m *SuggestConfig) GetVersion() uint32 { + if m != nil && m.Version != nil { + return *m.Version + } + return 0 +} + +func (m *SuggestConfig) GetPositional() bool { + if m != nil && m.Positional != nil { + return *m.Positional + } + return false +} + +func (m *SuggestConfig) GetPushToTalk() bool { + if m != nil && m.PushToTalk != nil { + return *m.PushToTalk + } + return false +} + +func init() { + proto.RegisterEnum("MumbleProto.Reject_RejectType", Reject_RejectType_name, Reject_RejectType_value) + proto.RegisterEnum("MumbleProto.PermissionDenied_DenyType", PermissionDenied_DenyType_name, PermissionDenied_DenyType_value) + proto.RegisterEnum("MumbleProto.ContextActionModify_Context", ContextActionModify_Context_name, ContextActionModify_Context_value) + proto.RegisterEnum("MumbleProto.ContextActionModify_Operation", ContextActionModify_Operation_name, ContextActionModify_Operation_value) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.proto b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.proto new file mode 100644 index 0000000..92b8737 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.proto @@ -0,0 +1,544 @@ +package MumbleProto; + +option optimize_for = SPEED; + +message Version { + // 2-byte Major, 1-byte Minor and 1-byte Patch version number. + optional uint32 version = 1; + // Client release name. + optional string release = 2; + // Client OS name. + optional string os = 3; + // Client OS version. + optional string os_version = 4; +} + +// Not used. Not even for tunneling UDP through TCP. +message UDPTunnel { + // Not used. + required bytes packet = 1; +} + +// Used by the client to send the authentication credentials to the server. +message Authenticate { + // UTF-8 encoded username. + optional string username = 1; + // Server or user password. + optional string password = 2; + // Additional access tokens for server ACL groups. + repeated string tokens = 3; + // A list of CELT bitstream version constants supported by the client. + repeated int32 celt_versions = 4; + optional bool opus = 5 [default = false]; +} + +// Sent by the client to notify the server that the client is still alive. +// Server must reply to the packet with the same timestamp and its own +// good/late/lost/resync numbers. None of the fields is strictly required. +message Ping { + // Client timestamp. Server should not attempt to decode. + optional uint64 timestamp = 1; + // The amount of good packets received. + optional uint32 good = 2; + // The amount of late packets received. + optional uint32 late = 3; + // The amount of packets never received. + optional uint32 lost = 4; + // The amount of nonce resyncs. + optional uint32 resync = 5; + // The total amount of UDP packets received. + optional uint32 udp_packets = 6; + // The total amount of TCP packets received. + optional uint32 tcp_packets = 7; + // UDP ping average. + optional float udp_ping_avg = 8; + // UDP ping variance. + optional float udp_ping_var = 9; + // TCP ping average. + optional float tcp_ping_avg = 10; + // TCP ping variance. + optional float tcp_ping_var = 11; +} + +// Sent by the server when it rejects the user connection. +message Reject { + enum RejectType { + // TODO ?? + None = 0; + // The client attempted to connect with an incompatible version. + WrongVersion = 1; + // The user name supplied by the client was invalid. + InvalidUsername = 2; + // The client attempted to authenticate as a user with a password but it + // was wrong. + WrongUserPW = 3; + // The client attempted to connect to a passworded server but the password + // was wrong. + WrongServerPW = 4; + // Supplied username is already in use. + UsernameInUse = 5; + // Server is currently full and cannot accept more users. + ServerFull = 6; + // The user did not provide a certificate but one is required. + NoCertificate = 7; + AuthenticatorFail = 8; + } + // Rejection type. + optional RejectType type = 1; + // Human readable rejection reason. + optional string reason = 2; +} + +// ServerSync message is sent by the server when it has authenticated the user +// and finished synchronizing the server state. +message ServerSync { + // The session of the current user. + optional uint32 session = 1; + // Maximum bandwidth that the user should use. + optional uint32 max_bandwidth = 2; + // Server welcome text. + optional string welcome_text = 3; + // Current user permissions TODO: Confirm?? + optional uint64 permissions = 4; +} + +// Sent by the client when it wants a channel removed. Sent by the server when +// a channel has been removed and clients should be notified. +message ChannelRemove { + required uint32 channel_id = 1; +} + +// Used to communicate channel properties between the client and the server. +// Sent by the server during the login process or when channel properties are +// updated. Client may use this message to update said channel properties. +message ChannelState { + // Unique ID for the channel within the server. + optional uint32 channel_id = 1; + // channel_id of the parent channel. + optional uint32 parent = 2; + // UTF-8 encoded channel name. + optional string name = 3; + // A collection of channel id values of the linked channels. Absent during + // the first channel listing. + repeated uint32 links = 4; + // UTF-8 encoded channel description. Only if the description is less than + // 128 bytes + optional string description = 5; + // A collection of channel_id values that should be added to links. + repeated uint32 links_add = 6; + // A collection of channel_id values that should be removed from links. + repeated uint32 links_remove = 7; + // True if the channel is temporary. + optional bool temporary = 8 [default = false]; + // Position weight to tweak the channel position in the channel list. + optional int32 position = 9 [default = 0]; + // SHA1 hash of the description if the description is 128 bytes or more. + optional bytes description_hash = 10; +} + +// Used to communicate user leaving or being kicked. May be sent by the client +// when it attempts to kick a user. Sent by the server when it informs the +// clients that a user is not present anymore. +message UserRemove { + // The user who is being kicked, identified by their session, not present + // when no one is being kicked. + required uint32 session = 1; + // The user who initiated the removal. Either the user who performs the kick + // or the user who is currently leaving. + optional uint32 actor = 2; + // Reason for the kick, stored as the ban reason if the user is banned. + optional string reason = 3; + // True if the kick should result in a ban. + optional bool ban = 4; +} + +// Sent by the server when it communicates new and changed users to client. +// First seen during login procedure. May be sent by the client when it wishes +// to alter its state. +message UserState { + // Unique user session ID of the user whose state this is, may change on + // reconnect. + optional uint32 session = 1; + // The session of the user who is updating this user. + optional uint32 actor = 2; + // User name, UTF-8 encoded. + optional string name = 3; + // Registered user ID if the user is registered. + optional uint32 user_id = 4; + // Channel on which the user is. + optional uint32 channel_id = 5; + // True if the user is muted by admin. + optional bool mute = 6; + // True if the user is deafened by admin. + optional bool deaf = 7; + // True if the user has been suppressed from talking by a reason other than + // being muted. + optional bool suppress = 8; + // True if the user has muted self. + optional bool self_mute = 9; + // True if the user has deafened self. + optional bool self_deaf = 10; + // User image if it is less than 128 bytes. + optional bytes texture = 11; + // TODO ?? + optional bytes plugin_context = 12; + // TODO ?? + optional string plugin_identity = 13; + // User comment if it is less than 128 bytes. + optional string comment = 14; + // The hash of the user certificate. + optional string hash = 15; + // SHA1 hash of the user comment if it 128 bytes or more. + optional bytes comment_hash = 16; + // SHA1 hash of the user picture if it 128 bytes or more. + optional bytes texture_hash = 17; + // True if the user is a priority speaker. + optional bool priority_speaker = 18; + // True if the user is currently recording. + optional bool recording = 19; +} + +// Relays information on the bans. The client may send the BanList message to +// either modify the list of bans or query them from the server. The server +// sends this list only after a client queries for it. +message BanList { + message BanEntry { + // Banned IP address. + required bytes address = 1; + // The length of the subnet mask for the ban. + required uint32 mask = 2; + // User name for identification purposes (does not affect the ban). + optional string name = 3; + // TODO ?? + optional string hash = 4; + // Reason for the ban (does not affect the ban). + optional string reason = 5; + // Ban start time. + optional string start = 6; + // Ban duration in seconds. + optional uint32 duration = 7; + } + // List of ban entries currently in place. + repeated BanEntry bans = 1; + // True if the server should return the list, false if it should replace old + // ban list with the one provided. + optional bool query = 2 [default = false]; +} + +// Used to send and broadcast text messages. +message TextMessage { + // The message sender, identified by its session. + optional uint32 actor = 1; + // Target users for the message, identified by their session. + repeated uint32 session = 2; + // The channels to which the message is sent, identified by their + // channel_ids. + repeated uint32 channel_id = 3; + // The root channels when sending message recursively to several channels, + // identified by their channel_ids. + repeated uint32 tree_id = 4; + // The UTF-8 encoded message. May be HTML if the server allows. + required string message = 5; +} + +message PermissionDenied { + enum DenyType { + // Operation denied for other reason, see reason field. + Text = 0; + // Permissions were denied. + Permission = 1; + // Cannot modify SuperUser. + SuperUser = 2; + // Invalid channel name. + ChannelName = 3; + // Text message too long. + TextTooLong = 4; + // The flux capacitor was spelled wrong. + H9K = 5; + // Operation not permitted in temporary channel. + TemporaryChannel = 6; + // Operation requires certificate. + MissingCertificate = 7; + // Invalid username. + UserName = 8; + // Channel is full. + ChannelFull = 9; + NestingLimit = 10; + } + // The denied permission when type is Permission. + optional uint32 permission = 1; + // channel_id for the channel where the permission was denied when type is + // Permission. + optional uint32 channel_id = 2; + // The user who was denied permissions, identified by session. + optional uint32 session = 3; + // Textual reason for the denial. + optional string reason = 4; + // Type of the denial. + optional DenyType type = 5; + // The name that is invalid when type is UserName. + optional string name = 6; +} + +message ACL { + message ChanGroup { + // Name of the channel group, UTF-8 encoded. + required string name = 1; + // True if the group has been inherited from the parent (Read only). + optional bool inherited = 2 [default = true]; + // True if the group members are inherited. + optional bool inherit = 3 [default = true]; + // True if the group can be inherited by sub channels. + optional bool inheritable = 4 [default = true]; + // Users explicitly included in this group, identified by user_id. + repeated uint32 add = 5; + // Users explicitly removed from this group in this channel if the group + // has been inherited, identified by user_id. + repeated uint32 remove = 6; + // Users inherited, identified by user_id. + repeated uint32 inherited_members = 7; + } + message ChanACL { + // True if this ACL applies to the current channel. + optional bool apply_here = 1 [default = true]; + // True if this ACL applies to the sub channels. + optional bool apply_subs = 2 [default = true]; + // True if the ACL has been inherited from the parent. + optional bool inherited = 3 [default = true]; + // ID of the user that is affected by this ACL. + optional uint32 user_id = 4; + // ID of the group that is affected by this ACL. + optional string group = 5; + // Bit flag field of the permissions granted by this ACL. + optional uint32 grant = 6; + // Bit flag field of the permissions denied by this ACL. + optional uint32 deny = 7; + } + // Channel ID of the channel this message affects. + required uint32 channel_id = 1; + // True if the channel inherits its parent's ACLs. + optional bool inherit_acls = 2 [default = true]; + // User group specifications. + repeated ChanGroup groups = 3; + // ACL specifications. + repeated ChanACL acls = 4; + // True if the message is a query for ACLs instead of setting them. + optional bool query = 5 [default = false]; +} + +// Client may use this message to refresh its registered user information. The +// client should fill the IDs or Names of the users it wants to refresh. The +// server fills the missing parts and sends the message back. +message QueryUsers { + // user_ids. + repeated uint32 ids = 1; + // User names in the same order as ids. + repeated string names = 2; +} + +// Used to initialize and resync the UDP encryption. Either side may request a +// resync by sending the message without any values filled. The resync is +// performed by sending the message with only the client or server nonce +// filled. +message CryptSetup { + // Encryption key. + optional bytes key = 1; + // Client nonce. + optional bytes client_nonce = 2; + // Server nonce. + optional bytes server_nonce = 3; +} + +message ContextActionModify { + enum Context { + // Action is applicable to the server. + Server = 0x01; + // Action can target a Channel. + Channel = 0x02; + // Action can target a User. + User = 0x04; + } + enum Operation { + Add = 0; + Remove = 1; + } + // The action name. + required string action = 1; + // The display name of the action. + optional string text = 2; + // Context bit flags defining where the action should be displayed. + optional uint32 context = 3; + optional Operation operation = 4; +} + +// Sent by the client when it wants to initiate a Context action. +message ContextAction { + // The target User for the action, identified by session. + optional uint32 session = 1; + // The target Channel for the action, identified by channel_id. + optional uint32 channel_id = 2; + // The action that should be executed. + required string action = 3; +} + +// Lists the registered users. +message UserList { + message User { + // Registered user ID. + required uint32 user_id = 1; + // Registered user name. + optional string name = 2; + optional string last_seen = 3; + optional uint32 last_channel = 4; + } + // A list of registered users. + repeated User users = 1; +} + +// Sent by the client when it wants to register or clear whisper targets. +// +// Note: The first available target ID is 1 as 0 is reserved for normal +// talking. Maximum target ID is 30. +message VoiceTarget { + message Target { + // Users that are included as targets. + repeated uint32 session = 1; + // Channels that are included as targets. + optional uint32 channel_id = 2; + // TODO ?? + optional string group = 3; + // True if the voice should follow links from the specified channel. + optional bool links = 4 [default = false]; + // True if the voice should also be sent to children of the specific + // channel. + optional bool children = 5 [default = false]; + } + // Voice target ID. + optional uint32 id = 1; + // The receivers that this voice target includes. + repeated Target targets = 2; +} + +// Sent by the client when it wants permissions for a certain channel. Sent by +// the server when it replies to the query or wants the user to resync all +// channel permissions. +message PermissionQuery { + // channel_id of the channel for which the permissions are queried. + optional uint32 channel_id = 1; + // Channel permissions. + optional uint32 permissions = 2; + // True if the client should drop its current permission information for all + // channels. + optional bool flush = 3 [default = false]; +} + +// Sent by the server to notify the users of the version of the CELT codec they +// should use. This may change during the connection when new users join. +message CodecVersion { + // The version of the CELT Alpha codec. + required int32 alpha = 1; + // The version of the CELT Beta codec. + required int32 beta = 2; + // True if the user should prefer Alpha over Beta. + required bool prefer_alpha = 3 [default = true]; + optional bool opus = 4 [default = false]; +} + +// Used to communicate user stats between the server and clients. +message UserStats { + message Stats { + // The amount of good packets received. + optional uint32 good = 1; + // The amount of late packets received. + optional uint32 late = 2; + // The amount of packets never received. + optional uint32 lost = 3; + // The amount of nonce resyncs. + optional uint32 resync = 4; + } + + // User whose stats these are. + optional uint32 session = 1; + // True if the message contains only mutable stats (packets, ping). + optional bool stats_only = 2 [default = false]; + // Full user certificate chain of the user certificate in DER format. + repeated bytes certificates = 3; + // Packet statistics for packets received from the client. + optional Stats from_client = 4; + // Packet statistics for packets sent by the server. + optional Stats from_server = 5; + + // Amount of UDP packets sent. + optional uint32 udp_packets = 6; + // Amount of TCP packets sent. + optional uint32 tcp_packets = 7; + // UDP ping average. + optional float udp_ping_avg = 8; + // UDP ping variance. + optional float udp_ping_var = 9; + // TCP ping average. + optional float tcp_ping_avg = 10; + // TCP ping variance. + optional float tcp_ping_var = 11; + + // Client version. + optional Version version = 12; + // A list of CELT bitstream version constants supported by the client of this + // user. + repeated int32 celt_versions = 13; + // Client IP address. + optional bytes address = 14; + // Bandwith used by this client. + optional uint32 bandwidth = 15; + // Connection duration. + optional uint32 onlinesecs = 16; + // Duration since last activity. + optional uint32 idlesecs = 17; + // True if the user has a strong certificate. + optional bool strong_certificate = 18 [default = false]; + optional bool opus = 19 [default = false]; +} + +// Used by the client to request binary data from the server. By default large +// comments or textures are not sent within standard messages but instead the +// hash is. If the client does not recognize the hash it may request the +// resource when it needs it. The client does so by sending a RequestBlob +// message with the correct fields filled with the user sessions or channel_ids +// it wants to receive. The server replies to this by sending a new +// UserState/ChannelState message with the resources filled even if they would +// normally be transmitted as hashes. +message RequestBlob { + // sessions of the requested UserState textures. + repeated uint32 session_texture = 1; + // sessions of the requested UserState comments. + repeated uint32 session_comment = 2; + // channel_ids of the requested ChannelState descriptions. + repeated uint32 channel_description = 3; +} + +// Sent by the server when it informs the clients on server configuration +// details. +message ServerConfig { + // The maximum bandwidth the clients should use. + optional uint32 max_bandwidth = 1; + // Server welcome text. + optional string welcome_text = 2; + // True if the server allows HTML. + optional bool allow_html = 3; + // Maximum text message length. + optional uint32 message_length = 4; + // Maximum image message length. + optional uint32 image_message_length = 5; +} + +// Sent by the server to inform the clients of suggested client configuration +// specified by the server administrator. +message SuggestConfig { + // Suggested client version. + optional uint32 version = 1; + // True if the administrator suggests positional audio to be used on this + // server. + optional bool positional = 2; + // True if the administrator suggests push to talk to be used on this server. + optional bool push_to_talk = 3; +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/generate.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/generate.go new file mode 100644 index 0000000..88da886 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/generate.go @@ -0,0 +1,2 @@ +//go:generate protoc --go_out=. Mumble.proto +package MumbleProto diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/acl.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/acl.go new file mode 100644 index 0000000..993be1c --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/acl.go @@ -0,0 +1,58 @@ +package gumble + +// ACL contains a list of ACLGroups and ACLRules linked to a channel. +type ACL struct { + // The channel to which the ACL belongs. + Channel *Channel + // The ACL's groups. + Groups []*ACLGroup + // The ACL's rules. + Rules []*ACLRule + // Does the ACL inherits the parent channel's ACL?s + Inherits bool +} + +// ACLUser is a registered user who is part of or can be part of an ACL group +// or rule. +type ACLUser struct { + // The user ID of the user. + UserID uint32 + // The name of the user. + Name string +} + +// ACLGroup is a named group of registered users which can be used in an +// ACLRule. +type ACLGroup struct { + // The ACL group name. + Name string + // Is the group inherited from the parent channel's ACL? + Inherited bool + // Are group members are inherited from the parent channel's ACL? + InheritUsers bool + // Can the group be inherited by child channels? + Inheritable bool + usersAdd, usersRemove, usersInherited map[uint32]*ACLUser +} + +// ACLRule is a set of granted and denied permissions given to an ACLUser or +// ACLGroup. +type ACLRule struct { + // Does the rule apply to the channel in which the rule is defined? + AppliesCurrent bool + // Does the rule apply to the children of the channel in which the rule is + // defined? + AppliesChildren bool + // Is the rule inherited from the parent channel's ACL? + Inherited bool + + // The permissions granted by the rule. + Granted Permission + // The permissions denied by the rule. + Denied Permission + + // The ACL user the rule applies to. Can be nil. + User *ACLUser + // The ACL group the rule applies to. Can be nil. + Group *ACLGroup +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audio.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audio.go new file mode 100644 index 0000000..d8f4591 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audio.go @@ -0,0 +1,85 @@ +package gumble + +import ( + "math" + "time" +) + +const ( + // AudioSampleRate is the audio sample rate (in hertz) for incoming and + // outgoing audio. + AudioSampleRate = 48000 + + // AudioDefaultInterval is the default interval that audio packets are sent + // at. + AudioDefaultInterval = 10 * time.Millisecond + + // AudioDefaultFrameSize is the number of audio frames that should be sent in + // a 10ms window. + AudioDefaultFrameSize = AudioSampleRate / 100 + + // AudioMaximumFrameSize is the maximum audio frame size from another user + // that will be processed. + AudioMaximumFrameSize = AudioDefaultFrameSize * 10 + + // AudioDefaultDataBytes is the default number of bytes that an audio frame + // can use. + AudioDefaultDataBytes = 40 +) + +// AudioListener is the interface that must be implemented by types wishing to +// receive incoming audio data from the server. +type AudioListener interface { + OnAudioPacket(e *AudioPacketEvent) +} + +// AudioPacketEvent is event that is passed to AudioListener.OnAudioPacket. +type AudioPacketEvent struct { + Client *Client + AudioPacket AudioPacket +} + +// AudioBuffer is a slice of PCM samples. +type AudioBuffer []int16 + +// PositionalAudioBuffer is an AudioBuffer that has a position in 3D space +// associated with it. +type PositionalAudioBuffer struct { + X, Y, Z float32 + AudioBuffer +} + +func (pab PositionalAudioBuffer) writeMessage(client *Client) error { + return writeAudioTo(client, pab.AudioBuffer, &pab) +} + +// AudioPacket contains incoming audio data and information. +type AudioPacket struct { + Sender *User + Target int + Sequence int + PositionalAudioBuffer +} + +func (ab AudioBuffer) writeMessage(client *Client) error { + return writeAudioTo(client, ab, nil) +} + +func writeAudioTo(client *Client, ab AudioBuffer, pab *PositionalAudioBuffer) error { + dataBytes := client.Config.GetAudioDataBytes() + opus, err := client.AudioEncoder.Encode(ab, len(ab), dataBytes) + if err != nil { + return err + } + + var targetID int + if target := client.VoiceTarget; target != nil { + targetID = int(target.ID) + } + seq := client.audioSequence + client.audioSequence = (client.audioSequence + 1) % math.MaxInt32 + if pab == nil { + return client.Conn.WriteAudio(4, targetID, seq, opus, nil, nil, nil) + } + return client.Conn.WriteAudio(4, targetID, seq, opus, &pab.X, &pab.Y, &pab.Z) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audiomultiplexer.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audiomultiplexer.go new file mode 100644 index 0000000..23983a4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audiomultiplexer.go @@ -0,0 +1,47 @@ +package gumble + +type audioEventMultiplexerItem struct { + mux *audioEventMultiplexer + prev, next *audioEventMultiplexerItem + listener AudioListener +} + +func (emi *audioEventMultiplexerItem) Detach() { + if emi.prev == nil { + emi.mux.head = emi.next + } else { + emi.prev.next = emi.next + } + if emi.next == nil { + emi.mux.tail = emi.prev + } else { + emi.next.prev = emi.prev + } +} + +type audioEventMultiplexer struct { + head, tail *audioEventMultiplexerItem +} + +func (aem *audioEventMultiplexer) Attach(listener AudioListener) Detacher { + item := &audioEventMultiplexerItem{ + mux: aem, + prev: aem.tail, + listener: listener, + } + if aem.head == nil { + aem.head = item + } + if aem.tail == nil { + aem.tail = item + } else { + aem.tail.next = item + } + return item +} + +func (aem audioEventMultiplexer) OnAudioPacket(event *AudioPacketEvent) { + for item := aem.head; item != nil; item = item.next { + item.listener.OnAudioPacket(event) + } +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/bans.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/bans.go new file mode 100644 index 0000000..833100e --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/bans.go @@ -0,0 +1,102 @@ +package gumble + +import ( + "net" + "time" + + "github.com/golang/protobuf/proto" + "github.com/layeh/gumble/gumble/MumbleProto" +) + +// BanList is a list of server ban entries. +// +// Whenever a ban is changed, it does not come into effect until the ban list +// is sent back to the server. +type BanList []*Ban + +// Add creates a new ban list entry with the given parameters. +func (bl *BanList) Add(address net.IP, mask net.IPMask, reason string, duration time.Duration) *Ban { + ban := &Ban{ + Address: address, + Mask: mask, + Reason: reason, + Duration: duration, + } + *bl = append(*bl, ban) + return ban +} + +// Ban represents an entry in the server ban list. +// +// This type should not be initialized manually. Instead, create new ban +// entries using BanList.Add(). +type Ban struct { + // The banned IP address. + Address net.IP + // The IP mask that the ban applies to. + Mask net.IPMask + // The name of the banned user. + Name string + // The certificate hash of the banned user. + Hash string + // The reason for the ban. + Reason string + // The start time from which the ban applies. + Start time.Time + // How long the ban is for. + Duration time.Duration + + unban bool +} + +// SetAddress sets the banned IP address. +func (b *Ban) SetAddress(address net.IP) { + b.Address = address +} + +// SetMask sets the IP mask that the ban applies to. +func (b *Ban) SetMask(mask net.IPMask) { + b.Mask = mask +} + +// SetReason changes the reason for the ban. +func (b *Ban) SetReason(reason string) { + b.Reason = reason +} + +// SetDuration changes the duration of the ban. +func (b *Ban) SetDuration(duration time.Duration) { + b.Duration = duration +} + +// Unban will unban the user from the server. +func (b *Ban) Unban() { + b.unban = true +} + +// Ban will ban the user from the server. This is only useful if Unban() was +// called on the ban entry. +func (b *Ban) Ban() { + b.unban = false +} + +func (bl BanList) writeMessage(client *Client) error { + packet := MumbleProto.BanList{ + Query: proto.Bool(false), + } + + for _, ban := range bl { + if !ban.unban { + maskSize, _ := ban.Mask.Size() + packet.Bans = append(packet.Bans, &MumbleProto.BanList_BanEntry{ + Address: ban.Address, + Mask: proto.Uint32(uint32(maskSize)), + Reason: &ban.Reason, + Duration: proto.Uint32(uint32(ban.Duration / time.Second)), + }) + } + } + + proto := protoMessage{&packet} + return proto.writeMessage(client) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channel.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channel.go new file mode 100644 index 0000000..606b4ef --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channel.go @@ -0,0 +1,147 @@ +package gumble + +import ( + "github.com/golang/protobuf/proto" + "github.com/layeh/gumble/gumble/MumbleProto" +) + +// Channel represents a channel in the server's channel tree. +type Channel struct { + // The channel's unique ID. + ID uint32 + // The channel's name. + Name string + // The channel's parent. Contains nil if the channel is the root channel. + Parent *Channel + // The channels directly underneath the channel. + Children Channels + // The users currently in the channel. + Users Users + // The channel's description. Contains the empty string if the channel does + // not have a description, or if it needs to be requested. + Description string + // The channel's description hash. Contains nil if Channel.Description has + // been populated. + DescriptionHash []byte + // The position at which the channel should be displayed in an ordered list. + Position int32 + // Is the channel temporary? + Temporary bool + + client *Client +} + +// IsRoot returns true if the channel is the server's root channel. +func (c *Channel) IsRoot() bool { + return c.ID == 0 +} + +// Add will add a sub-channel to the given channel. +func (c *Channel) Add(name string, temporary bool) { + packet := MumbleProto.ChannelState{ + Parent: &c.ID, + Name: &name, + Temporary: &temporary, + } + c.client.Send(protoMessage{&packet}) +} + +// Remove will remove the given channel and all sub-channels from the server's +// channel tree. +func (c *Channel) Remove() { + packet := MumbleProto.ChannelRemove{ + ChannelId: &c.ID, + } + c.client.Send(protoMessage{&packet}) +} + +// SetName will set the name of the channel. This will have no effect if the +// channel is the server's root channel. +func (c *Channel) SetName(name string) { + packet := MumbleProto.ChannelState{ + ChannelId: &c.ID, + Name: &name, + } + c.client.Send(protoMessage{&packet}) +} + +// SetDescription will set the description of the channel. +func (c *Channel) SetDescription(description string) { + packet := MumbleProto.ChannelState{ + ChannelId: &c.ID, + Description: &description, + } + c.client.Send(protoMessage{&packet}) +} + +// Find returns a channel whose path (by channel name) from the current channel +// is equal to the arguments passed. +// +// For example, given the following server channel tree: +// Root +// Child 1 +// Child 2 +// Child 2.1 +// Child 2.2 +// Child 2.2.1 +// Child 3 +// To get the "Child 2.2.1" channel: +// root.Find("Child 2", "Child 2.2", "Child 2.2.1") +func (c *Channel) Find(names ...string) *Channel { + if len(names) == 0 { + return c + } + for _, child := range c.Children { + if child.Name == names[0] { + return child.Find(names[1:]...) + } + } + return nil +} + +// Request requests channel information that has not yet been sent to the +// client. The supported request types are: RequestACL, RequestDescription, +// RequestPermission. +// +// Note: the server will not reply to a RequestPermission request if the client +// has up-to-date permission information. +func (c *Channel) Request(request Request) { + if (request & RequestDescription) != 0 { + packet := MumbleProto.RequestBlob{ + ChannelDescription: []uint32{c.ID}, + } + c.client.Send(protoMessage{&packet}) + } + if (request & RequestACL) != 0 { + packet := MumbleProto.ACL{ + ChannelId: &c.ID, + Query: proto.Bool(true), + } + c.client.Send(protoMessage{&packet}) + } + if (request & RequestPermission) != 0 { + packet := MumbleProto.PermissionQuery{ + ChannelId: &c.ID, + } + c.client.Send(protoMessage{&packet}) + } +} + +// Send will send a text message to the channel. +func (c *Channel) Send(message string, recursive bool) { + textMessage := TextMessage{ + Message: message, + } + if recursive { + textMessage.Trees = []*Channel{c} + } else { + textMessage.Channels = []*Channel{c} + } + c.client.Send(&textMessage) +} + +// Permission returns the permissions the user has in the channel, or nil if +// the permissions are unknown. +func (c *Channel) Permission() *Permission { + return c.client.permissions[c.ID] +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channels.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channels.go new file mode 100644 index 0000000..9963651 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channels.go @@ -0,0 +1,32 @@ +package gumble + +// Channels is a map of server channels. +// +// When accessed through Client.Channels, it contains all channels on the +// server. When accessed through a specific channel +// (e.g. client.Channels[0].Children), it contains only the children of the +// channel. +type Channels map[uint32]*Channel + +// create adds a new channel with the given id to the collection. If a channel +// with the given id already exists, it is overwritten. +func (c Channels) create(id uint32) *Channel { + channel := &Channel{ + ID: id, + Children: Channels{}, + Users: Users{}, + } + c[id] = channel + return channel +} + +// Find returns a channel whose path (by channel name) from the server root +// channel is equal to the arguments passed. If the root channel does not +// exist, nil is returned. +func (c Channels) Find(names ...string) *Channel { + root := c[0] + if names == nil || root == nil { + return root + } + return root.Find(names...) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/client.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/client.go new file mode 100644 index 0000000..c6d4118 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/client.go @@ -0,0 +1,230 @@ +package gumble + +import ( + "crypto/tls" + "errors" + "runtime" + "time" + + "github.com/golang/protobuf/proto" + "github.com/layeh/gopus" + "github.com/layeh/gumble/gumble/MumbleProto" +) + +// State is the current state of the client's connection to the server. +type State int + +const ( + // StateDisconnected means the client is not connected to a server. + StateDisconnected State = iota + + // StateConnected means the client is connected to a server, but has yet to + // receive the initial server state. + StateConnected + + // StateSynced means the client is connected to a server and has been sent + // the server state. + StateSynced +) + +// ClientVersion is the protocol version that Client implements. +const ClientVersion = 1<<16 | 2<<8 | 4 + +// Client is the type used to create a connection to a server. +type Client struct { + // The current state of the client. + State State + // The User associated with the client (nil if the client has not yet been + // synced). + Self *User + // The client's configuration. + Config *Config + // The underlying Conn to the server. + *Conn + + listeners eventMultiplexer + audioListeners audioEventMultiplexer + + // The users currently connected to the server. + Users Users + // The connected server's channels. + Channels Channels + permissions map[uint32]*Permission + tmpACL *ACL + + pingStats pingStats + + // A collection containing the server's context actions. + ContextActions ContextActions + + // The audio encoder used when sending audio to the server. + AudioEncoder *gopus.Encoder + audioSequence int + // To whom transmitted audio will be sent. The VoiceTarget must have already + // been sent to the server for targeting to work correctly. Setting to nil + // will disable voice targeting (i.e. switch back to regular speaking). + VoiceTarget *VoiceTarget + + end chan bool + disconnectEvent DisconnectEvent +} + +// NewClient creates a new gumble client. Returns nil if config is nil. +func NewClient(config *Config) *Client { + if config == nil { + return nil + } + client := &Client{ + Config: config, + end: make(chan bool), + } + return client +} + +// Connect connects to the server. +func (c *Client) Connect() error { + if c.State != StateDisconnected { + return errors.New("client is already connected") + } + encoder, err := gopus.NewEncoder(AudioSampleRate, 1, gopus.Voip) + if err != nil { + return err + } + encoder.SetBitrate(gopus.BitrateMaximum) + c.audioSequence = 0 + c.VoiceTarget = nil + + tlsConn, err := tls.DialWithDialer(&c.Config.Dialer, "tcp", c.Config.Address, &c.Config.TLSConfig) + if err != nil { + return err + } + if verify := c.Config.TLSVerify; verify != nil { + state := tlsConn.ConnectionState() + if err := verify(&state); err != nil { + tlsConn.Close() + return err + } + } + c.Conn = NewConn(tlsConn) + + c.AudioEncoder = encoder + c.Users = Users{} + c.Channels = Channels{} + c.permissions = make(map[uint32]*Permission) + c.ContextActions = ContextActions{} + c.State = StateConnected + + // Channels and goroutines + go c.readRoutine() + go c.pingRoutine() + + // Initial packets + versionPacket := MumbleProto.Version{ + Version: proto.Uint32(ClientVersion), + Release: proto.String("gumble"), + Os: proto.String(runtime.GOOS), + OsVersion: proto.String(runtime.GOARCH), + } + authenticationPacket := MumbleProto.Authenticate{ + Username: &c.Config.Username, + Password: &c.Config.Password, + Opus: proto.Bool(true), + Tokens: c.Config.Tokens, + } + c.Send(protoMessage{&versionPacket}) + c.Send(protoMessage{&authenticationPacket}) + return nil +} + +// Attach adds an event listener that will receive incoming connection events. +func (c *Client) Attach(listener EventListener) Detacher { + return c.listeners.Attach(listener) +} + +// AttachAudio adds an audio event listener that will receive incoming audio +// packets. +func (c *Client) AttachAudio(listener AudioListener) Detacher { + return c.audioListeners.Attach(listener) +} + +// pingRoutine sends ping packets to the server at regular intervals. +func (c *Client) pingRoutine() { + ticker := time.NewTicker(time.Second * 10) + defer ticker.Stop() + + pingPacket := MumbleProto.Ping{ + Timestamp: proto.Uint64(0), + TcpPackets: &c.pingStats.TCPPackets, + } + pingProto := protoMessage{&pingPacket} + + for { + select { + case <-c.end: + return + case time := <-ticker.C: + *pingPacket.Timestamp = uint64(time.Unix()) + c.Send(pingProto) + } + } +} + +// readRoutine reads protocol buffer messages from the server. +func (c *Client) readRoutine() { + c.disconnectEvent = DisconnectEvent{ + Client: c, + Type: DisconnectError, + } + + for { + pType, data, err := c.Conn.ReadPacket() + if err != nil { + break + } + if handle, ok := handlers[pType]; ok { + handle(c, data) + } + } + + c.end <- true + c.Conn = nil + c.State = StateDisconnected + c.tmpACL = nil + c.pingStats = pingStats{} + c.listeners.OnDisconnect(&c.disconnectEvent) +} + +// Request requests that specific server information be sent to the client. The +// supported request types are: RequestUserList, and RequestBanList. +func (c *Client) Request(request Request) { + if (request & RequestUserList) != 0 { + packet := MumbleProto.UserList{} + proto := protoMessage{&packet} + c.Send(proto) + } + if (request & RequestBanList) != 0 { + packet := MumbleProto.BanList{ + Query: proto.Bool(true), + } + proto := protoMessage{&packet} + c.Send(proto) + } +} + +// Disconnect disconnects the client from the server. +func (c *Client) Disconnect() error { + if c.State == StateDisconnected { + return errors.New("client is already disconnected") + } + c.disconnectEvent.Type = DisconnectUser + c.Conn.Close() + return nil +} + +// Send will send a message to the server. +func (c *Client) Send(message Message) error { + if err := message.writeMessage(c); err != nil { + return err + } + return nil +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/config.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/config.go new file mode 100644 index 0000000..0bb454b --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/config.go @@ -0,0 +1,72 @@ +package gumble + +import ( + "crypto/tls" + "net" + "time" + + "github.com/layeh/gumble/gumble/MumbleProto" +) + +// Config holds the configuration data used by Client. +type Config struct { + // User name used when authenticating with the server. + Username string + // Password used when authenticating with the server. A password is not + // usually required to connect to a server. + Password string + // Server address, including port (e.g. localhost:64738). + Address string + Tokens AccessTokens + + // AudioInterval is the interval at which audio packets are sent. Valid + // values are 10ms, 20ms, 40ms, and 60ms. + AudioInterval time.Duration + + // AudioDataBytes is the number of bytes that an audio frame can use. + AudioDataBytes int + + TLSConfig tls.Config + // If non-nil, this function will be called after the connection to the + // server has been made. If it returns nil, the connection will stay alive, + // otherwise, it will be closed and Client.Connect will return the returned + // error. + TLSVerify func(state *tls.ConnectionState) error + Dialer net.Dialer +} + +// GetAudioInterval returns c.AudioInterval if it is valid, else returns +// AudioDefaultInterval. +func (c *Config) GetAudioInterval() time.Duration { + if c.AudioInterval <= 0 { + return AudioDefaultInterval + } + return c.AudioInterval +} + +// GetAudioDataBytes returns c.AudioDataBytes if it is valid, else returns +// AudioDefaultDataBytes. +func (c *Config) GetAudioDataBytes() int { + if c.AudioDataBytes <= 0 { + return AudioDefaultDataBytes + } + return c.AudioDataBytes +} + +// GetAudioFrameSize returns the appropriate audio frame size, based off of the +// audio interval. +func (c *Config) GetAudioFrameSize() int { + return int(c.GetAudioInterval()/AudioDefaultInterval) * AudioDefaultFrameSize +} + +// AccessTokens are additional passwords that can be provided to the server to +// gain access to restricted channels. +type AccessTokens []string + +func (at AccessTokens) writeMessage(client *Client) error { + packet := MumbleProto.Authenticate{ + Tokens: at, + } + proto := protoMessage{&packet} + return proto.writeMessage(client) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/conn.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/conn.go new file mode 100644 index 0000000..9b4a7ee --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/conn.go @@ -0,0 +1,197 @@ +package gumble + +import ( + "bytes" + "encoding/binary" + "errors" + "io" + "net" + "sync" + "time" + + "github.com/golang/protobuf/proto" + "github.com/layeh/gumble/gumble/MumbleProto" + "github.com/layeh/gumble/gumble/varint" +) + +// Conn represents a connection to a Mumble client/server. +type Conn struct { + sync.Mutex + net.Conn + + MaximumPacketBytes int + Timeout time.Duration + + buffer []byte +} + +// NewConn creates a new Conn with the given net.Conn. +func NewConn(conn net.Conn) *Conn { + return &Conn{ + Conn: conn, + Timeout: time.Second * 20, + MaximumPacketBytes: 1024 * 1024 * 10, + } +} + +// ReadPacket reads a packet from the server. Returns the packet type, the +// packet data, and nil on success. +// +// This function should only be called by a single go routine. +func (c *Conn) ReadPacket() (uint16, []byte, error) { + var pType uint16 + var pLength uint32 + + c.Conn.SetReadDeadline(time.Now().Add(c.Timeout)) + if err := binary.Read(c.Conn, binary.BigEndian, &pType); err != nil { + return 0, nil, err + } + if err := binary.Read(c.Conn, binary.BigEndian, &pLength); err != nil { + return 0, nil, err + } + pLengthInt := int(pLength) + if pLengthInt > c.MaximumPacketBytes { + return 0, nil, errors.New("packet larger than maximum allowed size") + } + if pLengthInt > cap(c.buffer) { + c.buffer = make([]byte, pLengthInt) + } + if _, err := io.ReadFull(c.Conn, c.buffer[:pLengthInt]); err != nil { + return 0, nil, err + } + return pType, c.buffer[:pLengthInt], nil +} + +// WriteAudio writes an audio packet to the connection. +func (c *Conn) WriteAudio(format, target, sequence int, data []byte, X, Y, Z *float32) error { + var header bytes.Buffer + formatTarget := byte(format)<<5 | byte(target) + if err := header.WriteByte(formatTarget); err != nil { + return err + } + if _, err := varint.WriteTo(&header, int64(sequence)); err != nil { + return err + } + if _, err := varint.WriteTo(&header, int64(len(data))); err != nil { + return err + } + + var positionalLength int + if X != nil { + positionalLength = 3 * 4 + } + + c.Lock() + defer c.Unlock() + + if err := c.writeHeader(1, uint32(header.Len()+len(data)+positionalLength)); err != nil { + return err + } + if _, err := header.WriteTo(c.Conn); err != nil { + return err + } + if _, err := c.Conn.Write(data); err != nil { + return err + } + + if positionalLength > 0 { + if err := binary.Write(c.Conn, binary.LittleEndian, *X); err != nil { + return err + } + if err := binary.Write(c.Conn, binary.LittleEndian, *Y); err != nil { + return err + } + if err := binary.Write(c.Conn, binary.LittleEndian, *Z); err != nil { + return err + } + } + + return nil +} + +// WritePacket writes a data packet of the given type to the connection. +func (c *Conn) WritePacket(ptype uint16, data []byte) error { + c.Lock() + defer c.Unlock() + if err := c.writeHeader(uint16(ptype), uint32(len(data))); err != nil { + return err + } + if _, err := c.Conn.Write(data); err != nil { + return err + } + return nil +} + +func (c *Conn) writeHeader(pType uint16, pLength uint32) error { + if err := binary.Write(c.Conn, binary.BigEndian, pType); err != nil { + return err + } + if err := binary.Write(c.Conn, binary.BigEndian, pLength); err != nil { + return err + } + return nil +} + +// WriteProto writes a protocol buffer message to the connection. +func (c *Conn) WriteProto(message proto.Message) error { + var protoType uint16 + switch message.(type) { + case *MumbleProto.Version: + protoType = 0 + case *MumbleProto.Authenticate: + protoType = 2 + case *MumbleProto.Ping: + protoType = 3 + case *MumbleProto.Reject: + protoType = 4 + case *MumbleProto.ServerSync: + protoType = 5 + case *MumbleProto.ChannelRemove: + protoType = 6 + case *MumbleProto.ChannelState: + protoType = 7 + case *MumbleProto.UserRemove: + protoType = 8 + case *MumbleProto.UserState: + protoType = 9 + case *MumbleProto.BanList: + protoType = 10 + case *MumbleProto.TextMessage: + protoType = 11 + case *MumbleProto.PermissionDenied: + protoType = 12 + case *MumbleProto.ACL: + protoType = 13 + case *MumbleProto.QueryUsers: + protoType = 14 + case *MumbleProto.CryptSetup: + protoType = 15 + case *MumbleProto.ContextActionModify: + protoType = 16 + case *MumbleProto.ContextAction: + protoType = 17 + case *MumbleProto.UserList: + protoType = 18 + case *MumbleProto.VoiceTarget: + protoType = 19 + case *MumbleProto.PermissionQuery: + protoType = 20 + case *MumbleProto.CodecVersion: + protoType = 21 + case *MumbleProto.UserStats: + protoType = 22 + case *MumbleProto.RequestBlob: + protoType = 23 + case *MumbleProto.ServerConfig: + protoType = 24 + case *MumbleProto.SuggestConfig: + protoType = 25 + default: + return errors.New("unknown message type") + } + data, err := proto.Marshal(message) + if err != nil { + return err + } + return c.WritePacket(protoType, data) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextaction.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextaction.go new file mode 100644 index 0000000..7706e16 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextaction.go @@ -0,0 +1,57 @@ +package gumble + +import ( + "github.com/layeh/gumble/gumble/MumbleProto" +) + +// ContextActionType is a bitmask of contexts where a ContextAction can be +// triggered. +type ContextActionType int + +// Supported ContextAction contexts. +const ( + ContextActionServer ContextActionType = ContextActionType(MumbleProto.ContextActionModify_Server) + ContextActionChannel ContextActionType = ContextActionType(MumbleProto.ContextActionModify_Channel) + ContextActionUser ContextActionType = ContextActionType(MumbleProto.ContextActionModify_User) +) + +// ContextAction is an triggerable item that has been added by a server-side +// plugin. +type ContextAction struct { + client *Client + + // The context action type. + Type ContextActionType + // The name of the context action. + Name string + // The user-friendly description of the context action. + Label string +} + +// Trigger will trigger the context action in the context of the server. +func (ca *ContextAction) Trigger() { + packet := MumbleProto.ContextAction{ + Action: &ca.Name, + } + ca.client.Send(protoMessage{&packet}) +} + +// TriggerUser will trigger the context action in the context of the given +// user. +func (ca *ContextAction) TriggerUser(user *User) { + packet := MumbleProto.ContextAction{ + Session: &user.Session, + Action: &ca.Name, + } + ca.client.Send(protoMessage{&packet}) +} + +// TriggerChannel will trigger the context action in the context of the given +// channel. +func (ca *ContextAction) TriggerChannel(channel *Channel) { + packet := MumbleProto.ContextAction{ + ChannelId: &channel.ID, + Action: &ca.Name, + } + ca.client.Send(protoMessage{&packet}) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextactions.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextactions.go new file mode 100644 index 0000000..c1defee --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextactions.go @@ -0,0 +1,12 @@ +package gumble + +// ContextActions is a map of ContextActions. +type ContextActions map[string]*ContextAction + +func (ca ContextActions) create(action string) *ContextAction { + contextAction := &ContextAction{ + Name: action, + } + ca[action] = contextAction + return contextAction +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/doc.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/doc.go new file mode 100644 index 0000000..fae0daa --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/doc.go @@ -0,0 +1,39 @@ +// Package gumble is a client for the Mumble voice chat software. +// +// Getting started +// +//1. Create a new Config to hold your connection settings: +// +// config := gumble.Config{ +// Username: "gumble-test", +// Address: "example.com:64738", +// } +// +//2. Create a new Client: +// +// client := gumble.NewClient(&config) +// +//3. Implement EventListener (or use gumbleutil.Listener) and attach it to the client: +// +// client.Attach(gumbleutil.Listener{ +// TextMessage: func(e *gumble.TextMessageEvent) { +// fmt.Printf("Received text message: %s\n", e.Message) +// }, +// }) +// +//4. Connect to the server: +// +// if err := client.Connect(); err != nil { +// panic(err) +// } +// +// Audio codecs +// +// Currently, only the Opus codec (https://www.opus-codec.org/) is supported +// for transmitting and receiving audio. +// +// To ensure that gumble clients can always transmit and receive audio to and +// from your server, add the following line to your murmur configuration file: +// +// opusthreshold=0 +package gumble diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/event.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/event.go new file mode 100644 index 0000000..d279582 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/event.go @@ -0,0 +1,202 @@ +package gumble + +import ( + "github.com/layeh/gumble/gumble/MumbleProto" +) + +// EventListener is the interface that must be implemented by a type if it +// wishes to be notified of Client events. +type EventListener interface { + OnConnect(e *ConnectEvent) + OnDisconnect(e *DisconnectEvent) + OnTextMessage(e *TextMessageEvent) + OnUserChange(e *UserChangeEvent) + OnChannelChange(e *ChannelChangeEvent) + OnPermissionDenied(e *PermissionDeniedEvent) + OnUserList(e *UserListEvent) + OnACL(e *ACLEvent) + OnBanList(e *BanListEvent) + OnContextActionChange(e *ContextActionChangeEvent) +} + +// ConnectEvent is the event that is passed to EventListener.OnConnect. +type ConnectEvent struct { + Client *Client + WelcomeMessage string + MaximumBitrate int +} + +// DisconnectType specifies why a Client disconnected from a server. +type DisconnectType int + +// Client disconnect reasons. +const ( + DisconnectError DisconnectType = 0xFE - iota + DisconnectKicked + DisconnectBanned + DisconnectUser + + DisconnectOther DisconnectType = DisconnectType(MumbleProto.Reject_None) + DisconnectVersion DisconnectType = DisconnectType(MumbleProto.Reject_WrongVersion) + DisconnectUserName DisconnectType = DisconnectType(MumbleProto.Reject_InvalidUsername) + DisconnectUserCredentials DisconnectType = DisconnectType(MumbleProto.Reject_WrongUserPW) + DisconnectServerPassword DisconnectType = DisconnectType(MumbleProto.Reject_WrongServerPW) + DisconnectUsernameInUse DisconnectType = DisconnectType(MumbleProto.Reject_UsernameInUse) + DisconnectServerFull DisconnectType = DisconnectType(MumbleProto.Reject_ServerFull) + DisconnectNoCertificate DisconnectType = DisconnectType(MumbleProto.Reject_NoCertificate) + DisconnectAuthenticatorFail DisconnectType = DisconnectType(MumbleProto.Reject_AuthenticatorFail) +) + +// Has returns true if the DisconnectType has changeType part of its bitmask. +func (dt DisconnectType) Has(changeType DisconnectType) bool { + return (dt & changeType) != 0 +} + +// DisconnectEvent is the event that is passed to EventListener.OnDisconnect. +type DisconnectEvent struct { + Client *Client + Type DisconnectType + + String string +} + +// TextMessageEvent is the event that is passed to EventListener.OnTextMessage. +type TextMessageEvent struct { + Client *Client + TextMessage +} + +// UserChangeType is a bitmask of items that changed for a user. +type UserChangeType int + +// User change items. +const ( + UserChangeConnected UserChangeType = 1 << iota + UserChangeDisconnected + UserChangeKicked + UserChangeBanned + UserChangeRegistered + UserChangeUnregistered + UserChangeName + UserChangeChannel + UserChangeComment + UserChangeAudio + UserChangeTexture + UserChangePrioritySpeaker + UserChangeRecording + UserChangeStats +) + +// Has returns true if the UserChangeType has changeType part of its bitmask. +func (uct UserChangeType) Has(changeType UserChangeType) bool { + return (uct & changeType) != 0 +} + +// UserChangeEvent is the event that is passed to EventListener.OnUserChange. +type UserChangeEvent struct { + Client *Client + Type UserChangeType + User *User + Actor *User + + String string +} + +// ChannelChangeType is a bitmask of items that changed for a channel. +type ChannelChangeType int + +// Channel change items. +const ( + ChannelChangeCreated ChannelChangeType = 1 << iota + ChannelChangeRemoved + ChannelChangeMoved + ChannelChangeName + ChannelChangeDescription + ChannelChangePosition + ChannelChangePermission +) + +// Has returns true if the ChannelChangeType has changeType part of its +// bitmask. +func (cct ChannelChangeType) Has(changeType ChannelChangeType) bool { + return (cct & changeType) != 0 +} + +// ChannelChangeEvent is the event that is passed to +// EventListener.OnChannelChange. +type ChannelChangeEvent struct { + Client *Client + Type ChannelChangeType + Channel *Channel +} + +// PermissionDeniedType specifies why a Client was denied permission to perform +// a particular action. +type PermissionDeniedType int + +// Permission denied types. +const ( + PermissionDeniedOther PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_Text) + PermissionDeniedPermission PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_Permission) + PermissionDeniedSuperUser PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_SuperUser) + PermissionDeniedInvalidChannelName PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelName) + PermissionDeniedTextTooLong PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_TextTooLong) + PermissionDeniedTemporaryChannel PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_TemporaryChannel) + PermissionDeniedMissingCertificate PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_MissingCertificate) + PermissionDeniedInvalidUserName PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_UserName) + PermissionDeniedChannelFull PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelFull) + PermissionDeniedNestingLimit PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_NestingLimit) +) + +// Has returns true if the PermissionDeniedType has changeType part of its +// bitmask. +func (pdt PermissionDeniedType) Has(changeType PermissionDeniedType) bool { + return (pdt & changeType) != 0 +} + +// PermissionDeniedEvent is the event that is passed to +// EventListener.OnPermissionDenied. +type PermissionDeniedEvent struct { + Client *Client + Type PermissionDeniedType + Channel *Channel + User *User + + Permission Permission + String string +} + +// UserListEvent is the event that is passed to EventListener.OnUserList. +type UserListEvent struct { + Client *Client + UserList RegisteredUsers +} + +// ACLEvent is the event that is passed to EventListener.OnACL. +type ACLEvent struct { + Client *Client + ACL *ACL +} + +// BanListEvent is the event that is passed to EventListener.OnBanList. +type BanListEvent struct { + Client *Client + BanList BanList +} + +// ContextActionChangeType specifies how a ContextAction changed. +type ContextActionChangeType int + +// ContextAction change types. +const ( + ContextActionAdd ContextActionChangeType = ContextActionChangeType(MumbleProto.ContextActionModify_Add) + ContextActionRemove ContextActionChangeType = ContextActionChangeType(MumbleProto.ContextActionModify_Remove) +) + +// ContextActionChangeEvent is the event that is passed to +// EventListener.OnContextActionChange. +type ContextActionChangeEvent struct { + Client *Client + Type ContextActionChangeType + ContextAction *ContextAction +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/eventmultiplexer.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/eventmultiplexer.go new file mode 100644 index 0000000..3ee5915 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/eventmultiplexer.go @@ -0,0 +1,106 @@ +package gumble + +// Detacher is an interface that event listeners implement. After the Detach +// method is called, the listener will no longer receive events. +type Detacher interface { + Detach() +} + +type eventMultiplexerItem struct { + mux *eventMultiplexer + prev, next *eventMultiplexerItem + listener EventListener +} + +func (emi *eventMultiplexerItem) Detach() { + if emi.prev == nil { + emi.mux.head = emi.next + } else { + emi.prev.next = emi.next + } + if emi.next == nil { + emi.mux.tail = emi.prev + } else { + emi.next.prev = emi.prev + } +} + +type eventMultiplexer struct { + head, tail *eventMultiplexerItem +} + +func (em *eventMultiplexer) Attach(listener EventListener) Detacher { + item := &eventMultiplexerItem{ + mux: em, + prev: em.tail, + listener: listener, + } + if em.head == nil { + em.head = item + } + if em.tail != nil { + em.tail.next = item + } + em.tail = item + return item +} + +func (em eventMultiplexer) OnConnect(event *ConnectEvent) { + for item := em.head; item != nil; item = item.next { + item.listener.OnConnect(event) + } +} + +func (em eventMultiplexer) OnDisconnect(event *DisconnectEvent) { + for item := em.head; item != nil; item = item.next { + item.listener.OnDisconnect(event) + } +} + +func (em eventMultiplexer) OnTextMessage(event *TextMessageEvent) { + for item := em.head; item != nil; item = item.next { + item.listener.OnTextMessage(event) + } +} + +func (em eventMultiplexer) OnUserChange(event *UserChangeEvent) { + for item := em.head; item != nil; item = item.next { + item.listener.OnUserChange(event) + } +} + +func (em eventMultiplexer) OnChannelChange(event *ChannelChangeEvent) { + for item := em.head; item != nil; item = item.next { + item.listener.OnChannelChange(event) + } +} + +func (em eventMultiplexer) OnPermissionDenied(event *PermissionDeniedEvent) { + for item := em.head; item != nil; item = item.next { + item.listener.OnPermissionDenied(event) + } +} + +func (em eventMultiplexer) OnUserList(event *UserListEvent) { + for item := em.head; item != nil; item = item.next { + item.listener.OnUserList(event) + } +} + +func (em eventMultiplexer) OnACL(event *ACLEvent) { + for item := em.head; item != nil; item = item.next { + item.listener.OnACL(event) + } +} + +func (em eventMultiplexer) OnBanList(event *BanListEvent) { + for item := em.head; item != nil; item = item.next { + item.listener.OnBanList(event) + } +} + +func (em eventMultiplexer) OnContextActionChange(event *ContextActionChangeEvent) { + for item := em.head; item != nil; item = item.next { + item.listener.OnContextActionChange(event) + } +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/handlers.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/handlers.go new file mode 100644 index 0000000..e2e25c8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/handlers.go @@ -0,0 +1,962 @@ +package gumble + +import ( + "bytes" + "crypto/x509" + "encoding/binary" + "errors" + "math" + "net" + "time" + + "github.com/golang/protobuf/proto" + "github.com/layeh/gopus" + "github.com/layeh/gumble/gumble/MumbleProto" + "github.com/layeh/gumble/gumble/varint" +) + +type handlerFunc func(*Client, []byte) error + +var ( + errUnimplementedHandler = errors.New("the handler has not been implemented") + errIncompleteProtobuf = errors.New("protobuf message is missing a required field") + errInvalidProtobuf = errors.New("protobuf message has an invalid field") + errUnsupportedAudio = errors.New("unsupported audio codec") +) + +var handlers = map[uint16]handlerFunc{ + 0: (*Client).handleVersion, + 1: (*Client).handleUdpTunnel, + 2: (*Client).handleAuthenticate, + 3: (*Client).handlePing, + 4: (*Client).handleReject, + 5: (*Client).handleServerSync, + 6: (*Client).handleChannelRemove, + 7: (*Client).handleChannelState, + 8: (*Client).handleUserRemove, + 9: (*Client).handleUserState, + 10: (*Client).handleBanList, + 11: (*Client).handleTextMessage, + 12: (*Client).handlePermissionDenied, + 13: (*Client).handleACL, + 14: (*Client).handleQueryUsers, + 15: (*Client).handleCryptSetup, + 16: (*Client).handleContextActionModify, + 17: (*Client).handleContextAction, + 18: (*Client).handleUserList, + 19: (*Client).handleVoiceTarget, + 20: (*Client).handlePermissionQuery, + 21: (*Client).handleCodecVersion, + 22: (*Client).handleUserStats, + 23: (*Client).handleRequestBlob, + 24: (*Client).handleServerConfig, + 25: (*Client).handleSuggestConfig, +} + +func parseVersion(packet *MumbleProto.Version) Version { + var version Version + if packet.Version != nil { + version.Version = *packet.Version + } + if packet.Release != nil { + version.Release = *packet.Release + } + if packet.Os != nil { + version.OS = *packet.Os + } + if packet.OsVersion != nil { + version.OSVersion = *packet.OsVersion + } + return version +} + +func (c *Client) handleVersion(buffer []byte) error { + var packet MumbleProto.Version + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + return nil +} + +func (c *Client) handleUdpTunnel(buffer []byte) error { + reader := bytes.NewReader(buffer) + var bytesRead int64 + + var audioType byte + var audioTarget byte + var user *User + var audioLength int + + // Header byte + typeTarget, err := varint.ReadByte(reader) + if err != nil { + return err + } + audioType = (typeTarget >> 5) & 0x7 + audioTarget = typeTarget & 0x1F + // Opus only + if audioType != 4 { + return errUnsupportedAudio + } + bytesRead++ + + // Session + session, n, err := varint.ReadFrom(reader) + if err != nil { + return err + } + user = c.Users[uint32(session)] + if user == nil { + return errInvalidProtobuf + } + bytesRead += n + + // Sequence + sequence, n, err := varint.ReadFrom(reader) + if err != nil { + return err + } + bytesRead += n + + // Length + length, n, err := varint.ReadFrom(reader) + if err != nil { + return err + } + // Opus audio packets set the 13th bit in the size field as the terminator. + audioLength = int(length) &^ 0x2000 + if audioLength > reader.Len() { + return errInvalidProtobuf + } + audioLength64 := int64(audioLength) + bytesRead += n + + opus := buffer[bytesRead : bytesRead+audioLength64] + pcm, err := user.decoder.Decode(opus, AudioMaximumFrameSize, false) + if err != nil { + return err + } + event := AudioPacketEvent{ + Client: c, + } + event.AudioPacket.Sender = user + event.AudioPacket.Target = int(audioTarget) + event.AudioPacket.Sequence = int(sequence) + event.AudioPacket.PositionalAudioBuffer.AudioBuffer = pcm + + reader.Seek(audioLength64, 1) + binary.Read(reader, binary.LittleEndian, &event.AudioPacket.PositionalAudioBuffer.X) + binary.Read(reader, binary.LittleEndian, &event.AudioPacket.PositionalAudioBuffer.Y) + binary.Read(reader, binary.LittleEndian, &event.AudioPacket.PositionalAudioBuffer.Z) + + c.audioListeners.OnAudioPacket(&event) + return nil +} + +func (c *Client) handleAuthenticate(buffer []byte) error { + return errUnimplementedHandler +} + +func (c *Client) handlePing(buffer []byte) error { + var packet MumbleProto.Ping + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + c.pingStats.TCPPackets++ + return nil +} + +func (c *Client) handleReject(buffer []byte) error { + var packet MumbleProto.Reject + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + if packet.Type != nil { + c.disconnectEvent.Type = DisconnectType(*packet.Type) + } + if packet.Reason != nil { + c.disconnectEvent.String = *packet.Reason + } + c.Conn.Close() + return nil +} + +func (c *Client) handleServerSync(buffer []byte) error { + var packet MumbleProto.ServerSync + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + event := ConnectEvent{ + Client: c, + } + + if packet.Session != nil { + c.Self = c.Users[*packet.Session] + } + if packet.WelcomeText != nil { + event.WelcomeMessage = *packet.WelcomeText + } + if packet.MaxBandwidth != nil { + event.MaximumBitrate = int(*packet.MaxBandwidth) + } + c.State = StateSynced + + c.listeners.OnConnect(&event) + return nil +} + +func (c *Client) handleChannelRemove(buffer []byte) error { + var packet MumbleProto.ChannelRemove + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + if packet.ChannelId == nil { + return errIncompleteProtobuf + } + var channel *Channel + { + channelID := *packet.ChannelId + channel = c.Channels[channelID] + if channel == nil { + return errInvalidProtobuf + } + delete(c.Channels, channelID) + delete(c.permissions, channelID) + if parent := channel.Parent; parent != nil { + delete(parent.Children, channel.ID) + } + } + + if c.State == StateSynced { + event := ChannelChangeEvent{ + Client: c, + Type: ChannelChangeRemoved, + Channel: channel, + } + c.listeners.OnChannelChange(&event) + } + return nil +} + +func (c *Client) handleChannelState(buffer []byte) error { + var packet MumbleProto.ChannelState + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + if packet.ChannelId == nil { + return errIncompleteProtobuf + } + event := ChannelChangeEvent{ + Client: c, + } + channelID := *packet.ChannelId + channel := c.Channels[channelID] + if channel == nil { + channel = c.Channels.create(channelID) + channel.client = c + + event.Type |= ChannelChangeCreated + } + event.Channel = channel + if packet.Parent != nil { + if channel.Parent != nil { + delete(channel.Parent.Children, channelID) + } + newParent := c.Channels[*packet.Parent] + if newParent != channel.Parent { + event.Type |= ChannelChangeMoved + } + channel.Parent = newParent + if channel.Parent != nil { + channel.Parent.Children[channel.ID] = channel + } + } + if packet.Name != nil { + if *packet.Name != channel.Name { + event.Type |= ChannelChangeName + } + channel.Name = *packet.Name + } + if packet.Description != nil { + if *packet.Description != channel.Description { + event.Type |= ChannelChangeDescription + } + channel.Description = *packet.Description + channel.DescriptionHash = nil + } + if packet.Temporary != nil { + channel.Temporary = *packet.Temporary + } + if packet.Position != nil { + if *packet.Position != channel.Position { + event.Type |= ChannelChangePosition + } + channel.Position = *packet.Position + } + if packet.DescriptionHash != nil { + event.Type |= ChannelChangeDescription + channel.DescriptionHash = packet.DescriptionHash + channel.Description = "" + } + + if c.State == StateSynced { + c.listeners.OnChannelChange(&event) + } + return nil +} + +func (c *Client) handleUserRemove(buffer []byte) error { + var packet MumbleProto.UserRemove + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + if packet.Session == nil { + return errIncompleteProtobuf + } + event := UserChangeEvent{ + Client: c, + Type: UserChangeDisconnected, + } + { + session := *packet.Session + event.User = c.Users[session] + if event.User == nil { + return errInvalidProtobuf + } + if event.User.Channel != nil { + delete(event.User.Channel.Users, session) + } + delete(c.Users, session) + } + if packet.Actor != nil { + event.Actor = c.Users[*packet.Actor] + if event.Actor == nil { + return errInvalidProtobuf + } + event.Type |= UserChangeKicked + } + if packet.Reason != nil { + event.String = *packet.Reason + } + if packet.Ban != nil && *packet.Ban { + event.Type |= UserChangeBanned + } + if event.User == c.Self { + if packet.Ban != nil && *packet.Ban { + c.disconnectEvent.Type = DisconnectBanned + } else { + c.disconnectEvent.Type = DisconnectKicked + } + } + + if c.State == StateSynced { + c.listeners.OnUserChange(&event) + } + return nil +} + +func (c *Client) handleUserState(buffer []byte) error { + var packet MumbleProto.UserState + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + if packet.Session == nil { + return errIncompleteProtobuf + } + event := UserChangeEvent{ + Client: c, + } + var user, actor *User + { + session := *packet.Session + user = c.Users[session] + if user == nil { + user = c.Users.create(session) + user.Channel = c.Channels[0] + user.client = c + + event.Type |= UserChangeConnected + + decoder, _ := gopus.NewDecoder(AudioSampleRate, 1) + user.decoder = decoder + + if user.Channel == nil { + return errInvalidProtobuf + } + event.Type |= UserChangeChannel + user.Channel.Users[session] = user + } + } + event.User = user + if packet.Actor != nil { + actor = c.Users[*packet.Actor] + if actor == nil { + return errInvalidProtobuf + } + event.Actor = actor + } + if packet.Name != nil { + if *packet.Name != user.Name { + event.Type |= UserChangeName + } + user.Name = *packet.Name + } + if packet.UserId != nil { + if *packet.UserId != user.UserID && !event.Type.Has(UserChangeConnected) { + if *packet.UserId != math.MaxUint32 { + event.Type |= UserChangeRegistered + user.UserID = *packet.UserId + } else { + event.Type |= UserChangeUnregistered + user.UserID = 0 + } + } else { + user.UserID = *packet.UserId + } + } + if packet.ChannelId != nil { + if user.Channel != nil { + delete(user.Channel.Users, user.Session) + } + newChannel := c.Channels[*packet.ChannelId] + if newChannel == nil { + return errInvalidProtobuf + } + if newChannel != user.Channel { + event.Type |= UserChangeChannel + user.Channel = newChannel + } + user.Channel.Users[user.Session] = user + } + if packet.Mute != nil { + if *packet.Mute != user.Muted { + event.Type |= UserChangeAudio + } + user.Muted = *packet.Mute + } + if packet.Deaf != nil { + if *packet.Deaf != user.Deafened { + event.Type |= UserChangeAudio + } + user.Deafened = *packet.Deaf + } + if packet.Suppress != nil { + if *packet.Suppress != user.Suppressed { + event.Type |= UserChangeAudio + } + user.Suppressed = *packet.Suppress + } + if packet.SelfMute != nil { + if *packet.SelfMute != user.SelfMuted { + event.Type |= UserChangeAudio + } + user.SelfMuted = *packet.SelfMute + } + if packet.SelfDeaf != nil { + if *packet.SelfDeaf != user.SelfDeafened { + event.Type |= UserChangeAudio + } + user.SelfDeafened = *packet.SelfDeaf + } + if packet.Texture != nil { + event.Type |= UserChangeTexture + user.Texture = packet.Texture + user.TextureHash = nil + } + if packet.Comment != nil { + if *packet.Comment != user.Comment { + event.Type |= UserChangeComment + } + user.Comment = *packet.Comment + user.CommentHash = nil + } + if packet.Hash != nil { + user.Hash = *packet.Hash + } + if packet.CommentHash != nil { + event.Type |= UserChangeComment + user.CommentHash = packet.CommentHash + user.Comment = "" + } + if packet.TextureHash != nil { + event.Type |= UserChangeTexture + user.TextureHash = packet.TextureHash + user.Texture = nil + } + if packet.PrioritySpeaker != nil { + if *packet.PrioritySpeaker != user.PrioritySpeaker { + event.Type |= UserChangePrioritySpeaker + } + user.PrioritySpeaker = *packet.PrioritySpeaker + } + if packet.Recording != nil { + if *packet.Recording != user.Recording { + event.Type |= UserChangeRecording + } + user.Recording = *packet.Recording + } + + if c.State == StateSynced { + c.listeners.OnUserChange(&event) + } + return nil +} + +func (c *Client) handleBanList(buffer []byte) error { + var packet MumbleProto.BanList + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + event := BanListEvent{ + Client: c, + BanList: make(BanList, 0, len(packet.Bans)), + } + + for _, banPacket := range packet.Bans { + ban := &Ban{ + Address: net.IP(banPacket.Address), + } + if banPacket.Mask != nil { + size := net.IPv4len * 8 + if len(ban.Address) == net.IPv6len { + size = net.IPv6len * 8 + } + ban.Mask = net.CIDRMask(int(*banPacket.Mask), size) + } + if banPacket.Name != nil { + ban.Name = *banPacket.Name + } + if banPacket.Hash != nil { + ban.Hash = *banPacket.Hash + } + if banPacket.Reason != nil { + ban.Reason = *banPacket.Reason + } + if banPacket.Start != nil { + ban.Start, _ = time.Parse(time.RFC3339, *banPacket.Start) + } + if banPacket.Duration != nil { + ban.Duration = time.Duration(*banPacket.Duration) * time.Second + } + event.BanList = append(event.BanList, ban) + } + + c.listeners.OnBanList(&event) + return nil +} + +func (c *Client) handleTextMessage(buffer []byte) error { + var packet MumbleProto.TextMessage + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + event := TextMessageEvent{ + Client: c, + } + if packet.Actor != nil { + event.Sender = c.Users[*packet.Actor] + } + if packet.Session != nil { + event.Users = make([]*User, 0, len(packet.Session)) + for _, session := range packet.Session { + if user := c.Users[session]; user != nil { + event.Users = append(event.Users, user) + } + } + } + if packet.ChannelId != nil { + event.Channels = make([]*Channel, 0, len(packet.ChannelId)) + for _, id := range packet.ChannelId { + if channel := c.Channels[id]; channel != nil { + event.Channels = append(event.Channels, channel) + } + } + } + if packet.TreeId != nil { + event.Trees = make([]*Channel, 0, len(packet.TreeId)) + for _, id := range packet.TreeId { + if channel := c.Channels[id]; channel != nil { + event.Trees = append(event.Trees, channel) + } + } + } + if packet.Message != nil { + event.Message = *packet.Message + } + + c.listeners.OnTextMessage(&event) + return nil +} + +func (c *Client) handlePermissionDenied(buffer []byte) error { + var packet MumbleProto.PermissionDenied + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + if packet.Type == nil || *packet.Type == MumbleProto.PermissionDenied_H9K { + return errInvalidProtobuf + } + + event := PermissionDeniedEvent{ + Client: c, + Type: PermissionDeniedType(*packet.Type), + } + if packet.Reason != nil { + event.String = *packet.Reason + } + if packet.Name != nil { + event.String = *packet.Name + } + if packet.Session != nil { + event.User = c.Users[*packet.Session] + if event.User == nil { + return errInvalidProtobuf + } + } + if packet.ChannelId != nil { + event.Channel = c.Channels[*packet.ChannelId] + if event.Channel == nil { + return errInvalidProtobuf + } + } + if packet.Permission != nil { + event.Permission = Permission(*packet.Permission) + } + + c.listeners.OnPermissionDenied(&event) + return nil +} + +func (c *Client) handleACL(buffer []byte) error { + var packet MumbleProto.ACL + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + acl := &ACL{ + Inherits: packet.GetInheritAcls(), + } + if packet.ChannelId == nil { + return errInvalidProtobuf + } + acl.Channel = c.Channels[*packet.ChannelId] + if acl.Channel == nil { + return errInvalidProtobuf + } + + if packet.Groups != nil { + acl.Groups = make([]*ACLGroup, 0, len(packet.Groups)) + for _, group := range packet.Groups { + aclGroup := &ACLGroup{ + Name: *group.Name, + Inherited: group.GetInherited(), + InheritUsers: group.GetInherit(), + Inheritable: group.GetInheritable(), + } + if group.Add != nil { + aclGroup.usersAdd = make(map[uint32]*ACLUser) + for _, userID := range group.Add { + aclGroup.usersAdd[userID] = &ACLUser{ + UserID: userID, + } + } + } + if group.Remove != nil { + aclGroup.usersRemove = make(map[uint32]*ACLUser) + for _, userID := range group.Remove { + aclGroup.usersRemove[userID] = &ACLUser{ + UserID: userID, + } + } + } + if group.InheritedMembers != nil { + aclGroup.usersInherited = make(map[uint32]*ACLUser) + for _, userID := range group.InheritedMembers { + aclGroup.usersInherited[userID] = &ACLUser{ + UserID: userID, + } + } + } + acl.Groups = append(acl.Groups, aclGroup) + } + } + if packet.Acls != nil { + acl.Rules = make([]*ACLRule, 0, len(packet.Acls)) + for _, rule := range packet.Acls { + aclRule := &ACLRule{ + AppliesCurrent: rule.GetApplyHere(), + AppliesChildren: rule.GetApplySubs(), + Inherited: rule.GetInherited(), + Granted: Permission(rule.GetGrant()), + Denied: Permission(rule.GetDeny()), + } + if rule.UserId != nil { + aclRule.User = &ACLUser{ + UserID: *rule.UserId, + } + } else if rule.Group != nil { + var group *ACLGroup + for _, g := range acl.Groups { + if g.Name == *rule.Group { + group = g + break + } + } + if group == nil { + group = &ACLGroup{ + Name: *rule.Group, + } + } + aclRule.Group = group + } + acl.Rules = append(acl.Rules, aclRule) + } + } + c.tmpACL = acl + return nil +} + +func (c *Client) handleQueryUsers(buffer []byte) error { + var packet MumbleProto.QueryUsers + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + acl := c.tmpACL + if acl == nil { + return errIncompleteProtobuf + } + c.tmpACL = nil + + userMap := make(map[uint32]string) + for i := 0; i < len(packet.Ids) && i < len(packet.Names); i++ { + userMap[packet.Ids[i]] = packet.Names[i] + } + + for _, group := range acl.Groups { + for _, user := range group.usersAdd { + user.Name = userMap[user.UserID] + } + for _, user := range group.usersRemove { + user.Name = userMap[user.UserID] + } + for _, user := range group.usersInherited { + user.Name = userMap[user.UserID] + } + } + for _, rule := range acl.Rules { + if rule.User != nil { + rule.User.Name = userMap[rule.User.UserID] + } + } + + event := ACLEvent{ + Client: c, + ACL: acl, + } + c.listeners.OnACL(&event) + return nil +} + +func (c *Client) handleCryptSetup(buffer []byte) error { + return errUnimplementedHandler +} + +func (c *Client) handleContextActionModify(buffer []byte) error { + var packet MumbleProto.ContextActionModify + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + if packet.Action == nil || packet.Operation == nil { + return errInvalidProtobuf + } + + event := ContextActionChangeEvent{ + Client: c, + } + + switch *packet.Operation { + case MumbleProto.ContextActionModify_Add: + if ca := c.ContextActions[*packet.Action]; ca != nil { + return nil + } + event.Type = ContextActionAdd + contextAction := c.ContextActions.create(*packet.Action) + if packet.Text != nil { + contextAction.Label = *packet.Text + } + if packet.Context != nil { + contextAction.Type = ContextActionType(*packet.Context) + } + event.ContextAction = contextAction + case MumbleProto.ContextActionModify_Remove: + contextAction := c.ContextActions[*packet.Action] + if contextAction == nil { + return nil + } + event.Type = ContextActionRemove + delete(c.ContextActions, *packet.Action) + event.ContextAction = contextAction + default: + return errInvalidProtobuf + } + + c.listeners.OnContextActionChange(&event) + return nil +} + +func (c *Client) handleContextAction(buffer []byte) error { + return errUnimplementedHandler +} + +func (c *Client) handleUserList(buffer []byte) error { + var packet MumbleProto.UserList + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + event := UserListEvent{ + Client: c, + UserList: make(RegisteredUsers, 0, len(packet.Users)), + } + + for _, user := range packet.Users { + registeredUser := &RegisteredUser{ + UserID: *user.UserId, + } + if user.Name != nil { + registeredUser.Name = *user.Name + } + event.UserList = append(event.UserList, registeredUser) + } + + c.listeners.OnUserList(&event) + return nil +} + +func (c *Client) handleVoiceTarget(buffer []byte) error { + return errUnimplementedHandler +} + +func (c *Client) handlePermissionQuery(buffer []byte) error { + var packet MumbleProto.PermissionQuery + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + if packet.Flush != nil && *packet.Flush { + oldPermissions := c.permissions + c.permissions = make(map[uint32]*Permission) + for channelID := range oldPermissions { + channel := c.Channels[channelID] + event := ChannelChangeEvent{ + Client: c, + Type: ChannelChangePermission, + Channel: channel, + } + c.listeners.OnChannelChange(&event) + } + } + if packet.ChannelId != nil { + channel := c.Channels[*packet.ChannelId] + if packet.Permissions != nil { + p := Permission(*packet.Permissions) + c.permissions[channel.ID] = &p + event := ChannelChangeEvent{ + Client: c, + Type: ChannelChangePermission, + Channel: channel, + } + c.listeners.OnChannelChange(&event) + } + } + return nil +} + +func (c *Client) handleCodecVersion(buffer []byte) error { + return errUnimplementedHandler +} + +func (c *Client) handleUserStats(buffer []byte) error { + var packet MumbleProto.UserStats + if err := proto.Unmarshal(buffer, &packet); err != nil { + return err + } + + if packet.Session == nil { + return errIncompleteProtobuf + } + user := c.Users[*packet.Session] + if user == nil { + return errInvalidProtobuf + } + + if user.Stats == nil { + user.Stats = &UserStats{} + } + *user.Stats = UserStats{ + User: user, + } + stats := user.Stats + + if packet.Version != nil { + stats.Version = parseVersion(packet.Version) + } + if packet.Onlinesecs != nil { + stats.Connected = time.Now().Add(time.Duration(*packet.Onlinesecs) * -time.Second) + } + if packet.Idlesecs != nil { + stats.Idle = time.Duration(*packet.Idlesecs) * time.Second + } + if packet.Bandwidth != nil { + stats.Bandwidth = int(*packet.Bandwidth) + } + if packet.Address != nil { + stats.IP = net.IP(packet.Address) + } + if packet.Certificates != nil { + stats.Certificates = make([]*x509.Certificate, 0, len(packet.Certificates)) + for _, data := range packet.Certificates { + if data != nil { + if cert, err := x509.ParseCertificate(data); err == nil { + stats.Certificates = append(stats.Certificates, cert) + } + } + } + } + stats.StrongCertificate = packet.GetStrongCertificate() + stats.CELTVersions = packet.GetCeltVersions() + if packet.Opus != nil { + stats.Opus = *packet.Opus + } + + event := UserChangeEvent{ + Client: c, + Type: UserChangeStats, + User: user, + } + + c.listeners.OnUserChange(&event) + return nil +} + +func (c *Client) handleRequestBlob(buffer []byte) error { + return errUnimplementedHandler +} + +func (c *Client) handleServerConfig(buffer []byte) error { + return errUnimplementedHandler +} + +func (c *Client) handleSuggestConfig(buffer []byte) error { + return errUnimplementedHandler +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/message.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/message.go new file mode 100644 index 0000000..a84d8c1 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/message.go @@ -0,0 +1,8 @@ +package gumble + +// Message is data that be encoded and sent to the server. The following +// types implement this interface: AudioBuffer, AccessTokens, BanList, +// RegisteredUsers, TextMessage, and VoiceTarget. +type Message interface { + writeMessage(client *Client) error +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/permission.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/permission.go new file mode 100644 index 0000000..91a84e5 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/permission.go @@ -0,0 +1,27 @@ +package gumble + +// Permission is a bitmask of permissions given to a certain user. +type Permission int + +// Permissions that can be applied in any channel. +const ( + PermissionWrite Permission = 1 << iota + PermissionTraverse + PermissionEnter + PermissionSpeak + PermissionMuteDeafen + PermissionMove + PermissionMakeChannel + PermissionLinkChannel + PermissionWhisper + PermissionTextMessage + PermissionMakeTemporaryChannel +) + +// Permissions that can only be applied in the root channel. +const ( + PermissionKick Permission = 0x10000 << iota + PermissionBan + PermissionRegister + PermissionRegisterSelf +) diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/ping.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/ping.go new file mode 100644 index 0000000..719cb3b --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/ping.go @@ -0,0 +1,73 @@ +package gumble + +import ( + "bytes" + "crypto/rand" + "encoding/binary" + "io" + "net" + "time" +) + +// PingResponse contains information about a server that responded to a UDP +// ping packet. +type PingResponse struct { + // The address of the pinged server. + Address *net.UDPAddr + // The round-trip time from the client to the server. + Ping time.Duration + // The server's version. Only the Version field and SemanticVersion method of + // the value will be valid. + Version Version + // The number users currently connected to the server. + ConnectedUsers int + // The maximum number of users that can connect to the server. + MaximumUsers int + // The maximum audio bitrate per user for the server. + MaximumBitrate int +} + +// Ping sends a UDP ping packet to the given server. Returns a PingResponse and +// nil on success. The function will return nil and an error if a valid +// response is not received after the given timeout. +func Ping(address string, timeout time.Duration) (*PingResponse, error) { + addr, err := net.ResolveUDPAddr("udp", address) + if err != nil { + return nil, err + } + conn, err := net.DialUDP("udp", nil, addr) + if err != nil { + return nil, err + } + + var packet [12]byte + if _, err := rand.Read(packet[4:]); err != nil { + return nil, err + } + start := time.Now() + if _, err := conn.Write(packet[:]); err != nil { + return nil, err + } + + conn.SetReadDeadline(time.Now().Add(timeout)) + for { + var incoming [24]byte + if _, err := io.ReadFull(conn, incoming[:]); err != nil { + return nil, err + } + if !bytes.Equal(incoming[4:12], packet[4:]) { + continue + } + + return &PingResponse{ + Address: addr, + Ping: time.Since(start), + Version: Version{ + Version: binary.BigEndian.Uint32(incoming[0:]), + }, + ConnectedUsers: int(binary.BigEndian.Uint32(incoming[12:])), + MaximumUsers: int(binary.BigEndian.Uint32(incoming[16:])), + MaximumBitrate: int(binary.BigEndian.Uint32(incoming[20:])), + }, nil + } +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/pingstats.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/pingstats.go new file mode 100644 index 0000000..5748a82 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/pingstats.go @@ -0,0 +1,5 @@ +package gumble + +type pingStats struct { + TCPPackets uint32 +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/protomessage.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/protomessage.go new file mode 100644 index 0000000..3b1c5a7 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/protomessage.go @@ -0,0 +1,16 @@ +package gumble + +import ( + "github.com/golang/protobuf/proto" +) + +type protoMessage struct { + proto.Message +} + +func (pm protoMessage) writeMessage(client *Client) error { + if err := client.Conn.WriteProto(pm.Message); err != nil { + return err + } + return nil +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/request.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/request.go new file mode 100644 index 0000000..f38ef1b --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/request.go @@ -0,0 +1,18 @@ +package gumble + +// Request is a mask of items that the client can ask the server to send. +type Request int + +// Items that can be requested from the server. See the documentation for +// Channel.Request, Client.Request, and User.Request to see which request types +// each one supports. +const ( + RequestDescription Request = 1 << iota + RequestComment + RequestTexture + RequestStats + RequestUserList + RequestACL + RequestBanList + RequestPermission +) diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/textmessage.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/textmessage.go new file mode 100644 index 0000000..264d9a3 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/textmessage.go @@ -0,0 +1,50 @@ +package gumble + +import ( + "github.com/layeh/gumble/gumble/MumbleProto" +) + +// TextMessage is a chat message that can be received from and sent to the +// server. +type TextMessage struct { + // User who sent the message (can be nil). + Sender *User + + // Users that receive the message. + Users []*User + + // Channels that receive the message. + Channels []*Channel + + // Channels that receive the message and send it recursively to sub-channels. + Trees []*Channel + + // Chat message. + Message string +} + +func (tm *TextMessage) writeMessage(client *Client) error { + packet := MumbleProto.TextMessage{ + Message: &tm.Message, + } + if tm.Users != nil { + packet.Session = make([]uint32, len(tm.Users)) + for i, user := range tm.Users { + packet.Session[i] = user.Session + } + } + if tm.Channels != nil { + packet.ChannelId = make([]uint32, len(tm.Channels)) + for i, channel := range tm.Channels { + packet.ChannelId[i] = channel.ID + } + } + if tm.Trees != nil { + packet.TreeId = make([]uint32, len(tm.Trees)) + for i, channel := range tm.Trees { + packet.TreeId[i] = channel.ID + } + } + proto := protoMessage{&packet} + return proto.writeMessage(client) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/user.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/user.go new file mode 100644 index 0000000..c03c3e5 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/user.go @@ -0,0 +1,231 @@ +package gumble + +import ( + "github.com/golang/protobuf/proto" + "github.com/layeh/gopus" + "github.com/layeh/gumble/gumble/MumbleProto" +) + +// User represents a user that is currently connected to the server. +type User struct { + // The user's unique session ID. + Session uint32 + // The user's ID. Contains an invalid value if the user is not registered. + UserID uint32 + // The user's name. + Name string + // The channel that the user is currently in. + Channel *Channel + + // Has the user has been muted? + Muted bool + // Has the user been deafened? + Deafened bool + // Has the user been suppressed? + Suppressed bool + // Has the user been muted by him/herself? + SelfMuted bool + // Has the user been deafened by him/herself? + SelfDeafened bool + // Is the user a priority speaker in the channel? + PrioritySpeaker bool + // Is the user recording audio? + Recording bool + + // The user's comment. Contains the empty string if the user does not have a + // comment, or if the comment needs to be requested. + Comment string + // The user's comment hash. Contains nil if User.Comment has been populated. + CommentHash []byte + // The hash of the user's certificate (can be empty). + Hash string + // The user's texture (avatar). Contains nil if the user does not have a + // texture, or if the texture needs to be requested. + Texture []byte + // The user's texture hash. Contains nil if User.Texture has been populated. + TextureHash []byte + + // The user's stats. Containts nil if the stats have not yet been requested. + Stats *UserStats + + client *Client + decoder *gopus.Decoder +} + +// SetTexture sets the user's texture. +func (u *User) SetTexture(texture []byte) { + packet := MumbleProto.UserState{ + Session: &u.Session, + Texture: texture, + } + u.client.Send(protoMessage{&packet}) +} + +// SetPrioritySpeaker sets if the user is a priority speaker in the channel. +func (u *User) SetPrioritySpeaker(prioritySpeaker bool) { + packet := MumbleProto.UserState{ + Session: &u.Session, + PrioritySpeaker: &prioritySpeaker, + } + u.client.Send(protoMessage{&packet}) +} + +// SetRecording sets if the user is recording audio. +func (u *User) SetRecording(recording bool) { + packet := MumbleProto.UserState{ + Session: &u.Session, + Recording: &recording, + } + u.client.Send(protoMessage{&packet}) +} + +// IsRegistered returns true if the user's certificate has been registered with +// the server. A registered user will have a valid user ID. +func (u *User) IsRegistered() bool { + return u.UserID > 0 +} + +// Register will register the user with the server. If the client has +// permission to do so, the user will shortly be given a UserID. +func (u *User) Register() { + packet := MumbleProto.UserState{ + Session: &u.Session, + UserId: proto.Uint32(0), + } + u.client.Send(protoMessage{&packet}) +} + +// SetComment will set the user's comment to the given string. The user's +// comment will be erased if the comment is set to the empty string. +func (u *User) SetComment(comment string) { + packet := MumbleProto.UserState{ + Session: &u.Session, + Comment: &comment, + } + u.client.Send(protoMessage{&packet}) +} + +// Move will move the user to the given channel. +func (u *User) Move(channel *Channel) { + packet := MumbleProto.UserState{ + Session: &u.Session, + ChannelId: &channel.ID, + } + u.client.Send(protoMessage{&packet}) +} + +// Kick will kick the user from the server. +func (u *User) Kick(reason string) { + packet := MumbleProto.UserRemove{ + Session: &u.Session, + Reason: &reason, + } + u.client.Send(protoMessage{&packet}) +} + +// Ban will ban the user from the server. +func (u *User) Ban(reason string) { + packet := MumbleProto.UserRemove{ + Session: &u.Session, + Reason: &reason, + Ban: proto.Bool(true), + } + u.client.Send(protoMessage{&packet}) +} + +// SetMuted sets whether the user can transmit audio or not. +func (u *User) SetMuted(muted bool) { + packet := MumbleProto.UserState{ + Session: &u.Session, + Mute: &muted, + } + u.client.Send(protoMessage{&packet}) +} + +// SetSuppressed sets whether the user is suppressed by the server or not. +func (u *User) SetSuppressed(supressed bool) { + packet := MumbleProto.UserState{ + Session: &u.Session, + Suppress: &supressed, + } + u.client.Send(protoMessage{&packet}) +} + +// SetDeafened sets whether the user can receive audio or not. +func (u *User) SetDeafened(muted bool) { + packet := MumbleProto.UserState{ + Session: &u.Session, + Deaf: &muted, + } + u.client.Send(protoMessage{&packet}) +} + +// SetSelfMuted sets whether the user can transmit audio or not. +// +// This method should only be called on Client.Self(). +func (u *User) SetSelfMuted(muted bool) { + packet := MumbleProto.UserState{ + Session: &u.Session, + SelfMute: &muted, + } + u.client.Send(protoMessage{&packet}) +} + +// SetSelfDeafened sets whether the user can receive audio or not. +// +// This method should only be called on Client.Self(). +func (u *User) SetSelfDeafened(muted bool) { + packet := MumbleProto.UserState{ + Session: &u.Session, + SelfDeaf: &muted, + } + u.client.Send(protoMessage{&packet}) +} + +// Request requests user information that has not yet been sent to the client. +// The supported request types are: RequestStats, RequestTexture, and +// RequestComment. +func (u *User) Request(request Request) { + if (request & RequestStats) != 0 { + packet := MumbleProto.UserStats{ + Session: &u.Session, + } + u.client.Send(protoMessage{&packet}) + } + + packet := MumbleProto.RequestBlob{} + if (request & RequestTexture) != 0 { + packet.SessionTexture = []uint32{u.Session} + } + if (request & RequestComment) != 0 { + packet.SessionComment = []uint32{u.Session} + } + if packet.SessionTexture != nil || packet.SessionComment != nil { + u.client.Send(protoMessage{&packet}) + } +} + +// Send will send a text message to the user. +func (u *User) Send(message string) { + textMessage := TextMessage{ + Users: []*User{u}, + Message: message, + } + u.client.Send(&textMessage) +} + +// SetPlugin sets the user's plugin data. +// +// Plugins are currently only used for positional audio. Clients will receive +// positional audio information from other users if their plugin context is the +// same. The official Mumble client sets the context to: +// +// PluginShortName + "\x00" + AdditionalContextInformation +func (u *User) SetPlugin(context []byte, identity string) { + packet := MumbleProto.UserState{ + Session: &u.Session, + PluginContext: context, + PluginIdentity: &identity, + } + u.client.Send(protoMessage{&packet}) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userlist.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userlist.go new file mode 100644 index 0000000..b915ca6 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userlist.go @@ -0,0 +1,69 @@ +package gumble + +import ( + "github.com/layeh/gumble/gumble/MumbleProto" +) + +// RegisteredUser represents a registered user on the server. +type RegisteredUser struct { + // The registered user's ID. + UserID uint32 + // The registered user's name. + Name string + + changed bool + deregister bool +} + +// SetName sets the new name for the user. +func (ru *RegisteredUser) SetName(name string) { + ru.Name = name + ru.changed = true +} + +// Deregister will remove the registered user from the server. +func (ru *RegisteredUser) Deregister() { + ru.deregister = true +} + +// Register will keep the user registered on the server. This is only useful if +// Deregister() was called on the registered user. +func (ru *RegisteredUser) Register() { + ru.deregister = false +} + +// ACLUser returns an ACLUser for the given registered user. +func (ru *RegisteredUser) ACLUser() *ACLUser { + return &ACLUser{ + UserID: ru.UserID, + Name: ru.Name, + } +} + +// RegisteredUsers is a list of users who are registered on the server. +// +// Whenever a registered user is changed, it does not come into effect until +// the registered user list is sent back to the server. +type RegisteredUsers []*RegisteredUser + +func (pm RegisteredUsers) writeMessage(client *Client) error { + packet := MumbleProto.UserList{} + + for _, user := range pm { + if user.deregister || user.changed { + userListUser := &MumbleProto.UserList_User{ + UserId: &user.UserID, + } + if !user.deregister { + userListUser.Name = &user.Name + } + packet.Users = append(packet.Users, userListUser) + } + } + + if len(packet.Users) <= 0 { + return nil + } + proto := protoMessage{&packet} + return proto.writeMessage(client) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/users.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/users.go new file mode 100644 index 0000000..83845a9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/users.go @@ -0,0 +1,30 @@ +package gumble + +// Users is a map of server users. +// +// When accessed through client.Users, it contains all users currently on the +// server. When accessed through a specific channel +// (e.g. client.Channels[0].Users), it contains only the users in the +// channel. +type Users map[uint32]*User + +// create adds a new user with the given session to the collection. If a user +// with the given session already exists, it is overwritten. +func (u Users) create(session uint32) *User { + user := &User{ + Session: session, + } + u[session] = user + return user +} + +// Find returns the user with the given name. Nil is returned if no user exists +// with the given name. +func (u Users) Find(name string) *User { + for _, user := range u { + if user.Name == name { + return user + } + } + return nil +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userstats.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userstats.go new file mode 100644 index 0000000..3da4988 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userstats.go @@ -0,0 +1,34 @@ +package gumble + +import ( + "crypto/x509" + "net" + "time" +) + +// UserStats contains additional information about a user. +type UserStats struct { + // The owner of the stats. + User *User + + // The user's version. + Version Version + // When the user connected to the server. + Connected time.Time + // How long the user has been idle. + Idle time.Duration + // How much bandwidth the user is current using. + Bandwidth int + // The user's certificate chain. + Certificates []*x509.Certificate + // Does the user have a strong certificate? A strong certificate is one that + // is not self signed, nor expired, etc. + StrongCertificate bool + // A list of CELT versions supported by the user's client. + CELTVersions []int32 + // Does the user's client supports the Opus audio codec? + Opus bool + + // The user's IP address. + IP net.IP +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/read.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/read.go new file mode 100644 index 0000000..f7141a0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/read.go @@ -0,0 +1,48 @@ +package varint + +import ( + "io" +) + +// ReadFrom reads a varint encoded from the given io.Reader. +// +// On success, the function returns the varint as a int64, the number of bytes +// consumed, and nil. +func ReadFrom(r io.Reader) (int64, int64, error) { + var buffer [3]byte + b, err := ReadByte(r) + if err != nil { + return 0, 0, err + } + if (b & 0x80) == 0 { + return int64(b), 1, nil + } + if (b & 0xC0) == 0x80 { + if n, err := io.ReadFull(r, buffer[0:1]); err != nil { + return 0, int64(n + 1), err + } + return int64(b&0x3F)<<8 | int64(buffer[0]), 2, nil + } + if (b & 0xE0) == 0xC0 { + if n, err := io.ReadFull(r, buffer[0:2]); err != nil { + return 0, int64(n + 1), err + } + return int64(b&0x1F)<<16 | int64(buffer[0])<<8 | int64(buffer[1]), 3, nil + } + if (b & 0xF0) == 0xE0 { + if n, err := io.ReadFull(r, buffer[0:3]); err != nil { + return 0, int64(n + 1), err + } + return int64(b&0xF)<<24 | int64(buffer[0])<<16 | int64(buffer[1])<<8 | int64(buffer[2]), 4, nil + } + return 0, 1, ErrOutOfRange +} + +// ReadBytes reads a single byte from the given io.Reader. +func ReadByte(r io.Reader) (byte, error) { + var buff [1]byte + if _, err := io.ReadFull(r, buff[:]); err != nil { + return 0, err + } + return buff[0], nil +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/varint.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/varint.go new file mode 100644 index 0000000..185ecd6 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/varint.go @@ -0,0 +1,9 @@ +package varint + +import ( + "errors" +) + +var ( + ErrOutOfRange = errors.New("out of range") +) diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/write.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/write.go new file mode 100644 index 0000000..6d9bbff --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/write.go @@ -0,0 +1,51 @@ +package varint + +import ( + "encoding/binary" + "io" + "math" +) + +// WriteTo writes the given value to the given io.Writer as a varint encoded +// byte array. +// +// On success, the function returns the number of bytes written to the writer, +// and nil. +func WriteTo(w io.Writer, value int64) (int64, error) { + var length int + var buff [5]byte + if value < 0 { + return 0, ErrOutOfRange + } + if value <= 0x7F { + buff[0] = byte(value) + length = 1 + } else if value <= 0x3FFF { + buff[0] = byte(((value >> 8) & 0x3F) | 0x80) + buff[1] = byte(value & 0xFF) + length = 2 + } else if value <= 0x1FFFFF { + buff[0] = byte((value>>16)&0x1F | 0xC0) + buff[1] = byte((value >> 8) & 0xFF) + buff[2] = byte(value & 0xFF) + length = 3 + } else if value <= 0xFFFFFFF { + buff[0] = byte((value>>24)&0xF | 0xE0) + buff[1] = byte((value >> 16) & 0xFF) + buff[2] = byte((value >> 8) & 0xFF) + buff[3] = byte(value & 0xFF) + length = 4 + } else if value <= math.MaxInt32 { + buff[0] = 0xF0 + binary.BigEndian.PutUint32(buff[1:], uint32(value)) + length = 5 + } + if length > 0 { + if n, err := w.Write(buff[:length]); err != nil { + return int64(n), err + } else { + return int64(n), nil + } + } + return 0, ErrOutOfRange +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/version.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/version.go new file mode 100644 index 0000000..7270e57 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/version.go @@ -0,0 +1,24 @@ +package gumble + +// Version represents a Mumble client or server version. +type Version struct { + // The semantic version information as a single unsigned integer. + // + // Bits 0-15 are the major version, bits 16-23 are the minor version, and + // bits 24-31 are the patch version. + Version uint32 + // The name of the client. + Release string + // The operating system name. + OS string + // The operating system version. + OSVersion string +} + +// SemanticVersion returns the version's semantic version components. +func (v *Version) SemanticVersion() (major, minor, patch uint) { + major = uint(v.Version>>16) & 0xFFFF + minor = uint(v.Version>>8) & 0xFF + patch = uint(v.Version) & 0xFF + return +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/voicetarget.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/voicetarget.go new file mode 100644 index 0000000..d1f9a78 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/voicetarget.go @@ -0,0 +1,81 @@ +package gumble + +import ( + "github.com/layeh/gumble/gumble/MumbleProto" +) + +// VoiceTargetLoopback is a special voice target which causes any audio sent to +// the server to be returned to the client. +// +// Its ID should not be modified, and it does not have to to be sent to the +// server before use. +var VoiceTargetLoopback *VoiceTarget + +func init() { + VoiceTargetLoopback = &VoiceTarget{ + ID: 31, + } +} + +type voiceTargetChannel struct { + channel *Channel + links, recursive bool + group string +} + +// VoiceTarget represents a set of users and/or channels that the client can +// whisper to. +type VoiceTarget struct { + // The voice target ID. This value must be in the range [1, 30]. + ID uint32 + users []*User + channels []*voiceTargetChannel +} + +// Clear removes all users and channels from the voice target. +func (vt *VoiceTarget) Clear() { + vt.users = nil + vt.channels = nil +} + +// AddUser adds a user to the voice target. +func (vt *VoiceTarget) AddUser(user *User) { + vt.users = append(vt.users, user) +} + +// AddChannel adds a user to the voice target. If group is non-empty, only +// users belonging to that ACL group will be targeted. +func (vt *VoiceTarget) AddChannel(channel *Channel, recursive, links bool, group string) { + vt.channels = append(vt.channels, &voiceTargetChannel{ + channel: channel, + links: links, + recursive: recursive, + group: group, + }) +} + +func (vt *VoiceTarget) writeMessage(client *Client) error { + packet := MumbleProto.VoiceTarget{ + Id: &vt.ID, + Targets: make([]*MumbleProto.VoiceTarget_Target, 0, len(vt.users)+len(vt.channels)), + } + for _, user := range vt.users { + packet.Targets = append(packet.Targets, &MumbleProto.VoiceTarget_Target{ + Session: []uint32{user.Session}, + }) + } + for _, vtChannel := range vt.channels { + target := &MumbleProto.VoiceTarget_Target{ + ChannelId: &vtChannel.channel.ID, + Links: &vtChannel.links, + Children: &vtChannel.recursive, + } + if vtChannel.group != "" { + target.Group = &vtChannel.group + } + packet.Targets = append(packet.Targets, target) + } + + proto := protoMessage{&packet} + return proto.writeMessage(client) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/gumble_ffmpeg.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/gumble_ffmpeg.go new file mode 100644 index 0000000..cdf70a0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/gumble_ffmpeg.go @@ -0,0 +1,134 @@ +package gumble_ffmpeg + +import ( + "encoding/binary" + "errors" + "io" + "os/exec" + "strconv" + "sync" + "time" + + "github.com/layeh/gumble/gumble" +) + +const ( + DefaultCommand = "ffmpeg" +) + +type Stream struct { + // Command to execute to play the file. Defaults to "ffmpeg". + Command string + // Playback volume. This value can be changed while the source is playing. + Volume float32 + // Audio source. This value should not be closed until the stream is done + // playing. + Source Source + // Starting offset. + Offset time.Duration + + client *gumble.Client + cmd *exec.Cmd + pipe io.ReadCloser + + stop chan bool + stopWaitGroup sync.WaitGroup +} + +// New creates a new stream on the given gumble client. +func New(client *gumble.Client) *Stream { + stream := &Stream{ + client: client, + Volume: 1.0, + Command: DefaultCommand, + stop: make(chan bool), + } + return stream +} + +// Play starts playing the stream to the gumble client. Returns non-nil if the +// stream could not be started. +func (s *Stream) Play() error { + if s.IsPlaying() { + return errors.New("already playing") + } + if s.Source == nil { + return errors.New("nil source") + } + args := s.Source.arguments() + if secs := int(s.Offset.Seconds()); secs > 0 { + args = append([]string{"-ss", strconv.Itoa(secs)}, args...) + } + args = append(args, []string{"-ac", "1", "-ar", strconv.Itoa(gumble.AudioSampleRate), "-f", "s16le", "-"}...) + cmd := exec.Command(s.Command, args...) + if pipe, err := cmd.StdoutPipe(); err != nil { + return err + } else { + s.pipe = pipe + } + s.Source.start(cmd) + if err := cmd.Start(); err != nil { + s.Source.done() + return err + } + s.stopWaitGroup.Add(1) + s.cmd = cmd + go s.sourceRoutine() + return nil +} + +// IsPlaying returns if a stream is playing. +func (s *Stream) IsPlaying() bool { + return s.cmd != nil +} + +// Wait returns once the stream has finished playing. +func (s *Stream) Wait() { + s.stopWaitGroup.Wait() +} + +// Stop stops the currently playing stream. +func (s *Stream) Stop() error { + if !s.IsPlaying() { + return errors.New("nothing playing") + } + + s.stop <- true + s.stopWaitGroup.Wait() + return nil +} + +func (s *Stream) sourceRoutine() { + interval := s.client.Config.GetAudioInterval() + frameSize := s.client.Config.GetAudioFrameSize() + + ticker := time.NewTicker(interval) + + defer func() { + ticker.Stop() + s.cmd.Process.Kill() + s.cmd.Wait() + s.cmd = nil + s.Source.done() + s.stopWaitGroup.Done() + }() + + int16Buffer := make([]int16, frameSize) + byteBuffer := make([]byte, frameSize*2) + + for { + select { + case <-s.stop: + return + case <-ticker.C: + if _, err := io.ReadFull(s.pipe, byteBuffer); err != nil { + return + } + for i := range int16Buffer { + float := float32(int16(binary.LittleEndian.Uint16(byteBuffer[i*2 : (i+1)*2]))) + int16Buffer[i] = int16(s.Volume * float) + } + s.client.Send(gumble.AudioBuffer(int16Buffer)) + } + } +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/source.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/source.go new file mode 100644 index 0000000..4824d41 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/source.go @@ -0,0 +1,55 @@ +package gumble_ffmpeg + +import ( + "io" + "os/exec" +) + +type Source interface { + // must include the -i + arguments() []string + start(*exec.Cmd) + done() +} + +// sourceFile + +type sourceFile string + +// SourceFile is standard file source. +func SourceFile(filename string) Source { + return sourceFile(filename) +} + +func (s sourceFile) arguments() []string { + return []string{"-i", string(s)} +} + +func (sourceFile) start(*exec.Cmd) { +} + +func (sourceFile) done() { +} + +// sourceReader + +type sourceReader struct { + r io.ReadCloser +} + +// SourceReader is a ReadCloser source. +func SourceReader(r io.ReadCloser) Source { + return &sourceReader{r} +} + +func (*sourceReader) arguments() []string { + return []string{"-i", "-"} +} + +func (s *sourceReader) start(cmd *exec.Cmd) { + cmd.Stdin = s.r +} + +func (s *sourceReader) done() { + s.r.Close() +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/bitrate.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/bitrate.go new file mode 100644 index 0000000..ecf6d8f --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/bitrate.go @@ -0,0 +1,25 @@ +package gumbleutil + +import ( + "time" + + "github.com/layeh/gopus" + "github.com/layeh/gumble/gumble" +) + +var autoBitrate = &Listener{ + Connect: func(e *gumble.ConnectEvent) { + if e.MaximumBitrate > 0 { + const safety = 5 + interval := e.Client.Config.GetAudioInterval() + dataBytes := (e.MaximumBitrate / (8 * (int(time.Second/interval) + safety))) - 32 - 10 + + e.Client.Config.AudioDataBytes = dataBytes + e.Client.AudioEncoder.SetBitrate(gopus.BitrateMaximum) + } + }, +} + +// AutoBitrate is a gumble.EventListener that automatically sets the client's +// AudioDataBytes to suitable value, based on the server's bitrate. +var AutoBitrate gumble.EventListener = autoBitrate diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/certificatelock.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/certificatelock.go new file mode 100644 index 0000000..2364aca --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/certificatelock.go @@ -0,0 +1,75 @@ +package gumbleutil + +import ( + "crypto/tls" + "crypto/x509" + "encoding/pem" + "errors" + "io/ioutil" + "os" + + "github.com/layeh/gumble/gumble" +) + +// CertificateLockFile adds a new certificate lock on the given Client that +// ensures that a server's certificate chain is the same from +// connection-to-connection. This is helpful when connecting to servers with +// self-signed certificates. +// +// If filename does not exist, the server's certificate chain will be written +// to that file. If it does exist, certificates will be read from the file and +// checked against the server's certificate chain upon connection. +// +// Example: +// +// if allowSelfSignedCertificates { +// config.TLSConfig.InsecureSkipVerify = true +// } +// gumbleutil.CertificateLockFile(client, filename) +// +// if err := client.Connect(); err != nil { +// panic(err) +// } +func CertificateLockFile(client *gumble.Client, filename string) { + client.Config.TLSVerify = func(state *tls.ConnectionState) error { + if file, err := os.Open(filename); err == nil { + defer file.Close() + data, err := ioutil.ReadAll(file) + if err != nil { + return err + } + i := 0 + for block, data := pem.Decode(data); block != nil; block, data = pem.Decode(data) { + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return err + } + if i >= len(state.PeerCertificates) { + return errors.New("gumbleutil: invalid certificate chain length") + } + if !cert.Equal(state.PeerCertificates[i]) { + return errors.New("gumbleutil: certificate verification failure") + } + i++ + } + if i != len(state.PeerCertificates) { + return errors.New("gumbleutil: invalid certificate chain length") + } + return nil + } + + file, err := os.Create(filename) + if err != nil { + return err + } + defer file.Close() + block := pem.Block{ + Type: "CERTIFICATE", + } + for _, cert := range state.PeerCertificates { + block.Bytes = cert.Raw + pem.Encode(file, &block) + } + return nil + } +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/doc.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/doc.go new file mode 100644 index 0000000..864a3b8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/doc.go @@ -0,0 +1,2 @@ +// Package gumbleutil provides extras that can make working with gumble easier. +package gumbleutil diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listener.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listener.go new file mode 100644 index 0000000..c1112a7 --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listener.go @@ -0,0 +1,90 @@ +package gumbleutil + +import ( + "github.com/layeh/gumble/gumble" +) + +// Listener is a struct that implements the gumble.EventListener interface. The +// corresponding event function in the struct is called if it is non-nil. +type Listener struct { + Connect func(e *gumble.ConnectEvent) + Disconnect func(e *gumble.DisconnectEvent) + TextMessage func(e *gumble.TextMessageEvent) + UserChange func(e *gumble.UserChangeEvent) + ChannelChange func(e *gumble.ChannelChangeEvent) + PermissionDenied func(e *gumble.PermissionDeniedEvent) + UserList func(e *gumble.UserListEvent) + ACL func(e *gumble.ACLEvent) + BanList func(e *gumble.BanListEvent) + ContextActionChange func(e *gumble.ContextActionChangeEvent) +} + +// OnConnect implements gumble.EventListener.OnConnect. +func (l Listener) OnConnect(e *gumble.ConnectEvent) { + if l.Connect != nil { + l.Connect(e) + } +} + +// OnDisconnect implements gumble.EventListener.OnDisconnect. +func (l Listener) OnDisconnect(e *gumble.DisconnectEvent) { + if l.Disconnect != nil { + l.Disconnect(e) + } +} + +// OnTextMessage implements gumble.EventListener.OnTextMessage. +func (l Listener) OnTextMessage(e *gumble.TextMessageEvent) { + if l.TextMessage != nil { + l.TextMessage(e) + } +} + +// OnUserChange implements gumble.EventListener.OnUserChange. +func (l Listener) OnUserChange(e *gumble.UserChangeEvent) { + if l.UserChange != nil { + l.UserChange(e) + } +} + +// OnChannelChange implements gumble.EventListener.OnChannelChange. +func (l Listener) OnChannelChange(e *gumble.ChannelChangeEvent) { + if l.ChannelChange != nil { + l.ChannelChange(e) + } +} + +// OnPermissionDenied implements gumble.EventListener.OnPermissionDenied. +func (l Listener) OnPermissionDenied(e *gumble.PermissionDeniedEvent) { + if l.PermissionDenied != nil { + l.PermissionDenied(e) + } +} + +// OnUserList implements gumble.EventListener.OnUserList. +func (l Listener) OnUserList(e *gumble.UserListEvent) { + if l.UserList != nil { + l.UserList(e) + } +} + +// OnACL implements gumble.EventListener.OnACL. +func (l Listener) OnACL(e *gumble.ACLEvent) { + if l.ACL != nil { + l.ACL(e) + } +} + +// OnBanList implements gumble.EventListener.OnBanList. +func (l Listener) OnBanList(e *gumble.BanListEvent) { + if l.BanList != nil { + l.BanList(e) + } +} + +// OnContextActionChange implements gumble.EventListener.OnContextActionChange. +func (l Listener) OnContextActionChange(e *gumble.ContextActionChangeEvent) { + if l.ContextActionChange != nil { + l.ContextActionChange(e) + } +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listenerfunc.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listenerfunc.go new file mode 100644 index 0000000..60e42db --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listenerfunc.go @@ -0,0 +1,73 @@ +package gumbleutil + +import ( + "github.com/layeh/gumble/gumble" +) + +// ListenerFunc is a single listener function that implements the +// gumble.EventListener interface. This is useful if you would like to use a +// type-switch for handling the different event types. +// +// Example: +// handler := func(e interface{}) { +// switch e.(type) { +// case *gumble.ConnectEvent: +// println("Connected") +// case *gumble.DisconnectEvent: +// println("Disconnected") +// // ... +// } +// } +// +// client.Attach(gumbleutil.ListenerFunc(handler)) +type ListenerFunc func(e interface{}) + +// OnConnect implements gumble.EventListener.OnConnect. +func (lf ListenerFunc) OnConnect(e *gumble.ConnectEvent) { + lf(e) +} + +// OnDisconnect implements gumble.EventListener.OnDisconnect. +func (lf ListenerFunc) OnDisconnect(e *gumble.DisconnectEvent) { + lf(e) +} + +// OnTextMessage implements gumble.EventListener.OnTextMessage. +func (lf ListenerFunc) OnTextMessage(e *gumble.TextMessageEvent) { + lf(e) +} + +// OnUserChange implements gumble.EventListener.OnUserChange. +func (lf ListenerFunc) OnUserChange(e *gumble.UserChangeEvent) { + lf(e) +} + +// OnChannelChange implements gumble.EventListener.OnChannelChange. +func (lf ListenerFunc) OnChannelChange(e *gumble.ChannelChangeEvent) { + lf(e) +} + +// OnPermissionDenied implements gumble.EventListener.OnPermissionDenied. +func (lf ListenerFunc) OnPermissionDenied(e *gumble.PermissionDeniedEvent) { + lf(e) +} + +// OnUserList implements gumble.EventListener.OnUserList. +func (lf ListenerFunc) OnUserList(e *gumble.UserListEvent) { + lf(e) +} + +// OnACL implements gumble.EventListener.OnACL. +func (lf ListenerFunc) OnACL(e *gumble.ACLEvent) { + lf(e) +} + +// OnBanList implements gumble.EventListener.OnBanList. +func (lf ListenerFunc) OnBanList(e *gumble.BanListEvent) { + lf(e) +} + +// OnContextActionChange implements gumble.EventListener.OnContextActionChange. +func (lf ListenerFunc) OnContextActionChange(e *gumble.ContextActionChangeEvent) { + lf(e) +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/main.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/main.go new file mode 100644 index 0000000..fa1d2dd --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/main.go @@ -0,0 +1,67 @@ +package gumbleutil + +import ( + "crypto/tls" + "flag" + "fmt" + "os" + + "github.com/layeh/gumble/gumble" +) + +// Main aids in the creation of a basic command line gumble bot. It accepts the +// following flag arguments: --server, --username, --password, --insecure, +// --certificate, and --key. +// +// If init is non-nil, it is called before attempting to connect to the server. +func Main(init func(client *gumble.Client), listener gumble.EventListener) { + server := flag.String("server", "localhost:64738", "Mumble server address") + username := flag.String("username", "gumble-bot", "client username") + password := flag.String("password", "", "client password") + insecure := flag.Bool("insecure", false, "skip server certificate verification") + certificateFile := flag.String("certificate", "", "user certificate file (PEM)") + keyFile := flag.String("key", "", "user certificate key file (PEM)") + + if !flag.Parsed() { + flag.Parse() + } + + keepAlive := make(chan bool) + + // client + config := gumble.Config{ + Username: *username, + Password: *password, + Address: *server, + } + client := gumble.NewClient(&config) + if *insecure { + config.TLSConfig.InsecureSkipVerify = true + } + if *certificateFile != "" { + if *keyFile == "" { + keyFile = certificateFile + } + if certificate, err := tls.LoadX509KeyPair(*certificateFile, *keyFile); err != nil { + fmt.Printf("%s: %s\n", os.Args[0], err) + os.Exit(1) + } else { + config.TLSConfig.Certificates = append(config.TLSConfig.Certificates, certificate) + } + } + client.Attach(listener) + client.Attach(Listener{ + Disconnect: func(e *gumble.DisconnectEvent) { + keepAlive <- true + }, + }) + if init != nil { + init(client) + } + if err := client.Connect(); err != nil { + fmt.Printf("%s: %s\n", os.Args[0], err) + os.Exit(1) + } + + <-keepAlive +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/path.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/path.go new file mode 100644 index 0000000..6b60afa --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/path.go @@ -0,0 +1,18 @@ +package gumbleutil + +import ( + "github.com/layeh/gumble/gumble" +) + +// ChannelPath returns a slice of channel names, starting from the root channel +// to the given channel. +func ChannelPath(channel *gumble.Channel) []string { + var pieces []string + for ; channel != nil; channel = channel.Parent { + pieces = append(pieces, channel.Name) + } + for i := 0; i < (len(pieces) / 2); i++ { + pieces[len(pieces)-1-i], pieces[i] = pieces[i], pieces[len(pieces)-1-i] + } + return pieces +} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/textmessage.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/textmessage.go new file mode 100644 index 0000000..3c94b9c --- /dev/null +++ b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/textmessage.go @@ -0,0 +1,45 @@ +package gumbleutil + +import ( + "bytes" + "encoding/xml" + "strings" + + "github.com/layeh/gumble/gumble" +) + +// PlainText returns the Message string without HTML tags or entities. +func PlainText(tm *gumble.TextMessage) string { + d := xml.NewDecoder(strings.NewReader(tm.Message)) + d.Strict = false + d.AutoClose = xml.HTMLAutoClose + d.Entity = xml.HTMLEntity + + var b bytes.Buffer + newline := false + for { + t, _ := d.Token() + if t == nil { + break + } + switch node := t.(type) { + case xml.CharData: + if len(node) > 0 { + b.Write(node) + newline = false + } + case xml.StartElement: + switch node.Name.Local { + case "address", "article", "aside", "audio", "blockquote", "canvas", "dd", "div", "dl", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "noscript", "ol", "output", "p", "pre", "section", "table", "tfoot", "ul", "video": + if !newline { + b.WriteByte('\n') + newline = true + } + case "br": + b.WriteByte('\n') + newline = true + } + } + } + return b.String() +} From b8fb029f8010197a6761b034c123c0d58e1b9ed6 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 18:44:49 +0100 Subject: [PATCH 136/297] Revert "Fixing build errors" This reverts commit 9c6c65a03688ec16c73c6e559138fd9962434828. --- service_youtube.go | 1 + 1 file changed, 1 insertion(+) diff --git a/service_youtube.go b/service_youtube.go index a8c2b44..aa8561c 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -161,6 +161,7 @@ func (yt YouTube) NewSong(user, id, offset string, playlist Playlist) (Song, err title: title, id: id, offset: int((offsetDays * 86400) + (offsetHours * 3600) + (offsetMinutes * 60) + offsetSeconds), + filename: id + ".m4a", duration: durationString, thumbnail: thumbnail, skippers: make([]string, 0), From bf8a3f52be9af13f5bd91130c1a590d63601ce0a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 18:50:58 +0100 Subject: [PATCH 137/297] Actually reverting --- Godeps/Godeps.json | 34 - Godeps/Readme | 5 - Godeps/_workspace/.gitignore | 2 - .../src/code.google.com/p/gcfg/LICENSE | 57 - .../src/code.google.com/p/gcfg/README | 7 - .../src/code.google.com/p/gcfg/doc.go | 118 - .../code.google.com/p/gcfg/example_test.go | 132 - .../src/code.google.com/p/gcfg/go1_0.go | 7 - .../src/code.google.com/p/gcfg/go1_2.go | 9 - .../src/code.google.com/p/gcfg/issues_test.go | 63 - .../src/code.google.com/p/gcfg/read.go | 181 -- .../src/code.google.com/p/gcfg/read_test.go | 333 -- .../code.google.com/p/gcfg/scanner/errors.go | 121 - .../p/gcfg/scanner/example_test.go | 46 - .../code.google.com/p/gcfg/scanner/scanner.go | 342 -- .../p/gcfg/scanner/scanner_test.go | 417 --- .../src/code.google.com/p/gcfg/set.go | 281 -- .../p/gcfg/testdata/gcfg_test.gcfg | 3 - .../p/gcfg/testdata/gcfg_unicode_test.gcfg | 3 - .../code.google.com/p/gcfg/token/position.go | 435 --- .../p/gcfg/token/position_test.go | 181 -- .../code.google.com/p/gcfg/token/serialize.go | 56 - .../p/gcfg/token/serialize_test.go | 111 - .../src/code.google.com/p/gcfg/token/token.go | 83 - .../src/code.google.com/p/gcfg/types/bool.go | 23 - .../src/code.google.com/p/gcfg/types/doc.go | 4 - .../src/code.google.com/p/gcfg/types/enum.go | 44 - .../code.google.com/p/gcfg/types/enum_test.go | 29 - .../src/code.google.com/p/gcfg/types/int.go | 86 - .../code.google.com/p/gcfg/types/int_test.go | 67 - .../src/code.google.com/p/gcfg/types/scan.go | 23 - .../code.google.com/p/gcfg/types/scan_test.go | 36 - .../github.com/golang/protobuf/proto/Makefile | 43 - .../golang/protobuf/proto/all_test.go | 2083 ------------- .../github.com/golang/protobuf/proto/clone.go | 212 -- .../golang/protobuf/proto/clone_test.go | 245 -- .../golang/protobuf/proto/decode.go | 827 ----- .../golang/protobuf/proto/encode.go | 1293 -------- .../github.com/golang/protobuf/proto/equal.go | 256 -- .../golang/protobuf/proto/equal_test.go | 191 -- .../golang/protobuf/proto/extensions.go | 400 --- .../golang/protobuf/proto/extensions_test.go | 292 -- .../github.com/golang/protobuf/proto/lib.go | 813 ----- .../golang/protobuf/proto/message_set.go | 287 -- .../golang/protobuf/proto/message_set_test.go | 66 - .../golang/protobuf/proto/pointer_reflect.go | 479 --- .../golang/protobuf/proto/pointer_unsafe.go | 266 -- .../golang/protobuf/proto/properties.go | 742 ----- .../protobuf/proto/proto3_proto/proto3.pb.go | 122 - .../protobuf/proto/proto3_proto/proto3.proto | 68 - .../golang/protobuf/proto/proto3_test.go | 125 - .../golang/protobuf/proto/size2_test.go | 63 - .../golang/protobuf/proto/size_test.go | 142 - .../golang/protobuf/proto/testdata/Makefile | 50 - .../protobuf/proto/testdata/golden_test.go | 86 - .../golang/protobuf/proto/testdata/test.pb.go | 2746 ----------------- .../golang/protobuf/proto/testdata/test.proto | 480 --- .../github.com/golang/protobuf/proto/text.go | 769 ----- .../golang/protobuf/proto/text_parser.go | 772 ----- .../golang/protobuf/proto/text_parser_test.go | 511 --- .../golang/protobuf/proto/text_test.go | 441 --- .../src/github.com/jmoiron/jsonq/.gitignore | 1 - .../src/github.com/jmoiron/jsonq/LICENSE | 23 - .../src/github.com/jmoiron/jsonq/README.md | 83 - .../src/github.com/jmoiron/jsonq/autotest.sh | 13 - .../src/github.com/jmoiron/jsonq/doc.go | 68 - .../src/github.com/jmoiron/jsonq/jsonq.go | 311 -- .../github.com/jmoiron/jsonq/jsonq_test.go | 186 -- .../src/github.com/layeh/gopus/LICENSE | 19 - .../src/github.com/layeh/gopus/README.md | 20 - .../src/github.com/layeh/gopus/decoder.go | 71 - .../src/github.com/layeh/gopus/encoder.go | 119 - .../src/github.com/layeh/gopus/gopus.go | 53 - .../layeh/gumble/gumble/MumbleProto/LICENSE | 37 - .../gumble/gumble/MumbleProto/Mumble.pb.go | 2092 ------------- .../gumble/gumble/MumbleProto/Mumble.proto | 544 ---- .../gumble/gumble/MumbleProto/generate.go | 2 - .../src/github.com/layeh/gumble/gumble/acl.go | 58 - .../github.com/layeh/gumble/gumble/audio.go | 85 - .../layeh/gumble/gumble/audiomultiplexer.go | 47 - .../github.com/layeh/gumble/gumble/bans.go | 102 - .../github.com/layeh/gumble/gumble/channel.go | 147 - .../layeh/gumble/gumble/channels.go | 32 - .../github.com/layeh/gumble/gumble/client.go | 230 -- .../github.com/layeh/gumble/gumble/config.go | 72 - .../github.com/layeh/gumble/gumble/conn.go | 197 -- .../layeh/gumble/gumble/contextaction.go | 57 - .../layeh/gumble/gumble/contextactions.go | 12 - .../src/github.com/layeh/gumble/gumble/doc.go | 39 - .../github.com/layeh/gumble/gumble/event.go | 202 -- .../layeh/gumble/gumble/eventmultiplexer.go | 106 - .../layeh/gumble/gumble/handlers.go | 962 ------ .../github.com/layeh/gumble/gumble/message.go | 8 - .../layeh/gumble/gumble/permission.go | 27 - .../github.com/layeh/gumble/gumble/ping.go | 73 - .../layeh/gumble/gumble/pingstats.go | 5 - .../layeh/gumble/gumble/protomessage.go | 16 - .../github.com/layeh/gumble/gumble/request.go | 18 - .../layeh/gumble/gumble/textmessage.go | 50 - .../github.com/layeh/gumble/gumble/user.go | 231 -- .../layeh/gumble/gumble/userlist.go | 69 - .../github.com/layeh/gumble/gumble/users.go | 30 - .../layeh/gumble/gumble/userstats.go | 34 - .../layeh/gumble/gumble/varint/read.go | 48 - .../layeh/gumble/gumble/varint/varint.go | 9 - .../layeh/gumble/gumble/varint/write.go | 51 - .../github.com/layeh/gumble/gumble/version.go | 24 - .../layeh/gumble/gumble/voicetarget.go | 81 - .../gumble/gumble_ffmpeg/gumble_ffmpeg.go | 134 - .../layeh/gumble/gumble_ffmpeg/source.go | 55 - .../layeh/gumble/gumbleutil/bitrate.go | 25 - .../gumble/gumbleutil/certificatelock.go | 75 - .../github.com/layeh/gumble/gumbleutil/doc.go | 2 - .../layeh/gumble/gumbleutil/listener.go | 90 - .../layeh/gumble/gumbleutil/listenerfunc.go | 73 - .../layeh/gumble/gumbleutil/main.go | 67 - .../layeh/gumble/gumbleutil/path.go | 18 - .../layeh/gumble/gumbleutil/textmessage.go | 45 - 118 files changed, 25557 deletions(-) delete mode 100644 Godeps/Godeps.json delete mode 100644 Godeps/Readme delete mode 100644 Godeps/_workspace/.gitignore delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/LICENSE delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/README delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/doc.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/example_test.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/go1_0.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/go1_2.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/issues_test.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/read.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/read_test.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/scanner/errors.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/scanner/example_test.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner_test.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/set.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_test.gcfg delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_unicode_test.gcfg delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/token/position.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/token/position_test.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize_test.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/token/token.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/bool.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/doc.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/enum.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/enum_test.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/int.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/int_test.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/scan.go delete mode 100644 Godeps/_workspace/src/code.google.com/p/gcfg/types/scan_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go delete mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/.gitignore delete mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/LICENSE delete mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/README.md delete mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/autotest.sh delete mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/doc.go delete mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq.go delete mode 100644 Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq_test.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gopus/LICENSE delete mode 100644 Godeps/_workspace/src/github.com/layeh/gopus/README.md delete mode 100644 Godeps/_workspace/src/github.com/layeh/gopus/decoder.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gopus/encoder.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gopus/gopus.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/LICENSE delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.pb.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.proto delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/generate.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/acl.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/audio.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/audiomultiplexer.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/bans.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/channel.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/channels.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/client.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/config.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/conn.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextaction.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextactions.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/doc.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/event.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/eventmultiplexer.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/handlers.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/message.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/permission.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/ping.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/pingstats.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/protomessage.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/request.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/textmessage.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/user.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/userlist.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/users.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/userstats.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/read.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/varint.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/write.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/version.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble/voicetarget.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/gumble_ffmpeg.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/source.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/bitrate.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/certificatelock.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/doc.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listener.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listenerfunc.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/main.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/path.go delete mode 100644 Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/textmessage.go diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json deleted file mode 100644 index b5049e8..0000000 --- a/Godeps/Godeps.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "ImportPath": "github.com/MichaelOultram/mumbledj", - "GoVersion": "go1.4.2", - "Deps": [ - { - "ImportPath": "code.google.com/p/gcfg", - "Rev": "c2d3050044d05357eaf6c3547249ba57c5e235cb" - }, - { - "ImportPath": "github.com/golang/protobuf/proto", - "Rev": "0f7a9caded1fb3c9cc5a9b4bcf2ff633cc8ae644" - }, - { - "ImportPath": "github.com/jmoiron/jsonq", - "Rev": "7c27c8eb9f6831555a4209f6a7d579159e766a3c" - }, - { - "ImportPath": "github.com/layeh/gopus", - "Rev": "2f86fa22bc209cc0ccbc6418dfbad9199e3dbc78" - }, - { - "ImportPath": "github.com/layeh/gumble/gumble", - "Rev": "c9fcce8fc4b71c7c53a5d3d9d48a1e001ad19a19" - }, - { - "ImportPath": "github.com/layeh/gumble/gumble_ffmpeg", - "Rev": "c9fcce8fc4b71c7c53a5d3d9d48a1e001ad19a19" - }, - { - "ImportPath": "github.com/layeh/gumble/gumbleutil", - "Rev": "c9fcce8fc4b71c7c53a5d3d9d48a1e001ad19a19" - } - ] -} diff --git a/Godeps/Readme b/Godeps/Readme deleted file mode 100644 index 4cdaa53..0000000 --- a/Godeps/Readme +++ /dev/null @@ -1,5 +0,0 @@ -This directory tree is generated automatically by godep. - -Please do not edit. - -See https://github.com/tools/godep for more information. diff --git a/Godeps/_workspace/.gitignore b/Godeps/_workspace/.gitignore deleted file mode 100644 index f037d68..0000000 --- a/Godeps/_workspace/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/pkg -/bin diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/LICENSE b/Godeps/_workspace/src/code.google.com/p/gcfg/LICENSE deleted file mode 100644 index b0a9e76..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/LICENSE +++ /dev/null @@ -1,57 +0,0 @@ -Copyright (c) 2012 Péter Surányi. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------------------- -Portions of gcfg's source code have been derived from Go, and are -covered by the following license: ----------------------------------------------------------------------- - -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/README b/Godeps/_workspace/src/code.google.com/p/gcfg/README deleted file mode 100644 index 8f621c3..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/README +++ /dev/null @@ -1,7 +0,0 @@ -Gcfg reads INI-style configuration files into Go structs; -supports user-defined types and subsections. - -Project page: https://code.google.com/p/gcfg -Package docs: http://godoc.org/code.google.com/p/gcfg - -My other projects: https://speter.net diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/doc.go b/Godeps/_workspace/src/code.google.com/p/gcfg/doc.go deleted file mode 100644 index 99687b4..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/doc.go +++ /dev/null @@ -1,118 +0,0 @@ -// Package gcfg reads "INI-style" text-based configuration files with -// "name=value" pairs grouped into sections (gcfg files). -// -// This package is still a work in progress; see the sections below for planned -// changes. -// -// Syntax -// -// The syntax is based on that used by git config: -// http://git-scm.com/docs/git-config#_syntax . -// There are some (planned) differences compared to the git config format: -// - improve data portability: -// - must be encoded in UTF-8 (for now) and must not contain the 0 byte -// - include and "path" type is not supported -// (path type may be implementable as a user-defined type) -// - internationalization -// - section and variable names can contain unicode letters, unicode digits -// (as defined in http://golang.org/ref/spec#Characters ) and hyphens -// (U+002D), starting with a unicode letter -// - disallow potentially ambiguous or misleading definitions: -// - `[sec.sub]` format is not allowed (deprecated in gitconfig) -// - `[sec ""]` is not allowed -// - use `[sec]` for section name "sec" and empty subsection name -// - (planned) within a single file, definitions must be contiguous for each: -// - section: '[secA]' -> '[secB]' -> '[secA]' is an error -// - subsection: '[sec "A"]' -> '[sec "B"]' -> '[sec "A"]' is an error -// - multivalued variable: 'multi=a' -> 'other=x' -> 'multi=b' is an error -// -// Data structure -// -// The functions in this package read values into a user-defined struct. -// Each section corresponds to a struct field in the config struct, and each -// variable in a section corresponds to a data field in the section struct. -// The mapping of each section or variable name to fields is done either based -// on the "gcfg" struct tag or by matching the name of the section or variable, -// ignoring case. In the latter case, hyphens '-' in section and variable names -// correspond to underscores '_' in field names. -// Fields must be exported; to use a section or variable name starting with a -// letter that is neither upper- or lower-case, prefix the field name with 'X'. -// (See https://code.google.com/p/go/issues/detail?id=5763#c4 .) -// -// For sections with subsections, the corresponding field in config must be a -// map, rather than a struct, with string keys and pointer-to-struct values. -// Values for subsection variables are stored in the map with the subsection -// name used as the map key. -// (Note that unlike section and variable names, subsection names are case -// sensitive.) -// When using a map, and there is a section with the same section name but -// without a subsection name, its values are stored with the empty string used -// as the key. -// -// The functions in this package panic if config is not a pointer to a struct, -// or when a field is not of a suitable type (either a struct or a map with -// string keys and pointer-to-struct values). -// -// Parsing of values -// -// The section structs in the config struct may contain single-valued or -// multi-valued variables. Variables of unnamed slice type (that is, a type -// starting with `[]`) are treated as multi-value; all others (including named -// slice types) are treated as single-valued variables. -// -// Single-valued variables are handled based on the type as follows. -// Unnamed pointer types (that is, types starting with `*`) are dereferenced, -// and if necessary, a new instance is allocated. -// -// For types implementing the encoding.TextUnmarshaler interface, the -// UnmarshalText method is used to set the value. Implementing this method is -// the recommended way for parsing user-defined types. -// -// For fields of string kind, the value string is assigned to the field, after -// unquoting and unescaping as needed. -// For fields of bool kind, the field is set to true if the value is "true", -// "yes", "on" or "1", and set to false if the value is "false", "no", "off" or -// "0", ignoring case. In addition, single-valued bool fields can be specified -// with a "blank" value (variable name without equals sign and value); in such -// case the value is set to true. -// -// Predefined integer types [u]int(|8|16|32|64) and big.Int are parsed as -// decimal or hexadecimal (if having '0x' prefix). (This is to prevent -// unintuitively handling zero-padded numbers as octal.) Other types having -// [u]int* as the underlying type, such as os.FileMode and uintptr allow -// decimal, hexadecimal, or octal values. -// Parsing mode for integer types can be overridden using the struct tag option -// ",int=mode" where mode is a combination of the 'd', 'h', and 'o' characters -// (each standing for decimal, hexadecimal, and octal, respectively.) -// -// All other types are parsed using fmt.Sscanf with the "%v" verb. -// -// For multi-valued variables, each individual value is parsed as above and -// appended to the slice. If the first value is specified as a "blank" value -// (variable name without equals sign and value), a new slice is allocated; -// that is any values previously set in the slice will be ignored. -// -// The types subpackage for provides helpers for parsing "enum-like" and integer -// types. -// -// TODO -// -// The following is a list of changes under consideration: -// - documentation -// - self-contained syntax documentation -// - more practical examples -// - move TODOs to issue tracker (eventually) -// - syntax -// - reconsider valid escape sequences -// (gitconfig doesn't support \r in value, \t in subsection name, etc.) -// - reading / parsing gcfg files -// - define internal representation structure -// - support multiple inputs (readers, strings, files) -// - support declaring encoding (?) -// - support varying fields sets for subsections (?) -// - writing gcfg files -// - error handling -// - make error context accessible programmatically? -// - limit input size? -// -package gcfg diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/example_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/example_test.go deleted file mode 100644 index 884f3fb..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/example_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package gcfg_test - -import ( - "fmt" - "log" -) - -import "code.google.com/p/gcfg" - -func ExampleReadStringInto() { - cfgStr := `; Comment line -[section] -name=value # comment` - cfg := struct { - Section struct { - Name string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.Name) - // Output: value -} - -func ExampleReadStringInto_bool() { - cfgStr := `; Comment line -[section] -switch=on` - cfg := struct { - Section struct { - Switch bool - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.Switch) - // Output: true -} - -func ExampleReadStringInto_hyphens() { - cfgStr := `; Comment line -[section-name] -variable-name=value # comment` - cfg := struct { - Section_Name struct { - Variable_Name string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section_Name.Variable_Name) - // Output: value -} - -func ExampleReadStringInto_tags() { - cfgStr := `; Comment line -[section] -var-name=value # comment` - cfg := struct { - Section struct { - FieldName string `gcfg:"var-name"` - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.FieldName) - // Output: value -} - -func ExampleReadStringInto_subsections() { - cfgStr := `; Comment line -[profile "A"] -color = white - -[profile "B"] -color = black -` - cfg := struct { - Profile map[string]*struct { - Color string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Printf("%s %s\n", cfg.Profile["A"].Color, cfg.Profile["B"].Color) - // Output: white black -} - -func ExampleReadStringInto_multivalue() { - cfgStr := `; Comment line -[section] -multi=value1 -multi=value2` - cfg := struct { - Section struct { - Multi []string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.Multi) - // Output: [value1 value2] -} - -func ExampleReadStringInto_unicode() { - cfgStr := `; Comment line -[甲] -乙=丙 # comment` - cfg := struct { - X甲 struct { - X乙 string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.X甲.X乙) - // Output: 丙 -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/go1_0.go b/Godeps/_workspace/src/code.google.com/p/gcfg/go1_0.go deleted file mode 100644 index 6670210..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/go1_0.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !go1.2 - -package gcfg - -type textUnmarshaler interface { - UnmarshalText(text []byte) error -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/go1_2.go b/Godeps/_workspace/src/code.google.com/p/gcfg/go1_2.go deleted file mode 100644 index 6f5843b..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/go1_2.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build go1.2 - -package gcfg - -import ( - "encoding" -) - -type textUnmarshaler encoding.TextUnmarshaler diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/issues_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/issues_test.go deleted file mode 100644 index 796dd10..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/issues_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package gcfg - -import ( - "fmt" - "math/big" - "strings" - "testing" -) - -type Config1 struct { - Section struct { - Int int - BigInt big.Int - } -} - -var testsIssue1 = []struct { - cfg string - typename string -}{ - {"[section]\nint=X", "int"}, - {"[section]\nint=", "int"}, - {"[section]\nint=1A", "int"}, - {"[section]\nbigint=X", "big.Int"}, - {"[section]\nbigint=", "big.Int"}, - {"[section]\nbigint=1A", "big.Int"}, -} - -// Value parse error should: -// - include plain type name -// - not include reflect internals -func TestIssue1(t *testing.T) { - for i, tt := range testsIssue1 { - var c Config1 - err := ReadStringInto(&c, tt.cfg) - switch { - case err == nil: - t.Errorf("%d fail: got ok; wanted error", i) - case !strings.Contains(err.Error(), tt.typename): - t.Errorf("%d fail: error message doesn't contain type name %q: %v", - i, tt.typename, err) - case strings.Contains(err.Error(), "reflect"): - t.Errorf("%d fail: error message includes reflect internals: %v", - i, err) - default: - t.Logf("%d pass: %v", i, err) - } - } -} - -type confIssue2 struct{ Main struct{ Foo string } } - -var testsIssue2 = []readtest{ - {"[main]\n;\nfoo = bar\n", &confIssue2{struct{ Foo string }{"bar"}}, true}, - {"[main]\r\n;\r\nfoo = bar\r\n", &confIssue2{struct{ Foo string }{"bar"}}, true}, -} - -func TestIssue2(t *testing.T) { - for i, tt := range testsIssue2 { - id := fmt.Sprintf("issue2:%d", i) - testRead(t, id, tt) - } -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/read.go b/Godeps/_workspace/src/code.google.com/p/gcfg/read.go deleted file mode 100644 index 4719c2b..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/read.go +++ /dev/null @@ -1,181 +0,0 @@ -package gcfg - -import ( - "fmt" - "io" - "io/ioutil" - "os" - "strings" -) - -import ( - "code.google.com/p/gcfg/scanner" - "code.google.com/p/gcfg/token" -) - -var unescape = map[rune]rune{'\\': '\\', '"': '"', 'n': '\n', 't': '\t'} - -// no error: invalid literals should be caught by scanner -func unquote(s string) string { - u, q, esc := make([]rune, 0, len(s)), false, false - for _, c := range s { - if esc { - uc, ok := unescape[c] - switch { - case ok: - u = append(u, uc) - fallthrough - case !q && c == '\n': - esc = false - continue - } - panic("invalid escape sequence") - } - switch c { - case '"': - q = !q - case '\\': - esc = true - default: - u = append(u, c) - } - } - if q { - panic("missing end quote") - } - if esc { - panic("invalid escape sequence") - } - return string(u) -} - -func readInto(config interface{}, fset *token.FileSet, file *token.File, src []byte) error { - var s scanner.Scanner - var errs scanner.ErrorList - s.Init(file, src, func(p token.Position, m string) { errs.Add(p, m) }, 0) - sect, sectsub := "", "" - pos, tok, lit := s.Scan() - errfn := func(msg string) error { - return fmt.Errorf("%s: %s", fset.Position(pos), msg) - } - for { - if errs.Len() > 0 { - return errs.Err() - } - switch tok { - case token.EOF: - return nil - case token.EOL, token.COMMENT: - pos, tok, lit = s.Scan() - case token.LBRACK: - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - return errs.Err() - } - if tok != token.IDENT { - return errfn("expected section name") - } - sect, sectsub = lit, "" - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - return errs.Err() - } - if tok == token.STRING { - sectsub = unquote(lit) - if sectsub == "" { - return errfn("empty subsection name") - } - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - return errs.Err() - } - } - if tok != token.RBRACK { - if sectsub == "" { - return errfn("expected subsection name or right bracket") - } - return errfn("expected right bracket") - } - pos, tok, lit = s.Scan() - if tok != token.EOL && tok != token.EOF && tok != token.COMMENT { - return errfn("expected EOL, EOF, or comment") - } - case token.IDENT: - if sect == "" { - return errfn("expected section header") - } - n := lit - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - return errs.Err() - } - blank, v := tok == token.EOF || tok == token.EOL || tok == token.COMMENT, "" - if !blank { - if tok != token.ASSIGN { - return errfn("expected '='") - } - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - return errs.Err() - } - if tok != token.STRING { - return errfn("expected value") - } - v = unquote(lit) - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - return errs.Err() - } - if tok != token.EOL && tok != token.EOF && tok != token.COMMENT { - return errfn("expected EOL, EOF, or comment") - } - } - err := set(config, sect, sectsub, n, blank, v) - if err != nil { - return err - } - default: - if sect == "" { - return errfn("expected section header") - } - return errfn("expected section header or variable declaration") - } - } - panic("never reached") -} - -// ReadInto reads gcfg formatted data from reader and sets the values into the -// corresponding fields in config. -func ReadInto(config interface{}, reader io.Reader) error { - src, err := ioutil.ReadAll(reader) - if err != nil { - return err - } - fset := token.NewFileSet() - file := fset.AddFile("", fset.Base(), len(src)) - return readInto(config, fset, file, src) -} - -// ReadStringInto reads gcfg formatted data from str and sets the values into -// the corresponding fields in config. -func ReadStringInto(config interface{}, str string) error { - r := strings.NewReader(str) - return ReadInto(config, r) -} - -// ReadFileInto reads gcfg formatted data from the file filename and sets the -// values into the corresponding fields in config. -func ReadFileInto(config interface{}, filename string) error { - f, err := os.Open(filename) - if err != nil { - return err - } - defer f.Close() - src, err := ioutil.ReadAll(f) - if err != nil { - return err - } - fset := token.NewFileSet() - file := fset.AddFile(filename, fset.Base(), len(src)) - return readInto(config, fset, file, src) -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/read_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/read_test.go deleted file mode 100644 index 4a7d8e1..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/read_test.go +++ /dev/null @@ -1,333 +0,0 @@ -package gcfg - -import ( - "fmt" - "math/big" - "os" - "reflect" - "testing" -) - -const ( - // 64 spaces - sp64 = " " - // 512 spaces - sp512 = sp64 + sp64 + sp64 + sp64 + sp64 + sp64 + sp64 + sp64 - // 4096 spaces - sp4096 = sp512 + sp512 + sp512 + sp512 + sp512 + sp512 + sp512 + sp512 -) - -type cBasic struct { - Section cBasicS1 - Hyphen_In_Section cBasicS2 - unexported cBasicS1 - Exported cBasicS3 - TagName cBasicS1 `gcfg:"tag-name"` -} -type cBasicS1 struct { - Name string - Int int - PName *string -} -type cBasicS2 struct { - Hyphen_In_Name string -} -type cBasicS3 struct { - unexported string -} - -type nonMulti []string - -type unmarshalable string - -func (u *unmarshalable) UnmarshalText(text []byte) error { - s := string(text) - if s == "error" { - return fmt.Errorf("%s", s) - } - *u = unmarshalable(s) - return nil -} - -var _ textUnmarshaler = new(unmarshalable) - -type cUni struct { - X甲 cUniS1 - XSection cUniS2 -} -type cUniS1 struct { - X乙 string -} -type cUniS2 struct { - XName string -} - -type cMulti struct { - M1 cMultiS1 - M2 cMultiS2 - M3 cMultiS3 -} -type cMultiS1 struct{ Multi []string } -type cMultiS2 struct{ NonMulti nonMulti } -type cMultiS3 struct{ MultiInt []int } - -type cSubs struct{ Sub map[string]*cSubsS1 } -type cSubsS1 struct{ Name string } - -type cBool struct{ Section cBoolS1 } -type cBoolS1 struct{ Bool bool } - -type cTxUnm struct{ Section cTxUnmS1 } -type cTxUnmS1 struct{ Name unmarshalable } - -type cNum struct { - N1 cNumS1 - N2 cNumS2 - N3 cNumS3 -} -type cNumS1 struct { - Int int - IntDHO int `gcfg:",int=dho"` - Big *big.Int -} -type cNumS2 struct { - MultiInt []int - MultiBig []*big.Int -} -type cNumS3 struct{ FileMode os.FileMode } -type readtest struct { - gcfg string - exp interface{} - ok bool -} - -func newString(s string) *string { - return &s -} - -var readtests = []struct { - group string - tests []readtest -}{{"scanning", []readtest{ - {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - // hyphen in name - {"[hyphen-in-section]\nhyphen-in-name=value", &cBasic{Hyphen_In_Section: cBasicS2{Hyphen_In_Name: "value"}}, true}, - // quoted string value - {"[section]\nname=\"\"", &cBasic{Section: cBasicS1{Name: ""}}, true}, - {"[section]\nname=\" \"", &cBasic{Section: cBasicS1{Name: " "}}, true}, - {"[section]\nname=\"value\"", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=\" value \"", &cBasic{Section: cBasicS1{Name: " value "}}, true}, - {"\n[section]\nname=\"va ; lue\"", &cBasic{Section: cBasicS1{Name: "va ; lue"}}, true}, - {"[section]\nname=\"val\" \"ue\"", &cBasic{Section: cBasicS1{Name: "val ue"}}, true}, - {"[section]\nname=\"value", &cBasic{}, false}, - // escape sequences - {"[section]\nname=\"va\\\\lue\"", &cBasic{Section: cBasicS1{Name: "va\\lue"}}, true}, - {"[section]\nname=\"va\\\"lue\"", &cBasic{Section: cBasicS1{Name: "va\"lue"}}, true}, - {"[section]\nname=\"va\\nlue\"", &cBasic{Section: cBasicS1{Name: "va\nlue"}}, true}, - {"[section]\nname=\"va\\tlue\"", &cBasic{Section: cBasicS1{Name: "va\tlue"}}, true}, - {"\n[section]\nname=\\", &cBasic{}, false}, - {"\n[section]\nname=\\a", &cBasic{}, false}, - {"\n[section]\nname=\"val\\a\"", &cBasic{}, false}, - {"\n[section]\nname=val\\", &cBasic{}, false}, - {"\n[sub \"A\\\n\"]\nname=value", &cSubs{}, false}, - {"\n[sub \"A\\\t\"]\nname=value", &cSubs{}, false}, - // broken line - {"[section]\nname=value \\\n value", &cBasic{Section: cBasicS1{Name: "value value"}}, true}, - {"[section]\nname=\"value \\\n value\"", &cBasic{}, false}, -}}, {"scanning:whitespace", []readtest{ - {" \n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {" [section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\t[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[ section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section ]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\n name=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname =value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname= value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=value ", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\r\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\r\nname=value\r\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {";cmnt\r\n[section]\r\nname=value\r\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - // long lines - {sp4096 + "[section]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[" + sp4096 + "section]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section" + sp4096 + "]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]" + sp4096 + "\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\n" + sp4096 + "name=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname" + sp4096 + "=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=" + sp4096 + "value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=value\n" + sp4096, &cBasic{Section: cBasicS1{Name: "value"}}, true}, -}}, {"scanning:comments", []readtest{ - {"; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"# cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {" ; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\t; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]; cmnt\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section] ; cmnt\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=value; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=value ; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=\"value\" ; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=value ; \"cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=\"va ; lue\" ; cmnt", &cBasic{Section: cBasicS1{Name: "va ; lue"}}, true}, - {"\n[section]\nname=; cmnt", &cBasic{Section: cBasicS1{Name: ""}}, true}, -}}, {"scanning:subsections", []readtest{ - {"\n[sub \"A\"]\nname=value", &cSubs{map[string]*cSubsS1{"A": &cSubsS1{"value"}}}, true}, - {"\n[sub \"b\"]\nname=value", &cSubs{map[string]*cSubsS1{"b": &cSubsS1{"value"}}}, true}, - {"\n[sub \"A\\\\\"]\nname=value", &cSubs{map[string]*cSubsS1{"A\\": &cSubsS1{"value"}}}, true}, - {"\n[sub \"A\\\"\"]\nname=value", &cSubs{map[string]*cSubsS1{"A\"": &cSubsS1{"value"}}}, true}, -}}, {"syntax", []readtest{ - // invalid line - {"\n[section]\n=", &cBasic{}, false}, - // no section - {"name=value", &cBasic{}, false}, - // empty section - {"\n[]\nname=value", &cBasic{}, false}, - // empty subsection - {"\n[sub \"\"]\nname=value", &cSubs{}, false}, -}}, {"setting", []readtest{ - {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - // pointer - {"[section]", &cBasic{Section: cBasicS1{PName: nil}}, true}, - {"[section]\npname=value", &cBasic{Section: cBasicS1{PName: newString("value")}}, true}, - // section name not matched - {"\n[nonexistent]\nname=value", &cBasic{}, false}, - // subsection name not matched - {"\n[section \"nonexistent\"]\nname=value", &cBasic{}, false}, - // variable name not matched - {"\n[section]\nnonexistent=value", &cBasic{}, false}, - // hyphen in name - {"[hyphen-in-section]\nhyphen-in-name=value", &cBasic{Hyphen_In_Section: cBasicS2{Hyphen_In_Name: "value"}}, true}, - // ignore unexported fields - {"[unexported]\nname=value", &cBasic{}, false}, - {"[exported]\nunexported=value", &cBasic{}, false}, - // 'X' prefix for non-upper/lower-case letters - {"[甲]\n乙=丙", &cUni{X甲: cUniS1{X乙: "丙"}}, true}, - //{"[section]\nxname=value", &cBasic{XSection: cBasicS4{XName: "value"}}, false}, - //{"[xsection]\nname=value", &cBasic{XSection: cBasicS4{XName: "value"}}, false}, - // name specified as struct tag - {"[tag-name]\nname=value", &cBasic{TagName: cBasicS1{Name: "value"}}, true}, -}}, {"multivalue", []readtest{ - // unnamed slice type: treat as multi-value - {"\n[m1]", &cMulti{M1: cMultiS1{}}, true}, - {"\n[m1]\nmulti=value", &cMulti{M1: cMultiS1{[]string{"value"}}}, true}, - {"\n[m1]\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true}, - // "blank" empties multi-valued slice -- here same result as above - {"\n[m1]\nmulti\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true}, - // named slice type: do not treat as multi-value - {"\n[m2]", &cMulti{}, true}, - {"\n[m2]\nmulti=value", &cMulti{}, false}, - {"\n[m2]\nmulti=value1\nmulti=value2", &cMulti{}, false}, -}}, {"type:string", []readtest{ - {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=", &cBasic{Section: cBasicS1{Name: ""}}, true}, -}}, {"type:bool", []readtest{ - // explicit values - {"[section]\nbool=true", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=yes", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=on", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=1", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=tRuE", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=false", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=no", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=off", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=0", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=NO", &cBool{cBoolS1{false}}, true}, - // "blank" value handled as true - {"[section]\nbool", &cBool{cBoolS1{true}}, true}, - // bool parse errors - {"[section]\nbool=maybe", &cBool{}, false}, - {"[section]\nbool=t", &cBool{}, false}, - {"[section]\nbool=truer", &cBool{}, false}, - {"[section]\nbool=2", &cBool{}, false}, - {"[section]\nbool=-1", &cBool{}, false}, -}}, {"type:numeric", []readtest{ - {"[section]\nint=0", &cBasic{Section: cBasicS1{Int: 0}}, true}, - {"[section]\nint=1", &cBasic{Section: cBasicS1{Int: 1}}, true}, - {"[section]\nint=-1", &cBasic{Section: cBasicS1{Int: -1}}, true}, - {"[section]\nint=0.2", &cBasic{}, false}, - {"[section]\nint=1e3", &cBasic{}, false}, - // primitive [u]int(|8|16|32|64) and big.Int is parsed as dec or hex (not octal) - {"[n1]\nint=010", &cNum{N1: cNumS1{Int: 10}}, true}, - {"[n1]\nint=0x10", &cNum{N1: cNumS1{Int: 0x10}}, true}, - {"[n1]\nbig=1", &cNum{N1: cNumS1{Big: big.NewInt(1)}}, true}, - {"[n1]\nbig=0x10", &cNum{N1: cNumS1{Big: big.NewInt(0x10)}}, true}, - {"[n1]\nbig=010", &cNum{N1: cNumS1{Big: big.NewInt(10)}}, true}, - {"[n2]\nmultiint=010", &cNum{N2: cNumS2{MultiInt: []int{10}}}, true}, - {"[n2]\nmultibig=010", &cNum{N2: cNumS2{MultiBig: []*big.Int{big.NewInt(10)}}}, true}, - // set parse mode for int types via struct tag - {"[n1]\nintdho=010", &cNum{N1: cNumS1{IntDHO: 010}}, true}, - // octal allowed for named type - {"[n3]\nfilemode=0777", &cNum{N3: cNumS3{FileMode: 0777}}, true}, -}}, {"type:textUnmarshaler", []readtest{ - {"[section]\nname=value", &cTxUnm{Section: cTxUnmS1{Name: "value"}}, true}, - {"[section]\nname=error", &cTxUnm{}, false}, -}}, -} - -func TestReadStringInto(t *testing.T) { - for _, tg := range readtests { - for i, tt := range tg.tests { - id := fmt.Sprintf("%s:%d", tg.group, i) - testRead(t, id, tt) - } - } -} - -func TestReadStringIntoMultiBlankPreset(t *testing.T) { - tt := readtest{"\n[m1]\nmulti\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true} - cfg := &cMulti{M1: cMultiS1{[]string{"preset1", "preset2"}}} - testReadInto(t, "multi:blank", tt, cfg) -} - -func testRead(t *testing.T, id string, tt readtest) { - // get the type of the expected result - restyp := reflect.TypeOf(tt.exp).Elem() - // create a new instance to hold the actual result - res := reflect.New(restyp).Interface() - testReadInto(t, id, tt, res) -} - -func testReadInto(t *testing.T, id string, tt readtest, res interface{}) { - err := ReadStringInto(res, tt.gcfg) - if tt.ok { - if err != nil { - t.Errorf("%s fail: got error %v, wanted ok", id, err) - return - } else if !reflect.DeepEqual(res, tt.exp) { - t.Errorf("%s fail: got value %#v, wanted value %#v", id, res, tt.exp) - return - } - if !testing.Short() { - t.Logf("%s pass: got value %#v", id, res) - } - } else { // !tt.ok - if err == nil { - t.Errorf("%s fail: got value %#v, wanted error", id, res) - return - } - if !testing.Short() { - t.Logf("%s pass: got error %v", id, err) - } - } -} - -func TestReadFileInto(t *testing.T) { - res := &struct{ Section struct{ Name string } }{} - err := ReadFileInto(res, "testdata/gcfg_test.gcfg") - if err != nil { - t.Errorf(err.Error()) - } - if "value" != res.Section.Name { - t.Errorf("got %q, wanted %q", res.Section.Name, "value") - } -} - -func TestReadFileIntoUnicode(t *testing.T) { - res := &struct{ X甲 struct{ X乙 string } }{} - err := ReadFileInto(res, "testdata/gcfg_unicode_test.gcfg") - if err != nil { - t.Errorf(err.Error()) - } - if "丙" != res.X甲.X乙 { - t.Errorf("got %q, wanted %q", res.X甲.X乙, "丙") - } -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/errors.go b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/errors.go deleted file mode 100644 index 4ff920a..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/errors.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package scanner - -import ( - "fmt" - "io" - "sort" -) - -import ( - "code.google.com/p/gcfg/token" -) - -// In an ErrorList, an error is represented by an *Error. -// The position Pos, if valid, points to the beginning of -// the offending token, and the error condition is described -// by Msg. -// -type Error struct { - Pos token.Position - Msg string -} - -// Error implements the error interface. -func (e Error) Error() string { - if e.Pos.Filename != "" || e.Pos.IsValid() { - // don't print "" - // TODO(gri) reconsider the semantics of Position.IsValid - return e.Pos.String() + ": " + e.Msg - } - return e.Msg -} - -// ErrorList is a list of *Errors. -// The zero value for an ErrorList is an empty ErrorList ready to use. -// -type ErrorList []*Error - -// Add adds an Error with given position and error message to an ErrorList. -func (p *ErrorList) Add(pos token.Position, msg string) { - *p = append(*p, &Error{pos, msg}) -} - -// Reset resets an ErrorList to no errors. -func (p *ErrorList) Reset() { *p = (*p)[0:0] } - -// ErrorList implements the sort Interface. -func (p ErrorList) Len() int { return len(p) } -func (p ErrorList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p ErrorList) Less(i, j int) bool { - e := &p[i].Pos - f := &p[j].Pos - if e.Filename < f.Filename { - return true - } - if e.Filename == f.Filename { - return e.Offset < f.Offset - } - return false -} - -// Sort sorts an ErrorList. *Error entries are sorted by position, -// other errors are sorted by error message, and before any *Error -// entry. -// -func (p ErrorList) Sort() { - sort.Sort(p) -} - -// RemoveMultiples sorts an ErrorList and removes all but the first error per line. -func (p *ErrorList) RemoveMultiples() { - sort.Sort(p) - var last token.Position // initial last.Line is != any legal error line - i := 0 - for _, e := range *p { - if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line { - last = e.Pos - (*p)[i] = e - i++ - } - } - (*p) = (*p)[0:i] -} - -// An ErrorList implements the error interface. -func (p ErrorList) Error() string { - switch len(p) { - case 0: - return "no errors" - case 1: - return p[0].Error() - } - return fmt.Sprintf("%s (and %d more errors)", p[0], len(p)-1) -} - -// Err returns an error equivalent to this error list. -// If the list is empty, Err returns nil. -func (p ErrorList) Err() error { - if len(p) == 0 { - return nil - } - return p -} - -// PrintError is a utility function that prints a list of errors to w, -// one error per line, if the err parameter is an ErrorList. Otherwise -// it prints the err string. -// -func PrintError(w io.Writer, err error) { - if list, ok := err.(ErrorList); ok { - for _, e := range list { - fmt.Fprintf(w, "%s\n", e) - } - } else if err != nil { - fmt.Fprintf(w, "%s\n", err) - } -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/example_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/example_test.go deleted file mode 100644 index 05eadf5..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/example_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package scanner_test - -import ( - "fmt" -) - -import ( - "code.google.com/p/gcfg/scanner" - "code.google.com/p/gcfg/token" -) - -func ExampleScanner_Scan() { - // src is the input that we want to tokenize. - src := []byte(`[profile "A"] -color = blue ; Comment`) - - // Initialize the scanner. - var s scanner.Scanner - fset := token.NewFileSet() // positions are relative to fset - file := fset.AddFile("", fset.Base(), len(src)) // register input "file" - s.Init(file, src, nil /* no error handler */, scanner.ScanComments) - - // Repeated calls to Scan yield the token sequence found in the input. - for { - pos, tok, lit := s.Scan() - if tok == token.EOF { - break - } - fmt.Printf("%s\t%q\t%q\n", fset.Position(pos), tok, lit) - } - - // output: - // 1:1 "[" "" - // 1:2 "IDENT" "profile" - // 1:10 "STRING" "\"A\"" - // 1:13 "]" "" - // 1:14 "\n" "" - // 2:1 "IDENT" "color" - // 2:7 "=" "" - // 2:9 "STRING" "blue" - // 2:14 "COMMENT" "; Comment" -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner.go b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner.go deleted file mode 100644 index f65a4f5..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner.go +++ /dev/null @@ -1,342 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package scanner implements a scanner for gcfg configuration text. -// It takes a []byte as source which can then be tokenized -// through repeated calls to the Scan method. -// -// Note that the API for the scanner package may change to accommodate new -// features or implementation changes in gcfg. -// -package scanner - -import ( - "fmt" - "path/filepath" - "unicode" - "unicode/utf8" -) - -import ( - "code.google.com/p/gcfg/token" -) - -// An ErrorHandler may be provided to Scanner.Init. If a syntax error is -// encountered and a handler was installed, the handler is called with a -// position and an error message. The position points to the beginning of -// the offending token. -// -type ErrorHandler func(pos token.Position, msg string) - -// A Scanner holds the scanner's internal state while processing -// a given text. It can be allocated as part of another data -// structure but must be initialized via Init before use. -// -type Scanner struct { - // immutable state - file *token.File // source file handle - dir string // directory portion of file.Name() - src []byte // source - err ErrorHandler // error reporting; or nil - mode Mode // scanning mode - - // scanning state - ch rune // current character - offset int // character offset - rdOffset int // reading offset (position after current character) - lineOffset int // current line offset - nextVal bool // next token is expected to be a value - - // public state - ok to modify - ErrorCount int // number of errors encountered -} - -// Read the next Unicode char into s.ch. -// s.ch < 0 means end-of-file. -// -func (s *Scanner) next() { - if s.rdOffset < len(s.src) { - s.offset = s.rdOffset - if s.ch == '\n' { - s.lineOffset = s.offset - s.file.AddLine(s.offset) - } - r, w := rune(s.src[s.rdOffset]), 1 - switch { - case r == 0: - s.error(s.offset, "illegal character NUL") - case r >= 0x80: - // not ASCII - r, w = utf8.DecodeRune(s.src[s.rdOffset:]) - if r == utf8.RuneError && w == 1 { - s.error(s.offset, "illegal UTF-8 encoding") - } - } - s.rdOffset += w - s.ch = r - } else { - s.offset = len(s.src) - if s.ch == '\n' { - s.lineOffset = s.offset - s.file.AddLine(s.offset) - } - s.ch = -1 // eof - } -} - -// A mode value is a set of flags (or 0). -// They control scanner behavior. -// -type Mode uint - -const ( - ScanComments Mode = 1 << iota // return comments as COMMENT tokens -) - -// Init prepares the scanner s to tokenize the text src by setting the -// scanner at the beginning of src. The scanner uses the file set file -// for position information and it adds line information for each line. -// It is ok to re-use the same file when re-scanning the same file as -// line information which is already present is ignored. Init causes a -// panic if the file size does not match the src size. -// -// Calls to Scan will invoke the error handler err if they encounter a -// syntax error and err is not nil. Also, for each error encountered, -// the Scanner field ErrorCount is incremented by one. The mode parameter -// determines how comments are handled. -// -// Note that Init may call err if there is an error in the first character -// of the file. -// -func (s *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode Mode) { - // Explicitly initialize all fields since a scanner may be reused. - if file.Size() != len(src) { - panic(fmt.Sprintf("file size (%d) does not match src len (%d)", file.Size(), len(src))) - } - s.file = file - s.dir, _ = filepath.Split(file.Name()) - s.src = src - s.err = err - s.mode = mode - - s.ch = ' ' - s.offset = 0 - s.rdOffset = 0 - s.lineOffset = 0 - s.ErrorCount = 0 - s.nextVal = false - - s.next() -} - -func (s *Scanner) error(offs int, msg string) { - if s.err != nil { - s.err(s.file.Position(s.file.Pos(offs)), msg) - } - s.ErrorCount++ -} - -func (s *Scanner) scanComment() string { - // initial [;#] already consumed - offs := s.offset - 1 // position of initial [;#] - - for s.ch != '\n' && s.ch >= 0 { - s.next() - } - return string(s.src[offs:s.offset]) -} - -func isLetter(ch rune) bool { - return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch >= 0x80 && unicode.IsLetter(ch) -} - -func isDigit(ch rune) bool { - return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch) -} - -func (s *Scanner) scanIdentifier() string { - offs := s.offset - for isLetter(s.ch) || isDigit(s.ch) || s.ch == '-' { - s.next() - } - return string(s.src[offs:s.offset]) -} - -func (s *Scanner) scanEscape(val bool) { - offs := s.offset - ch := s.ch - s.next() // always make progress - switch ch { - case '\\', '"': - // ok - case 'n', 't': - if val { - break // ok - } - fallthrough - default: - s.error(offs, "unknown escape sequence") - } -} - -func (s *Scanner) scanString() string { - // '"' opening already consumed - offs := s.offset - 1 - - for s.ch != '"' { - ch := s.ch - s.next() - if ch == '\n' || ch < 0 { - s.error(offs, "string not terminated") - break - } - if ch == '\\' { - s.scanEscape(false) - } - } - - s.next() - - return string(s.src[offs:s.offset]) -} - -func stripCR(b []byte) []byte { - c := make([]byte, len(b)) - i := 0 - for _, ch := range b { - if ch != '\r' { - c[i] = ch - i++ - } - } - return c[:i] -} - -func (s *Scanner) scanValString() string { - offs := s.offset - - hasCR := false - end := offs - inQuote := false -loop: - for inQuote || s.ch >= 0 && s.ch != '\n' && s.ch != ';' && s.ch != '#' { - ch := s.ch - s.next() - switch { - case inQuote && ch == '\\': - s.scanEscape(true) - case !inQuote && ch == '\\': - if s.ch == '\r' { - hasCR = true - s.next() - } - if s.ch != '\n' { - s.error(offs, "unquoted '\\' must be followed by new line") - break loop - } - s.next() - case ch == '"': - inQuote = !inQuote - case ch == '\r': - hasCR = true - case ch < 0 || inQuote && ch == '\n': - s.error(offs, "string not terminated") - break loop - } - if inQuote || !isWhiteSpace(ch) { - end = s.offset - } - } - - lit := s.src[offs:end] - if hasCR { - lit = stripCR(lit) - } - - return string(lit) -} - -func isWhiteSpace(ch rune) bool { - return ch == ' ' || ch == '\t' || ch == '\r' -} - -func (s *Scanner) skipWhitespace() { - for isWhiteSpace(s.ch) { - s.next() - } -} - -// Scan scans the next token and returns the token position, the token, -// and its literal string if applicable. The source end is indicated by -// token.EOF. -// -// If the returned token is a literal (token.IDENT, token.STRING) or -// token.COMMENT, the literal string has the corresponding value. -// -// If the returned token is token.ILLEGAL, the literal string is the -// offending character. -// -// In all other cases, Scan returns an empty literal string. -// -// For more tolerant parsing, Scan will return a valid token if -// possible even if a syntax error was encountered. Thus, even -// if the resulting token sequence contains no illegal tokens, -// a client may not assume that no error occurred. Instead it -// must check the scanner's ErrorCount or the number of calls -// of the error handler, if there was one installed. -// -// Scan adds line information to the file added to the file -// set with Init. Token positions are relative to that file -// and thus relative to the file set. -// -func (s *Scanner) Scan() (pos token.Pos, tok token.Token, lit string) { -scanAgain: - s.skipWhitespace() - - // current token start - pos = s.file.Pos(s.offset) - - // determine token value - switch ch := s.ch; { - case s.nextVal: - lit = s.scanValString() - tok = token.STRING - s.nextVal = false - case isLetter(ch): - lit = s.scanIdentifier() - tok = token.IDENT - default: - s.next() // always make progress - switch ch { - case -1: - tok = token.EOF - case '\n': - tok = token.EOL - case '"': - tok = token.STRING - lit = s.scanString() - case '[': - tok = token.LBRACK - case ']': - tok = token.RBRACK - case ';', '#': - // comment - lit = s.scanComment() - if s.mode&ScanComments == 0 { - // skip comment - goto scanAgain - } - tok = token.COMMENT - case '=': - tok = token.ASSIGN - s.nextVal = true - default: - s.error(s.file.Offset(pos), fmt.Sprintf("illegal character %#U", ch)) - tok = token.ILLEGAL - lit = string(ch) - } - } - - return -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner_test.go deleted file mode 100644 index 33227c1..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/scanner/scanner_test.go +++ /dev/null @@ -1,417 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package scanner - -import ( - "os" - "strings" - "testing" -) - -import ( - "code.google.com/p/gcfg/token" -) - -var fset = token.NewFileSet() - -const /* class */ ( - special = iota - literal - operator -) - -func tokenclass(tok token.Token) int { - switch { - case tok.IsLiteral(): - return literal - case tok.IsOperator(): - return operator - } - return special -} - -type elt struct { - tok token.Token - lit string - class int - pre string - suf string -} - -var tokens = [...]elt{ - // Special tokens - {token.COMMENT, "; a comment", special, "", "\n"}, - {token.COMMENT, "# a comment", special, "", "\n"}, - - // Operators and delimiters - {token.ASSIGN, "=", operator, "", "value"}, - {token.LBRACK, "[", operator, "", ""}, - {token.RBRACK, "]", operator, "", ""}, - {token.EOL, "\n", operator, "", ""}, - - // Identifiers - {token.IDENT, "foobar", literal, "", ""}, - {token.IDENT, "a۰۱۸", literal, "", ""}, - {token.IDENT, "foo६४", literal, "", ""}, - {token.IDENT, "bar9876", literal, "", ""}, - {token.IDENT, "foo-bar", literal, "", ""}, - {token.IDENT, "foo", literal, ";\n", ""}, - // String literals (subsection names) - {token.STRING, `"foobar"`, literal, "", ""}, - {token.STRING, `"\""`, literal, "", ""}, - // String literals (values) - {token.STRING, `"\n"`, literal, "=", ""}, - {token.STRING, `"foobar"`, literal, "=", ""}, - {token.STRING, `"foo\nbar"`, literal, "=", ""}, - {token.STRING, `"foo\"bar"`, literal, "=", ""}, - {token.STRING, `"foo\\bar"`, literal, "=", ""}, - {token.STRING, `"foobar"`, literal, "=", ""}, - {token.STRING, `"foobar"`, literal, "= ", ""}, - {token.STRING, `"foobar"`, literal, "=", "\n"}, - {token.STRING, `"foobar"`, literal, "=", ";"}, - {token.STRING, `"foobar"`, literal, "=", " ;"}, - {token.STRING, `"foobar"`, literal, "=", "#"}, - {token.STRING, `"foobar"`, literal, "=", " #"}, - {token.STRING, "foobar", literal, "=", ""}, - {token.STRING, "foobar", literal, "= ", ""}, - {token.STRING, "foobar", literal, "=", " "}, - {token.STRING, `"foo" "bar"`, literal, "=", " "}, - {token.STRING, "foo\\\nbar", literal, "=", ""}, - {token.STRING, "foo\\\r\nbar", literal, "=", ""}, -} - -const whitespace = " \t \n\n\n" // to separate tokens - -var source = func() []byte { - var src []byte - for _, t := range tokens { - src = append(src, t.pre...) - src = append(src, t.lit...) - src = append(src, t.suf...) - src = append(src, whitespace...) - } - return src -}() - -func newlineCount(s string) int { - n := 0 - for i := 0; i < len(s); i++ { - if s[i] == '\n' { - n++ - } - } - return n -} - -func checkPos(t *testing.T, lit string, p token.Pos, expected token.Position) { - pos := fset.Position(p) - if pos.Filename != expected.Filename { - t.Errorf("bad filename for %q: got %s, expected %s", lit, pos.Filename, expected.Filename) - } - if pos.Offset != expected.Offset { - t.Errorf("bad position for %q: got %d, expected %d", lit, pos.Offset, expected.Offset) - } - if pos.Line != expected.Line { - t.Errorf("bad line for %q: got %d, expected %d", lit, pos.Line, expected.Line) - } - if pos.Column != expected.Column { - t.Errorf("bad column for %q: got %d, expected %d", lit, pos.Column, expected.Column) - } -} - -// Verify that calling Scan() provides the correct results. -func TestScan(t *testing.T) { - // make source - src_linecount := newlineCount(string(source)) - whitespace_linecount := newlineCount(whitespace) - - index := 0 - - // error handler - eh := func(_ token.Position, msg string) { - t.Errorf("%d: error handler called (msg = %s)", index, msg) - } - - // verify scan - var s Scanner - s.Init(fset.AddFile("", fset.Base(), len(source)), source, eh, ScanComments) - // epos is the expected position - epos := token.Position{ - Filename: "", - Offset: 0, - Line: 1, - Column: 1, - } - for { - pos, tok, lit := s.Scan() - if lit == "" { - // no literal value for non-literal tokens - lit = tok.String() - } - e := elt{token.EOF, "", special, "", ""} - if index < len(tokens) { - e = tokens[index] - } - if tok == token.EOF { - lit = "" - epos.Line = src_linecount - epos.Column = 2 - } - if e.pre != "" && strings.ContainsRune("=;#", rune(e.pre[0])) { - epos.Column = 1 - checkPos(t, lit, pos, epos) - var etok token.Token - if e.pre[0] == '=' { - etok = token.ASSIGN - } else { - etok = token.COMMENT - } - if tok != etok { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, etok) - } - pos, tok, lit = s.Scan() - } - epos.Offset += len(e.pre) - if tok != token.EOF { - epos.Column = 1 + len(e.pre) - } - if e.pre != "" && e.pre[len(e.pre)-1] == '\n' { - epos.Offset-- - epos.Column-- - checkPos(t, lit, pos, epos) - if tok != token.EOL { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.EOL) - } - epos.Line++ - epos.Offset++ - epos.Column = 1 - pos, tok, lit = s.Scan() - } - checkPos(t, lit, pos, epos) - if tok != e.tok { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, e.tok) - } - if e.tok.IsLiteral() { - // no CRs in value string literals - elit := e.lit - if strings.ContainsRune(e.pre, '=') { - elit = string(stripCR([]byte(elit))) - epos.Offset += len(e.lit) - len(lit) // correct position - } - if lit != elit { - t.Errorf("bad literal for %q: got %q, expected %q", lit, lit, elit) - } - } - if tokenclass(tok) != e.class { - t.Errorf("bad class for %q: got %d, expected %d", lit, tokenclass(tok), e.class) - } - epos.Offset += len(lit) + len(e.suf) + len(whitespace) - epos.Line += newlineCount(lit) + newlineCount(e.suf) + whitespace_linecount - index++ - if tok == token.EOF { - break - } - if e.suf == "value" { - pos, tok, lit = s.Scan() - if tok != token.STRING { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.STRING) - } - } else if strings.ContainsRune(e.suf, ';') || strings.ContainsRune(e.suf, '#') { - pos, tok, lit = s.Scan() - if tok != token.COMMENT { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.COMMENT) - } - } - // skip EOLs - for i := 0; i < whitespace_linecount+newlineCount(e.suf); i++ { - pos, tok, lit = s.Scan() - if tok != token.EOL { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.EOL) - } - } - } - if s.ErrorCount != 0 { - t.Errorf("found %d errors", s.ErrorCount) - } -} - -func TestScanValStringEOF(t *testing.T) { - var s Scanner - src := "= value" - f := fset.AddFile("src", fset.Base(), len(src)) - s.Init(f, []byte(src), nil, 0) - s.Scan() // = - s.Scan() // value - _, tok, _ := s.Scan() // EOF - if tok != token.EOF { - t.Errorf("bad token: got %s, expected %s", tok, token.EOF) - } - if s.ErrorCount > 0 { - t.Error("scanning error") - } -} - -// Verify that initializing the same scanner more then once works correctly. -func TestInit(t *testing.T) { - var s Scanner - - // 1st init - src1 := "\nname = value" - f1 := fset.AddFile("src1", fset.Base(), len(src1)) - s.Init(f1, []byte(src1), nil, 0) - if f1.Size() != len(src1) { - t.Errorf("bad file size: got %d, expected %d", f1.Size(), len(src1)) - } - s.Scan() // \n - s.Scan() // name - _, tok, _ := s.Scan() // = - if tok != token.ASSIGN { - t.Errorf("bad token: got %s, expected %s", tok, token.ASSIGN) - } - - // 2nd init - src2 := "[section]" - f2 := fset.AddFile("src2", fset.Base(), len(src2)) - s.Init(f2, []byte(src2), nil, 0) - if f2.Size() != len(src2) { - t.Errorf("bad file size: got %d, expected %d", f2.Size(), len(src2)) - } - _, tok, _ = s.Scan() // [ - if tok != token.LBRACK { - t.Errorf("bad token: got %s, expected %s", tok, token.LBRACK) - } - - if s.ErrorCount != 0 { - t.Errorf("found %d errors", s.ErrorCount) - } -} - -func TestStdErrorHandler(t *testing.T) { - const src = "@\n" + // illegal character, cause an error - "@ @\n" // two errors on the same line - - var list ErrorList - eh := func(pos token.Position, msg string) { list.Add(pos, msg) } - - var s Scanner - s.Init(fset.AddFile("File1", fset.Base(), len(src)), []byte(src), eh, 0) - for { - if _, tok, _ := s.Scan(); tok == token.EOF { - break - } - } - - if len(list) != s.ErrorCount { - t.Errorf("found %d errors, expected %d", len(list), s.ErrorCount) - } - - if len(list) != 3 { - t.Errorf("found %d raw errors, expected 3", len(list)) - PrintError(os.Stderr, list) - } - - list.Sort() - if len(list) != 3 { - t.Errorf("found %d sorted errors, expected 3", len(list)) - PrintError(os.Stderr, list) - } - - list.RemoveMultiples() - if len(list) != 2 { - t.Errorf("found %d one-per-line errors, expected 2", len(list)) - PrintError(os.Stderr, list) - } -} - -type errorCollector struct { - cnt int // number of errors encountered - msg string // last error message encountered - pos token.Position // last error position encountered -} - -func checkError(t *testing.T, src string, tok token.Token, pos int, err string) { - var s Scanner - var h errorCollector - eh := func(pos token.Position, msg string) { - h.cnt++ - h.msg = msg - h.pos = pos - } - s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), eh, ScanComments) - if src[0] == '=' { - _, _, _ = s.Scan() - } - _, tok0, _ := s.Scan() - _, tok1, _ := s.Scan() - if tok0 != tok { - t.Errorf("%q: got %s, expected %s", src, tok0, tok) - } - if tok1 != token.EOF { - t.Errorf("%q: got %s, expected EOF", src, tok1) - } - cnt := 0 - if err != "" { - cnt = 1 - } - if h.cnt != cnt { - t.Errorf("%q: got cnt %d, expected %d", src, h.cnt, cnt) - } - if h.msg != err { - t.Errorf("%q: got msg %q, expected %q", src, h.msg, err) - } - if h.pos.Offset != pos { - t.Errorf("%q: got offset %d, expected %d", src, h.pos.Offset, pos) - } -} - -var errors = []struct { - src string - tok token.Token - pos int - err string -}{ - {"\a", token.ILLEGAL, 0, "illegal character U+0007"}, - {"/", token.ILLEGAL, 0, "illegal character U+002F '/'"}, - {"_", token.ILLEGAL, 0, "illegal character U+005F '_'"}, - {`…`, token.ILLEGAL, 0, "illegal character U+2026 '…'"}, - {`""`, token.STRING, 0, ""}, - {`"`, token.STRING, 0, "string not terminated"}, - {"\"\n", token.STRING, 0, "string not terminated"}, - {`="`, token.STRING, 1, "string not terminated"}, - {"=\"\n", token.STRING, 1, "string not terminated"}, - {"=\\", token.STRING, 1, "unquoted '\\' must be followed by new line"}, - {"=\\\r", token.STRING, 1, "unquoted '\\' must be followed by new line"}, - {`"\z"`, token.STRING, 2, "unknown escape sequence"}, - {`"\a"`, token.STRING, 2, "unknown escape sequence"}, - {`"\b"`, token.STRING, 2, "unknown escape sequence"}, - {`"\f"`, token.STRING, 2, "unknown escape sequence"}, - {`"\r"`, token.STRING, 2, "unknown escape sequence"}, - {`"\t"`, token.STRING, 2, "unknown escape sequence"}, - {`"\v"`, token.STRING, 2, "unknown escape sequence"}, - {`"\0"`, token.STRING, 2, "unknown escape sequence"}, -} - -func TestScanErrors(t *testing.T) { - for _, e := range errors { - checkError(t, e.src, e.tok, e.pos, e.err) - } -} - -func BenchmarkScan(b *testing.B) { - b.StopTimer() - fset := token.NewFileSet() - file := fset.AddFile("", fset.Base(), len(source)) - var s Scanner - b.StartTimer() - for i := b.N - 1; i >= 0; i-- { - s.Init(file, source, nil, ScanComments) - for { - _, tok, _ := s.Scan() - if tok == token.EOF { - break - } - } - } -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/set.go b/Godeps/_workspace/src/code.google.com/p/gcfg/set.go deleted file mode 100644 index 4e15604..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/set.go +++ /dev/null @@ -1,281 +0,0 @@ -package gcfg - -import ( - "fmt" - "math/big" - "reflect" - "strings" - "unicode" - "unicode/utf8" - - "code.google.com/p/gcfg/types" -) - -type tag struct { - ident string - intMode string -} - -func newTag(ts string) tag { - t := tag{} - s := strings.Split(ts, ",") - t.ident = s[0] - for _, tse := range s[1:] { - if strings.HasPrefix(tse, "int=") { - t.intMode = tse[len("int="):] - } - } - return t -} - -func fieldFold(v reflect.Value, name string) (reflect.Value, tag) { - var n string - r0, _ := utf8.DecodeRuneInString(name) - if unicode.IsLetter(r0) && !unicode.IsLower(r0) && !unicode.IsUpper(r0) { - n = "X" - } - n += strings.Replace(name, "-", "_", -1) - f, ok := v.Type().FieldByNameFunc(func(fieldName string) bool { - if !v.FieldByName(fieldName).CanSet() { - return false - } - f, _ := v.Type().FieldByName(fieldName) - t := newTag(f.Tag.Get("gcfg")) - if t.ident != "" { - return strings.EqualFold(t.ident, name) - } - return strings.EqualFold(n, fieldName) - }) - if !ok { - return reflect.Value{}, tag{} - } - return v.FieldByName(f.Name), newTag(f.Tag.Get("gcfg")) -} - -type setter func(destp interface{}, blank bool, val string, t tag) error - -var errUnsupportedType = fmt.Errorf("unsupported type") -var errBlankUnsupported = fmt.Errorf("blank value not supported for type") - -var setters = []setter{ - typeSetter, textUnmarshalerSetter, kindSetter, scanSetter, -} - -func textUnmarshalerSetter(d interface{}, blank bool, val string, t tag) error { - dtu, ok := d.(textUnmarshaler) - if !ok { - return errUnsupportedType - } - if blank { - return errBlankUnsupported - } - return dtu.UnmarshalText([]byte(val)) -} - -func boolSetter(d interface{}, blank bool, val string, t tag) error { - if blank { - reflect.ValueOf(d).Elem().Set(reflect.ValueOf(true)) - return nil - } - b, err := types.ParseBool(val) - if err == nil { - reflect.ValueOf(d).Elem().Set(reflect.ValueOf(b)) - } - return err -} - -func intMode(mode string) types.IntMode { - var m types.IntMode - if strings.ContainsAny(mode, "dD") { - m |= types.Dec - } - if strings.ContainsAny(mode, "hH") { - m |= types.Hex - } - if strings.ContainsAny(mode, "oO") { - m |= types.Oct - } - return m -} - -var typeModes = map[reflect.Type]types.IntMode{ - reflect.TypeOf(int(0)): types.Dec | types.Hex, - reflect.TypeOf(int8(0)): types.Dec | types.Hex, - reflect.TypeOf(int16(0)): types.Dec | types.Hex, - reflect.TypeOf(int32(0)): types.Dec | types.Hex, - reflect.TypeOf(int64(0)): types.Dec | types.Hex, - reflect.TypeOf(uint(0)): types.Dec | types.Hex, - reflect.TypeOf(uint8(0)): types.Dec | types.Hex, - reflect.TypeOf(uint16(0)): types.Dec | types.Hex, - reflect.TypeOf(uint32(0)): types.Dec | types.Hex, - reflect.TypeOf(uint64(0)): types.Dec | types.Hex, - // use default mode (allow dec/hex/oct) for uintptr type - reflect.TypeOf(big.Int{}): types.Dec | types.Hex, -} - -func intModeDefault(t reflect.Type) types.IntMode { - m, ok := typeModes[t] - if !ok { - m = types.Dec | types.Hex | types.Oct - } - return m -} - -func intSetter(d interface{}, blank bool, val string, t tag) error { - if blank { - return errBlankUnsupported - } - mode := intMode(t.intMode) - if mode == 0 { - mode = intModeDefault(reflect.TypeOf(d).Elem()) - } - return types.ParseInt(d, val, mode) -} - -func stringSetter(d interface{}, blank bool, val string, t tag) error { - if blank { - return errBlankUnsupported - } - dsp, ok := d.(*string) - if !ok { - return errUnsupportedType - } - *dsp = val - return nil -} - -var kindSetters = map[reflect.Kind]setter{ - reflect.String: stringSetter, - reflect.Bool: boolSetter, - reflect.Int: intSetter, - reflect.Int8: intSetter, - reflect.Int16: intSetter, - reflect.Int32: intSetter, - reflect.Int64: intSetter, - reflect.Uint: intSetter, - reflect.Uint8: intSetter, - reflect.Uint16: intSetter, - reflect.Uint32: intSetter, - reflect.Uint64: intSetter, - reflect.Uintptr: intSetter, -} - -var typeSetters = map[reflect.Type]setter{ - reflect.TypeOf(big.Int{}): intSetter, -} - -func typeSetter(d interface{}, blank bool, val string, tt tag) error { - t := reflect.ValueOf(d).Type().Elem() - setter, ok := typeSetters[t] - if !ok { - return errUnsupportedType - } - return setter(d, blank, val, tt) -} - -func kindSetter(d interface{}, blank bool, val string, tt tag) error { - k := reflect.ValueOf(d).Type().Elem().Kind() - setter, ok := kindSetters[k] - if !ok { - return errUnsupportedType - } - return setter(d, blank, val, tt) -} - -func scanSetter(d interface{}, blank bool, val string, tt tag) error { - if blank { - return errBlankUnsupported - } - return types.ScanFully(d, val, 'v') -} - -func set(cfg interface{}, sect, sub, name string, blank bool, value string) error { - vPCfg := reflect.ValueOf(cfg) - if vPCfg.Kind() != reflect.Ptr || vPCfg.Elem().Kind() != reflect.Struct { - panic(fmt.Errorf("config must be a pointer to a struct")) - } - vCfg := vPCfg.Elem() - vSect, _ := fieldFold(vCfg, sect) - if !vSect.IsValid() { - return fmt.Errorf("invalid section: section %q", sect) - } - if vSect.Kind() == reflect.Map { - vst := vSect.Type() - if vst.Key().Kind() != reflect.String || - vst.Elem().Kind() != reflect.Ptr || - vst.Elem().Elem().Kind() != reflect.Struct { - panic(fmt.Errorf("map field for section must have string keys and "+ - " pointer-to-struct values: section %q", sect)) - } - if vSect.IsNil() { - vSect.Set(reflect.MakeMap(vst)) - } - k := reflect.ValueOf(sub) - pv := vSect.MapIndex(k) - if !pv.IsValid() { - vType := vSect.Type().Elem().Elem() - pv = reflect.New(vType) - vSect.SetMapIndex(k, pv) - } - vSect = pv.Elem() - } else if vSect.Kind() != reflect.Struct { - panic(fmt.Errorf("field for section must be a map or a struct: "+ - "section %q", sect)) - } else if sub != "" { - return fmt.Errorf("invalid subsection: "+ - "section %q subsection %q", sect, sub) - } - vVar, t := fieldFold(vSect, name) - if !vVar.IsValid() { - return fmt.Errorf("invalid variable: "+ - "section %q subsection %q variable %q", sect, sub, name) - } - // vVal is either single-valued var, or newly allocated value within multi-valued var - var vVal reflect.Value - // multi-value if unnamed slice type - isMulti := vVar.Type().Name() == "" && vVar.Kind() == reflect.Slice - if isMulti && blank { - vVar.Set(reflect.Zero(vVar.Type())) - return nil - } - if isMulti { - vVal = reflect.New(vVar.Type().Elem()).Elem() - } else { - vVal = vVar - } - isDeref := vVal.Type().Name() == "" && vVal.Type().Kind() == reflect.Ptr - isNew := isDeref && vVal.IsNil() - // vAddr is address of value to set (dereferenced & allocated as needed) - var vAddr reflect.Value - switch { - case isNew: - vAddr = reflect.New(vVal.Type().Elem()) - case isDeref && !isNew: - vAddr = vVal - default: - vAddr = vVal.Addr() - } - vAddrI := vAddr.Interface() - err, ok := error(nil), false - for _, s := range setters { - err = s(vAddrI, blank, value, t) - if err == nil { - ok = true - break - } - if err != errUnsupportedType { - return err - } - } - if !ok { - // in case all setters returned errUnsupportedType - return err - } - if isNew { // set reference if it was dereferenced and newly allocated - vVal.Set(vAddr) - } - if isMulti { // append if multi-valued - vVar.Set(reflect.Append(vVar, vVal)) - } - return nil -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_test.gcfg b/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_test.gcfg deleted file mode 100644 index cddff29..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_test.gcfg +++ /dev/null @@ -1,3 +0,0 @@ -; Comment line -[section] -name=value # comment diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_unicode_test.gcfg b/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_unicode_test.gcfg deleted file mode 100644 index 3762a20..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/testdata/gcfg_unicode_test.gcfg +++ /dev/null @@ -1,3 +0,0 @@ -; Comment line -[甲] -乙=丙 # comment diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/token/position.go b/Godeps/_workspace/src/code.google.com/p/gcfg/token/position.go deleted file mode 100644 index fc45c1e..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/token/position.go +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// TODO(gri) consider making this a separate package outside the go directory. - -package token - -import ( - "fmt" - "sort" - "sync" -) - -// ----------------------------------------------------------------------------- -// Positions - -// Position describes an arbitrary source position -// including the file, line, and column location. -// A Position is valid if the line number is > 0. -// -type Position struct { - Filename string // filename, if any - Offset int // offset, starting at 0 - Line int // line number, starting at 1 - Column int // column number, starting at 1 (character count) -} - -// IsValid returns true if the position is valid. -func (pos *Position) IsValid() bool { return pos.Line > 0 } - -// String returns a string in one of several forms: -// -// file:line:column valid position with file name -// line:column valid position without file name -// file invalid position with file name -// - invalid position without file name -// -func (pos Position) String() string { - s := pos.Filename - if pos.IsValid() { - if s != "" { - s += ":" - } - s += fmt.Sprintf("%d:%d", pos.Line, pos.Column) - } - if s == "" { - s = "-" - } - return s -} - -// Pos is a compact encoding of a source position within a file set. -// It can be converted into a Position for a more convenient, but much -// larger, representation. -// -// The Pos value for a given file is a number in the range [base, base+size], -// where base and size are specified when adding the file to the file set via -// AddFile. -// -// To create the Pos value for a specific source offset, first add -// the respective file to the current file set (via FileSet.AddFile) -// and then call File.Pos(offset) for that file. Given a Pos value p -// for a specific file set fset, the corresponding Position value is -// obtained by calling fset.Position(p). -// -// Pos values can be compared directly with the usual comparison operators: -// If two Pos values p and q are in the same file, comparing p and q is -// equivalent to comparing the respective source file offsets. If p and q -// are in different files, p < q is true if the file implied by p was added -// to the respective file set before the file implied by q. -// -type Pos int - -// The zero value for Pos is NoPos; there is no file and line information -// associated with it, and NoPos().IsValid() is false. NoPos is always -// smaller than any other Pos value. The corresponding Position value -// for NoPos is the zero value for Position. -// -const NoPos Pos = 0 - -// IsValid returns true if the position is valid. -func (p Pos) IsValid() bool { - return p != NoPos -} - -// ----------------------------------------------------------------------------- -// File - -// A File is a handle for a file belonging to a FileSet. -// A File has a name, size, and line offset table. -// -type File struct { - set *FileSet - name string // file name as provided to AddFile - base int // Pos value range for this file is [base...base+size] - size int // file size as provided to AddFile - - // lines and infos are protected by set.mutex - lines []int - infos []lineInfo -} - -// Name returns the file name of file f as registered with AddFile. -func (f *File) Name() string { - return f.name -} - -// Base returns the base offset of file f as registered with AddFile. -func (f *File) Base() int { - return f.base -} - -// Size returns the size of file f as registered with AddFile. -func (f *File) Size() int { - return f.size -} - -// LineCount returns the number of lines in file f. -func (f *File) LineCount() int { - f.set.mutex.RLock() - n := len(f.lines) - f.set.mutex.RUnlock() - return n -} - -// AddLine adds the line offset for a new line. -// The line offset must be larger than the offset for the previous line -// and smaller than the file size; otherwise the line offset is ignored. -// -func (f *File) AddLine(offset int) { - f.set.mutex.Lock() - if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size { - f.lines = append(f.lines, offset) - } - f.set.mutex.Unlock() -} - -// SetLines sets the line offsets for a file and returns true if successful. -// The line offsets are the offsets of the first character of each line; -// for instance for the content "ab\nc\n" the line offsets are {0, 3}. -// An empty file has an empty line offset table. -// Each line offset must be larger than the offset for the previous line -// and smaller than the file size; otherwise SetLines fails and returns -// false. -// -func (f *File) SetLines(lines []int) bool { - // verify validity of lines table - size := f.size - for i, offset := range lines { - if i > 0 && offset <= lines[i-1] || size <= offset { - return false - } - } - - // set lines table - f.set.mutex.Lock() - f.lines = lines - f.set.mutex.Unlock() - return true -} - -// SetLinesForContent sets the line offsets for the given file content. -func (f *File) SetLinesForContent(content []byte) { - var lines []int - line := 0 - for offset, b := range content { - if line >= 0 { - lines = append(lines, line) - } - line = -1 - if b == '\n' { - line = offset + 1 - } - } - - // set lines table - f.set.mutex.Lock() - f.lines = lines - f.set.mutex.Unlock() -} - -// A lineInfo object describes alternative file and line number -// information (such as provided via a //line comment in a .go -// file) for a given file offset. -type lineInfo struct { - // fields are exported to make them accessible to gob - Offset int - Filename string - Line int -} - -// AddLineInfo adds alternative file and line number information for -// a given file offset. The offset must be larger than the offset for -// the previously added alternative line info and smaller than the -// file size; otherwise the information is ignored. -// -// AddLineInfo is typically used to register alternative position -// information for //line filename:line comments in source files. -// -func (f *File) AddLineInfo(offset int, filename string, line int) { - f.set.mutex.Lock() - if i := len(f.infos); i == 0 || f.infos[i-1].Offset < offset && offset < f.size { - f.infos = append(f.infos, lineInfo{offset, filename, line}) - } - f.set.mutex.Unlock() -} - -// Pos returns the Pos value for the given file offset; -// the offset must be <= f.Size(). -// f.Pos(f.Offset(p)) == p. -// -func (f *File) Pos(offset int) Pos { - if offset > f.size { - panic("illegal file offset") - } - return Pos(f.base + offset) -} - -// Offset returns the offset for the given file position p; -// p must be a valid Pos value in that file. -// f.Offset(f.Pos(offset)) == offset. -// -func (f *File) Offset(p Pos) int { - if int(p) < f.base || int(p) > f.base+f.size { - panic("illegal Pos value") - } - return int(p) - f.base -} - -// Line returns the line number for the given file position p; -// p must be a Pos value in that file or NoPos. -// -func (f *File) Line(p Pos) int { - // TODO(gri) this can be implemented much more efficiently - return f.Position(p).Line -} - -func searchLineInfos(a []lineInfo, x int) int { - return sort.Search(len(a), func(i int) bool { return a[i].Offset > x }) - 1 -} - -// info returns the file name, line, and column number for a file offset. -func (f *File) info(offset int) (filename string, line, column int) { - filename = f.name - if i := searchInts(f.lines, offset); i >= 0 { - line, column = i+1, offset-f.lines[i]+1 - } - if len(f.infos) > 0 { - // almost no files have extra line infos - if i := searchLineInfos(f.infos, offset); i >= 0 { - alt := &f.infos[i] - filename = alt.Filename - if i := searchInts(f.lines, alt.Offset); i >= 0 { - line += alt.Line - i - 1 - } - } - } - return -} - -func (f *File) position(p Pos) (pos Position) { - offset := int(p) - f.base - pos.Offset = offset - pos.Filename, pos.Line, pos.Column = f.info(offset) - return -} - -// Position returns the Position value for the given file position p; -// p must be a Pos value in that file or NoPos. -// -func (f *File) Position(p Pos) (pos Position) { - if p != NoPos { - if int(p) < f.base || int(p) > f.base+f.size { - panic("illegal Pos value") - } - pos = f.position(p) - } - return -} - -// ----------------------------------------------------------------------------- -// FileSet - -// A FileSet represents a set of source files. -// Methods of file sets are synchronized; multiple goroutines -// may invoke them concurrently. -// -type FileSet struct { - mutex sync.RWMutex // protects the file set - base int // base offset for the next file - files []*File // list of files in the order added to the set - last *File // cache of last file looked up -} - -// NewFileSet creates a new file set. -func NewFileSet() *FileSet { - s := new(FileSet) - s.base = 1 // 0 == NoPos - return s -} - -// Base returns the minimum base offset that must be provided to -// AddFile when adding the next file. -// -func (s *FileSet) Base() int { - s.mutex.RLock() - b := s.base - s.mutex.RUnlock() - return b - -} - -// AddFile adds a new file with a given filename, base offset, and file size -// to the file set s and returns the file. Multiple files may have the same -// name. The base offset must not be smaller than the FileSet's Base(), and -// size must not be negative. -// -// Adding the file will set the file set's Base() value to base + size + 1 -// as the minimum base value for the next file. The following relationship -// exists between a Pos value p for a given file offset offs: -// -// int(p) = base + offs -// -// with offs in the range [0, size] and thus p in the range [base, base+size]. -// For convenience, File.Pos may be used to create file-specific position -// values from a file offset. -// -func (s *FileSet) AddFile(filename string, base, size int) *File { - s.mutex.Lock() - defer s.mutex.Unlock() - if base < s.base || size < 0 { - panic("illegal base or size") - } - // base >= s.base && size >= 0 - f := &File{s, filename, base, size, []int{0}, nil} - base += size + 1 // +1 because EOF also has a position - if base < 0 { - panic("token.Pos offset overflow (> 2G of source code in file set)") - } - // add the file to the file set - s.base = base - s.files = append(s.files, f) - s.last = f - return f -} - -// Iterate calls f for the files in the file set in the order they were added -// until f returns false. -// -func (s *FileSet) Iterate(f func(*File) bool) { - for i := 0; ; i++ { - var file *File - s.mutex.RLock() - if i < len(s.files) { - file = s.files[i] - } - s.mutex.RUnlock() - if file == nil || !f(file) { - break - } - } -} - -func searchFiles(a []*File, x int) int { - return sort.Search(len(a), func(i int) bool { return a[i].base > x }) - 1 -} - -func (s *FileSet) file(p Pos) *File { - // common case: p is in last file - if f := s.last; f != nil && f.base <= int(p) && int(p) <= f.base+f.size { - return f - } - // p is not in last file - search all files - if i := searchFiles(s.files, int(p)); i >= 0 { - f := s.files[i] - // f.base <= int(p) by definition of searchFiles - if int(p) <= f.base+f.size { - s.last = f - return f - } - } - return nil -} - -// File returns the file that contains the position p. -// If no such file is found (for instance for p == NoPos), -// the result is nil. -// -func (s *FileSet) File(p Pos) (f *File) { - if p != NoPos { - s.mutex.RLock() - f = s.file(p) - s.mutex.RUnlock() - } - return -} - -// Position converts a Pos in the fileset into a general Position. -func (s *FileSet) Position(p Pos) (pos Position) { - if p != NoPos { - s.mutex.RLock() - if f := s.file(p); f != nil { - pos = f.position(p) - } - s.mutex.RUnlock() - } - return -} - -// ----------------------------------------------------------------------------- -// Helper functions - -func searchInts(a []int, x int) int { - // This function body is a manually inlined version of: - // - // return sort.Search(len(a), func(i int) bool { return a[i] > x }) - 1 - // - // With better compiler optimizations, this may not be needed in the - // future, but at the moment this change improves the go/printer - // benchmark performance by ~30%. This has a direct impact on the - // speed of gofmt and thus seems worthwhile (2011-04-29). - // TODO(gri): Remove this when compilers have caught up. - i, j := 0, len(a) - for i < j { - h := i + (j-i)/2 // avoid overflow when computing h - // i ≤ h < j - if a[h] <= x { - i = h + 1 - } else { - j = h - } - } - return i - 1 -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/token/position_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/token/position_test.go deleted file mode 100644 index 160107d..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/token/position_test.go +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package token - -import ( - "fmt" - "testing" -) - -func checkPos(t *testing.T, msg string, p, q Position) { - if p.Filename != q.Filename { - t.Errorf("%s: expected filename = %q; got %q", msg, q.Filename, p.Filename) - } - if p.Offset != q.Offset { - t.Errorf("%s: expected offset = %d; got %d", msg, q.Offset, p.Offset) - } - if p.Line != q.Line { - t.Errorf("%s: expected line = %d; got %d", msg, q.Line, p.Line) - } - if p.Column != q.Column { - t.Errorf("%s: expected column = %d; got %d", msg, q.Column, p.Column) - } -} - -func TestNoPos(t *testing.T) { - if NoPos.IsValid() { - t.Errorf("NoPos should not be valid") - } - var fset *FileSet - checkPos(t, "nil NoPos", fset.Position(NoPos), Position{}) - fset = NewFileSet() - checkPos(t, "fset NoPos", fset.Position(NoPos), Position{}) -} - -var tests = []struct { - filename string - source []byte // may be nil - size int - lines []int -}{ - {"a", []byte{}, 0, []int{}}, - {"b", []byte("01234"), 5, []int{0}}, - {"c", []byte("\n\n\n\n\n\n\n\n\n"), 9, []int{0, 1, 2, 3, 4, 5, 6, 7, 8}}, - {"d", nil, 100, []int{0, 5, 10, 20, 30, 70, 71, 72, 80, 85, 90, 99}}, - {"e", nil, 777, []int{0, 80, 100, 120, 130, 180, 267, 455, 500, 567, 620}}, - {"f", []byte("package p\n\nimport \"fmt\""), 23, []int{0, 10, 11}}, - {"g", []byte("package p\n\nimport \"fmt\"\n"), 24, []int{0, 10, 11}}, - {"h", []byte("package p\n\nimport \"fmt\"\n "), 25, []int{0, 10, 11, 24}}, -} - -func linecol(lines []int, offs int) (int, int) { - prevLineOffs := 0 - for line, lineOffs := range lines { - if offs < lineOffs { - return line, offs - prevLineOffs + 1 - } - prevLineOffs = lineOffs - } - return len(lines), offs - prevLineOffs + 1 -} - -func verifyPositions(t *testing.T, fset *FileSet, f *File, lines []int) { - for offs := 0; offs < f.Size(); offs++ { - p := f.Pos(offs) - offs2 := f.Offset(p) - if offs2 != offs { - t.Errorf("%s, Offset: expected offset %d; got %d", f.Name(), offs, offs2) - } - line, col := linecol(lines, offs) - msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) - checkPos(t, msg, f.Position(f.Pos(offs)), Position{f.Name(), offs, line, col}) - checkPos(t, msg, fset.Position(p), Position{f.Name(), offs, line, col}) - } -} - -func makeTestSource(size int, lines []int) []byte { - src := make([]byte, size) - for _, offs := range lines { - if offs > 0 { - src[offs-1] = '\n' - } - } - return src -} - -func TestPositions(t *testing.T) { - const delta = 7 // a non-zero base offset increment - fset := NewFileSet() - for _, test := range tests { - // verify consistency of test case - if test.source != nil && len(test.source) != test.size { - t.Errorf("%s: inconsistent test case: expected file size %d; got %d", test.filename, test.size, len(test.source)) - } - - // add file and verify name and size - f := fset.AddFile(test.filename, fset.Base()+delta, test.size) - if f.Name() != test.filename { - t.Errorf("expected filename %q; got %q", test.filename, f.Name()) - } - if f.Size() != test.size { - t.Errorf("%s: expected file size %d; got %d", f.Name(), test.size, f.Size()) - } - if fset.File(f.Pos(0)) != f { - t.Errorf("%s: f.Pos(0) was not found in f", f.Name()) - } - - // add lines individually and verify all positions - for i, offset := range test.lines { - f.AddLine(offset) - if f.LineCount() != i+1 { - t.Errorf("%s, AddLine: expected line count %d; got %d", f.Name(), i+1, f.LineCount()) - } - // adding the same offset again should be ignored - f.AddLine(offset) - if f.LineCount() != i+1 { - t.Errorf("%s, AddLine: expected unchanged line count %d; got %d", f.Name(), i+1, f.LineCount()) - } - verifyPositions(t, fset, f, test.lines[0:i+1]) - } - - // add lines with SetLines and verify all positions - if ok := f.SetLines(test.lines); !ok { - t.Errorf("%s: SetLines failed", f.Name()) - } - if f.LineCount() != len(test.lines) { - t.Errorf("%s, SetLines: expected line count %d; got %d", f.Name(), len(test.lines), f.LineCount()) - } - verifyPositions(t, fset, f, test.lines) - - // add lines with SetLinesForContent and verify all positions - src := test.source - if src == nil { - // no test source available - create one from scratch - src = makeTestSource(test.size, test.lines) - } - f.SetLinesForContent(src) - if f.LineCount() != len(test.lines) { - t.Errorf("%s, SetLinesForContent: expected line count %d; got %d", f.Name(), len(test.lines), f.LineCount()) - } - verifyPositions(t, fset, f, test.lines) - } -} - -func TestLineInfo(t *testing.T) { - fset := NewFileSet() - f := fset.AddFile("foo", fset.Base(), 500) - lines := []int{0, 42, 77, 100, 210, 220, 277, 300, 333, 401} - // add lines individually and provide alternative line information - for _, offs := range lines { - f.AddLine(offs) - f.AddLineInfo(offs, "bar", 42) - } - // verify positions for all offsets - for offs := 0; offs <= f.Size(); offs++ { - p := f.Pos(offs) - _, col := linecol(lines, offs) - msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) - checkPos(t, msg, f.Position(f.Pos(offs)), Position{"bar", offs, 42, col}) - checkPos(t, msg, fset.Position(p), Position{"bar", offs, 42, col}) - } -} - -func TestFiles(t *testing.T) { - fset := NewFileSet() - for i, test := range tests { - fset.AddFile(test.filename, fset.Base(), test.size) - j := 0 - fset.Iterate(func(f *File) bool { - if f.Name() != tests[j].filename { - t.Errorf("expected filename = %s; got %s", tests[j].filename, f.Name()) - } - j++ - return true - }) - if j != i+1 { - t.Errorf("expected %d files; got %d", i+1, j) - } - } -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize.go b/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize.go deleted file mode 100644 index 4adc8f9..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package token - -type serializedFile struct { - // fields correspond 1:1 to fields with same (lower-case) name in File - Name string - Base int - Size int - Lines []int - Infos []lineInfo -} - -type serializedFileSet struct { - Base int - Files []serializedFile -} - -// Read calls decode to deserialize a file set into s; s must not be nil. -func (s *FileSet) Read(decode func(interface{}) error) error { - var ss serializedFileSet - if err := decode(&ss); err != nil { - return err - } - - s.mutex.Lock() - s.base = ss.Base - files := make([]*File, len(ss.Files)) - for i := 0; i < len(ss.Files); i++ { - f := &ss.Files[i] - files[i] = &File{s, f.Name, f.Base, f.Size, f.Lines, f.Infos} - } - s.files = files - s.last = nil - s.mutex.Unlock() - - return nil -} - -// Write calls encode to serialize the file set s. -func (s *FileSet) Write(encode func(interface{}) error) error { - var ss serializedFileSet - - s.mutex.Lock() - ss.Base = s.base - files := make([]serializedFile, len(s.files)) - for i, f := range s.files { - files[i] = serializedFile{f.name, f.base, f.size, f.lines, f.infos} - } - ss.Files = files - s.mutex.Unlock() - - return encode(ss) -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize_test.go deleted file mode 100644 index 4e925ad..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/token/serialize_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package token - -import ( - "bytes" - "encoding/gob" - "fmt" - "testing" -) - -// equal returns nil if p and q describe the same file set; -// otherwise it returns an error describing the discrepancy. -func equal(p, q *FileSet) error { - if p == q { - // avoid deadlock if p == q - return nil - } - - // not strictly needed for the test - p.mutex.Lock() - q.mutex.Lock() - defer q.mutex.Unlock() - defer p.mutex.Unlock() - - if p.base != q.base { - return fmt.Errorf("different bases: %d != %d", p.base, q.base) - } - - if len(p.files) != len(q.files) { - return fmt.Errorf("different number of files: %d != %d", len(p.files), len(q.files)) - } - - for i, f := range p.files { - g := q.files[i] - if f.set != p { - return fmt.Errorf("wrong fileset for %q", f.name) - } - if g.set != q { - return fmt.Errorf("wrong fileset for %q", g.name) - } - if f.name != g.name { - return fmt.Errorf("different filenames: %q != %q", f.name, g.name) - } - if f.base != g.base { - return fmt.Errorf("different base for %q: %d != %d", f.name, f.base, g.base) - } - if f.size != g.size { - return fmt.Errorf("different size for %q: %d != %d", f.name, f.size, g.size) - } - for j, l := range f.lines { - m := g.lines[j] - if l != m { - return fmt.Errorf("different offsets for %q", f.name) - } - } - for j, l := range f.infos { - m := g.infos[j] - if l.Offset != m.Offset || l.Filename != m.Filename || l.Line != m.Line { - return fmt.Errorf("different infos for %q", f.name) - } - } - } - - // we don't care about .last - it's just a cache - return nil -} - -func checkSerialize(t *testing.T, p *FileSet) { - var buf bytes.Buffer - encode := func(x interface{}) error { - return gob.NewEncoder(&buf).Encode(x) - } - if err := p.Write(encode); err != nil { - t.Errorf("writing fileset failed: %s", err) - return - } - q := NewFileSet() - decode := func(x interface{}) error { - return gob.NewDecoder(&buf).Decode(x) - } - if err := q.Read(decode); err != nil { - t.Errorf("reading fileset failed: %s", err) - return - } - if err := equal(p, q); err != nil { - t.Errorf("filesets not identical: %s", err) - } -} - -func TestSerialization(t *testing.T) { - p := NewFileSet() - checkSerialize(t, p) - // add some files - for i := 0; i < 10; i++ { - f := p.AddFile(fmt.Sprintf("file%d", i), p.Base()+i, i*100) - checkSerialize(t, p) - // add some lines and alternative file infos - line := 1000 - for offs := 0; offs < f.Size(); offs += 40 + i { - f.AddLine(offs) - if offs%7 == 0 { - f.AddLineInfo(offs, fmt.Sprintf("file%d", offs), line) - line += 33 - } - } - checkSerialize(t, p) - } -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/token/token.go b/Godeps/_workspace/src/code.google.com/p/gcfg/token/token.go deleted file mode 100644 index b3c7c83..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/token/token.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package token defines constants representing the lexical tokens of the gcfg -// configuration syntax and basic operations on tokens (printing, predicates). -// -// Note that the API for the token package may change to accommodate new -// features or implementation changes in gcfg. -// -package token - -import "strconv" - -// Token is the set of lexical tokens of the gcfg configuration syntax. -type Token int - -// The list of tokens. -const ( - // Special tokens - ILLEGAL Token = iota - EOF - COMMENT - - literal_beg - // Identifiers and basic type literals - // (these tokens stand for classes of literals) - IDENT // section-name, variable-name - STRING // "subsection-name", variable value - literal_end - - operator_beg - // Operators and delimiters - ASSIGN // = - LBRACK // [ - RBRACK // ] - EOL // \n - operator_end -) - -var tokens = [...]string{ - ILLEGAL: "ILLEGAL", - - EOF: "EOF", - COMMENT: "COMMENT", - - IDENT: "IDENT", - STRING: "STRING", - - ASSIGN: "=", - LBRACK: "[", - RBRACK: "]", - EOL: "\n", -} - -// String returns the string corresponding to the token tok. -// For operators and delimiters, the string is the actual token character -// sequence (e.g., for the token ASSIGN, the string is "="). For all other -// tokens the string corresponds to the token constant name (e.g. for the -// token IDENT, the string is "IDENT"). -// -func (tok Token) String() string { - s := "" - if 0 <= tok && tok < Token(len(tokens)) { - s = tokens[tok] - } - if s == "" { - s = "token(" + strconv.Itoa(int(tok)) + ")" - } - return s -} - -// Predicates - -// IsLiteral returns true for tokens corresponding to identifiers -// and basic type literals; it returns false otherwise. -// -func (tok Token) IsLiteral() bool { return literal_beg < tok && tok < literal_end } - -// IsOperator returns true for tokens corresponding to operators and -// delimiters; it returns false otherwise. -// -func (tok Token) IsOperator() bool { return operator_beg < tok && tok < operator_end } diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/bool.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/bool.go deleted file mode 100644 index 8dcae0d..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/types/bool.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -// BoolValues defines the name and value mappings for ParseBool. -var BoolValues = map[string]interface{}{ - "true": true, "yes": true, "on": true, "1": true, - "false": false, "no": false, "off": false, "0": false, -} - -var boolParser = func() *EnumParser { - ep := &EnumParser{} - ep.AddVals(BoolValues) - return ep -}() - -// ParseBool parses bool values according to the definitions in BoolValues. -// Parsing is case-insensitive. -func ParseBool(s string) (bool, error) { - v, err := boolParser.Parse(s) - if err != nil { - return false, err - } - return v.(bool), nil -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/doc.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/doc.go deleted file mode 100644 index 9f9c345..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/types/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package types defines helpers for type conversions. -// -// The API for this package is not finalized yet. -package types diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum.go deleted file mode 100644 index 1a0c7ef..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum.go +++ /dev/null @@ -1,44 +0,0 @@ -package types - -import ( - "fmt" - "reflect" - "strings" -) - -// EnumParser parses "enum" values; i.e. a predefined set of strings to -// predefined values. -type EnumParser struct { - Type string // type name; if not set, use type of first value added - CaseMatch bool // if true, matching of strings is case-sensitive - // PrefixMatch bool - vals map[string]interface{} -} - -// AddVals adds strings and values to an EnumParser. -func (ep *EnumParser) AddVals(vals map[string]interface{}) { - if ep.vals == nil { - ep.vals = make(map[string]interface{}) - } - for k, v := range vals { - if ep.Type == "" { - ep.Type = reflect.TypeOf(v).Name() - } - if !ep.CaseMatch { - k = strings.ToLower(k) - } - ep.vals[k] = v - } -} - -// Parse parses the string and returns the value or an error. -func (ep EnumParser) Parse(s string) (interface{}, error) { - if !ep.CaseMatch { - s = strings.ToLower(s) - } - v, ok := ep.vals[s] - if !ok { - return false, fmt.Errorf("failed to parse %s %#q", ep.Type, s) - } - return v, nil -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum_test.go deleted file mode 100644 index 4bf135e..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/types/enum_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package types - -import ( - "testing" -) - -func TestEnumParserBool(t *testing.T) { - for _, tt := range []struct { - val string - res bool - ok bool - }{ - {val: "tRuE", res: true, ok: true}, - {val: "False", res: false, ok: true}, - {val: "t", ok: false}, - } { - b, err := ParseBool(tt.val) - switch { - case tt.ok && err != nil: - t.Errorf("%q: got error %v, want %v", tt.val, err, tt.res) - case !tt.ok && err == nil: - t.Errorf("%q: got %v, want error", tt.val, b) - case tt.ok && b != tt.res: - t.Errorf("%q: got %v, want %v", tt.val, b, tt.res) - default: - t.Logf("%q: got %v, %v", tt.val, b, err) - } - } -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/int.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/int.go deleted file mode 100644 index af7e75c..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/types/int.go +++ /dev/null @@ -1,86 +0,0 @@ -package types - -import ( - "fmt" - "strings" -) - -// An IntMode is a mode for parsing integer values, representing a set of -// accepted bases. -type IntMode uint8 - -// IntMode values for ParseInt; can be combined using binary or. -const ( - Dec IntMode = 1 << iota - Hex - Oct -) - -// String returns a string representation of IntMode; e.g. `IntMode(Dec|Hex)`. -func (m IntMode) String() string { - var modes []string - if m&Dec != 0 { - modes = append(modes, "Dec") - } - if m&Hex != 0 { - modes = append(modes, "Hex") - } - if m&Oct != 0 { - modes = append(modes, "Oct") - } - return "IntMode(" + strings.Join(modes, "|") + ")" -} - -var errIntAmbig = fmt.Errorf("ambiguous integer value; must include '0' prefix") - -func prefix0(val string) bool { - return strings.HasPrefix(val, "0") || strings.HasPrefix(val, "-0") -} - -func prefix0x(val string) bool { - return strings.HasPrefix(val, "0x") || strings.HasPrefix(val, "-0x") -} - -// ParseInt parses val using mode into intptr, which must be a pointer to an -// integer kind type. Non-decimal value require prefix `0` or `0x` in the cases -// when mode permits ambiguity of base; otherwise the prefix can be omitted. -func ParseInt(intptr interface{}, val string, mode IntMode) error { - val = strings.TrimSpace(val) - verb := byte(0) - switch mode { - case Dec: - verb = 'd' - case Dec + Hex: - if prefix0x(val) { - verb = 'v' - } else { - verb = 'd' - } - case Dec + Oct: - if prefix0(val) && !prefix0x(val) { - verb = 'v' - } else { - verb = 'd' - } - case Dec + Hex + Oct: - verb = 'v' - case Hex: - if prefix0x(val) { - verb = 'v' - } else { - verb = 'x' - } - case Oct: - verb = 'o' - case Hex + Oct: - if prefix0(val) { - verb = 'v' - } else { - return errIntAmbig - } - } - if verb == 0 { - panic("unsupported mode") - } - return ScanFully(intptr, val, verb) -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/int_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/int_test.go deleted file mode 100644 index b63dbcb..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/types/int_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package types - -import ( - "reflect" - "testing" -) - -func elem(p interface{}) interface{} { - return reflect.ValueOf(p).Elem().Interface() -} - -func TestParseInt(t *testing.T) { - for _, tt := range []struct { - val string - mode IntMode - exp interface{} - ok bool - }{ - {"0", Dec, int(0), true}, - {"10", Dec, int(10), true}, - {"-10", Dec, int(-10), true}, - {"x", Dec, int(0), false}, - {"0xa", Hex, int(0xa), true}, - {"a", Hex, int(0xa), true}, - {"10", Hex, int(0x10), true}, - {"-0xa", Hex, int(-0xa), true}, - {"0x", Hex, int(0x0), true}, // Scanf doesn't require digit behind 0x - {"-0x", Hex, int(0x0), true}, // Scanf doesn't require digit behind 0x - {"-a", Hex, int(-0xa), true}, - {"-10", Hex, int(-0x10), true}, - {"x", Hex, int(0), false}, - {"10", Oct, int(010), true}, - {"010", Oct, int(010), true}, - {"-10", Oct, int(-010), true}, - {"-010", Oct, int(-010), true}, - {"10", Dec | Hex, int(10), true}, - {"010", Dec | Hex, int(10), true}, - {"0x10", Dec | Hex, int(0x10), true}, - {"10", Dec | Oct, int(10), true}, - {"010", Dec | Oct, int(010), true}, - {"0x10", Dec | Oct, int(0), false}, - {"10", Hex | Oct, int(0), false}, // need prefix to distinguish Hex/Oct - {"010", Hex | Oct, int(010), true}, - {"0x10", Hex | Oct, int(0x10), true}, - {"10", Dec | Hex | Oct, int(10), true}, - {"010", Dec | Hex | Oct, int(010), true}, - {"0x10", Dec | Hex | Oct, int(0x10), true}, - } { - typ := reflect.TypeOf(tt.exp) - res := reflect.New(typ).Interface() - err := ParseInt(res, tt.val, tt.mode) - switch { - case tt.ok && err != nil: - t.Errorf("ParseInt(%v, %#v, %v): fail; got error %v, want ok", - typ, tt.val, tt.mode, err) - case !tt.ok && err == nil: - t.Errorf("ParseInt(%v, %#v, %v): fail; got %v, want error", - typ, tt.val, tt.mode, elem(res)) - case tt.ok && !reflect.DeepEqual(elem(res), tt.exp): - t.Errorf("ParseInt(%v, %#v, %v): fail; got %v, want %v", - typ, tt.val, tt.mode, elem(res), tt.exp) - default: - t.Logf("ParseInt(%v, %#v, %s): pass; got %v, error %v", - typ, tt.val, tt.mode, elem(res), err) - } - } -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan.go deleted file mode 100644 index db2f6ed..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -import ( - "fmt" - "io" - "reflect" -) - -// ScanFully uses fmt.Sscanf with verb to fully scan val into ptr. -func ScanFully(ptr interface{}, val string, verb byte) error { - t := reflect.ValueOf(ptr).Elem().Type() - // attempt to read extra bytes to make sure the value is consumed - var b []byte - n, err := fmt.Sscanf(val, "%"+string(verb)+"%s", ptr, &b) - switch { - case n < 1 || n == 1 && err != io.EOF: - return fmt.Errorf("failed to parse %q as %v: %v", val, t, err) - case n > 1: - return fmt.Errorf("failed to parse %q as %v: extra characters %q", val, t, string(b)) - } - // n == 1 && err == io.EOF - return nil -} diff --git a/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan_test.go b/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan_test.go deleted file mode 100644 index a8083e0..0000000 --- a/Godeps/_workspace/src/code.google.com/p/gcfg/types/scan_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package types - -import ( - "reflect" - "testing" -) - -func TestScanFully(t *testing.T) { - for _, tt := range []struct { - val string - verb byte - res interface{} - ok bool - }{ - {"a", 'v', int(0), false}, - {"0x", 'v', int(0), true}, - {"0x", 'd', int(0), false}, - } { - d := reflect.New(reflect.TypeOf(tt.res)).Interface() - err := ScanFully(d, tt.val, tt.verb) - switch { - case tt.ok && err != nil: - t.Errorf("ScanFully(%T, %q, '%c'): want ok, got error %v", - d, tt.val, tt.verb, err) - case !tt.ok && err == nil: - t.Errorf("ScanFully(%T, %q, '%c'): want error, got %v", - d, tt.val, tt.verb, elem(d)) - case tt.ok && err == nil && !reflect.DeepEqual(tt.res, elem(d)): - t.Errorf("ScanFully(%T, %q, '%c'): want %v, got %v", - d, tt.val, tt.verb, tt.res, elem(d)) - default: - t.Logf("ScanFully(%T, %q, '%c') = %v; *ptr==%v", - d, tt.val, tt.verb, err, elem(d)) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile deleted file mode 100644 index f1f0656..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -install: - go install - -test: install generate-test-pbs - go test - - -generate-test-pbs: - make install - make -C testdata - protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata:. proto3_proto/proto3.proto - make diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go deleted file mode 100644 index 5a9b6a4..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go +++ /dev/null @@ -1,2083 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "testing" - "time" - - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { - data := b.Bytes() - ld := len(data) - ls := len(s) / 2 - - fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) - - // find the interesting spot - n - n := ls - if ld < ls { - n = ld - } - j := 0 - for i := 0; i < n; i++ { - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - if data[i] == bs { - continue - } - n = i - break - } - l := n - 10 - if l < 0 { - l = 0 - } - h := n + 10 - - // find the interesting spot - n - fmt.Printf("is[%d]:", l) - for i := l; i < h; i++ { - if i >= ld { - fmt.Printf(" --") - continue - } - fmt.Printf(" %.2x", data[i]) - } - fmt.Printf("\n") - - fmt.Printf("sb[%d]:", l) - for i := l; i < h; i++ { - if i >= ls { - fmt.Printf(" --") - continue - } - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - fmt.Printf(" %.2x", bs) - } - fmt.Printf("\n") - - t.Fail() - - // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) - // Print the output in a partially-decoded format; can - // be helpful when updating the test. It produces the output - // that is pasted, with minor edits, into the argument to verify(). - // data := b.Bytes() - // nesting := 0 - // for b.Len() > 0 { - // start := len(data) - b.Len() - // var u uint64 - // u, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // wire := u & 0x7 - // tag := u >> 3 - // switch wire { - // case WireVarint: - // v, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed32: - // v, err := DecodeFixed32(b) - // if err != nil { - // fmt.Printf("decode error on fixed32:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed64: - // v, err := DecodeFixed64(b) - // if err != nil { - // fmt.Printf("decode error on fixed64:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireBytes: - // nb, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // after_tag := len(data) - b.Len() - // str := make([]byte, nb) - // _, err = b.Read(str) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", - // data[start:after_tag], str, tag, wire) - // case WireStartGroup: - // nesting++ - // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // case WireEndGroup: - // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // nesting-- - // default: - // fmt.Printf("unrecognized wire type %d\n", wire) - // return - // } - // } -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f fakeMarshaler) Marshal() ([]byte, error) { - return f.b, f.err -} - -func (f fakeMarshaler) String() string { - return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) -} - -func (f fakeMarshaler) ProtoMessage() {} - -func (f fakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - wantErr error - }{ - { - name: "Marshaler that fails", - m: fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since there's an error, nothing should be written to buffer. - want: nil, - wantErr: errors.New("some marshal err"), - }, - { - name: "Marshaler that succeeds", - m: fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - wantErr: nil, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if !reflect.DeepEqual(test.wantErr, err) { - t.Errorf("%s: got err %v wanted %v", test.name, err, test.wantErr) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if strings.Index(err.Error(), "Kind") < 0 { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f") // field 103, encoding 0, 0x7f zigzag64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f") // value 64, value -64 -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err := Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - var x uint64 - x = uint64(pbd.F_Sint64Repeated[i]) - if x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - x = uint64(pbd.F_Sint32Repeated[i]) - if x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - x = uint64(pbd.F_DoubleRepeated[i]) - if x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - x = uint64(pbd.F_FloatRepeated[i]) - if x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - x = pbd.F_Uint64Repeated[i] - if x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - x = uint64(pbd.F_Uint32Repeated[i]) - if x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - x = pbd.F_Fixed64Repeated[i] - if x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - x = uint64(pbd.F_Fixed32Repeated[i]) - if x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - x = uint64(pbd.F_Int64Repeated[i]) - if x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - x = uint64(pbd.F_Int32Repeated[i]) - if x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if pbd.F_BoolRepeated[i] != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -// Verify we give a useful message when decoding to the wrong structure type. -func TestTypeMismatch(t *testing.T) { - pb1 := initGoTest(true) - - // Marshal - o := old() - o.Marshal(pb1) - - // Now Unmarshal it to the wrong type. - pb2 := initGoTestField() - err := o.Unmarshal(pb2) - if err == nil { - t.Error("expected error, got no error") - } else if !strings.Contains(err.Error(), "bad wiretype") { - t.Error("expected bad wiretype error, got", err) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - err := o.Marshal(pb) - if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if strings.Index(err.Error(), "Label") < 0 { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if strings.Index(err.Error(), "{Unknown}") < 0 { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - _, err := Marshal((*GoEnum)(nil)) - if err != ErrNil { - t.Errorf("Marshal: got err %v, want ErrNil", err) - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -// A type that implements the Marshaler interface and is nillable. -type nillableMessage struct { - x uint64 -} - -func (nm *nillableMessage) Marshal() ([]byte, error) { - return EncodeVarint(nm.x), nil -} - -type NMMessage struct { - nm *nillableMessage -} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { - m := &MyMessage{ - Pet: []string{"turtle", "wombat"}, - } - expected := Clone(m) - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err := Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" // field 103, encoding 0, 0x7f zigzag64 - - o := old() - bytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("expected = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 1", bytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(bytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { - t.Errorf("unmarshal wrong err msg: %v", err) - } - bytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 2", bytes) - t.Fatalf("string = %s", expected) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: &FloatingPoint{F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for _, pair := range [][2]interface{}{ - {m.NameMapping, m2.NameMapping}, - {m.MsgMapping, m2.MsgMapping}, - {m.ByteMapping, m2.ByteMapping}, - } { - if !reflect.DeepEqual(pair[0], pair[1]) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) - } - } -} - -func TestMapFieldWithNil(t *testing.T) { - m := &MessageWithMap{ - MsgMapping: map[int64]*FloatingPoint{ - 1: nil, - }, - } - b, err := Marshal(m) - if err == nil { - t.Fatalf("Marshal of bad map should have failed, got these bytes: %v", b) - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go deleted file mode 100644 index 915a68b..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go +++ /dev/null @@ -1,212 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Protocol buffer deep copy and merge. -// TODO: MessageSet and RawMessage. - -package proto - -import ( - "log" - "reflect" - "strings" -) - -// Clone returns a deep copy of a protocol buffer. -func Clone(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - - out := reflect.New(in.Type().Elem()) - // out is empty so a merge is a deep copy. - mergeStruct(out.Elem(), in.Elem()) - return out.Interface().(Message) -} - -// Merge merges src into dst. -// Required and optional fields that are set in src will be set to that value in dst. -// Elements of repeated fields will be appended. -// Merge panics if src and dst are not the same type, or if dst is nil. -func Merge(dst, src Message) { - in := reflect.ValueOf(src) - out := reflect.ValueOf(dst) - if out.IsNil() { - panic("proto: nil destination") - } - if in.Type() != out.Type() { - // Explicit test prior to mergeStruct so that mistyped nils will fail - panic("proto: type mismatch") - } - if in.IsNil() { - // Merging nil into non-nil is a quiet no-op - return - } - mergeStruct(out.Elem(), in.Elem()) -} - -func mergeStruct(out, in reflect.Value) { - sprop := GetProperties(in.Type()) - for i := 0; i < in.NumField(); i++ { - f := in.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) - } - - if emIn, ok := in.Addr().Interface().(extendableProto); ok { - emOut := out.Addr().Interface().(extendableProto) - mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap()) - } - - uf := in.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return - } - uin := uf.Bytes() - if len(uin) > 0 { - out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) - } -} - -// mergeAny performs a merge between two values of the same type. -// viaPtr indicates whether the values were indirected through a pointer (implying proto2). -// prop is set if this is a struct field (it may be nil). -func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { - if in.Type() == protoMessageType { - if !in.IsNil() { - if out.IsNil() { - out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) - } else { - Merge(out.Interface().(Message), in.Interface().(Message)) - } - } - return - } - switch in.Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - if !viaPtr && isProto3Zero(in) { - return - } - out.Set(in) - case reflect.Map: - if in.Len() == 0 { - return - } - if out.IsNil() { - out.Set(reflect.MakeMap(in.Type())) - } - // For maps with value types of *T or []byte we need to deep copy each value. - elemKind := in.Type().Elem().Kind() - for _, key := range in.MapKeys() { - var val reflect.Value - switch elemKind { - case reflect.Ptr: - val = reflect.New(in.Type().Elem().Elem()) - mergeAny(val, in.MapIndex(key), false, nil) - case reflect.Slice: - val = in.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - default: - val = in.MapIndex(key) - } - out.SetMapIndex(key, val) - } - case reflect.Ptr: - if in.IsNil() { - return - } - if out.IsNil() { - out.Set(reflect.New(in.Elem().Type())) - } - mergeAny(out.Elem(), in.Elem(), true, nil) - case reflect.Slice: - if in.IsNil() { - return - } - if in.Type().Elem().Kind() == reflect.Uint8 { - // []byte is a scalar bytes field, not a repeated field. - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value, and should not - // be merged. - if prop != nil && prop.proto3 && in.Len() == 0 { - return - } - - // Make a deep copy. - // Append to []byte{} instead of []byte(nil) so that we never end up - // with a nil result. - out.SetBytes(append([]byte{}, in.Bytes()...)) - return - } - n := in.Len() - if out.IsNil() { - out.Set(reflect.MakeSlice(in.Type(), 0, n)) - } - switch in.Type().Elem().Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - out.Set(reflect.AppendSlice(out, in)) - default: - for i := 0; i < n; i++ { - x := reflect.Indirect(reflect.New(in.Type().Elem())) - mergeAny(x, in.Index(i), false, nil) - out.Set(reflect.Append(out, x)) - } - } - case reflect.Struct: - mergeStruct(out, in) - default: - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to copy %v", in) - } -} - -func mergeExtension(out, in map[int32]Extension) { - for extNum, eIn := range in { - eOut := Extension{desc: eIn.desc} - if eIn.value != nil { - v := reflect.New(reflect.TypeOf(eIn.value)).Elem() - mergeAny(v, reflect.ValueOf(eIn.value), false, nil) - eOut.value = v.Interface() - } - if eIn.enc != nil { - eOut.enc = make([]byte, len(eIn.enc)) - copy(eOut.enc, eIn.enc) - } - - out[extNum] = eOut - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go deleted file mode 100644 index a1c697b..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go +++ /dev/null @@ -1,245 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Errorf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, - // proto3 shouldn't merge zero values, - // in the same way that proto2 shouldn't merge nils. - { - src: &proto3pb.Message{ - Name: "Aaron", - Data: []byte(""), // zero value, but not nil - }, - dst: &proto3pb.Message{ - HeightInCm: 176, - Data: []byte("texas!"), - }, - want: &proto3pb.Message{ - Name: "Aaron", - HeightInCm: 176, - Data: []byte("texas!"), - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go deleted file mode 100644 index bf71dca..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go +++ /dev/null @@ -1,827 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for decoding protocol buffer data to construct in-memory representations. - */ - -import ( - "errors" - "fmt" - "io" - "os" - "reflect" -) - -// errOverflow is returned when an integer is too large to be represented. -var errOverflow = errors.New("proto: integer overflow") - -// The fundamental decoders that interpret bytes on the wire. -// Those that take integer types all return uint64 and are -// therefore of type valueDecoder. - -// DecodeVarint reads a varint-encoded integer from the slice. -// It returns the integer and the number of bytes consumed, or -// zero if there is not enough. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func DecodeVarint(buf []byte) (x uint64, n int) { - // x, n already 0 - for shift := uint(0); shift < 64; shift += 7 { - if n >= len(buf) { - return 0, 0 - } - b := uint64(buf[n]) - n++ - x |= (b & 0x7F) << shift - if (b & 0x80) == 0 { - return x, n - } - } - - // The number is too large to represent in a 64-bit value. - return 0, 0 -} - -// DecodeVarint reads a varint-encoded integer from the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) DecodeVarint() (x uint64, err error) { - // x, err already 0 - - i := p.index - l := len(p.buf) - - for shift := uint(0); shift < 64; shift += 7 { - if i >= l { - err = io.ErrUnexpectedEOF - return - } - b := p.buf[i] - i++ - x |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - p.index = i - return - } - } - - // The number is too large to represent in a 64-bit value. - err = errOverflow - return -} - -// DecodeFixed64 reads a 64-bit integer from the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) DecodeFixed64() (x uint64, err error) { - // x, err already 0 - i := p.index + 8 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-8]) - x |= uint64(p.buf[i-7]) << 8 - x |= uint64(p.buf[i-6]) << 16 - x |= uint64(p.buf[i-5]) << 24 - x |= uint64(p.buf[i-4]) << 32 - x |= uint64(p.buf[i-3]) << 40 - x |= uint64(p.buf[i-2]) << 48 - x |= uint64(p.buf[i-1]) << 56 - return -} - -// DecodeFixed32 reads a 32-bit integer from the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) DecodeFixed32() (x uint64, err error) { - // x, err already 0 - i := p.index + 4 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-4]) - x |= uint64(p.buf[i-3]) << 8 - x |= uint64(p.buf[i-2]) << 16 - x |= uint64(p.buf[i-1]) << 24 - return -} - -// DecodeZigzag64 reads a zigzag-encoded 64-bit integer -// from the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) DecodeZigzag64() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) - return -} - -// DecodeZigzag32 reads a zigzag-encoded 32-bit integer -// from the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) DecodeZigzag32() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) - return -} - -// These are not ValueDecoders: they produce an array of bytes or a string. -// bytes, embedded messages - -// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { - n, err := p.DecodeVarint() - if err != nil { - return nil, err - } - - nb := int(n) - if nb < 0 { - return nil, fmt.Errorf("proto: bad byte length %d", nb) - } - end := p.index + nb - if end < p.index || end > len(p.buf) { - return nil, io.ErrUnexpectedEOF - } - - if !alloc { - // todo: check if can get more uses of alloc=false - buf = p.buf[p.index:end] - p.index += nb - return - } - - buf = make([]byte, nb) - copy(buf, p.buf[p.index:]) - p.index += nb - return -} - -// DecodeStringBytes reads an encoded string from the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) DecodeStringBytes() (s string, err error) { - buf, err := p.DecodeRawBytes(false) - if err != nil { - return - } - return string(buf), nil -} - -// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. -// If the protocol buffer has extensions, and the field matches, add it as an extension. -// Otherwise, if the XXX_unrecognized field exists, append the skipped data there. -func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { - oi := o.index - - err := o.skip(t, tag, wire) - if err != nil { - return err - } - - if !unrecField.IsValid() { - return nil - } - - ptr := structPointer_Bytes(base, unrecField) - - // Add the skipped field to struct field - obuf := o.buf - - o.buf = *ptr - o.EncodeVarint(uint64(tag<<3 | wire)) - *ptr = append(o.buf, obuf[oi:o.index]...) - - o.buf = obuf - - return nil -} - -// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. -func (o *Buffer) skip(t reflect.Type, tag, wire int) error { - - var u uint64 - var err error - - switch wire { - case WireVarint: - _, err = o.DecodeVarint() - case WireFixed64: - _, err = o.DecodeFixed64() - case WireBytes: - _, err = o.DecodeRawBytes(false) - case WireFixed32: - _, err = o.DecodeFixed32() - case WireStartGroup: - for { - u, err = o.DecodeVarint() - if err != nil { - break - } - fwire := int(u & 0x7) - if fwire == WireEndGroup { - break - } - ftag := int(u >> 3) - err = o.skip(t, ftag, fwire) - if err != nil { - break - } - } - default: - err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) - } - return err -} - -// Unmarshaler is the interface representing objects that can -// unmarshal themselves. The method should reset the receiver before -// decoding starts. The argument points to data that may be -// overwritten, so implementations should not keep references to the -// buffer. -type Unmarshaler interface { - Unmarshal([]byte) error -} - -// Unmarshal parses the protocol buffer representation in buf and places the -// decoded result in pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// Unmarshal resets pb before starting to unmarshal, so any -// existing data in pb is always removed. Use UnmarshalMerge -// to preserve and append to existing data. -func Unmarshal(buf []byte, pb Message) error { - pb.Reset() - return UnmarshalMerge(buf, pb) -} - -// UnmarshalMerge parses the protocol buffer representation in buf and -// writes the decoded result to pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// UnmarshalMerge merges into existing data in pb. -// Most code should use Unmarshal instead. -func UnmarshalMerge(buf []byte, pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(Unmarshaler); ok { - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// Unmarshal parses the protocol buffer representation in the -// Buffer and places the decoded result in pb. If the struct -// underlying pb does not match the data in the buffer, the results can be -// unpredictable. -func (p *Buffer) Unmarshal(pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(Unmarshaler); ok { - err := u.Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - - typ, base, err := getbase(pb) - if err != nil { - return err - } - - err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) - - if collectStats { - stats.Decode++ - } - - return err -} - -// unmarshalType does the work of unmarshaling a structure. -func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { - var state errorState - required, reqFields := prop.reqCount, uint64(0) - - var err error - for err == nil && o.index < len(o.buf) { - oi := o.index - var u uint64 - u, err = o.DecodeVarint() - if err != nil { - break - } - wire := int(u & 0x7) - if wire == WireEndGroup { - if is_group { - return nil // input is satisfied - } - return fmt.Errorf("proto: %s: wiretype end group for non-group", st) - } - tag := int(u >> 3) - if tag <= 0 { - return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire) - } - fieldnum, ok := prop.decoderTags.get(tag) - if !ok { - // Maybe it's an extension? - if prop.extendable { - if e := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) { - if err = o.skip(st, tag, wire); err == nil { - ext := e.ExtensionMap()[int32(tag)] // may be missing - ext.enc = append(ext.enc, o.buf[oi:o.index]...) - e.ExtensionMap()[int32(tag)] = ext - } - continue - } - } - err = o.skipAndSave(st, tag, wire, base, prop.unrecField) - continue - } - p := prop.Prop[fieldnum] - - if p.dec == nil { - fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) - continue - } - dec := p.dec - if wire != WireStartGroup && wire != p.WireType { - if wire == WireBytes && p.packedDec != nil { - // a packable field - dec = p.packedDec - } else { - err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) - continue - } - } - decErr := dec(o, p, base) - if decErr != nil && !state.shouldContinue(decErr, p) { - err = decErr - } - if err == nil && p.Required { - // Successfully decoded a required field. - if tag <= 64 { - // use bitmap for fields 1-64 to catch field reuse. - var mask uint64 = 1 << uint64(tag-1) - if reqFields&mask == 0 { - // new required field - reqFields |= mask - required-- - } - } else { - // This is imprecise. It can be fooled by a required field - // with a tag > 64 that is encoded twice; that's very rare. - // A fully correct implementation would require allocating - // a data structure, which we would like to avoid. - required-- - } - } - } - if err == nil { - if is_group { - return io.ErrUnexpectedEOF - } - if state.err != nil { - return state.err - } - if required > 0 { - // Not enough information to determine the exact field. If we use extra - // CPU, we could determine the field only if the missing required field - // has a tag <= 64 and we check reqFields. - return &RequiredNotSetError{"{Unknown}"} - } - } - return err -} - -// Individual type decoders -// For each, -// u is the decoded value, -// v is a pointer to the field (pointer) in the struct - -// Sizes of the pools to allocate inside the Buffer. -// The goal is modest amortization and allocation -// on at least 16-byte boundaries. -const ( - boolPoolSize = 16 - uint32PoolSize = 8 - uint64PoolSize = 4 -) - -// Decode a bool. -func (o *Buffer) dec_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - if len(o.bools) == 0 { - o.bools = make([]bool, boolPoolSize) - } - o.bools[0] = u != 0 - *structPointer_Bool(base, p.field) = &o.bools[0] - o.bools = o.bools[1:] - return nil -} - -func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - *structPointer_BoolVal(base, p.field) = u != 0 - return nil -} - -// Decode an int32. -func (o *Buffer) dec_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) - return nil -} - -func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u)) - return nil -} - -// Decode an int64. -func (o *Buffer) dec_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word64_Set(structPointer_Word64(base, p.field), o, u) - return nil -} - -func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word64Val_Set(structPointer_Word64Val(base, p.field), o, u) - return nil -} - -// Decode a string. -func (o *Buffer) dec_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - *structPointer_String(base, p.field) = &s - return nil -} - -func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - *structPointer_StringVal(base, p.field) = s - return nil -} - -// Decode a slice of bytes ([]byte). -func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - *structPointer_Bytes(base, p.field) = b - return nil -} - -// Decode a slice of bools ([]bool). -func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - v := structPointer_BoolSlice(base, p.field) - *v = append(*v, u != 0) - return nil -} - -// Decode a slice of bools ([]bool) in packed format. -func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { - v := structPointer_BoolSlice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded bools - - y := *v - for i := 0; i < nb; i++ { - u, err := p.valDec(o) - if err != nil { - return err - } - y = append(y, u != 0) - } - - *v = y - return nil -} - -// Decode a slice of int32s ([]int32). -func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - structPointer_Word32Slice(base, p.field).Append(uint32(u)) - return nil -} - -// Decode a slice of int32s ([]int32) in packed format. -func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Slice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded int32s - - fin := o.index + nb - if fin < o.index { - return errOverflow - } - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - v.Append(uint32(u)) - } - return nil -} - -// Decode a slice of int64s ([]int64). -func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - - structPointer_Word64Slice(base, p.field).Append(u) - return nil -} - -// Decode a slice of int64s ([]int64) in packed format. -func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Slice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded int64s - - fin := o.index + nb - if fin < o.index { - return errOverflow - } - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - v.Append(u) - } - return nil -} - -// Decode a slice of strings ([]string). -func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - v := structPointer_StringSlice(base, p.field) - *v = append(*v, s) - return nil -} - -// Decode a slice of slice of bytes ([][]byte). -func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - v := structPointer_BytesSlice(base, p.field) - *v = append(*v, b) - return nil -} - -// Decode a map field. -func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { - raw, err := o.DecodeRawBytes(false) - if err != nil { - return err - } - oi := o.index // index at the end of this map entry - o.index -= len(raw) // move buffer back to start of map entry - - mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V - if mptr.Elem().IsNil() { - mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) - } - v := mptr.Elem() // map[K]V - - // Prepare addressable doubly-indirect placeholders for the key and value types. - // See enc_new_map for why. - keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K - keybase := toStructPointer(keyptr.Addr()) // **K - - var valbase structPointer - var valptr reflect.Value - switch p.mtype.Elem().Kind() { - case reflect.Slice: - // []byte - var dummy []byte - valptr = reflect.ValueOf(&dummy) // *[]byte - valbase = toStructPointer(valptr) // *[]byte - case reflect.Ptr: - // message; valptr is **Msg; need to allocate the intermediate pointer - valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V - valptr.Set(reflect.New(valptr.Type().Elem())) - valbase = toStructPointer(valptr) - default: - // everything else - valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V - valbase = toStructPointer(valptr.Addr()) // **V - } - - // Decode. - // This parses a restricted wire format, namely the encoding of a message - // with two fields. See enc_new_map for the format. - for o.index < oi { - // tagcode for key and value properties are always a single byte - // because they have tags 1 and 2. - tagcode := o.buf[o.index] - o.index++ - switch tagcode { - case p.mkeyprop.tagcode[0]: - if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil { - return err - } - case p.mvalprop.tagcode[0]: - if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil { - return err - } - default: - // TODO: Should we silently skip this instead? - return fmt.Errorf("proto: bad map data tag %d", raw[0]) - } - } - keyelem, valelem := keyptr.Elem(), valptr.Elem() - if !keyelem.IsValid() || !valelem.IsValid() { - // We did not decode the key or the value in the map entry. - // Either way, it's an invalid map entry. - return fmt.Errorf("proto: bad map data: missing key/val") - } - - v.SetMapIndex(keyelem, valelem) - return nil -} - -// Decode a group. -func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { - bas := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(bas) { - // allocate new nested message - bas = toStructPointer(reflect.New(p.stype)) - structPointer_SetStructPointer(base, p.field, bas) - } - return o.unmarshalType(p.stype, p.sprop, true, bas) -} - -// Decode an embedded message. -func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { - raw, e := o.DecodeRawBytes(false) - if e != nil { - return e - } - - bas := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(bas) { - // allocate new nested message - bas = toStructPointer(reflect.New(p.stype)) - structPointer_SetStructPointer(base, p.field, bas) - } - - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - iv := structPointer_Interface(bas, p.stype) - return iv.(Unmarshaler).Unmarshal(raw) - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, false, bas) - o.buf = obuf - o.index = oi - - return err -} - -// Decode a slice of embedded messages. -func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { - return o.dec_slice_struct(p, false, base) -} - -// Decode a slice of embedded groups. -func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { - return o.dec_slice_struct(p, true, base) -} - -// Decode a slice of structs ([]*struct). -func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { - v := reflect.New(p.stype) - bas := toStructPointer(v) - structPointer_StructPointerSlice(base, p.field).Append(bas) - - if is_group { - err := o.unmarshalType(p.stype, p.sprop, is_group, bas) - return err - } - - raw, err := o.DecodeRawBytes(false) - if err != nil { - return err - } - - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - iv := v.Interface() - return iv.(Unmarshaler).Unmarshal(raw) - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, is_group, bas) - - o.buf = obuf - o.index = oi - - return err -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go deleted file mode 100644 index 72c780b..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go +++ /dev/null @@ -1,1293 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "errors" - "fmt" - "reflect" - "sort" -) - -// RequiredNotSetError is the error returned if Marshal is called with -// a protocol buffer struct whose required fields have not -// all been initialized. It is also the error returned if Unmarshal is -// called with an encoded protocol buffer that does not include all the -// required fields. -// -// When printed, RequiredNotSetError reports the first unset required field in a -// message. If the field cannot be precisely determined, it is reported as -// "{Unknown}". -type RequiredNotSetError struct { - field string -} - -func (e *RequiredNotSetError) Error() string { - return fmt.Sprintf("proto: required field %q not set", e.field) -} - -var ( - // errRepeatedHasNil is the error returned if Marshal is called with - // a struct with a repeated field containing a nil element. - errRepeatedHasNil = errors.New("proto: repeated field has nil element") - - // ErrNil is the error returned if Marshal is called with nil. - ErrNil = errors.New("proto: Marshal called with nil") -) - -// The fundamental encoders that put bytes on the wire. -// Those that take integer types all accept uint64 and are -// therefore of type valueEncoder. - -const maxVarintBytes = 10 // maximum length of a varint - -// EncodeVarint returns the varint encoding of x. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -// Not used by the package itself, but helpful to clients -// wishing to use the same encoding. -func EncodeVarint(x uint64) []byte { - var buf [maxVarintBytes]byte - var n int - for n = 0; x > 127; n++ { - buf[n] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - buf[n] = uint8(x) - n++ - return buf[0:n] -} - -// EncodeVarint writes a varint-encoded integer to the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) EncodeVarint(x uint64) error { - for x >= 1<<7 { - p.buf = append(p.buf, uint8(x&0x7f|0x80)) - x >>= 7 - } - p.buf = append(p.buf, uint8(x)) - return nil -} - -func sizeVarint(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} - -// EncodeFixed64 writes a 64-bit integer to the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) EncodeFixed64(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24), - uint8(x>>32), - uint8(x>>40), - uint8(x>>48), - uint8(x>>56)) - return nil -} - -func sizeFixed64(x uint64) int { - return 8 -} - -// EncodeFixed32 writes a 32-bit integer to the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) EncodeFixed32(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24)) - return nil -} - -func sizeFixed32(x uint64) int { - return 4 -} - -// EncodeZigzag64 writes a zigzag-encoded 64-bit integer -// to the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) EncodeZigzag64(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func sizeZigzag64(x uint64) int { - return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -// EncodeZigzag32 writes a zigzag-encoded 32-bit integer -// to the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) EncodeZigzag32(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -func sizeZigzag32(x uint64) int { - return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) EncodeRawBytes(b []byte) error { - p.EncodeVarint(uint64(len(b))) - p.buf = append(p.buf, b...) - return nil -} - -func sizeRawBytes(b []byte) int { - return sizeVarint(uint64(len(b))) + - len(b) -} - -// EncodeStringBytes writes an encoded string to the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) EncodeStringBytes(s string) error { - p.EncodeVarint(uint64(len(s))) - p.buf = append(p.buf, s...) - return nil -} - -func sizeStringBytes(s string) int { - return sizeVarint(uint64(len(s))) + - len(s) -} - -// Marshaler is the interface representing objects that can marshal themselves. -type Marshaler interface { - Marshal() ([]byte, error) -} - -// Marshal takes the protocol buffer -// and encodes it into the wire format, returning the data. -func Marshal(pb Message) ([]byte, error) { - // Can the object marshal itself? - if m, ok := pb.(Marshaler); ok { - return m.Marshal() - } - p := NewBuffer(nil) - err := p.Marshal(pb) - var state errorState - if err != nil && !state.shouldContinue(err, nil) { - return nil, err - } - if p.buf == nil && err == nil { - // Return a non-nil slice on success. - return []byte{}, nil - } - return p.buf, err -} - -// Marshal takes the protocol buffer -// and encodes it into the wire format, writing the result to the -// Buffer. -func (p *Buffer) Marshal(pb Message) error { - // Can the object marshal itself? - if m, ok := pb.(Marshaler); ok { - data, err := m.Marshal() - if err != nil { - return err - } - p.buf = append(p.buf, data...) - return nil - } - - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return ErrNil - } - if err == nil { - err = p.enc_struct(GetProperties(t.Elem()), base) - } - - if collectStats { - stats.Encode++ - } - - return err -} - -// Size returns the encoded size of a protocol buffer. -func Size(pb Message) (n int) { - // Can the object marshal itself? If so, Size is slow. - // TODO: add Size to Marshaler, or add a Sizer interface. - if m, ok := pb.(Marshaler); ok { - b, _ := m.Marshal() - return len(b) - } - - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return 0 - } - if err == nil { - n = size_struct(GetProperties(t.Elem()), base) - } - - if collectStats { - stats.Size++ - } - - return -} - -// Individual type encoders. - -// Encode a bool. -func (o *Buffer) enc_bool(p *Properties, base structPointer) error { - v := *structPointer_Bool(base, p.field) - if v == nil { - return ErrNil - } - x := 0 - if *v { - x = 1 - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error { - v := *structPointer_BoolVal(base, p.field) - if !v { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, 1) - return nil -} - -func size_bool(p *Properties, base structPointer) int { - v := *structPointer_Bool(base, p.field) - if v == nil { - return 0 - } - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -func size_proto3_bool(p *Properties, base structPointer) int { - v := *structPointer_BoolVal(base, p.field) - if !v { - return 0 - } - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -// Encode an int32. -func (o *Buffer) enc_int32(p *Properties, base structPointer) error { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return ErrNil - } - x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_int32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return 0 - } - x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -func size_proto3_int32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range - if x == 0 { - return 0 - } - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode a uint32. -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return ErrNil - } - x := word32_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return 0 - } - x := word32_Get(v) - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -func size_proto3_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - if x == 0 { - return 0 - } - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode an int64. -func (o *Buffer) enc_int64(p *Properties, base structPointer) error { - v := structPointer_Word64(base, p.field) - if word64_IsNil(v) { - return ErrNil - } - x := word64_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func size_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64(base, p.field) - if word64_IsNil(v) { - return 0 - } - x := word64_Get(v) - n += len(p.tagcode) - n += p.valSize(x) - return -} - -func size_proto3_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - if x == 0 { - return 0 - } - n += len(p.tagcode) - n += p.valSize(x) - return -} - -// Encode a string. -func (o *Buffer) enc_string(p *Properties, base structPointer) error { - v := *structPointer_String(base, p.field) - if v == nil { - return ErrNil - } - x := *v - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(x) - return nil -} - -func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error { - v := *structPointer_StringVal(base, p.field) - if v == "" { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(v) - return nil -} - -func size_string(p *Properties, base structPointer) (n int) { - v := *structPointer_String(base, p.field) - if v == nil { - return 0 - } - x := *v - n += len(p.tagcode) - n += sizeStringBytes(x) - return -} - -func size_proto3_string(p *Properties, base structPointer) (n int) { - v := *structPointer_StringVal(base, p.field) - if v == "" { - return 0 - } - n += len(p.tagcode) - n += sizeStringBytes(v) - return -} - -// All protocol buffer fields are nillable, but be careful. -func isNil(v reflect.Value) bool { - switch v.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - return false -} - -// Encode a message struct. -func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { - var state errorState - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return ErrNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return nil - } - - o.buf = append(o.buf, p.tagcode...) - return o.enc_len_struct(p.sprop, structp, &state) -} - -func size_struct_message(p *Properties, base structPointer) int { - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return 0 - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n0 := len(p.tagcode) - n1 := sizeRawBytes(data) - return n0 + n1 - } - - n0 := len(p.tagcode) - n1 := size_struct(p.sprop, structp) - n2 := sizeVarint(uint64(n1)) // size of encoded length - return n0 + n1 + n2 -} - -// Encode a group struct. -func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error { - var state errorState - b := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(b) { - return ErrNil - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) - err := o.enc_struct(p.sprop, b) - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) - return state.err -} - -func size_struct_group(p *Properties, base structPointer) (n int) { - b := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(b) { - return 0 - } - - n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup)) - n += size_struct(p.sprop, b) - n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup)) - return -} - -// Encode a slice of bools ([]bool). -func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return ErrNil - } - for _, x := range s { - o.buf = append(o.buf, p.tagcode...) - v := uint64(0) - if x { - v = 1 - } - p.valEnc(o, v) - } - return nil -} - -func size_slice_bool(p *Properties, base structPointer) int { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return 0 - } - return l * (len(p.tagcode) + 1) // each bool takes exactly one byte -} - -// Encode a slice of bools ([]bool) in packed format. -func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(l)) // each bool takes exactly one byte - for _, x := range s { - v := uint64(0) - if x { - v = 1 - } - p.valEnc(o, v) - } - return nil -} - -func size_slice_packed_bool(p *Properties, base structPointer) (n int) { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return 0 - } - n += len(p.tagcode) - n += sizeVarint(uint64(l)) - n += l // each bool takes exactly one byte - return -} - -// Encode a slice of bytes ([]byte). -func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if s == nil { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(s) - return nil -} - -func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if len(s) == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(s) - return nil -} - -func size_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if s == nil { - return 0 - } - n += len(p.tagcode) - n += sizeRawBytes(s) - return -} - -func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if len(s) == 0 { - return 0 - } - n += len(p.tagcode) - n += sizeRawBytes(s) - return -} - -// Encode a slice of int32s ([]int32). -func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - p.valEnc(o, uint64(x)) - } - return nil -} - -func size_slice_int32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - n += p.valSize(uint64(x)) - } - return -} - -// Encode a slice of int32s ([]int32) in packed format. -func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - p.valEnc(buf, uint64(x)) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_int32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - bufSize += p.valSize(uint64(x)) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of uint32s ([]uint32). -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - x := s.Index(i) - p.valEnc(o, uint64(x)) - } - return nil -} - -func size_slice_uint32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - x := s.Index(i) - n += p.valSize(uint64(x)) - } - return -} - -// Encode a slice of uint32s ([]uint32) in packed format. -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - p.valEnc(buf, uint64(s.Index(i))) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_uint32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - bufSize += p.valSize(uint64(s.Index(i))) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of int64s ([]int64). -func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, s.Index(i)) - } - return nil -} - -func size_slice_int64(p *Properties, base structPointer) (n int) { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - n += p.valSize(s.Index(i)) - } - return -} - -// Encode a slice of int64s ([]int64) in packed format. -func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - p.valEnc(buf, s.Index(i)) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_int64(p *Properties, base structPointer) (n int) { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - bufSize += p.valSize(s.Index(i)) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of slice of bytes ([][]byte). -func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error { - ss := *structPointer_BytesSlice(base, p.field) - l := len(ss) - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(ss[i]) - } - return nil -} - -func size_slice_slice_byte(p *Properties, base structPointer) (n int) { - ss := *structPointer_BytesSlice(base, p.field) - l := len(ss) - if l == 0 { - return 0 - } - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - n += sizeRawBytes(ss[i]) - } - return -} - -// Encode a slice of strings ([]string). -func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error { - ss := *structPointer_StringSlice(base, p.field) - l := len(ss) - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(ss[i]) - } - return nil -} - -func size_slice_string(p *Properties, base structPointer) (n int) { - ss := *structPointer_StringSlice(base, p.field) - l := len(ss) - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - n += sizeStringBytes(ss[i]) - } - return -} - -// Encode a slice of message structs ([]*struct). -func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error { - var state errorState - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - for i := 0; i < l; i++ { - structp := s.Index(i) - if structPointer_IsNil(structp) { - return errRepeatedHasNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - continue - } - - o.buf = append(o.buf, p.tagcode...) - err := o.enc_len_struct(p.sprop, structp, &state) - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - } - return state.err -} - -func size_slice_struct_message(p *Properties, base structPointer) (n int) { - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - structp := s.Index(i) - if structPointer_IsNil(structp) { - return // return the size up to this point - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n += len(p.tagcode) - n += sizeRawBytes(data) - continue - } - - n0 := size_struct(p.sprop, structp) - n1 := sizeVarint(uint64(n0)) // size of encoded length - n += n0 + n1 - } - return -} - -// Encode a slice of group structs ([]*struct). -func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error { - var state errorState - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - for i := 0; i < l; i++ { - b := s.Index(i) - if structPointer_IsNil(b) { - return errRepeatedHasNil - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) - - err := o.enc_struct(p.sprop, b) - - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) - } - return state.err -} - -func size_slice_struct_group(p *Properties, base structPointer) (n int) { - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup)) - n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup)) - for i := 0; i < l; i++ { - b := s.Index(i) - if structPointer_IsNil(b) { - return // return size up to this point - } - - n += size_struct(p.sprop, b) - } - return -} - -// Encode an extension map. -func (o *Buffer) enc_map(p *Properties, base structPointer) error { - v := *structPointer_ExtMap(base, p.field) - if err := encodeExtensionMap(v); err != nil { - return err - } - // Fast-path for common cases: zero or one extensions. - if len(v) <= 1 { - for _, e := range v { - o.buf = append(o.buf, e.enc...) - } - return nil - } - - // Sort keys to provide a deterministic encoding. - keys := make([]int, 0, len(v)) - for k := range v { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - o.buf = append(o.buf, v[int32(k)].enc...) - } - return nil -} - -func size_map(p *Properties, base structPointer) int { - v := *structPointer_ExtMap(base, p.field) - return sizeExtensionMap(v) -} - -// Encode a map field. -func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { - var state errorState // XXX: or do we need to plumb this through? - - /* - A map defined as - map map_field = N; - is encoded in the same way as - message MapFieldEntry { - key_type key = 1; - value_type value = 2; - } - repeated MapFieldEntry map_field = N; - */ - - v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V - if v.Len() == 0 { - return nil - } - - keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) - - enc := func() error { - if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil { - return err - } - if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil { - return err - } - return nil - } - - keys := v.MapKeys() - sort.Sort(mapKeys(keys)) - for _, key := range keys { - val := v.MapIndex(key) - - // The only illegal map entry values are nil message pointers. - if val.Kind() == reflect.Ptr && val.IsNil() { - return errors.New("proto: map has nil element") - } - - keycopy.Set(key) - valcopy.Set(val) - - o.buf = append(o.buf, p.tagcode...) - if err := o.enc_len_thing(enc, &state); err != nil { - return err - } - } - return nil -} - -func size_new_map(p *Properties, base structPointer) int { - v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V - - keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) - - n := 0 - for _, key := range v.MapKeys() { - val := v.MapIndex(key) - keycopy.Set(key) - valcopy.Set(val) - - // Tag codes for key and val are the responsibility of the sub-sizer. - keysize := p.mkeyprop.size(p.mkeyprop, keybase) - valsize := p.mvalprop.size(p.mvalprop, valbase) - entry := keysize + valsize - // Add on tag code and length of map entry itself. - n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry - } - return n -} - -// mapEncodeScratch returns a new reflect.Value matching the map's value type, -// and a structPointer suitable for passing to an encoder or sizer. -func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { - // Prepare addressable doubly-indirect placeholders for the key and value types. - // This is needed because the element-type encoders expect **T, but the map iteration produces T. - - keycopy = reflect.New(mapType.Key()).Elem() // addressable K - keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K - keyptr.Set(keycopy.Addr()) // - keybase = toStructPointer(keyptr.Addr()) // **K - - // Value types are more varied and require special handling. - switch mapType.Elem().Kind() { - case reflect.Slice: - // []byte - var dummy []byte - valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte - valbase = toStructPointer(valcopy.Addr()) - case reflect.Ptr: - // message; the generated field type is map[K]*Msg (so V is *Msg), - // so we only need one level of indirection. - valcopy = reflect.New(mapType.Elem()).Elem() // addressable V - valbase = toStructPointer(valcopy.Addr()) - default: - // everything else - valcopy = reflect.New(mapType.Elem()).Elem() // addressable V - valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V - valptr.Set(valcopy.Addr()) // - valbase = toStructPointer(valptr.Addr()) // **V - } - return -} - -// Encode a struct. -func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { - var state errorState - // Encode fields in tag order so that decoders may use optimizations - // that depend on the ordering. - // https://developers.google.com/protocol-buffers/docs/encoding#order - for _, i := range prop.order { - p := prop.Prop[i] - if p.enc != nil { - err := p.enc(o, p, base) - if err != nil { - if err == ErrNil { - if p.Required && state.err == nil { - state.err = &RequiredNotSetError{p.Name} - } - } else if err == errRepeatedHasNil { - // Give more context to nil values in repeated fields. - return errors.New("repeated field " + p.OrigName + " has nil element") - } else if !state.shouldContinue(err, p) { - return err - } - } - } - } - - // Add unrecognized fields at the end. - if prop.unrecField.IsValid() { - v := *structPointer_Bytes(base, prop.unrecField) - if len(v) > 0 { - o.buf = append(o.buf, v...) - } - } - - return state.err -} - -func size_struct(prop *StructProperties, base structPointer) (n int) { - for _, i := range prop.order { - p := prop.Prop[i] - if p.size != nil { - n += p.size(p, base) - } - } - - // Add unrecognized fields at the end. - if prop.unrecField.IsValid() { - v := *structPointer_Bytes(base, prop.unrecField) - n += len(v) - } - - return -} - -var zeroes [20]byte // longer than any conceivable sizeVarint - -// Encode a struct, preceded by its encoded length (as a varint). -func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error { - return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state) -} - -// Encode something, preceded by its encoded length (as a varint). -func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error { - iLen := len(o.buf) - o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length - iMsg := len(o.buf) - err := enc() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - lMsg := len(o.buf) - iMsg - lLen := sizeVarint(uint64(lMsg)) - switch x := lLen - (iMsg - iLen); { - case x > 0: // actual length is x bytes larger than the space we reserved - // Move msg x bytes right. - o.buf = append(o.buf, zeroes[:x]...) - copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) - case x < 0: // actual length is x bytes smaller than the space we reserved - // Move msg x bytes left. - copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) - o.buf = o.buf[:len(o.buf)+x] // x is negative - } - // Encode the length in the reserved space. - o.buf = o.buf[:iLen] - o.EncodeVarint(uint64(lMsg)) - o.buf = o.buf[:len(o.buf)+lMsg] - return state.err -} - -// errorState maintains the first error that occurs and updates that error -// with additional context. -type errorState struct { - err error -} - -// shouldContinue reports whether encoding should continue upon encountering the -// given error. If the error is RequiredNotSetError, shouldContinue returns true -// and, if this is the first appearance of that error, remembers it for future -// reporting. -// -// If prop is not nil, it may update any error with additional context about the -// field with the error. -func (s *errorState) shouldContinue(err error, prop *Properties) bool { - // Ignore unset required fields. - reqNotSet, ok := err.(*RequiredNotSetError) - if !ok { - return false - } - if s.err == nil { - if prop != nil { - err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field} - } - s.err = err - } - return true -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go deleted file mode 100644 index d8673a3..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go +++ /dev/null @@ -1,256 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Protocol buffer comparison. -// TODO: MessageSet. - -package proto - -import ( - "bytes" - "log" - "reflect" - "strings" -) - -/* -Equal returns true iff protocol buffers a and b are equal. -The arguments must both be pointers to protocol buffer structs. - -Equality is defined in this way: - - Two messages are equal iff they are the same type, - corresponding fields are equal, unknown field sets - are equal, and extensions sets are equal. - - Two set scalar fields are equal iff their values are equal. - If the fields are of a floating-point type, remember that - NaN != x for all x, including NaN. - - Two repeated fields are equal iff their lengths are the same, - and their corresponding elements are equal (a "bytes" field, - although represented by []byte, is not a repeated field) - - Two unset fields are equal. - - Two unknown field sets are equal if their current - encoded state is equal. - - Two extension sets are equal iff they have corresponding - elements that are pairwise equal. - - Every other combination of things are not equal. - -The return value is undefined if a and b are not protocol buffers. -*/ -func Equal(a, b Message) bool { - if a == nil || b == nil { - return a == b - } - v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) - if v1.Type() != v2.Type() { - return false - } - if v1.Kind() == reflect.Ptr { - if v1.IsNil() { - return v2.IsNil() - } - if v2.IsNil() { - return false - } - v1, v2 = v1.Elem(), v2.Elem() - } - if v1.Kind() != reflect.Struct { - return false - } - return equalStruct(v1, v2) -} - -// v1 and v2 are known to have the same type. -func equalStruct(v1, v2 reflect.Value) bool { - for i := 0; i < v1.NumField(); i++ { - f := v1.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - f1, f2 := v1.Field(i), v2.Field(i) - if f.Type.Kind() == reflect.Ptr { - if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { - // both unset - continue - } else if n1 != n2 { - // set/unset mismatch - return false - } - b1, ok := f1.Interface().(raw) - if ok { - b2 := f2.Interface().(raw) - // RawMessage - if !bytes.Equal(b1.Bytes(), b2.Bytes()) { - return false - } - continue - } - f1, f2 = f1.Elem(), f2.Elem() - } - if !equalAny(f1, f2) { - return false - } - } - - if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_extensions") - if !equalExtensions(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { - return false - } - } - - uf := v1.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return true - } - - u1 := uf.Bytes() - u2 := v2.FieldByName("XXX_unrecognized").Bytes() - if !bytes.Equal(u1, u2) { - return false - } - - return true -} - -// v1 and v2 are known to have the same type. -func equalAny(v1, v2 reflect.Value) bool { - if v1.Type() == protoMessageType { - m1, _ := v1.Interface().(Message) - m2, _ := v2.Interface().(Message) - return Equal(m1, m2) - } - switch v1.Kind() { - case reflect.Bool: - return v1.Bool() == v2.Bool() - case reflect.Float32, reflect.Float64: - return v1.Float() == v2.Float() - case reflect.Int32, reflect.Int64: - return v1.Int() == v2.Int() - case reflect.Map: - if v1.Len() != v2.Len() { - return false - } - for _, key := range v1.MapKeys() { - val2 := v2.MapIndex(key) - if !val2.IsValid() { - // This key was not found in the second map. - return false - } - if !equalAny(v1.MapIndex(key), val2) { - return false - } - } - return true - case reflect.Ptr: - return equalAny(v1.Elem(), v2.Elem()) - case reflect.Slice: - if v1.Type().Elem().Kind() == reflect.Uint8 { - // short circuit: []byte - if v1.IsNil() != v2.IsNil() { - return false - } - return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) - } - - if v1.Len() != v2.Len() { - return false - } - for i := 0; i < v1.Len(); i++ { - if !equalAny(v1.Index(i), v2.Index(i)) { - return false - } - } - return true - case reflect.String: - return v1.Interface().(string) == v2.Interface().(string) - case reflect.Struct: - return equalStruct(v1, v2) - case reflect.Uint32, reflect.Uint64: - return v1.Uint() == v2.Uint() - } - - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to compare %v", v1) - return false -} - -// base is the struct type that the extensions are based on. -// em1 and em2 are extension maps. -func equalExtensions(base reflect.Type, em1, em2 map[int32]Extension) bool { - if len(em1) != len(em2) { - return false - } - - for extNum, e1 := range em1 { - e2, ok := em2[extNum] - if !ok { - return false - } - - m1, m2 := e1.value, e2.value - - if m1 != nil && m2 != nil { - // Both are unencoded. - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) { - return false - } - continue - } - - // At least one is encoded. To do a semantically correct comparison - // we need to unmarshal them first. - var desc *ExtensionDesc - if m := extensionMaps[base]; m != nil { - desc = m[extNum] - } - if desc == nil { - log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) - continue - } - var err error - if m1 == nil { - m1, err = decodeExtension(e1.enc, desc) - } - if m2 == nil && err == nil { - m2, err = decodeExtension(e2.enc, desc) - } - if err != nil { - // The encoded form is invalid. - log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) - return false - } - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) { - return false - } - } - - return true -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go deleted file mode 100644 index b322f65..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go +++ /dev/null @@ -1,191 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - . "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -// Four identical base messages. -// The init function adds extensions to some of them. -var messageWithoutExtension = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension1a = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension1b = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension2 = &pb.MyMessage{Count: Int32(7)} - -// Two messages with non-message extensions. -var messageWithInt32Extension1 = &pb.MyMessage{Count: Int32(8)} -var messageWithInt32Extension2 = &pb.MyMessage{Count: Int32(8)} - -func init() { - ext1 := &pb.Ext{Data: String("Kirk")} - ext2 := &pb.Ext{Data: String("Picard")} - - // messageWithExtension1a has ext1, but never marshals it. - if err := SetExtension(messageWithExtension1a, pb.E_Ext_More, ext1); err != nil { - panic("SetExtension on 1a failed: " + err.Error()) - } - - // messageWithExtension1b is the unmarshaled form of messageWithExtension1a. - if err := SetExtension(messageWithExtension1b, pb.E_Ext_More, ext1); err != nil { - panic("SetExtension on 1b failed: " + err.Error()) - } - buf, err := Marshal(messageWithExtension1b) - if err != nil { - panic("Marshal of 1b failed: " + err.Error()) - } - messageWithExtension1b.Reset() - if err := Unmarshal(buf, messageWithExtension1b); err != nil { - panic("Unmarshal of 1b failed: " + err.Error()) - } - - // messageWithExtension2 has ext2. - if err := SetExtension(messageWithExtension2, pb.E_Ext_More, ext2); err != nil { - panic("SetExtension on 2 failed: " + err.Error()) - } - - if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(23)); err != nil { - panic("SetExtension on Int32-1 failed: " + err.Error()) - } - if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(24)); err != nil { - panic("SetExtension on Int32-2 failed: " + err.Error()) - } -} - -var EqualTests = []struct { - desc string - a, b Message - exp bool -}{ - {"different types", &pb.GoEnum{}, &pb.GoTestField{}, false}, - {"equal empty", &pb.GoEnum{}, &pb.GoEnum{}, true}, - {"nil vs nil", nil, nil, true}, - {"typed nil vs typed nil", (*pb.GoEnum)(nil), (*pb.GoEnum)(nil), true}, - {"typed nil vs empty", (*pb.GoEnum)(nil), &pb.GoEnum{}, false}, - {"different typed nil", (*pb.GoEnum)(nil), (*pb.GoTestField)(nil), false}, - - {"one set field, one unset field", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{}, false}, - {"one set field zero, one unset field", &pb.GoTest{Param: Int32(0)}, &pb.GoTest{}, false}, - {"different set fields", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("bar")}, false}, - {"equal set", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("foo")}, true}, - - {"repeated, one set", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{}, false}, - {"repeated, different length", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{F_Int32Repeated: []int32{2}}, false}, - {"repeated, different value", &pb.GoTest{F_Int32Repeated: []int32{2}}, &pb.GoTest{F_Int32Repeated: []int32{3}}, false}, - {"repeated, equal", &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, true}, - {"repeated, nil equal nil", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: nil}, true}, - {"repeated, nil equal empty", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: []int32{}}, true}, - {"repeated, empty equal nil", &pb.GoTest{F_Int32Repeated: []int32{}}, &pb.GoTest{F_Int32Repeated: nil}, true}, - - { - "nested, different", - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("foo")}}, - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("bar")}}, - false, - }, - { - "nested, equal", - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, - true, - }, - - {"bytes", &pb.OtherMessage{Value: []byte("foo")}, &pb.OtherMessage{Value: []byte("foo")}, true}, - {"bytes, empty", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: []byte{}}, true}, - {"bytes, empty vs nil", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: nil}, false}, - { - "repeated bytes", - &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, - &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, - true, - }, - - {"extension vs. no extension", messageWithoutExtension, messageWithExtension1a, false}, - {"extension vs. same extension", messageWithExtension1a, messageWithExtension1b, true}, - {"extension vs. different extension", messageWithExtension1a, messageWithExtension2, false}, - - {"int32 extension vs. itself", messageWithInt32Extension1, messageWithInt32Extension1, true}, - {"int32 extension vs. a different int32", messageWithInt32Extension1, messageWithInt32Extension2, false}, - - { - "message with group", - &pb.MyMessage{ - Count: Int32(1), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: Int32(5), - }, - }, - &pb.MyMessage{ - Count: Int32(1), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: Int32(5), - }, - }, - true, - }, - - { - "map same", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - true, - }, - { - "map different entry", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{2: "Rob"}}, - false, - }, - { - "map different key only", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{2: "Ken"}}, - false, - }, - { - "map different value only", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob"}}, - false, - }, -} - -func TestEqual(t *testing.T) { - for _, tc := range EqualTests { - if res := Equal(tc.a, tc.b); res != tc.exp { - t.Errorf("%v: Equal(%v, %v) = %v, want %v", tc.desc, tc.a, tc.b, res, tc.exp) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go deleted file mode 100644 index e591cce..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go +++ /dev/null @@ -1,400 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Types and routines for supporting protocol buffer extensions. - */ - -import ( - "errors" - "fmt" - "reflect" - "strconv" - "sync" -) - -// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. -var ErrMissingExtension = errors.New("proto: missing extension") - -// ExtensionRange represents a range of message extensions for a protocol buffer. -// Used in code generated by the protocol compiler. -type ExtensionRange struct { - Start, End int32 // both inclusive -} - -// extendableProto is an interface implemented by any protocol buffer that may be extended. -type extendableProto interface { - Message - ExtensionRangeArray() []ExtensionRange - ExtensionMap() map[int32]Extension -} - -var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem() - -// ExtensionDesc represents an extension specification. -// Used in generated code from the protocol compiler. -type ExtensionDesc struct { - ExtendedType Message // nil pointer to the type that is being extended - ExtensionType interface{} // nil pointer to the extension type - Field int32 // field number - Name string // fully-qualified name of extension, for text formatting - Tag string // protobuf tag style -} - -func (ed *ExtensionDesc) repeated() bool { - t := reflect.TypeOf(ed.ExtensionType) - return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 -} - -// Extension represents an extension in a message. -type Extension struct { - // When an extension is stored in a message using SetExtension - // only desc and value are set. When the message is marshaled - // enc will be set to the encoded form of the message. - // - // When a message is unmarshaled and contains extensions, each - // extension will have only enc set. When such an extension is - // accessed using GetExtension (or GetExtensions) desc and value - // will be set. - desc *ExtensionDesc - value interface{} - enc []byte -} - -// SetRawExtension is for testing only. -func SetRawExtension(base extendableProto, id int32, b []byte) { - base.ExtensionMap()[id] = Extension{enc: b} -} - -// isExtensionField returns true iff the given field number is in an extension range. -func isExtensionField(pb extendableProto, field int32) bool { - for _, er := range pb.ExtensionRangeArray() { - if er.Start <= field && field <= er.End { - return true - } - } - return false -} - -// checkExtensionTypes checks that the given extension is valid for pb. -func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { - // Check the extended type. - if a, b := reflect.TypeOf(pb), reflect.TypeOf(extension.ExtendedType); a != b { - return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String()) - } - // Check the range. - if !isExtensionField(pb, extension.Field) { - return errors.New("proto: bad extension number; not in declared ranges") - } - return nil -} - -// extPropKey is sufficient to uniquely identify an extension. -type extPropKey struct { - base reflect.Type - field int32 -} - -var extProp = struct { - sync.RWMutex - m map[extPropKey]*Properties -}{ - m: make(map[extPropKey]*Properties), -} - -func extensionProperties(ed *ExtensionDesc) *Properties { - key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} - - extProp.RLock() - if prop, ok := extProp.m[key]; ok { - extProp.RUnlock() - return prop - } - extProp.RUnlock() - - extProp.Lock() - defer extProp.Unlock() - // Check again. - if prop, ok := extProp.m[key]; ok { - return prop - } - - prop := new(Properties) - prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) - extProp.m[key] = prop - return prop -} - -// encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m. -func encodeExtensionMap(m map[int32]Extension) error { - for k, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - et := reflect.TypeOf(e.desc.ExtensionType) - props := extensionProperties(e.desc) - - p := NewBuffer(nil) - // If e.value has type T, the encoder expects a *struct{ X T }. - // Pass a *T with a zero field and hope it all works out. - x := reflect.New(et) - x.Elem().Set(reflect.ValueOf(e.value)) - if err := props.enc(p, props, toStructPointer(x)); err != nil { - return err - } - e.enc = p.buf - m[k] = e - } - return nil -} - -func sizeExtensionMap(m map[int32]Extension) (n int) { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - et := reflect.TypeOf(e.desc.ExtensionType) - props := extensionProperties(e.desc) - - // If e.value has type T, the encoder expects a *struct{ X T }. - // Pass a *T with a zero field and hope it all works out. - x := reflect.New(et) - x.Elem().Set(reflect.ValueOf(e.value)) - n += props.size(props, toStructPointer(x)) - } - return -} - -// HasExtension returns whether the given extension is present in pb. -func HasExtension(pb extendableProto, extension *ExtensionDesc) bool { - // TODO: Check types, field numbers, etc.? - _, ok := pb.ExtensionMap()[extension.Field] - return ok -} - -// ClearExtension removes the given extension from pb. -func ClearExtension(pb extendableProto, extension *ExtensionDesc) { - // TODO: Check types, field numbers, etc.? - delete(pb.ExtensionMap(), extension.Field) -} - -// GetExtension parses and returns the given extension of pb. -// If the extension is not present and has no default value it returns ErrMissingExtension. -func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, error) { - if err := checkExtensionTypes(pb, extension); err != nil { - return nil, err - } - - emap := pb.ExtensionMap() - e, ok := emap[extension.Field] - if !ok { - // defaultExtensionValue returns the default value or - // ErrMissingExtension if there is no default. - return defaultExtensionValue(extension) - } - - if e.value != nil { - // Already decoded. Check the descriptor, though. - if e.desc != extension { - // This shouldn't happen. If it does, it means that - // GetExtension was called twice with two different - // descriptors with the same field number. - return nil, errors.New("proto: descriptor conflict") - } - return e.value, nil - } - - v, err := decodeExtension(e.enc, extension) - if err != nil { - return nil, err - } - - // Remember the decoded version and drop the encoded version. - // That way it is safe to mutate what we return. - e.value = v - e.desc = extension - e.enc = nil - emap[extension.Field] = e - return e.value, nil -} - -// defaultExtensionValue returns the default value for extension. -// If no default for an extension is defined ErrMissingExtension is returned. -func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { - t := reflect.TypeOf(extension.ExtensionType) - props := extensionProperties(extension) - - sf, _, err := fieldDefault(t, props) - if err != nil { - return nil, err - } - - if sf == nil || sf.value == nil { - // There is no default value. - return nil, ErrMissingExtension - } - - if t.Kind() != reflect.Ptr { - // We do not need to return a Ptr, we can directly return sf.value. - return sf.value, nil - } - - // We need to return an interface{} that is a pointer to sf.value. - value := reflect.New(t).Elem() - value.Set(reflect.New(value.Type().Elem())) - if sf.kind == reflect.Int32 { - // We may have an int32 or an enum, but the underlying data is int32. - // Since we can't set an int32 into a non int32 reflect.value directly - // set it as a int32. - value.Elem().SetInt(int64(sf.value.(int32))) - } else { - value.Elem().Set(reflect.ValueOf(sf.value)) - } - return value.Interface(), nil -} - -// decodeExtension decodes an extension encoded in b. -func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { - o := NewBuffer(b) - - t := reflect.TypeOf(extension.ExtensionType) - rep := extension.repeated() - - props := extensionProperties(extension) - - // t is a pointer to a struct, pointer to basic type or a slice. - // Allocate a "field" to store the pointer/slice itself; the - // pointer/slice will be stored here. We pass - // the address of this field to props.dec. - // This passes a zero field and a *t and lets props.dec - // interpret it as a *struct{ x t }. - value := reflect.New(t).Elem() - - for { - // Discard wire type and field number varint. It isn't needed. - if _, err := o.DecodeVarint(); err != nil { - return nil, err - } - - if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil { - return nil, err - } - - if !rep || o.index >= len(o.buf) { - break - } - } - return value.Interface(), nil -} - -// GetExtensions returns a slice of the extensions present in pb that are also listed in es. -// The returned slice has the same length as es; missing extensions will appear as nil elements. -func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { - epb, ok := pb.(extendableProto) - if !ok { - err = errors.New("proto: not an extendable proto") - return - } - extensions = make([]interface{}, len(es)) - for i, e := range es { - extensions[i], err = GetExtension(epb, e) - if err == ErrMissingExtension { - err = nil - } - if err != nil { - return - } - } - return -} - -// SetExtension sets the specified extension of pb to the specified value. -func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error { - if err := checkExtensionTypes(pb, extension); err != nil { - return err - } - typ := reflect.TypeOf(extension.ExtensionType) - if typ != reflect.TypeOf(value) { - return errors.New("proto: bad extension value type") - } - // nil extension values need to be caught early, because the - // encoder can't distinguish an ErrNil due to a nil extension - // from an ErrNil due to a missing field. Extensions are - // always optional, so the encoder would just swallow the error - // and drop all the extensions from the encoded message. - if reflect.ValueOf(value).IsNil() { - return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) - } - - pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value} - return nil -} - -// A global registry of extensions. -// The generated code will register the generated descriptors by calling RegisterExtension. - -var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) - -// RegisterExtension is called from the generated code. -func RegisterExtension(desc *ExtensionDesc) { - st := reflect.TypeOf(desc.ExtendedType).Elem() - m := extensionMaps[st] - if m == nil { - m = make(map[int32]*ExtensionDesc) - extensionMaps[st] = m - } - if _, ok := m[desc.Field]; ok { - panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) - } - m[desc.Field] = desc -} - -// RegisteredExtensions returns a map of the registered extensions of a -// protocol buffer struct, indexed by the extension number. -// The argument pb should be a nil pointer to the struct type. -func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { - return extensionMaps[reflect.TypeOf(pb).Elem()] -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go deleted file mode 100644 index 7255276..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go +++ /dev/null @@ -1,292 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -func TestGetExtensionsWithMissingExtensions(t *testing.T) { - msg := &pb.MyMessage{} - ext1 := &pb.Ext{} - if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { - t.Fatalf("Could not set ext1: %s", ext1) - } - exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{ - pb.E_Ext_More, - pb.E_Ext_Text, - }) - if err != nil { - t.Fatalf("GetExtensions() failed: %s", err) - } - if exts[0] != ext1 { - t.Errorf("ext1 not in returned extensions: %T %v", exts[0], exts[0]) - } - if exts[1] != nil { - t.Errorf("ext2 in returned extensions: %T %v", exts[1], exts[1]) - } -} - -func TestGetExtensionStability(t *testing.T) { - check := func(m *pb.MyMessage) bool { - ext1, err := proto.GetExtension(m, pb.E_Ext_More) - if err != nil { - t.Fatalf("GetExtension() failed: %s", err) - } - ext2, err := proto.GetExtension(m, pb.E_Ext_More) - if err != nil { - t.Fatalf("GetExtension() failed: %s", err) - } - return ext1 == ext2 - } - msg := &pb.MyMessage{Count: proto.Int32(4)} - ext0 := &pb.Ext{} - if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil { - t.Fatalf("Could not set ext1: %s", ext0) - } - if !check(msg) { - t.Errorf("GetExtension() not stable before marshaling") - } - bb, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("Marshal() failed: %s", err) - } - msg1 := &pb.MyMessage{} - err = proto.Unmarshal(bb, msg1) - if err != nil { - t.Fatalf("Unmarshal() failed: %s", err) - } - if !check(msg1) { - t.Errorf("GetExtension() not stable after unmarshaling") - } -} - -func TestGetExtensionDefaults(t *testing.T) { - var setFloat64 float64 = 1 - var setFloat32 float32 = 2 - var setInt32 int32 = 3 - var setInt64 int64 = 4 - var setUint32 uint32 = 5 - var setUint64 uint64 = 6 - var setBool = true - var setBool2 = false - var setString = "Goodnight string" - var setBytes = []byte("Goodnight bytes") - var setEnum = pb.DefaultsMessage_TWO - - type testcase struct { - ext *proto.ExtensionDesc // Extension we are testing. - want interface{} // Expected value of extension, or nil (meaning that GetExtension will fail). - def interface{} // Expected value of extension after ClearExtension(). - } - tests := []testcase{ - {pb.E_NoDefaultDouble, setFloat64, nil}, - {pb.E_NoDefaultFloat, setFloat32, nil}, - {pb.E_NoDefaultInt32, setInt32, nil}, - {pb.E_NoDefaultInt64, setInt64, nil}, - {pb.E_NoDefaultUint32, setUint32, nil}, - {pb.E_NoDefaultUint64, setUint64, nil}, - {pb.E_NoDefaultSint32, setInt32, nil}, - {pb.E_NoDefaultSint64, setInt64, nil}, - {pb.E_NoDefaultFixed32, setUint32, nil}, - {pb.E_NoDefaultFixed64, setUint64, nil}, - {pb.E_NoDefaultSfixed32, setInt32, nil}, - {pb.E_NoDefaultSfixed64, setInt64, nil}, - {pb.E_NoDefaultBool, setBool, nil}, - {pb.E_NoDefaultBool, setBool2, nil}, - {pb.E_NoDefaultString, setString, nil}, - {pb.E_NoDefaultBytes, setBytes, nil}, - {pb.E_NoDefaultEnum, setEnum, nil}, - {pb.E_DefaultDouble, setFloat64, float64(3.1415)}, - {pb.E_DefaultFloat, setFloat32, float32(3.14)}, - {pb.E_DefaultInt32, setInt32, int32(42)}, - {pb.E_DefaultInt64, setInt64, int64(43)}, - {pb.E_DefaultUint32, setUint32, uint32(44)}, - {pb.E_DefaultUint64, setUint64, uint64(45)}, - {pb.E_DefaultSint32, setInt32, int32(46)}, - {pb.E_DefaultSint64, setInt64, int64(47)}, - {pb.E_DefaultFixed32, setUint32, uint32(48)}, - {pb.E_DefaultFixed64, setUint64, uint64(49)}, - {pb.E_DefaultSfixed32, setInt32, int32(50)}, - {pb.E_DefaultSfixed64, setInt64, int64(51)}, - {pb.E_DefaultBool, setBool, true}, - {pb.E_DefaultBool, setBool2, true}, - {pb.E_DefaultString, setString, "Hello, string"}, - {pb.E_DefaultBytes, setBytes, []byte("Hello, bytes")}, - {pb.E_DefaultEnum, setEnum, pb.DefaultsMessage_ONE}, - } - - checkVal := func(test testcase, msg *pb.DefaultsMessage, valWant interface{}) error { - val, err := proto.GetExtension(msg, test.ext) - if err != nil { - if valWant != nil { - return fmt.Errorf("GetExtension(): %s", err) - } - if want := proto.ErrMissingExtension; err != want { - return fmt.Errorf("Unexpected error: got %v, want %v", err, want) - } - return nil - } - - // All proto2 extension values are either a pointer to a value or a slice of values. - ty := reflect.TypeOf(val) - tyWant := reflect.TypeOf(test.ext.ExtensionType) - if got, want := ty, tyWant; got != want { - return fmt.Errorf("unexpected reflect.TypeOf(): got %v want %v", got, want) - } - tye := ty.Elem() - tyeWant := tyWant.Elem() - if got, want := tye, tyeWant; got != want { - return fmt.Errorf("unexpected reflect.TypeOf().Elem(): got %v want %v", got, want) - } - - // Check the name of the type of the value. - // If it is an enum it will be type int32 with the name of the enum. - if got, want := tye.Name(), tye.Name(); got != want { - return fmt.Errorf("unexpected reflect.TypeOf().Elem().Name(): got %v want %v", got, want) - } - - // Check that value is what we expect. - // If we have a pointer in val, get the value it points to. - valExp := val - if ty.Kind() == reflect.Ptr { - valExp = reflect.ValueOf(val).Elem().Interface() - } - if got, want := valExp, valWant; !reflect.DeepEqual(got, want) { - return fmt.Errorf("unexpected reflect.DeepEqual(): got %v want %v", got, want) - } - - return nil - } - - setTo := func(test testcase) interface{} { - setTo := reflect.ValueOf(test.want) - if typ := reflect.TypeOf(test.ext.ExtensionType); typ.Kind() == reflect.Ptr { - setTo = reflect.New(typ).Elem() - setTo.Set(reflect.New(setTo.Type().Elem())) - setTo.Elem().Set(reflect.ValueOf(test.want)) - } - return setTo.Interface() - } - - for _, test := range tests { - msg := &pb.DefaultsMessage{} - name := test.ext.Name - - // Check the initial value. - if err := checkVal(test, msg, test.def); err != nil { - t.Errorf("%s: %v", name, err) - } - - // Set the per-type value and check value. - name = fmt.Sprintf("%s (set to %T %v)", name, test.want, test.want) - if err := proto.SetExtension(msg, test.ext, setTo(test)); err != nil { - t.Errorf("%s: SetExtension(): %v", name, err) - continue - } - if err := checkVal(test, msg, test.want); err != nil { - t.Errorf("%s: %v", name, err) - continue - } - - // Set and check the value. - name += " (cleared)" - proto.ClearExtension(msg, test.ext) - if err := checkVal(test, msg, test.def); err != nil { - t.Errorf("%s: %v", name, err) - } - } -} - -func TestExtensionsRoundTrip(t *testing.T) { - msg := &pb.MyMessage{} - ext1 := &pb.Ext{ - Data: proto.String("hi"), - } - ext2 := &pb.Ext{ - Data: proto.String("there"), - } - exists := proto.HasExtension(msg, pb.E_Ext_More) - if exists { - t.Error("Extension More present unexpectedly") - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { - t.Error(err) - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil { - t.Error(err) - } - e, err := proto.GetExtension(msg, pb.E_Ext_More) - if err != nil { - t.Error(err) - } - x, ok := e.(*pb.Ext) - if !ok { - t.Errorf("e has type %T, expected testdata.Ext", e) - } else if *x.Data != "there" { - t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x) - } - proto.ClearExtension(msg, pb.E_Ext_More) - if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension { - t.Errorf("got %v, expected ErrMissingExtension", e) - } - if _, err := proto.GetExtension(msg, pb.E_X215); err == nil { - t.Error("expected bad extension error, got nil") - } - if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil { - t.Error("expected extension err") - } - if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil { - t.Error("expected some sort of type mismatch error, got nil") - } -} - -func TestNilExtension(t *testing.T) { - msg := &pb.MyMessage{ - Count: proto.Int32(1), - } - if err := proto.SetExtension(msg, pb.E_Ext_Text, proto.String("hello")); err != nil { - t.Fatal(err) - } - if err := proto.SetExtension(msg, pb.E_Ext_More, (*pb.Ext)(nil)); err == nil { - t.Error("expected SetExtension to fail due to a nil extension") - } else if want := "proto: SetExtension called with nil value of type *testdata.Ext"; err.Error() != want { - t.Errorf("expected error %v, got %v", want, err) - } - // Note: if the behavior of Marshal is ever changed to ignore nil extensions, update - // this test to verify that E_Ext_Text is properly propagated through marshal->unmarshal. -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go deleted file mode 100644 index 0b28b08..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go +++ /dev/null @@ -1,813 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package proto converts data structures to and from the wire format of -protocol buffers. It works in concert with the Go source code generated -for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed by the enclosing message's name, or by the - enum's type name if it is a top-level enum. Enum types have a String - method, and a Enum method to assist in message construction. - - Nested messages, groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -The simplest way to describe this is to see an example. -Given file test.proto, containing - - package example; - - enum FOO { X = 17; } - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - } - -The resulting file, test.pb.go, is: - - package example - - import proto "github.com/golang/protobuf/proto" - import math "math" - - type FOO int32 - const ( - FOO_X FOO = 17 - ) - var FOO_name = map[int32]string{ - 17: "X", - } - var FOO_value = map[string]int32{ - "X": 17, - } - - func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p - } - func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) - } - func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data) - if err != nil { - return err - } - *x = FOO(value) - return nil - } - - type Test struct { - Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` - Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` - Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` - Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` - } - func (m *Test) Reset() { *m = Test{} } - func (m *Test) String() string { return proto.CompactTextString(m) } - func (*Test) ProtoMessage() {} - const Default_Test_Type int32 = 77 - - func (m *Test) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" - } - - func (m *Test) GetType() int32 { - if m != nil && m.Type != nil { - return *m.Type - } - return Default_Test_Type - } - - func (m *Test) GetOptionalgroup() *Test_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil - } - - type Test_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` - } - func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } - func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } - - func (m *Test_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" - } - - func init() { - proto.RegisterEnum("example.FOO", FOO_name, FOO_value) - } - -To create and play with a Test object: - -package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - pb "./example.pb" - ) - - func main() { - test := &pb.Test{ - Label: proto.String("hello"), - Type: proto.Int32(17), - Optionalgroup: &pb.Test_OptionalGroup{ - RequiredField: proto.String("good bye"), - }, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &pb.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // etc. - } -*/ -package proto - -import ( - "encoding/json" - "fmt" - "log" - "reflect" - "strconv" - "sync" -) - -// Message is implemented by generated protocol buffer messages. -type Message interface { - Reset() - String() string - ProtoMessage() -} - -// Stats records allocation details about the protocol buffer encoders -// and decoders. Useful for tuning the library itself. -type Stats struct { - Emalloc uint64 // mallocs in encode - Dmalloc uint64 // mallocs in decode - Encode uint64 // number of encodes - Decode uint64 // number of decodes - Chit uint64 // number of cache hits - Cmiss uint64 // number of cache misses - Size uint64 // number of sizes -} - -// Set to true to enable stats collection. -const collectStats = false - -var stats Stats - -// GetStats returns a copy of the global Stats structure. -func GetStats() Stats { return stats } - -// A Buffer is a buffer manager for marshaling and unmarshaling -// protocol buffers. It may be reused between invocations to -// reduce memory usage. It is not necessary to use a Buffer; -// the global functions Marshal and Unmarshal create a -// temporary Buffer and are fine for most applications. -type Buffer struct { - buf []byte // encode/decode byte stream - index int // write point - - // pools of basic types to amortize allocation. - bools []bool - uint32s []uint32 - uint64s []uint64 - - // extra pools, only used with pointer_reflect.go - int32s []int32 - int64s []int64 - float32s []float32 - float64s []float64 -} - -// NewBuffer allocates a new Buffer and initializes its internal data to -// the contents of the argument slice. -func NewBuffer(e []byte) *Buffer { - return &Buffer{buf: e} -} - -// Reset resets the Buffer, ready for marshaling a new protocol buffer. -func (p *Buffer) Reset() { - p.buf = p.buf[0:0] // for reading/writing - p.index = 0 // for reading -} - -// SetBuf replaces the internal buffer with the slice, -// ready for unmarshaling the contents of the slice. -func (p *Buffer) SetBuf(s []byte) { - p.buf = s - p.index = 0 -} - -// Bytes returns the contents of the Buffer. -func (p *Buffer) Bytes() []byte { return p.buf } - -/* - * Helper routines for simplifying the creation of optional fields of basic type. - */ - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { - return &v -} - -// Int32 is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it. -func Int32(v int32) *int32 { - return &v -} - -// Int is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it, but unlike Int32 -// its argument value is an int. -func Int(v int) *int32 { - p := new(int32) - *p = int32(v) - return p -} - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { - return &v -} - -// Float32 is a helper routine that allocates a new float32 value -// to store v and returns a pointer to it. -func Float32(v float32) *float32 { - return &v -} - -// Float64 is a helper routine that allocates a new float64 value -// to store v and returns a pointer to it. -func Float64(v float64) *float64 { - return &v -} - -// Uint32 is a helper routine that allocates a new uint32 value -// to store v and returns a pointer to it. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint64 is a helper routine that allocates a new uint64 value -// to store v and returns a pointer to it. -func Uint64(v uint64) *uint64 { - return &v -} - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { - return &v -} - -// EnumName is a helper function to simplify printing protocol buffer enums -// by name. Given an enum map and a value, it returns a useful string. -func EnumName(m map[int32]string, v int32) string { - s, ok := m[v] - if ok { - return s - } - return strconv.Itoa(int(v)) -} - -// UnmarshalJSONEnum is a helper function to simplify recovering enum int values -// from their JSON-encoded representation. Given a map from the enum's symbolic -// names to its int values, and a byte buffer containing the JSON-encoded -// value, it returns an int32 that can be cast to the enum type by the caller. -// -// The function can deal with both JSON representations, numeric and symbolic. -func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { - if data[0] == '"' { - // New style: enums are strings. - var repr string - if err := json.Unmarshal(data, &repr); err != nil { - return -1, err - } - val, ok := m[repr] - if !ok { - return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) - } - return val, nil - } - // Old style: enums are ints. - var val int32 - if err := json.Unmarshal(data, &val); err != nil { - return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) - } - return val, nil -} - -// DebugPrint dumps the encoded data in b in a debugging format with a header -// including the string s. Used in testing but made available for general debugging. -func (p *Buffer) DebugPrint(s string, b []byte) { - var u uint64 - - obuf := p.buf - index := p.index - p.buf = b - p.index = 0 - depth := 0 - - fmt.Printf("\n--- %s ---\n", s) - -out: - for { - for i := 0; i < depth; i++ { - fmt.Print(" ") - } - - index := p.index - if index == len(p.buf) { - break - } - - op, err := p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: fetching op err %v\n", index, err) - break out - } - tag := op >> 3 - wire := op & 7 - - switch wire { - default: - fmt.Printf("%3d: t=%3d unknown wire=%d\n", - index, tag, wire) - break out - - case WireBytes: - var r []byte - - r, err = p.DecodeRawBytes(false) - if err != nil { - break out - } - fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) - if len(r) <= 6 { - for i := 0; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } else { - for i := 0; i < 3; i++ { - fmt.Printf(" %.2x", r[i]) - } - fmt.Printf(" ..") - for i := len(r) - 3; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } - fmt.Printf("\n") - - case WireFixed32: - u, err = p.DecodeFixed32() - if err != nil { - fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) - - case WireFixed64: - u, err = p.DecodeFixed64() - if err != nil { - fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) - break - - case WireVarint: - u, err = p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) - - case WireStartGroup: - if err != nil { - fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d start\n", index, tag) - depth++ - - case WireEndGroup: - depth-- - if err != nil { - fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d end\n", index, tag) - } - } - - if depth != 0 { - fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) - } - fmt.Printf("\n") - - p.buf = obuf - p.index = index -} - -// SetDefaults sets unset protocol buffer fields to their default values. -// It only modifies fields that are both unset and have defined defaults. -// It recursively sets default values in any non-nil sub-messages. -func SetDefaults(pb Message) { - setDefaults(reflect.ValueOf(pb), true, false) -} - -// v is a pointer to a struct. -func setDefaults(v reflect.Value, recur, zeros bool) { - v = v.Elem() - - defaultMu.RLock() - dm, ok := defaults[v.Type()] - defaultMu.RUnlock() - if !ok { - dm = buildDefaultMessage(v.Type()) - defaultMu.Lock() - defaults[v.Type()] = dm - defaultMu.Unlock() - } - - for _, sf := range dm.scalars { - f := v.Field(sf.index) - if !f.IsNil() { - // field already set - continue - } - dv := sf.value - if dv == nil && !zeros { - // no explicit default, and don't want to set zeros - continue - } - fptr := f.Addr().Interface() // **T - // TODO: Consider batching the allocations we do here. - switch sf.kind { - case reflect.Bool: - b := new(bool) - if dv != nil { - *b = dv.(bool) - } - *(fptr.(**bool)) = b - case reflect.Float32: - f := new(float32) - if dv != nil { - *f = dv.(float32) - } - *(fptr.(**float32)) = f - case reflect.Float64: - f := new(float64) - if dv != nil { - *f = dv.(float64) - } - *(fptr.(**float64)) = f - case reflect.Int32: - // might be an enum - if ft := f.Type(); ft != int32PtrType { - // enum - f.Set(reflect.New(ft.Elem())) - if dv != nil { - f.Elem().SetInt(int64(dv.(int32))) - } - } else { - // int32 field - i := new(int32) - if dv != nil { - *i = dv.(int32) - } - *(fptr.(**int32)) = i - } - case reflect.Int64: - i := new(int64) - if dv != nil { - *i = dv.(int64) - } - *(fptr.(**int64)) = i - case reflect.String: - s := new(string) - if dv != nil { - *s = dv.(string) - } - *(fptr.(**string)) = s - case reflect.Uint8: - // exceptional case: []byte - var b []byte - if dv != nil { - db := dv.([]byte) - b = make([]byte, len(db)) - copy(b, db) - } else { - b = []byte{} - } - *(fptr.(*[]byte)) = b - case reflect.Uint32: - u := new(uint32) - if dv != nil { - *u = dv.(uint32) - } - *(fptr.(**uint32)) = u - case reflect.Uint64: - u := new(uint64) - if dv != nil { - *u = dv.(uint64) - } - *(fptr.(**uint64)) = u - default: - log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) - } - } - - for _, ni := range dm.nested { - f := v.Field(ni) - // f is *T or []*T or map[T]*T - switch f.Kind() { - case reflect.Ptr: - if f.IsNil() { - continue - } - setDefaults(f, recur, zeros) - - case reflect.Slice: - for i := 0; i < f.Len(); i++ { - e := f.Index(i) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - - case reflect.Map: - for _, k := range f.MapKeys() { - e := f.MapIndex(k) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - } - } -} - -var ( - // defaults maps a protocol buffer struct type to a slice of the fields, - // with its scalar fields set to their proto-declared non-zero default values. - defaultMu sync.RWMutex - defaults = make(map[reflect.Type]defaultMessage) - - int32PtrType = reflect.TypeOf((*int32)(nil)) -) - -// defaultMessage represents information about the default values of a message. -type defaultMessage struct { - scalars []scalarField - nested []int // struct field index of nested messages -} - -type scalarField struct { - index int // struct field index - kind reflect.Kind // element type (the T in *T or []T) - value interface{} // the proto-declared default value, or nil -} - -// t is a struct type. -func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { - sprop := GetProperties(t) - for _, prop := range sprop.Prop { - fi, ok := sprop.decoderTags.get(prop.Tag) - if !ok { - // XXX_unrecognized - continue - } - ft := t.Field(fi).Type - - sf, nested, err := fieldDefault(ft, prop) - switch { - case err != nil: - log.Print(err) - case nested: - dm.nested = append(dm.nested, fi) - case sf != nil: - sf.index = fi - dm.scalars = append(dm.scalars, *sf) - } - } - - return dm -} - -// fieldDefault returns the scalarField for field type ft. -// sf will be nil if the field can not have a default. -// nestedMessage will be true if this is a nested message. -// Note that sf.index is not set on return. -func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { - var canHaveDefault bool - switch ft.Kind() { - case reflect.Ptr: - if ft.Elem().Kind() == reflect.Struct { - nestedMessage = true - } else { - canHaveDefault = true // proto2 scalar field - } - - case reflect.Slice: - switch ft.Elem().Kind() { - case reflect.Ptr: - nestedMessage = true // repeated message - case reflect.Uint8: - canHaveDefault = true // bytes field - } - - case reflect.Map: - if ft.Elem().Kind() == reflect.Ptr { - nestedMessage = true // map with message values - } - } - - if !canHaveDefault { - if nestedMessage { - return nil, true, nil - } - return nil, false, nil - } - - // We now know that ft is a pointer or slice. - sf = &scalarField{kind: ft.Elem().Kind()} - - // scalar fields without defaults - if !prop.HasDefault { - return sf, false, nil - } - - // a scalar field: either *T or []byte - switch ft.Elem().Kind() { - case reflect.Bool: - x, err := strconv.ParseBool(prop.Default) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Float32: - x, err := strconv.ParseFloat(prop.Default, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) - } - sf.value = float32(x) - case reflect.Float64: - x, err := strconv.ParseFloat(prop.Default, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Int32: - x, err := strconv.ParseInt(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) - } - sf.value = int32(x) - case reflect.Int64: - x, err := strconv.ParseInt(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.String: - sf.value = prop.Default - case reflect.Uint8: - // []byte (not *uint8) - sf.value = []byte(prop.Default) - case reflect.Uint32: - x, err := strconv.ParseUint(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) - } - sf.value = uint32(x) - case reflect.Uint64: - x, err := strconv.ParseUint(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) - } - sf.value = x - default: - return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) - } - - return sf, false, nil -} - -// Map fields may have key types of non-float scalars, strings and enums. -// The easiest way to sort them in some deterministic order is to use fmt. -// If this turns out to be inefficient we can always consider other options, -// such as doing a Schwartzian transform. - -type mapKeys []reflect.Value - -func (s mapKeys) Len() int { return len(s) } -func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s mapKeys) Less(i, j int) bool { - return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) -} - -// isProto3Zero reports whether v is a zero proto3 value. -func isProto3Zero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return !v.Bool() - case reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint32, reflect.Uint64: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.String: - return v.String() == "" - } - return false -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go deleted file mode 100644 index 9d912bc..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go +++ /dev/null @@ -1,287 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Support for message sets. - */ - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "reflect" - "sort" -) - -// ErrNoMessageTypeId occurs when a protocol buffer does not have a message type ID. -// A message type ID is required for storing a protocol buffer in a message set. -var ErrNoMessageTypeId = errors.New("proto does not have a message type ID") - -// The first two types (_MessageSet_Item and MessageSet) -// model what the protocol compiler produces for the following protocol message: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } -// That is the MessageSet wire format. We can't use a proto to generate these -// because that would introduce a circular dependency between it and this package. -// -// When a proto1 proto has a field that looks like: -// optional message info = 3; -// the protocol compiler produces a field in the generated struct that looks like: -// Info *_proto_.MessageSet `protobuf:"bytes,3,opt,name=info"` -// The package is automatically inserted so there is no need for that proto file to -// import this package. - -type _MessageSet_Item struct { - TypeId *int32 `protobuf:"varint,2,req,name=type_id"` - Message []byte `protobuf:"bytes,3,req,name=message"` -} - -type MessageSet struct { - Item []*_MessageSet_Item `protobuf:"group,1,rep"` - XXX_unrecognized []byte - // TODO: caching? -} - -// Make sure MessageSet is a Message. -var _ Message = (*MessageSet)(nil) - -// messageTypeIder is an interface satisfied by a protocol buffer type -// that may be stored in a MessageSet. -type messageTypeIder interface { - MessageTypeId() int32 -} - -func (ms *MessageSet) find(pb Message) *_MessageSet_Item { - mti, ok := pb.(messageTypeIder) - if !ok { - return nil - } - id := mti.MessageTypeId() - for _, item := range ms.Item { - if *item.TypeId == id { - return item - } - } - return nil -} - -func (ms *MessageSet) Has(pb Message) bool { - if ms.find(pb) != nil { - return true - } - return false -} - -func (ms *MessageSet) Unmarshal(pb Message) error { - if item := ms.find(pb); item != nil { - return Unmarshal(item.Message, pb) - } - if _, ok := pb.(messageTypeIder); !ok { - return ErrNoMessageTypeId - } - return nil // TODO: return error instead? -} - -func (ms *MessageSet) Marshal(pb Message) error { - msg, err := Marshal(pb) - if err != nil { - return err - } - if item := ms.find(pb); item != nil { - // reuse existing item - item.Message = msg - return nil - } - - mti, ok := pb.(messageTypeIder) - if !ok { - return ErrNoMessageTypeId - } - - mtid := mti.MessageTypeId() - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: &mtid, - Message: msg, - }) - return nil -} - -func (ms *MessageSet) Reset() { *ms = MessageSet{} } -func (ms *MessageSet) String() string { return CompactTextString(ms) } -func (*MessageSet) ProtoMessage() {} - -// Support for the message_set_wire_format message option. - -func skipVarint(buf []byte) []byte { - i := 0 - for ; buf[i]&0x80 != 0; i++ { - } - return buf[i+1:] -} - -// MarshalMessageSet encodes the extension map represented by m in the message set wire format. -// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSet(m map[int32]Extension) ([]byte, error) { - if err := encodeExtensionMap(m); err != nil { - return nil, err - } - - // Sort extension IDs to provide a deterministic encoding. - // See also enc_map in encode.go. - ids := make([]int, 0, len(m)) - for id := range m { - ids = append(ids, int(id)) - } - sort.Ints(ids) - - ms := &MessageSet{Item: make([]*_MessageSet_Item, 0, len(m))} - for _, id := range ids { - e := m[int32(id)] - // Remove the wire type and field number varint, as well as the length varint. - msg := skipVarint(skipVarint(e.enc)) - - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: Int32(int32(id)), - Message: msg, - }) - } - return Marshal(ms) -} - -// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. -// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error { - ms := new(MessageSet) - if err := Unmarshal(buf, ms); err != nil { - return err - } - for _, item := range ms.Item { - id := *item.TypeId - msg := item.Message - - // Restore wire type and field number varint, plus length varint. - // Be careful to preserve duplicate items. - b := EncodeVarint(uint64(id)<<3 | WireBytes) - if ext, ok := m[id]; ok { - // Existing data; rip off the tag and length varint - // so we join the new data correctly. - // We can assume that ext.enc is set because we are unmarshaling. - o := ext.enc[len(b):] // skip wire type and field number - _, n := DecodeVarint(o) // calculate length of length varint - o = o[n:] // skip length varint - msg = append(o, msg...) // join old data and new data - } - b = append(b, EncodeVarint(uint64(len(msg)))...) - b = append(b, msg...) - - m[id] = Extension{enc: b} - } - return nil -} - -// MarshalMessageSetJSON encodes the extension map represented by m in JSON format. -// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSetJSON(m map[int32]Extension) ([]byte, error) { - var b bytes.Buffer - b.WriteByte('{') - - // Process the map in key order for deterministic output. - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) // int32Slice defined in text.go - - for i, id := range ids { - ext := m[id] - if i > 0 { - b.WriteByte(',') - } - - msd, ok := messageSetMap[id] - if !ok { - // Unknown type; we can't render it, so skip it. - continue - } - fmt.Fprintf(&b, `"[%s]":`, msd.name) - - x := ext.value - if x == nil { - x = reflect.New(msd.t.Elem()).Interface() - if err := Unmarshal(ext.enc, x.(Message)); err != nil { - return nil, err - } - } - d, err := json.Marshal(x) - if err != nil { - return nil, err - } - b.Write(d) - } - b.WriteByte('}') - return b.Bytes(), nil -} - -// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. -// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSetJSON(buf []byte, m map[int32]Extension) error { - // Common-case fast path. - if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { - return nil - } - - // This is fairly tricky, and it's not clear that it is needed. - return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") -} - -// A global registry of types that can be used in a MessageSet. - -var messageSetMap = make(map[int32]messageSetDesc) - -type messageSetDesc struct { - t reflect.Type // pointer to struct - name string -} - -// RegisterMessageSetType is called from the generated code. -func RegisterMessageSetType(m Message, fieldNum int32, name string) { - messageSetMap[fieldNum] = messageSetDesc{ - t: reflect.TypeOf(m), - name: name, - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go deleted file mode 100644 index 7c29bcc..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &MessageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - m := make(map[int32]Extension) - if err := UnmarshalMessageSet(b, m); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := m[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", m) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go deleted file mode 100644 index 749919d..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go +++ /dev/null @@ -1,479 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build appengine - -// This file contains an implementation of proto field accesses using package reflect. -// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can -// be used on App Engine. - -package proto - -import ( - "math" - "reflect" -) - -// A structPointer is a pointer to a struct. -type structPointer struct { - v reflect.Value -} - -// toStructPointer returns a structPointer equivalent to the given reflect value. -// The reflect value must itself be a pointer to a struct. -func toStructPointer(v reflect.Value) structPointer { - return structPointer{v} -} - -// IsNil reports whether p is nil. -func structPointer_IsNil(p structPointer) bool { - return p.v.IsNil() -} - -// Interface returns the struct pointer as an interface value. -func structPointer_Interface(p structPointer, _ reflect.Type) interface{} { - return p.v.Interface() -} - -// A field identifies a field in a struct, accessible from a structPointer. -// In this implementation, a field is identified by the sequence of field indices -// passed to reflect's FieldByIndex. -type field []int - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return f.Index -} - -// invalidField is an invalid field identifier. -var invalidField = field(nil) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { return f != nil } - -// field returns the given field in the struct as a reflect value. -func structPointer_field(p structPointer, f field) reflect.Value { - // Special case: an extension map entry with a value of type T - // passes a *T to the struct-handling code with a zero field, - // expecting that it will be treated as equivalent to *struct{ X T }, - // which has the same memory layout. We have to handle that case - // specially, because reflect will panic if we call FieldByIndex on a - // non-struct. - if f == nil { - return p.v.Elem() - } - - return p.v.Elem().FieldByIndex(f) -} - -// ifield returns the given field in the struct as an interface value. -func structPointer_ifield(p structPointer, f field) interface{} { - return structPointer_field(p, f).Addr().Interface() -} - -// Bytes returns the address of a []byte field in the struct. -func structPointer_Bytes(p structPointer, f field) *[]byte { - return structPointer_ifield(p, f).(*[]byte) -} - -// BytesSlice returns the address of a [][]byte field in the struct. -func structPointer_BytesSlice(p structPointer, f field) *[][]byte { - return structPointer_ifield(p, f).(*[][]byte) -} - -// Bool returns the address of a *bool field in the struct. -func structPointer_Bool(p structPointer, f field) **bool { - return structPointer_ifield(p, f).(**bool) -} - -// BoolVal returns the address of a bool field in the struct. -func structPointer_BoolVal(p structPointer, f field) *bool { - return structPointer_ifield(p, f).(*bool) -} - -// BoolSlice returns the address of a []bool field in the struct. -func structPointer_BoolSlice(p structPointer, f field) *[]bool { - return structPointer_ifield(p, f).(*[]bool) -} - -// String returns the address of a *string field in the struct. -func structPointer_String(p structPointer, f field) **string { - return structPointer_ifield(p, f).(**string) -} - -// StringVal returns the address of a string field in the struct. -func structPointer_StringVal(p structPointer, f field) *string { - return structPointer_ifield(p, f).(*string) -} - -// StringSlice returns the address of a []string field in the struct. -func structPointer_StringSlice(p structPointer, f field) *[]string { - return structPointer_ifield(p, f).(*[]string) -} - -// ExtMap returns the address of an extension map field in the struct. -func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { - return structPointer_ifield(p, f).(*map[int32]Extension) -} - -// NewAt returns the reflect.Value for a pointer to a field in the struct. -func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { - return structPointer_field(p, f).Addr() -} - -// SetStructPointer writes a *struct field in the struct. -func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { - structPointer_field(p, f).Set(q.v) -} - -// GetStructPointer reads a *struct field in the struct. -func structPointer_GetStructPointer(p structPointer, f field) structPointer { - return structPointer{structPointer_field(p, f)} -} - -// StructPointerSlice the address of a []*struct field in the struct. -func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice { - return structPointerSlice{structPointer_field(p, f)} -} - -// A structPointerSlice represents the address of a slice of pointers to structs -// (themselves messages or groups). That is, v.Type() is *[]*struct{...}. -type structPointerSlice struct { - v reflect.Value -} - -func (p structPointerSlice) Len() int { return p.v.Len() } -func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} } -func (p structPointerSlice) Append(q structPointer) { - p.v.Set(reflect.Append(p.v, q.v)) -} - -var ( - int32Type = reflect.TypeOf(int32(0)) - uint32Type = reflect.TypeOf(uint32(0)) - float32Type = reflect.TypeOf(float32(0)) - int64Type = reflect.TypeOf(int64(0)) - uint64Type = reflect.TypeOf(uint64(0)) - float64Type = reflect.TypeOf(float64(0)) -) - -// A word32 represents a field of type *int32, *uint32, *float32, or *enum. -// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable. -type word32 struct { - v reflect.Value -} - -// IsNil reports whether p is nil. -func word32_IsNil(p word32) bool { - return p.v.IsNil() -} - -// Set sets p to point at a newly allocated word with bits set to x. -func word32_Set(p word32, o *Buffer, x uint32) { - t := p.v.Type().Elem() - switch t { - case int32Type: - if len(o.int32s) == 0 { - o.int32s = make([]int32, uint32PoolSize) - } - o.int32s[0] = int32(x) - p.v.Set(reflect.ValueOf(&o.int32s[0])) - o.int32s = o.int32s[1:] - return - case uint32Type: - if len(o.uint32s) == 0 { - o.uint32s = make([]uint32, uint32PoolSize) - } - o.uint32s[0] = x - p.v.Set(reflect.ValueOf(&o.uint32s[0])) - o.uint32s = o.uint32s[1:] - return - case float32Type: - if len(o.float32s) == 0 { - o.float32s = make([]float32, uint32PoolSize) - } - o.float32s[0] = math.Float32frombits(x) - p.v.Set(reflect.ValueOf(&o.float32s[0])) - o.float32s = o.float32s[1:] - return - } - - // must be enum - p.v.Set(reflect.New(t)) - p.v.Elem().SetInt(int64(int32(x))) -} - -// Get gets the bits pointed at by p, as a uint32. -func word32_Get(p word32) uint32 { - elem := p.v.Elem() - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") -} - -// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32(p structPointer, f field) word32 { - return word32{structPointer_field(p, f)} -} - -// A word32Val represents a field of type int32, uint32, float32, or enum. -// That is, v.Type() is int32, uint32, float32, or enum and v is assignable. -type word32Val struct { - v reflect.Value -} - -// Set sets *p to x. -func word32Val_Set(p word32Val, x uint32) { - switch p.v.Type() { - case int32Type: - p.v.SetInt(int64(x)) - return - case uint32Type: - p.v.SetUint(uint64(x)) - return - case float32Type: - p.v.SetFloat(float64(math.Float32frombits(x))) - return - } - - // must be enum - p.v.SetInt(int64(int32(x))) -} - -// Get gets the bits pointed at by p, as a uint32. -func word32Val_Get(p word32Val) uint32 { - elem := p.v - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") -} - -// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct. -func structPointer_Word32Val(p structPointer, f field) word32Val { - return word32Val{structPointer_field(p, f)} -} - -// A word32Slice is a slice of 32-bit values. -// That is, v.Type() is []int32, []uint32, []float32, or []enum. -type word32Slice struct { - v reflect.Value -} - -func (p word32Slice) Append(x uint32) { - n, m := p.v.Len(), p.v.Cap() - if n < m { - p.v.SetLen(n + 1) - } else { - t := p.v.Type().Elem() - p.v.Set(reflect.Append(p.v, reflect.Zero(t))) - } - elem := p.v.Index(n) - switch elem.Kind() { - case reflect.Int32: - elem.SetInt(int64(int32(x))) - case reflect.Uint32: - elem.SetUint(uint64(x)) - case reflect.Float32: - elem.SetFloat(float64(math.Float32frombits(x))) - } -} - -func (p word32Slice) Len() int { - return p.v.Len() -} - -func (p word32Slice) Index(i int) uint32 { - elem := p.v.Index(i) - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") -} - -// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct. -func structPointer_Word32Slice(p structPointer, f field) word32Slice { - return word32Slice{structPointer_field(p, f)} -} - -// word64 is like word32 but for 64-bit values. -type word64 struct { - v reflect.Value -} - -func word64_Set(p word64, o *Buffer, x uint64) { - t := p.v.Type().Elem() - switch t { - case int64Type: - if len(o.int64s) == 0 { - o.int64s = make([]int64, uint64PoolSize) - } - o.int64s[0] = int64(x) - p.v.Set(reflect.ValueOf(&o.int64s[0])) - o.int64s = o.int64s[1:] - return - case uint64Type: - if len(o.uint64s) == 0 { - o.uint64s = make([]uint64, uint64PoolSize) - } - o.uint64s[0] = x - p.v.Set(reflect.ValueOf(&o.uint64s[0])) - o.uint64s = o.uint64s[1:] - return - case float64Type: - if len(o.float64s) == 0 { - o.float64s = make([]float64, uint64PoolSize) - } - o.float64s[0] = math.Float64frombits(x) - p.v.Set(reflect.ValueOf(&o.float64s[0])) - o.float64s = o.float64s[1:] - return - } - panic("unreachable") -} - -func word64_IsNil(p word64) bool { - return p.v.IsNil() -} - -func word64_Get(p word64) uint64 { - elem := p.v.Elem() - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return elem.Uint() - case reflect.Float64: - return math.Float64bits(elem.Float()) - } - panic("unreachable") -} - -func structPointer_Word64(p structPointer, f field) word64 { - return word64{structPointer_field(p, f)} -} - -// word64Val is like word32Val but for 64-bit values. -type word64Val struct { - v reflect.Value -} - -func word64Val_Set(p word64Val, o *Buffer, x uint64) { - switch p.v.Type() { - case int64Type: - p.v.SetInt(int64(x)) - return - case uint64Type: - p.v.SetUint(x) - return - case float64Type: - p.v.SetFloat(math.Float64frombits(x)) - return - } - panic("unreachable") -} - -func word64Val_Get(p word64Val) uint64 { - elem := p.v - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return elem.Uint() - case reflect.Float64: - return math.Float64bits(elem.Float()) - } - panic("unreachable") -} - -func structPointer_Word64Val(p structPointer, f field) word64Val { - return word64Val{structPointer_field(p, f)} -} - -type word64Slice struct { - v reflect.Value -} - -func (p word64Slice) Append(x uint64) { - n, m := p.v.Len(), p.v.Cap() - if n < m { - p.v.SetLen(n + 1) - } else { - t := p.v.Type().Elem() - p.v.Set(reflect.Append(p.v, reflect.Zero(t))) - } - elem := p.v.Index(n) - switch elem.Kind() { - case reflect.Int64: - elem.SetInt(int64(int64(x))) - case reflect.Uint64: - elem.SetUint(uint64(x)) - case reflect.Float64: - elem.SetFloat(float64(math.Float64frombits(x))) - } -} - -func (p word64Slice) Len() int { - return p.v.Len() -} - -func (p word64Slice) Index(i int) uint64 { - elem := p.v.Index(i) - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return uint64(elem.Uint()) - case reflect.Float64: - return math.Float64bits(float64(elem.Float())) - } - panic("unreachable") -} - -func structPointer_Word64Slice(p structPointer, f field) word64Slice { - return word64Slice{structPointer_field(p, f)} -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go deleted file mode 100644 index e9be0fe..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go +++ /dev/null @@ -1,266 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build !appengine - -// This file contains the implementation of the proto field accesses using package unsafe. - -package proto - -import ( - "reflect" - "unsafe" -) - -// NOTE: These type_Foo functions would more idiomatically be methods, -// but Go does not allow methods on pointer types, and we must preserve -// some pointer type for the garbage collector. We use these -// funcs with clunky names as our poor approximation to methods. -// -// An alternative would be -// type structPointer struct { p unsafe.Pointer } -// but that does not registerize as well. - -// A structPointer is a pointer to a struct. -type structPointer unsafe.Pointer - -// toStructPointer returns a structPointer equivalent to the given reflect value. -func toStructPointer(v reflect.Value) structPointer { - return structPointer(unsafe.Pointer(v.Pointer())) -} - -// IsNil reports whether p is nil. -func structPointer_IsNil(p structPointer) bool { - return p == nil -} - -// Interface returns the struct pointer, assumed to have element type t, -// as an interface value. -func structPointer_Interface(p structPointer, t reflect.Type) interface{} { - return reflect.NewAt(t, unsafe.Pointer(p)).Interface() -} - -// A field identifies a field in a struct, accessible from a structPointer. -// In this implementation, a field is identified by its byte offset from the start of the struct. -type field uintptr - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return field(f.Offset) -} - -// invalidField is an invalid field identifier. -const invalidField = ^field(0) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { - return f != ^field(0) -} - -// Bytes returns the address of a []byte field in the struct. -func structPointer_Bytes(p structPointer, f field) *[]byte { - return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// BytesSlice returns the address of a [][]byte field in the struct. -func structPointer_BytesSlice(p structPointer, f field) *[][]byte { - return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// Bool returns the address of a *bool field in the struct. -func structPointer_Bool(p structPointer, f field) **bool { - return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// BoolVal returns the address of a bool field in the struct. -func structPointer_BoolVal(p structPointer, f field) *bool { - return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// BoolSlice returns the address of a []bool field in the struct. -func structPointer_BoolSlice(p structPointer, f field) *[]bool { - return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// String returns the address of a *string field in the struct. -func structPointer_String(p structPointer, f field) **string { - return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// StringVal returns the address of a string field in the struct. -func structPointer_StringVal(p structPointer, f field) *string { - return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// StringSlice returns the address of a []string field in the struct. -func structPointer_StringSlice(p structPointer, f field) *[]string { - return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// ExtMap returns the address of an extension map field in the struct. -func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { - return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// NewAt returns the reflect.Value for a pointer to a field in the struct. -func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { - return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f))) -} - -// SetStructPointer writes a *struct field in the struct. -func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { - *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q -} - -// GetStructPointer reads a *struct field in the struct. -func structPointer_GetStructPointer(p structPointer, f field) structPointer { - return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// StructPointerSlice the address of a []*struct field in the struct. -func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice { - return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups). -type structPointerSlice []structPointer - -func (v *structPointerSlice) Len() int { return len(*v) } -func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] } -func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) } - -// A word32 is the address of a "pointer to 32-bit value" field. -type word32 **uint32 - -// IsNil reports whether *v is nil. -func word32_IsNil(p word32) bool { - return *p == nil -} - -// Set sets *v to point at a newly allocated word set to x. -func word32_Set(p word32, o *Buffer, x uint32) { - if len(o.uint32s) == 0 { - o.uint32s = make([]uint32, uint32PoolSize) - } - o.uint32s[0] = x - *p = &o.uint32s[0] - o.uint32s = o.uint32s[1:] -} - -// Get gets the value pointed at by *v. -func word32_Get(p word32) uint32 { - return **p -} - -// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32(p structPointer, f field) word32 { - return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// A word32Val is the address of a 32-bit value field. -type word32Val *uint32 - -// Set sets *p to x. -func word32Val_Set(p word32Val, x uint32) { - *p = x -} - -// Get gets the value pointed at by p. -func word32Val_Get(p word32Val) uint32 { - return *p -} - -// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32Val(p structPointer, f field) word32Val { - return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// A word32Slice is a slice of 32-bit values. -type word32Slice []uint32 - -func (v *word32Slice) Append(x uint32) { *v = append(*v, x) } -func (v *word32Slice) Len() int { return len(*v) } -func (v *word32Slice) Index(i int) uint32 { return (*v)[i] } - -// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct. -func structPointer_Word32Slice(p structPointer, f field) *word32Slice { - return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// word64 is like word32 but for 64-bit values. -type word64 **uint64 - -func word64_Set(p word64, o *Buffer, x uint64) { - if len(o.uint64s) == 0 { - o.uint64s = make([]uint64, uint64PoolSize) - } - o.uint64s[0] = x - *p = &o.uint64s[0] - o.uint64s = o.uint64s[1:] -} - -func word64_IsNil(p word64) bool { - return *p == nil -} - -func word64_Get(p word64) uint64 { - return **p -} - -func structPointer_Word64(p structPointer, f field) word64 { - return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// word64Val is like word32Val but for 64-bit values. -type word64Val *uint64 - -func word64Val_Set(p word64Val, o *Buffer, x uint64) { - *p = x -} - -func word64Val_Get(p word64Val) uint64 { - return *p -} - -func structPointer_Word64Val(p structPointer, f field) word64Val { - return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// word64Slice is like word32Slice but for 64-bit values. -type word64Slice []uint64 - -func (v *word64Slice) Append(x uint64) { *v = append(*v, x) } -func (v *word64Slice) Len() int { return len(*v) } -func (v *word64Slice) Index(i int) uint64 { return (*v)[i] } - -func structPointer_Word64Slice(p structPointer, f field) *word64Slice { - return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go deleted file mode 100644 index d74844a..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go +++ /dev/null @@ -1,742 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "fmt" - "os" - "reflect" - "sort" - "strconv" - "strings" - "sync" -) - -const debug bool = false - -// Constants that identify the encoding of a value on the wire. -const ( - WireVarint = 0 - WireFixed64 = 1 - WireBytes = 2 - WireStartGroup = 3 - WireEndGroup = 4 - WireFixed32 = 5 -) - -const startSize = 10 // initial slice/string sizes - -// Encoders are defined in encode.go -// An encoder outputs the full representation of a field, including its -// tag and encoder type. -type encoder func(p *Buffer, prop *Properties, base structPointer) error - -// A valueEncoder encodes a single integer in a particular encoding. -type valueEncoder func(o *Buffer, x uint64) error - -// Sizers are defined in encode.go -// A sizer returns the encoded size of a field, including its tag and encoder -// type. -type sizer func(prop *Properties, base structPointer) int - -// A valueSizer returns the encoded size of a single integer in a particular -// encoding. -type valueSizer func(x uint64) int - -// Decoders are defined in decode.go -// A decoder creates a value from its wire representation. -// Unrecognized subelements are saved in unrec. -type decoder func(p *Buffer, prop *Properties, base structPointer) error - -// A valueDecoder decodes a single integer in a particular encoding. -type valueDecoder func(o *Buffer) (x uint64, err error) - -// tagMap is an optimization over map[int]int for typical protocol buffer -// use-cases. Encoded protocol buffers are often in tag order with small tag -// numbers. -type tagMap struct { - fastTags []int - slowTags map[int]int -} - -// tagMapFastLimit is the upper bound on the tag number that will be stored in -// the tagMap slice rather than its map. -const tagMapFastLimit = 1024 - -func (p *tagMap) get(t int) (int, bool) { - if t > 0 && t < tagMapFastLimit { - if t >= len(p.fastTags) { - return 0, false - } - fi := p.fastTags[t] - return fi, fi >= 0 - } - fi, ok := p.slowTags[t] - return fi, ok -} - -func (p *tagMap) put(t int, fi int) { - if t > 0 && t < tagMapFastLimit { - for len(p.fastTags) < t+1 { - p.fastTags = append(p.fastTags, -1) - } - p.fastTags[t] = fi - return - } - if p.slowTags == nil { - p.slowTags = make(map[int]int) - } - p.slowTags[t] = fi -} - -// StructProperties represents properties for all the fields of a struct. -// decoderTags and decoderOrigNames should only be used by the decoder. -type StructProperties struct { - Prop []*Properties // properties for each field - reqCount int // required count - decoderTags tagMap // map from proto tag to struct field number - decoderOrigNames map[string]int // map from original name to struct field number - order []int // list of struct field numbers in tag order - unrecField field // field id of the XXX_unrecognized []byte field - extendable bool // is this an extendable proto -} - -// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. -// See encode.go, (*Buffer).enc_struct. - -func (sp *StructProperties) Len() int { return len(sp.order) } -func (sp *StructProperties) Less(i, j int) bool { - return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag -} -func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } - -// Properties represents the protocol-specific behavior of a single struct field. -type Properties struct { - Name string // name of the field, for error messages - OrigName string // original name before protocol compiler (always set) - Wire string - WireType int - Tag int - Required bool - Optional bool - Repeated bool - Packed bool // relevant for repeated primitives only - Enum string // set for enum types only - proto3 bool // whether this is known to be a proto3 field; set for []byte only - - Default string // default value - HasDefault bool // whether an explicit default was provided - def_uint64 uint64 - - enc encoder - valEnc valueEncoder // set for bool and numeric types only - field field - tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType) - tagbuf [8]byte - stype reflect.Type // set for struct types only - sprop *StructProperties // set for struct types only - isMarshaler bool - isUnmarshaler bool - - mtype reflect.Type // set for map types only - mkeyprop *Properties // set for map types only - mvalprop *Properties // set for map types only - - size sizer - valSize valueSizer // set for bool and numeric types only - - dec decoder - valDec valueDecoder // set for bool and numeric types only - - // If this is a packable field, this will be the decoder for the packed version of the field. - packedDec decoder -} - -// String formats the properties in the protobuf struct field tag style. -func (p *Properties) String() string { - s := p.Wire - s = "," - s += strconv.Itoa(p.Tag) - if p.Required { - s += ",req" - } - if p.Optional { - s += ",opt" - } - if p.Repeated { - s += ",rep" - } - if p.Packed { - s += ",packed" - } - if p.OrigName != p.Name { - s += ",name=" + p.OrigName - } - if p.proto3 { - s += ",proto3" - } - if len(p.Enum) > 0 { - s += ",enum=" + p.Enum - } - if p.HasDefault { - s += ",def=" + p.Default - } - return s -} - -// Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(s string) { - // "bytes,49,opt,name=foo,def=hello!" - fields := strings.Split(s, ",") // breaks def=, but handled below. - if len(fields) < 2 { - fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) - return - } - - p.Wire = fields[0] - switch p.Wire { - case "varint": - p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeVarint - p.valDec = (*Buffer).DecodeVarint - p.valSize = sizeVarint - case "fixed32": - p.WireType = WireFixed32 - p.valEnc = (*Buffer).EncodeFixed32 - p.valDec = (*Buffer).DecodeFixed32 - p.valSize = sizeFixed32 - case "fixed64": - p.WireType = WireFixed64 - p.valEnc = (*Buffer).EncodeFixed64 - p.valDec = (*Buffer).DecodeFixed64 - p.valSize = sizeFixed64 - case "zigzag32": - p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeZigzag32 - p.valDec = (*Buffer).DecodeZigzag32 - p.valSize = sizeZigzag32 - case "zigzag64": - p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeZigzag64 - p.valDec = (*Buffer).DecodeZigzag64 - p.valSize = sizeZigzag64 - case "bytes", "group": - p.WireType = WireBytes - // no numeric converter for non-numeric types - default: - fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) - return - } - - var err error - p.Tag, err = strconv.Atoi(fields[1]) - if err != nil { - return - } - - for i := 2; i < len(fields); i++ { - f := fields[i] - switch { - case f == "req": - p.Required = true - case f == "opt": - p.Optional = true - case f == "rep": - p.Repeated = true - case f == "packed": - p.Packed = true - case strings.HasPrefix(f, "name="): - p.OrigName = f[5:] - case strings.HasPrefix(f, "enum="): - p.Enum = f[5:] - case f == "proto3": - p.proto3 = true - case strings.HasPrefix(f, "def="): - p.HasDefault = true - p.Default = f[4:] // rest of string - if i+1 < len(fields) { - // Commas aren't escaped, and def is always last. - p.Default += "," + strings.Join(fields[i+1:], ",") - break - } - } - } -} - -func logNoSliceEnc(t1, t2 reflect.Type) { - fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2) -} - -var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() - -// Initialize the fields for encoding and decoding. -func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - p.enc = nil - p.dec = nil - p.size = nil - - switch t1 := typ; t1.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1) - - // proto3 scalar types - - case reflect.Bool: - p.enc = (*Buffer).enc_proto3_bool - p.dec = (*Buffer).dec_proto3_bool - p.size = size_proto3_bool - case reflect.Int32: - p.enc = (*Buffer).enc_proto3_int32 - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_proto3_int32 - case reflect.Uint32: - p.enc = (*Buffer).enc_proto3_uint32 - p.dec = (*Buffer).dec_proto3_int32 // can reuse - p.size = size_proto3_uint32 - case reflect.Int64, reflect.Uint64: - p.enc = (*Buffer).enc_proto3_int64 - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_proto3_int64 - case reflect.Float32: - p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_proto3_uint32 - case reflect.Float64: - p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_proto3_int64 - case reflect.String: - p.enc = (*Buffer).enc_proto3_string - p.dec = (*Buffer).dec_proto3_string - p.size = size_proto3_string - - case reflect.Ptr: - switch t2 := t1.Elem(); t2.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2) - break - case reflect.Bool: - p.enc = (*Buffer).enc_bool - p.dec = (*Buffer).dec_bool - p.size = size_bool - case reflect.Int32: - p.enc = (*Buffer).enc_int32 - p.dec = (*Buffer).dec_int32 - p.size = size_int32 - case reflect.Uint32: - p.enc = (*Buffer).enc_uint32 - p.dec = (*Buffer).dec_int32 // can reuse - p.size = size_uint32 - case reflect.Int64, reflect.Uint64: - p.enc = (*Buffer).enc_int64 - p.dec = (*Buffer).dec_int64 - p.size = size_int64 - case reflect.Float32: - p.enc = (*Buffer).enc_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_int32 - p.size = size_uint32 - case reflect.Float64: - p.enc = (*Buffer).enc_int64 // can just treat them as bits - p.dec = (*Buffer).dec_int64 - p.size = size_int64 - case reflect.String: - p.enc = (*Buffer).enc_string - p.dec = (*Buffer).dec_string - p.size = size_string - case reflect.Struct: - p.stype = t1.Elem() - p.isMarshaler = isMarshaler(t1) - p.isUnmarshaler = isUnmarshaler(t1) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_struct_message - p.dec = (*Buffer).dec_struct_message - p.size = size_struct_message - } else { - p.enc = (*Buffer).enc_struct_group - p.dec = (*Buffer).dec_struct_group - p.size = size_struct_group - } - } - - case reflect.Slice: - switch t2 := t1.Elem(); t2.Kind() { - default: - logNoSliceEnc(t1, t2) - break - case reflect.Bool: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_bool - p.size = size_slice_packed_bool - } else { - p.enc = (*Buffer).enc_slice_bool - p.size = size_slice_bool - } - p.dec = (*Buffer).dec_slice_bool - p.packedDec = (*Buffer).dec_slice_packed_bool - case reflect.Int32: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int32 - p.size = size_slice_packed_int32 - } else { - p.enc = (*Buffer).enc_slice_int32 - p.size = size_slice_int32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case reflect.Uint32: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_uint32 - p.size = size_slice_packed_uint32 - } else { - p.enc = (*Buffer).enc_slice_uint32 - p.size = size_slice_uint32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case reflect.Int64, reflect.Uint64: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int64 - p.size = size_slice_packed_int64 - } else { - p.enc = (*Buffer).enc_slice_int64 - p.size = size_slice_int64 - } - p.dec = (*Buffer).dec_slice_int64 - p.packedDec = (*Buffer).dec_slice_packed_int64 - case reflect.Uint8: - p.enc = (*Buffer).enc_slice_byte - p.dec = (*Buffer).dec_slice_byte - p.size = size_slice_byte - // This is a []byte, which is either a bytes field, - // or the value of a map field. In the latter case, - // we always encode an empty []byte, so we should not - // use the proto3 enc/size funcs. - // f == nil iff this is the key/value of a map field. - if p.proto3 && f != nil { - p.enc = (*Buffer).enc_proto3_slice_byte - p.size = size_proto3_slice_byte - } - case reflect.Float32, reflect.Float64: - switch t2.Bits() { - case 32: - // can just treat them as bits - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_uint32 - p.size = size_slice_packed_uint32 - } else { - p.enc = (*Buffer).enc_slice_uint32 - p.size = size_slice_uint32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case 64: - // can just treat them as bits - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int64 - p.size = size_slice_packed_int64 - } else { - p.enc = (*Buffer).enc_slice_int64 - p.size = size_slice_int64 - } - p.dec = (*Buffer).dec_slice_int64 - p.packedDec = (*Buffer).dec_slice_packed_int64 - default: - logNoSliceEnc(t1, t2) - break - } - case reflect.String: - p.enc = (*Buffer).enc_slice_string - p.dec = (*Buffer).dec_slice_string - p.size = size_slice_string - case reflect.Ptr: - switch t3 := t2.Elem(); t3.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3) - break - case reflect.Struct: - p.stype = t2.Elem() - p.isMarshaler = isMarshaler(t2) - p.isUnmarshaler = isUnmarshaler(t2) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_slice_struct_message - p.dec = (*Buffer).dec_slice_struct_message - p.size = size_slice_struct_message - } else { - p.enc = (*Buffer).enc_slice_struct_group - p.dec = (*Buffer).dec_slice_struct_group - p.size = size_slice_struct_group - } - } - case reflect.Slice: - switch t2.Elem().Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem()) - break - case reflect.Uint8: - p.enc = (*Buffer).enc_slice_slice_byte - p.dec = (*Buffer).dec_slice_slice_byte - p.size = size_slice_slice_byte - } - } - - case reflect.Map: - p.enc = (*Buffer).enc_new_map - p.dec = (*Buffer).dec_new_map - p.size = size_new_map - - p.mtype = t1 - p.mkeyprop = &Properties{} - p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) - p.mvalprop = &Properties{} - vtype := p.mtype.Elem() - if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { - // The value type is not a message (*T) or bytes ([]byte), - // so we need encoders for the pointer to this type. - vtype = reflect.PtrTo(vtype) - } - p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) - } - - // precalculate tag code - wire := p.WireType - if p.Packed { - wire = WireBytes - } - x := uint32(p.Tag)<<3 | uint32(wire) - i := 0 - for i = 0; x > 127; i++ { - p.tagbuf[i] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - p.tagbuf[i] = uint8(x) - p.tagcode = p.tagbuf[0 : i+1] - - if p.stype != nil { - if lockGetProp { - p.sprop = GetProperties(p.stype) - } else { - p.sprop = getPropertiesLocked(p.stype) - } - } -} - -var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() - unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() -) - -// isMarshaler reports whether type t implements Marshaler. -func isMarshaler(t reflect.Type) bool { - // We're checking for (likely) pointer-receiver methods - // so if t is not a pointer, something is very wrong. - // The calls above only invoke isMarshaler on pointer types. - if t.Kind() != reflect.Ptr { - panic("proto: misuse of isMarshaler") - } - return t.Implements(marshalerType) -} - -// isUnmarshaler reports whether type t implements Unmarshaler. -func isUnmarshaler(t reflect.Type) bool { - // We're checking for (likely) pointer-receiver methods - // so if t is not a pointer, something is very wrong. - // The calls above only invoke isUnmarshaler on pointer types. - if t.Kind() != reflect.Ptr { - panic("proto: misuse of isUnmarshaler") - } - return t.Implements(unmarshalerType) -} - -// Init populates the properties from a protocol buffer struct tag. -func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { - p.init(typ, name, tag, f, true) -} - -func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { - // "bytes,49,opt,def=hello!" - p.Name = name - p.OrigName = name - if f != nil { - p.field = toField(f) - } - if tag == "" { - return - } - p.Parse(tag) - p.setEncAndDec(typ, f, lockGetProp) -} - -var ( - propertiesMu sync.RWMutex - propertiesMap = make(map[reflect.Type]*StructProperties) -) - -// GetProperties returns the list of properties for the type represented by t. -// t must represent a generated struct type of a protocol message. -func GetProperties(t reflect.Type) *StructProperties { - if t.Kind() != reflect.Struct { - panic("proto: type must have kind struct") - } - - // Most calls to GetProperties in a long-running program will be - // retrieving details for types we have seen before. - propertiesMu.RLock() - sprop, ok := propertiesMap[t] - propertiesMu.RUnlock() - if ok { - if collectStats { - stats.Chit++ - } - return sprop - } - - propertiesMu.Lock() - sprop = getPropertiesLocked(t) - propertiesMu.Unlock() - return sprop -} - -// getPropertiesLocked requires that propertiesMu is held. -func getPropertiesLocked(t reflect.Type) *StructProperties { - if prop, ok := propertiesMap[t]; ok { - if collectStats { - stats.Chit++ - } - return prop - } - if collectStats { - stats.Cmiss++ - } - - prop := new(StructProperties) - // in case of recursive protos, fill this in now. - propertiesMap[t] = prop - - // build properties - prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) - prop.unrecField = invalidField - prop.Prop = make([]*Properties, t.NumField()) - prop.order = make([]int, t.NumField()) - - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - p := new(Properties) - name := f.Name - p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) - - if f.Name == "XXX_extensions" { // special case - p.enc = (*Buffer).enc_map - p.dec = nil // not needed - p.size = size_map - } - if f.Name == "XXX_unrecognized" { // special case - prop.unrecField = toField(&f) - } - prop.Prop[i] = p - prop.order[i] = i - if debug { - print(i, " ", f.Name, " ", t.String(), " ") - if p.Tag > 0 { - print(p.String()) - } - print("\n") - } - if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") { - fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") - } - } - - // Re-order prop.order. - sort.Sort(prop) - - // build required counts - // build tags - reqCount := 0 - prop.decoderOrigNames = make(map[string]int) - for i, p := range prop.Prop { - if strings.HasPrefix(p.Name, "XXX_") { - // Internal fields should not appear in tags/origNames maps. - // They are handled specially when encoding and decoding. - continue - } - if p.Required { - reqCount++ - } - prop.decoderTags.put(p.Tag, i) - prop.decoderOrigNames[p.OrigName] = i - } - prop.reqCount = reqCount - - return prop -} - -// Return the Properties object for the x[0]'th field of the structure. -func propByIndex(t reflect.Type, x []int) *Properties { - if len(x) != 1 { - fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t) - return nil - } - prop := GetProperties(t) - return prop.Prop[x[0]] -} - -// Get the address and type of a pointer to a struct from an interface. -func getbase(pb Message) (t reflect.Type, b structPointer, err error) { - if pb == nil { - err = ErrNil - return - } - // get the reflect type of the pointer to the struct. - t = reflect.TypeOf(pb) - // get the address of the struct. - value := reflect.ValueOf(pb) - b = toStructPointer(value) - return -} - -// A global registry of enum types. -// The generated code will register the generated maps by calling RegisterEnum. - -var enumValueMaps = make(map[string]map[string]int32) - -// RegisterEnum is called from the generated code to install the enum descriptor -// maps into the global table to aid parsing text format protocol buffers. -func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { - if _, ok := enumValueMaps[typeName]; ok { - panic("proto: duplicate enum registered: " + typeName) - } - enumValueMaps[typeName] = valueMap -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go deleted file mode 100644 index 37c7782..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go +++ /dev/null @@ -1,122 +0,0 @@ -// Code generated by protoc-gen-go. -// source: proto3_proto/proto3.proto -// DO NOT EDIT! - -/* -Package proto3_proto is a generated protocol buffer package. - -It is generated from these files: - proto3_proto/proto3.proto - -It has these top-level messages: - Message - Nested - MessageWithMap -*/ -package proto3_proto - -import proto "github.com/golang/protobuf/proto" -import testdata "github.com/golang/protobuf/proto/testdata" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal - -type Message_Humour int32 - -const ( - Message_UNKNOWN Message_Humour = 0 - Message_PUNS Message_Humour = 1 - Message_SLAPSTICK Message_Humour = 2 - Message_BILL_BAILEY Message_Humour = 3 -) - -var Message_Humour_name = map[int32]string{ - 0: "UNKNOWN", - 1: "PUNS", - 2: "SLAPSTICK", - 3: "BILL_BAILEY", -} -var Message_Humour_value = map[string]int32{ - "UNKNOWN": 0, - "PUNS": 1, - "SLAPSTICK": 2, - "BILL_BAILEY": 3, -} - -func (x Message_Humour) String() string { - return proto.EnumName(Message_Humour_name, int32(x)) -} - -type Message struct { - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"` - HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm" json:"height_in_cm,omitempty"` - Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` - ResultCount int64 `protobuf:"varint,7,opt,name=result_count" json:"result_count,omitempty"` - TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman" json:"true_scotsman,omitempty"` - Score float32 `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"` - Key []uint64 `protobuf:"varint,5,rep,name=key" json:"key,omitempty"` - Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"` - Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - Proto2Field *testdata.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field" json:"proto2_field,omitempty"` - Proto2Value map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} - -func (m *Message) GetNested() *Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *Message) GetTerrain() map[string]*Nested { - if m != nil { - return m.Terrain - } - return nil -} - -func (m *Message) GetProto2Field() *testdata.SubDefaults { - if m != nil { - return m.Proto2Field - } - return nil -} - -func (m *Message) GetProto2Value() map[string]*testdata.SubDefaults { - if m != nil { - return m.Proto2Value - } - return nil -} - -type Nested struct { - Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"` -} - -func (m *Nested) Reset() { *m = Nested{} } -func (m *Nested) String() string { return proto.CompactTextString(m) } -func (*Nested) ProtoMessage() {} - -type MessageWithMap struct { - ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"` -} - -func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } -func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } -func (*MessageWithMap) ProtoMessage() {} - -func (m *MessageWithMap) GetByteMapping() map[bool][]byte { - if m != nil { - return m.ByteMapping - } - return nil -} - -func init() { - proto.RegisterEnum("proto3_proto.Message_Humour", Message_Humour_name, Message_Humour_value) -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto deleted file mode 100644 index e2311d9..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto +++ /dev/null @@ -1,68 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -import "testdata/test.proto"; - -package proto3_proto; - -message Message { - enum Humour { - UNKNOWN = 0; - PUNS = 1; - SLAPSTICK = 2; - BILL_BAILEY = 3; - } - - string name = 1; - Humour hilarity = 2; - uint32 height_in_cm = 3; - bytes data = 4; - int64 result_count = 7; - bool true_scotsman = 8; - float score = 9; - - repeated uint64 key = 5; - Nested nested = 6; - - map terrain = 10; - testdata.SubDefaults proto2_field = 11; - map proto2_value = 13; -} - -message Nested { - string bunny = 1; -} - -message MessageWithMap { - map byte_mapping = 1; -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go deleted file mode 100644 index 462f805..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,125 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/proto/proto3_proto" - tpb "github.com/golang/protobuf/proto/testdata" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} - -func TestProto3SetDefaults(t *testing.T) { - in := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: new(tpb.SubDefaults), - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": new(tpb.SubDefaults), - }, - } - - got := proto.Clone(in).(*pb.Message) - proto.SetDefaults(got) - - // There are no defaults in proto3. Everything should be the zero value, but - // we need to remember to set defaults for nested proto2 messages. - want := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": &tpb.SubDefaults{N: proto.Int64(7)}, - }, - } - - if !proto.Equal(got, want) { - t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go deleted file mode 100644 index a2729c3..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := sizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go deleted file mode 100644 index db5614f..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go +++ /dev/null @@ -1,142 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "log" - "strings" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, - {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}}, - - {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, - {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, - {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile deleted file mode 100644 index fc28862..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile +++ /dev/null @@ -1,50 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -include ../../Make.protobuf - -all: regenerate - -regenerate: - rm -f test.pb.go - make test.pb.go - -# The following rules are just aids to development. Not needed for typical testing. - -diff: regenerate - git diff test.pb.go - -restore: - cp test.pb.go.golden test.pb.go - -preserve: - cp test.pb.go test.pb.go.golden diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go deleted file mode 100644 index 7172d0e..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Verify that the compiler output for test.proto is unchanged. - -package testdata - -import ( - "crypto/sha1" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "testing" -) - -// sum returns in string form (for easy comparison) the SHA-1 hash of the named file. -func sum(t *testing.T, name string) string { - data, err := ioutil.ReadFile(name) - if err != nil { - t.Fatal(err) - } - t.Logf("sum(%q): length is %d", name, len(data)) - hash := sha1.New() - _, err = hash.Write(data) - if err != nil { - t.Fatal(err) - } - return fmt.Sprintf("% x", hash.Sum(nil)) -} - -func run(t *testing.T, name string, args ...string) { - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - err := cmd.Run() - if err != nil { - t.Fatal(err) - } -} - -func TestGolden(t *testing.T) { - // Compute the original checksum. - goldenSum := sum(t, "test.pb.go") - // Run the proto compiler. - run(t, "protoc", "--go_out="+os.TempDir(), "test.proto") - newFile := filepath.Join(os.TempDir(), "test.pb.go") - defer os.Remove(newFile) - // Compute the new checksum. - newSum := sum(t, newFile) - // Verify - if newSum != goldenSum { - run(t, "diff", "-u", "test.pb.go", newFile) - t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go") - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go deleted file mode 100644 index 13674a4..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go +++ /dev/null @@ -1,2746 +0,0 @@ -// Code generated by protoc-gen-go. -// source: test.proto -// DO NOT EDIT! - -/* -Package testdata is a generated protocol buffer package. - -It is generated from these files: - test.proto - -It has these top-level messages: - GoEnum - GoTestField - GoTest - GoSkipTest - NonPackedTest - PackedTest - MaxTag - OldMessage - NewMessage - InnerMessage - OtherMessage - MyMessage - Ext - DefaultsMessage - MyMessageSet - Empty - MessageList - Strings - Defaults - SubDefaults - RepeatedEnum - MoreRepeated - GroupOld - GroupNew - FloatingPoint - MessageWithMap -*/ -package testdata - -import proto "github.com/golang/protobuf/proto" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = math.Inf - -type FOO int32 - -const ( - FOO_FOO1 FOO = 1 -) - -var FOO_name = map[int32]string{ - 1: "FOO1", -} -var FOO_value = map[string]int32{ - "FOO1": 1, -} - -func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p -} -func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) -} -func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO") - if err != nil { - return err - } - *x = FOO(value) - return nil -} - -// An enum, for completeness. -type GoTest_KIND int32 - -const ( - GoTest_VOID GoTest_KIND = 0 - // Basic types - GoTest_BOOL GoTest_KIND = 1 - GoTest_BYTES GoTest_KIND = 2 - GoTest_FINGERPRINT GoTest_KIND = 3 - GoTest_FLOAT GoTest_KIND = 4 - GoTest_INT GoTest_KIND = 5 - GoTest_STRING GoTest_KIND = 6 - GoTest_TIME GoTest_KIND = 7 - // Groupings - GoTest_TUPLE GoTest_KIND = 8 - GoTest_ARRAY GoTest_KIND = 9 - GoTest_MAP GoTest_KIND = 10 - // Table types - GoTest_TABLE GoTest_KIND = 11 - // Functions - GoTest_FUNCTION GoTest_KIND = 12 -) - -var GoTest_KIND_name = map[int32]string{ - 0: "VOID", - 1: "BOOL", - 2: "BYTES", - 3: "FINGERPRINT", - 4: "FLOAT", - 5: "INT", - 6: "STRING", - 7: "TIME", - 8: "TUPLE", - 9: "ARRAY", - 10: "MAP", - 11: "TABLE", - 12: "FUNCTION", -} -var GoTest_KIND_value = map[string]int32{ - "VOID": 0, - "BOOL": 1, - "BYTES": 2, - "FINGERPRINT": 3, - "FLOAT": 4, - "INT": 5, - "STRING": 6, - "TIME": 7, - "TUPLE": 8, - "ARRAY": 9, - "MAP": 10, - "TABLE": 11, - "FUNCTION": 12, -} - -func (x GoTest_KIND) Enum() *GoTest_KIND { - p := new(GoTest_KIND) - *p = x - return p -} -func (x GoTest_KIND) String() string { - return proto.EnumName(GoTest_KIND_name, int32(x)) -} -func (x *GoTest_KIND) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND") - if err != nil { - return err - } - *x = GoTest_KIND(value) - return nil -} - -type MyMessage_Color int32 - -const ( - MyMessage_RED MyMessage_Color = 0 - MyMessage_GREEN MyMessage_Color = 1 - MyMessage_BLUE MyMessage_Color = 2 -) - -var MyMessage_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var MyMessage_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x MyMessage_Color) Enum() *MyMessage_Color { - p := new(MyMessage_Color) - *p = x - return p -} -func (x MyMessage_Color) String() string { - return proto.EnumName(MyMessage_Color_name, int32(x)) -} -func (x *MyMessage_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color") - if err != nil { - return err - } - *x = MyMessage_Color(value) - return nil -} - -type DefaultsMessage_DefaultsEnum int32 - -const ( - DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0 - DefaultsMessage_ONE DefaultsMessage_DefaultsEnum = 1 - DefaultsMessage_TWO DefaultsMessage_DefaultsEnum = 2 -) - -var DefaultsMessage_DefaultsEnum_name = map[int32]string{ - 0: "ZERO", - 1: "ONE", - 2: "TWO", -} -var DefaultsMessage_DefaultsEnum_value = map[string]int32{ - "ZERO": 0, - "ONE": 1, - "TWO": 2, -} - -func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum { - p := new(DefaultsMessage_DefaultsEnum) - *p = x - return p -} -func (x DefaultsMessage_DefaultsEnum) String() string { - return proto.EnumName(DefaultsMessage_DefaultsEnum_name, int32(x)) -} -func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(DefaultsMessage_DefaultsEnum_value, data, "DefaultsMessage_DefaultsEnum") - if err != nil { - return err - } - *x = DefaultsMessage_DefaultsEnum(value) - return nil -} - -type Defaults_Color int32 - -const ( - Defaults_RED Defaults_Color = 0 - Defaults_GREEN Defaults_Color = 1 - Defaults_BLUE Defaults_Color = 2 -) - -var Defaults_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var Defaults_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x Defaults_Color) Enum() *Defaults_Color { - p := new(Defaults_Color) - *p = x - return p -} -func (x Defaults_Color) String() string { - return proto.EnumName(Defaults_Color_name, int32(x)) -} -func (x *Defaults_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color") - if err != nil { - return err - } - *x = Defaults_Color(value) - return nil -} - -type RepeatedEnum_Color int32 - -const ( - RepeatedEnum_RED RepeatedEnum_Color = 1 -) - -var RepeatedEnum_Color_name = map[int32]string{ - 1: "RED", -} -var RepeatedEnum_Color_value = map[string]int32{ - "RED": 1, -} - -func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color { - p := new(RepeatedEnum_Color) - *p = x - return p -} -func (x RepeatedEnum_Color) String() string { - return proto.EnumName(RepeatedEnum_Color_name, int32(x)) -} -func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color") - if err != nil { - return err - } - *x = RepeatedEnum_Color(value) - return nil -} - -type GoEnum struct { - Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoEnum) Reset() { *m = GoEnum{} } -func (m *GoEnum) String() string { return proto.CompactTextString(m) } -func (*GoEnum) ProtoMessage() {} - -func (m *GoEnum) GetFoo() FOO { - if m != nil && m.Foo != nil { - return *m.Foo - } - return FOO_FOO1 -} - -type GoTestField struct { - Label *string `protobuf:"bytes,1,req" json:"Label,omitempty"` - Type *string `protobuf:"bytes,2,req" json:"Type,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTestField) Reset() { *m = GoTestField{} } -func (m *GoTestField) String() string { return proto.CompactTextString(m) } -func (*GoTestField) ProtoMessage() {} - -func (m *GoTestField) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" -} - -func (m *GoTestField) GetType() string { - if m != nil && m.Type != nil { - return *m.Type - } - return "" -} - -type GoTest struct { - // Some typical parameters - Kind *GoTest_KIND `protobuf:"varint,1,req,enum=testdata.GoTest_KIND" json:"Kind,omitempty"` - Table *string `protobuf:"bytes,2,opt" json:"Table,omitempty"` - Param *int32 `protobuf:"varint,3,opt" json:"Param,omitempty"` - // Required, repeated and optional foreign fields. - RequiredField *GoTestField `protobuf:"bytes,4,req" json:"RequiredField,omitempty"` - RepeatedField []*GoTestField `protobuf:"bytes,5,rep" json:"RepeatedField,omitempty"` - OptionalField *GoTestField `protobuf:"bytes,6,opt" json:"OptionalField,omitempty"` - // Required fields of all basic types - F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required" json:"F_Bool_required,omitempty"` - F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required" json:"F_Int32_required,omitempty"` - F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required" json:"F_Int64_required,omitempty"` - F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required" json:"F_Fixed32_required,omitempty"` - F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required" json:"F_Fixed64_required,omitempty"` - F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required" json:"F_Uint32_required,omitempty"` - F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required" json:"F_Uint64_required,omitempty"` - F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required" json:"F_Float_required,omitempty"` - F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required" json:"F_Double_required,omitempty"` - F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required" json:"F_String_required,omitempty"` - F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required" json:"F_Bytes_required,omitempty"` - F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required" json:"F_Sint32_required,omitempty"` - F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required" json:"F_Sint64_required,omitempty"` - // Repeated fields of all basic types - F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated" json:"F_Bool_repeated,omitempty"` - F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated" json:"F_Int32_repeated,omitempty"` - F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated" json:"F_Int64_repeated,omitempty"` - F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated" json:"F_Fixed32_repeated,omitempty"` - F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated" json:"F_Fixed64_repeated,omitempty"` - F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated" json:"F_Uint32_repeated,omitempty"` - F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated" json:"F_Uint64_repeated,omitempty"` - F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated" json:"F_Float_repeated,omitempty"` - F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated" json:"F_Double_repeated,omitempty"` - F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated" json:"F_String_repeated,omitempty"` - F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated" json:"F_Bytes_repeated,omitempty"` - F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated" json:"F_Sint32_repeated,omitempty"` - F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated" json:"F_Sint64_repeated,omitempty"` - // Optional fields of all basic types - F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional" json:"F_Bool_optional,omitempty"` - F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional" json:"F_Int32_optional,omitempty"` - F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional" json:"F_Int64_optional,omitempty"` - F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional" json:"F_Fixed32_optional,omitempty"` - F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional" json:"F_Fixed64_optional,omitempty"` - F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional" json:"F_Uint32_optional,omitempty"` - F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional" json:"F_Uint64_optional,omitempty"` - F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional" json:"F_Float_optional,omitempty"` - F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional" json:"F_Double_optional,omitempty"` - F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional" json:"F_String_optional,omitempty"` - F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional" json:"F_Bytes_optional,omitempty"` - F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional" json:"F_Sint32_optional,omitempty"` - F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional" json:"F_Sint64_optional,omitempty"` - // Default-valued fields of all basic types - F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,def=1" json:"F_Bool_defaulted,omitempty"` - F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,def=32" json:"F_Int32_defaulted,omitempty"` - F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,def=64" json:"F_Int64_defaulted,omitempty"` - F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"` - F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"` - F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"` - F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"` - F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,def=314159" json:"F_Float_defaulted,omitempty"` - F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,def=271828" json:"F_Double_defaulted,omitempty"` - F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"` - F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"` - F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"` - F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"` - // Packed repeated fields (no string or bytes). - F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed" json:"F_Bool_repeated_packed,omitempty"` - F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed" json:"F_Int32_repeated_packed,omitempty"` - F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed" json:"F_Int64_repeated_packed,omitempty"` - F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed" json:"F_Fixed32_repeated_packed,omitempty"` - F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed" json:"F_Fixed64_repeated_packed,omitempty"` - F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed" json:"F_Uint32_repeated_packed,omitempty"` - F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed" json:"F_Uint64_repeated_packed,omitempty"` - F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed" json:"F_Float_repeated_packed,omitempty"` - F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed" json:"F_Double_repeated_packed,omitempty"` - F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed" json:"F_Sint32_repeated_packed,omitempty"` - F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed" json:"F_Sint64_repeated_packed,omitempty"` - Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup" json:"requiredgroup,omitempty"` - Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup" json:"repeatedgroup,omitempty"` - Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest) Reset() { *m = GoTest{} } -func (m *GoTest) String() string { return proto.CompactTextString(m) } -func (*GoTest) ProtoMessage() {} - -const Default_GoTest_F_BoolDefaulted bool = true -const Default_GoTest_F_Int32Defaulted int32 = 32 -const Default_GoTest_F_Int64Defaulted int64 = 64 -const Default_GoTest_F_Fixed32Defaulted uint32 = 320 -const Default_GoTest_F_Fixed64Defaulted uint64 = 640 -const Default_GoTest_F_Uint32Defaulted uint32 = 3200 -const Default_GoTest_F_Uint64Defaulted uint64 = 6400 -const Default_GoTest_F_FloatDefaulted float32 = 314159 -const Default_GoTest_F_DoubleDefaulted float64 = 271828 -const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n" - -var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose") - -const Default_GoTest_F_Sint32Defaulted int32 = -32 -const Default_GoTest_F_Sint64Defaulted int64 = -64 - -func (m *GoTest) GetKind() GoTest_KIND { - if m != nil && m.Kind != nil { - return *m.Kind - } - return GoTest_VOID -} - -func (m *GoTest) GetTable() string { - if m != nil && m.Table != nil { - return *m.Table - } - return "" -} - -func (m *GoTest) GetParam() int32 { - if m != nil && m.Param != nil { - return *m.Param - } - return 0 -} - -func (m *GoTest) GetRequiredField() *GoTestField { - if m != nil { - return m.RequiredField - } - return nil -} - -func (m *GoTest) GetRepeatedField() []*GoTestField { - if m != nil { - return m.RepeatedField - } - return nil -} - -func (m *GoTest) GetOptionalField() *GoTestField { - if m != nil { - return m.OptionalField - } - return nil -} - -func (m *GoTest) GetF_BoolRequired() bool { - if m != nil && m.F_BoolRequired != nil { - return *m.F_BoolRequired - } - return false -} - -func (m *GoTest) GetF_Int32Required() int32 { - if m != nil && m.F_Int32Required != nil { - return *m.F_Int32Required - } - return 0 -} - -func (m *GoTest) GetF_Int64Required() int64 { - if m != nil && m.F_Int64Required != nil { - return *m.F_Int64Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Required() uint32 { - if m != nil && m.F_Fixed32Required != nil { - return *m.F_Fixed32Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Required() uint64 { - if m != nil && m.F_Fixed64Required != nil { - return *m.F_Fixed64Required - } - return 0 -} - -func (m *GoTest) GetF_Uint32Required() uint32 { - if m != nil && m.F_Uint32Required != nil { - return *m.F_Uint32Required - } - return 0 -} - -func (m *GoTest) GetF_Uint64Required() uint64 { - if m != nil && m.F_Uint64Required != nil { - return *m.F_Uint64Required - } - return 0 -} - -func (m *GoTest) GetF_FloatRequired() float32 { - if m != nil && m.F_FloatRequired != nil { - return *m.F_FloatRequired - } - return 0 -} - -func (m *GoTest) GetF_DoubleRequired() float64 { - if m != nil && m.F_DoubleRequired != nil { - return *m.F_DoubleRequired - } - return 0 -} - -func (m *GoTest) GetF_StringRequired() string { - if m != nil && m.F_StringRequired != nil { - return *m.F_StringRequired - } - return "" -} - -func (m *GoTest) GetF_BytesRequired() []byte { - if m != nil { - return m.F_BytesRequired - } - return nil -} - -func (m *GoTest) GetF_Sint32Required() int32 { - if m != nil && m.F_Sint32Required != nil { - return *m.F_Sint32Required - } - return 0 -} - -func (m *GoTest) GetF_Sint64Required() int64 { - if m != nil && m.F_Sint64Required != nil { - return *m.F_Sint64Required - } - return 0 -} - -func (m *GoTest) GetF_BoolRepeated() []bool { - if m != nil { - return m.F_BoolRepeated - } - return nil -} - -func (m *GoTest) GetF_Int32Repeated() []int32 { - if m != nil { - return m.F_Int32Repeated - } - return nil -} - -func (m *GoTest) GetF_Int64Repeated() []int64 { - if m != nil { - return m.F_Int64Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed32Repeated() []uint32 { - if m != nil { - return m.F_Fixed32Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed64Repeated() []uint64 { - if m != nil { - return m.F_Fixed64Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint32Repeated() []uint32 { - if m != nil { - return m.F_Uint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint64Repeated() []uint64 { - if m != nil { - return m.F_Uint64Repeated - } - return nil -} - -func (m *GoTest) GetF_FloatRepeated() []float32 { - if m != nil { - return m.F_FloatRepeated - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeated() []float64 { - if m != nil { - return m.F_DoubleRepeated - } - return nil -} - -func (m *GoTest) GetF_StringRepeated() []string { - if m != nil { - return m.F_StringRepeated - } - return nil -} - -func (m *GoTest) GetF_BytesRepeated() [][]byte { - if m != nil { - return m.F_BytesRepeated - } - return nil -} - -func (m *GoTest) GetF_Sint32Repeated() []int32 { - if m != nil { - return m.F_Sint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Sint64Repeated() []int64 { - if m != nil { - return m.F_Sint64Repeated - } - return nil -} - -func (m *GoTest) GetF_BoolOptional() bool { - if m != nil && m.F_BoolOptional != nil { - return *m.F_BoolOptional - } - return false -} - -func (m *GoTest) GetF_Int32Optional() int32 { - if m != nil && m.F_Int32Optional != nil { - return *m.F_Int32Optional - } - return 0 -} - -func (m *GoTest) GetF_Int64Optional() int64 { - if m != nil && m.F_Int64Optional != nil { - return *m.F_Int64Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Optional() uint32 { - if m != nil && m.F_Fixed32Optional != nil { - return *m.F_Fixed32Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Optional() uint64 { - if m != nil && m.F_Fixed64Optional != nil { - return *m.F_Fixed64Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint32Optional() uint32 { - if m != nil && m.F_Uint32Optional != nil { - return *m.F_Uint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint64Optional() uint64 { - if m != nil && m.F_Uint64Optional != nil { - return *m.F_Uint64Optional - } - return 0 -} - -func (m *GoTest) GetF_FloatOptional() float32 { - if m != nil && m.F_FloatOptional != nil { - return *m.F_FloatOptional - } - return 0 -} - -func (m *GoTest) GetF_DoubleOptional() float64 { - if m != nil && m.F_DoubleOptional != nil { - return *m.F_DoubleOptional - } - return 0 -} - -func (m *GoTest) GetF_StringOptional() string { - if m != nil && m.F_StringOptional != nil { - return *m.F_StringOptional - } - return "" -} - -func (m *GoTest) GetF_BytesOptional() []byte { - if m != nil { - return m.F_BytesOptional - } - return nil -} - -func (m *GoTest) GetF_Sint32Optional() int32 { - if m != nil && m.F_Sint32Optional != nil { - return *m.F_Sint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Sint64Optional() int64 { - if m != nil && m.F_Sint64Optional != nil { - return *m.F_Sint64Optional - } - return 0 -} - -func (m *GoTest) GetF_BoolDefaulted() bool { - if m != nil && m.F_BoolDefaulted != nil { - return *m.F_BoolDefaulted - } - return Default_GoTest_F_BoolDefaulted -} - -func (m *GoTest) GetF_Int32Defaulted() int32 { - if m != nil && m.F_Int32Defaulted != nil { - return *m.F_Int32Defaulted - } - return Default_GoTest_F_Int32Defaulted -} - -func (m *GoTest) GetF_Int64Defaulted() int64 { - if m != nil && m.F_Int64Defaulted != nil { - return *m.F_Int64Defaulted - } - return Default_GoTest_F_Int64Defaulted -} - -func (m *GoTest) GetF_Fixed32Defaulted() uint32 { - if m != nil && m.F_Fixed32Defaulted != nil { - return *m.F_Fixed32Defaulted - } - return Default_GoTest_F_Fixed32Defaulted -} - -func (m *GoTest) GetF_Fixed64Defaulted() uint64 { - if m != nil && m.F_Fixed64Defaulted != nil { - return *m.F_Fixed64Defaulted - } - return Default_GoTest_F_Fixed64Defaulted -} - -func (m *GoTest) GetF_Uint32Defaulted() uint32 { - if m != nil && m.F_Uint32Defaulted != nil { - return *m.F_Uint32Defaulted - } - return Default_GoTest_F_Uint32Defaulted -} - -func (m *GoTest) GetF_Uint64Defaulted() uint64 { - if m != nil && m.F_Uint64Defaulted != nil { - return *m.F_Uint64Defaulted - } - return Default_GoTest_F_Uint64Defaulted -} - -func (m *GoTest) GetF_FloatDefaulted() float32 { - if m != nil && m.F_FloatDefaulted != nil { - return *m.F_FloatDefaulted - } - return Default_GoTest_F_FloatDefaulted -} - -func (m *GoTest) GetF_DoubleDefaulted() float64 { - if m != nil && m.F_DoubleDefaulted != nil { - return *m.F_DoubleDefaulted - } - return Default_GoTest_F_DoubleDefaulted -} - -func (m *GoTest) GetF_StringDefaulted() string { - if m != nil && m.F_StringDefaulted != nil { - return *m.F_StringDefaulted - } - return Default_GoTest_F_StringDefaulted -} - -func (m *GoTest) GetF_BytesDefaulted() []byte { - if m != nil && m.F_BytesDefaulted != nil { - return m.F_BytesDefaulted - } - return append([]byte(nil), Default_GoTest_F_BytesDefaulted...) -} - -func (m *GoTest) GetF_Sint32Defaulted() int32 { - if m != nil && m.F_Sint32Defaulted != nil { - return *m.F_Sint32Defaulted - } - return Default_GoTest_F_Sint32Defaulted -} - -func (m *GoTest) GetF_Sint64Defaulted() int64 { - if m != nil && m.F_Sint64Defaulted != nil { - return *m.F_Sint64Defaulted - } - return Default_GoTest_F_Sint64Defaulted -} - -func (m *GoTest) GetF_BoolRepeatedPacked() []bool { - if m != nil { - return m.F_BoolRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int32RepeatedPacked() []int32 { - if m != nil { - return m.F_Int32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int64RepeatedPacked() []int64 { - if m != nil { - return m.F_Int64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Fixed32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Fixed64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Uint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Uint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_FloatRepeatedPacked() []float32 { - if m != nil { - return m.F_FloatRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 { - if m != nil { - return m.F_DoubleRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 { - if m != nil { - return m.F_Sint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 { - if m != nil { - return m.F_Sint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup { - if m != nil { - return m.Requiredgroup - } - return nil -} - -func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup { - if m != nil { - return m.Repeatedgroup - } - return nil -} - -func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil -} - -// Required, repeated, and optional groups. -type GoTest_RequiredGroup struct { - RequiredField *string `protobuf:"bytes,71,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} } -func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_RequiredGroup) ProtoMessage() {} - -func (m *GoTest_RequiredGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_RepeatedGroup struct { - RequiredField *string `protobuf:"bytes,81,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} } -func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_RepeatedGroup) ProtoMessage() {} - -func (m *GoTest_RepeatedGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,91,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} } -func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_OptionalGroup) ProtoMessage() {} - -func (m *GoTest_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -// For testing skipping of unrecognized fields. -// Numbers are all big, larger than tag numbers in GoTestField, -// the message used in the corresponding test. -type GoSkipTest struct { - SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32" json:"skip_int32,omitempty"` - SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32" json:"skip_fixed32,omitempty"` - SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64" json:"skip_fixed64,omitempty"` - SkipString *string `protobuf:"bytes,14,req,name=skip_string" json:"skip_string,omitempty"` - Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup" json:"skipgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoSkipTest) Reset() { *m = GoSkipTest{} } -func (m *GoSkipTest) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest) ProtoMessage() {} - -func (m *GoSkipTest) GetSkipInt32() int32 { - if m != nil && m.SkipInt32 != nil { - return *m.SkipInt32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed32() uint32 { - if m != nil && m.SkipFixed32 != nil { - return *m.SkipFixed32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed64() uint64 { - if m != nil && m.SkipFixed64 != nil { - return *m.SkipFixed64 - } - return 0 -} - -func (m *GoSkipTest) GetSkipString() string { - if m != nil && m.SkipString != nil { - return *m.SkipString - } - return "" -} - -func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup { - if m != nil { - return m.Skipgroup - } - return nil -} - -type GoSkipTest_SkipGroup struct { - GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32" json:"group_int32,omitempty"` - GroupString *string `protobuf:"bytes,17,req,name=group_string" json:"group_string,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} } -func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest_SkipGroup) ProtoMessage() {} - -func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 { - if m != nil && m.GroupInt32 != nil { - return *m.GroupInt32 - } - return 0 -} - -func (m *GoSkipTest_SkipGroup) GetGroupString() string { - if m != nil && m.GroupString != nil { - return *m.GroupString - } - return "" -} - -// For testing packed/non-packed decoder switching. -// A serialized instance of one should be deserializable as the other. -type NonPackedTest struct { - A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NonPackedTest) Reset() { *m = NonPackedTest{} } -func (m *NonPackedTest) String() string { return proto.CompactTextString(m) } -func (*NonPackedTest) ProtoMessage() {} - -func (m *NonPackedTest) GetA() []int32 { - if m != nil { - return m.A - } - return nil -} - -type PackedTest struct { - B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PackedTest) Reset() { *m = PackedTest{} } -func (m *PackedTest) String() string { return proto.CompactTextString(m) } -func (*PackedTest) ProtoMessage() {} - -func (m *PackedTest) GetB() []int32 { - if m != nil { - return m.B - } - return nil -} - -type MaxTag struct { - // Maximum possible tag number. - LastField *string `protobuf:"bytes,536870911,opt,name=last_field" json:"last_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MaxTag) Reset() { *m = MaxTag{} } -func (m *MaxTag) String() string { return proto.CompactTextString(m) } -func (*MaxTag) ProtoMessage() {} - -func (m *MaxTag) GetLastField() string { - if m != nil && m.LastField != nil { - return *m.LastField - } - return "" -} - -type OldMessage struct { - Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OldMessage) Reset() { *m = OldMessage{} } -func (m *OldMessage) String() string { return proto.CompactTextString(m) } -func (*OldMessage) ProtoMessage() {} - -func (m *OldMessage) GetNested() *OldMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *OldMessage) GetNum() int32 { - if m != nil && m.Num != nil { - return *m.Num - } - return 0 -} - -type OldMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} } -func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*OldMessage_Nested) ProtoMessage() {} - -func (m *OldMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -// NewMessage is wire compatible with OldMessage; -// imagine it as a future version. -type NewMessage struct { - Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - // This is an int32 in OldMessage. - Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NewMessage) Reset() { *m = NewMessage{} } -func (m *NewMessage) String() string { return proto.CompactTextString(m) } -func (*NewMessage) ProtoMessage() {} - -func (m *NewMessage) GetNested() *NewMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *NewMessage) GetNum() int64 { - if m != nil && m.Num != nil { - return *m.Num - } - return 0 -} - -type NewMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - FoodGroup *string `protobuf:"bytes,2,opt,name=food_group" json:"food_group,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} } -func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*NewMessage_Nested) ProtoMessage() {} - -func (m *NewMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *NewMessage_Nested) GetFoodGroup() string { - if m != nil && m.FoodGroup != nil { - return *m.FoodGroup - } - return "" -} - -type InnerMessage struct { - Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"` - Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"` - Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *InnerMessage) Reset() { *m = InnerMessage{} } -func (m *InnerMessage) String() string { return proto.CompactTextString(m) } -func (*InnerMessage) ProtoMessage() {} - -const Default_InnerMessage_Port int32 = 4000 - -func (m *InnerMessage) GetHost() string { - if m != nil && m.Host != nil { - return *m.Host - } - return "" -} - -func (m *InnerMessage) GetPort() int32 { - if m != nil && m.Port != nil { - return *m.Port - } - return Default_InnerMessage_Port -} - -func (m *InnerMessage) GetConnected() bool { - if m != nil && m.Connected != nil { - return *m.Connected - } - return false -} - -type OtherMessage struct { - Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` - Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` - Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"` - Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OtherMessage) Reset() { *m = OtherMessage{} } -func (m *OtherMessage) String() string { return proto.CompactTextString(m) } -func (*OtherMessage) ProtoMessage() {} - -func (m *OtherMessage) GetKey() int64 { - if m != nil && m.Key != nil { - return *m.Key - } - return 0 -} - -func (m *OtherMessage) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func (m *OtherMessage) GetWeight() float32 { - if m != nil && m.Weight != nil { - return *m.Weight - } - return 0 -} - -func (m *OtherMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -type MyMessage struct { - Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"` - Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` - Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"` - Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"` - Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"` - Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"` - RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner" json:"rep_inner,omitempty"` - Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"` - Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup" json:"somegroup,omitempty"` - // This field becomes [][]byte in the generated code. - RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes" json:"rep_bytes,omitempty"` - Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"` - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessage) Reset() { *m = MyMessage{} } -func (m *MyMessage) String() string { return proto.CompactTextString(m) } -func (*MyMessage) ProtoMessage() {} - -var extRange_MyMessage = []proto.ExtensionRange{ - {100, 536870911}, -} - -func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessage -} -func (m *MyMessage) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -func (m *MyMessage) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -func (m *MyMessage) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MyMessage) GetQuote() string { - if m != nil && m.Quote != nil { - return *m.Quote - } - return "" -} - -func (m *MyMessage) GetPet() []string { - if m != nil { - return m.Pet - } - return nil -} - -func (m *MyMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -func (m *MyMessage) GetOthers() []*OtherMessage { - if m != nil { - return m.Others - } - return nil -} - -func (m *MyMessage) GetRepInner() []*InnerMessage { - if m != nil { - return m.RepInner - } - return nil -} - -func (m *MyMessage) GetBikeshed() MyMessage_Color { - if m != nil && m.Bikeshed != nil { - return *m.Bikeshed - } - return MyMessage_RED -} - -func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup { - if m != nil { - return m.Somegroup - } - return nil -} - -func (m *MyMessage) GetRepBytes() [][]byte { - if m != nil { - return m.RepBytes - } - return nil -} - -func (m *MyMessage) GetBigfloat() float64 { - if m != nil && m.Bigfloat != nil { - return *m.Bigfloat - } - return 0 -} - -type MyMessage_SomeGroup struct { - GroupField *int32 `protobuf:"varint,9,opt,name=group_field" json:"group_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} } -func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) } -func (*MyMessage_SomeGroup) ProtoMessage() {} - -func (m *MyMessage_SomeGroup) GetGroupField() int32 { - if m != nil && m.GroupField != nil { - return *m.GroupField - } - return 0 -} - -type Ext struct { - Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Ext) Reset() { *m = Ext{} } -func (m *Ext) String() string { return proto.CompactTextString(m) } -func (*Ext) ProtoMessage() {} - -func (m *Ext) GetData() string { - if m != nil && m.Data != nil { - return *m.Data - } - return "" -} - -var E_Ext_More = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*Ext)(nil), - Field: 103, - Name: "testdata.Ext.more", - Tag: "bytes,103,opt,name=more", -} - -var E_Ext_Text = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*string)(nil), - Field: 104, - Name: "testdata.Ext.text", - Tag: "bytes,104,opt,name=text", -} - -var E_Ext_Number = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 105, - Name: "testdata.Ext.number", - Tag: "varint,105,opt,name=number", -} - -type DefaultsMessage struct { - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *DefaultsMessage) Reset() { *m = DefaultsMessage{} } -func (m *DefaultsMessage) String() string { return proto.CompactTextString(m) } -func (*DefaultsMessage) ProtoMessage() {} - -var extRange_DefaultsMessage = []proto.ExtensionRange{ - {100, 536870911}, -} - -func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_DefaultsMessage -} -func (m *DefaultsMessage) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -type MyMessageSet struct { - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessageSet) Reset() { *m = MyMessageSet{} } -func (m *MyMessageSet) String() string { return proto.CompactTextString(m) } -func (*MyMessageSet) ProtoMessage() {} - -func (m *MyMessageSet) Marshal() ([]byte, error) { - return proto.MarshalMessageSet(m.ExtensionMap()) -} -func (m *MyMessageSet) Unmarshal(buf []byte) error { - return proto.UnmarshalMessageSet(buf, m.ExtensionMap()) -} -func (m *MyMessageSet) MarshalJSON() ([]byte, error) { - return proto.MarshalMessageSetJSON(m.XXX_extensions) -} -func (m *MyMessageSet) UnmarshalJSON(buf []byte) error { - return proto.UnmarshalMessageSetJSON(buf, m.XXX_extensions) -} - -// ensure MyMessageSet satisfies proto.Marshaler and proto.Unmarshaler -var _ proto.Marshaler = (*MyMessageSet)(nil) -var _ proto.Unmarshaler = (*MyMessageSet)(nil) - -var extRange_MyMessageSet = []proto.ExtensionRange{ - {100, 2147483646}, -} - -func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessageSet -} -func (m *MyMessageSet) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -type Empty struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} - -type MessageList struct { - Message []*MessageList_Message `protobuf:"group,1,rep" json:"message,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageList) Reset() { *m = MessageList{} } -func (m *MessageList) String() string { return proto.CompactTextString(m) } -func (*MessageList) ProtoMessage() {} - -func (m *MessageList) GetMessage() []*MessageList_Message { - if m != nil { - return m.Message - } - return nil -} - -type MessageList_Message struct { - Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` - Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageList_Message) Reset() { *m = MessageList_Message{} } -func (m *MessageList_Message) String() string { return proto.CompactTextString(m) } -func (*MessageList_Message) ProtoMessage() {} - -func (m *MessageList_Message) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MessageList_Message) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -type Strings struct { - StringField *string `protobuf:"bytes,1,opt,name=string_field" json:"string_field,omitempty"` - BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field" json:"bytes_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Strings) Reset() { *m = Strings{} } -func (m *Strings) String() string { return proto.CompactTextString(m) } -func (*Strings) ProtoMessage() {} - -func (m *Strings) GetStringField() string { - if m != nil && m.StringField != nil { - return *m.StringField - } - return "" -} - -func (m *Strings) GetBytesField() []byte { - if m != nil { - return m.BytesField - } - return nil -} - -type Defaults struct { - // Default-valued fields of all basic types. - // Same as GoTest, but copied here to make testing easier. - F_Bool *bool `protobuf:"varint,1,opt,def=1" json:"F_Bool,omitempty"` - F_Int32 *int32 `protobuf:"varint,2,opt,def=32" json:"F_Int32,omitempty"` - F_Int64 *int64 `protobuf:"varint,3,opt,def=64" json:"F_Int64,omitempty"` - F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,def=320" json:"F_Fixed32,omitempty"` - F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,def=640" json:"F_Fixed64,omitempty"` - F_Uint32 *uint32 `protobuf:"varint,6,opt,def=3200" json:"F_Uint32,omitempty"` - F_Uint64 *uint64 `protobuf:"varint,7,opt,def=6400" json:"F_Uint64,omitempty"` - F_Float *float32 `protobuf:"fixed32,8,opt,def=314159" json:"F_Float,omitempty"` - F_Double *float64 `protobuf:"fixed64,9,opt,def=271828" json:"F_Double,omitempty"` - F_String *string `protobuf:"bytes,10,opt,def=hello, \"world!\"\n" json:"F_String,omitempty"` - F_Bytes []byte `protobuf:"bytes,11,opt,def=Bignose" json:"F_Bytes,omitempty"` - F_Sint32 *int32 `protobuf:"zigzag32,12,opt,def=-32" json:"F_Sint32,omitempty"` - F_Sint64 *int64 `protobuf:"zigzag64,13,opt,def=-64" json:"F_Sint64,omitempty"` - F_Enum *Defaults_Color `protobuf:"varint,14,opt,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"` - // More fields with crazy defaults. - F_Pinf *float32 `protobuf:"fixed32,15,opt,def=inf" json:"F_Pinf,omitempty"` - F_Ninf *float32 `protobuf:"fixed32,16,opt,def=-inf" json:"F_Ninf,omitempty"` - F_Nan *float32 `protobuf:"fixed32,17,opt,def=nan" json:"F_Nan,omitempty"` - // Sub-message. - Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"` - // Redundant but explicit defaults. - StrZero *string `protobuf:"bytes,19,opt,name=str_zero,def=" json:"str_zero,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Defaults) Reset() { *m = Defaults{} } -func (m *Defaults) String() string { return proto.CompactTextString(m) } -func (*Defaults) ProtoMessage() {} - -const Default_Defaults_F_Bool bool = true -const Default_Defaults_F_Int32 int32 = 32 -const Default_Defaults_F_Int64 int64 = 64 -const Default_Defaults_F_Fixed32 uint32 = 320 -const Default_Defaults_F_Fixed64 uint64 = 640 -const Default_Defaults_F_Uint32 uint32 = 3200 -const Default_Defaults_F_Uint64 uint64 = 6400 -const Default_Defaults_F_Float float32 = 314159 -const Default_Defaults_F_Double float64 = 271828 -const Default_Defaults_F_String string = "hello, \"world!\"\n" - -var Default_Defaults_F_Bytes []byte = []byte("Bignose") - -const Default_Defaults_F_Sint32 int32 = -32 -const Default_Defaults_F_Sint64 int64 = -64 -const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN - -var Default_Defaults_F_Pinf float32 = float32(math.Inf(1)) -var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1)) -var Default_Defaults_F_Nan float32 = float32(math.NaN()) - -func (m *Defaults) GetF_Bool() bool { - if m != nil && m.F_Bool != nil { - return *m.F_Bool - } - return Default_Defaults_F_Bool -} - -func (m *Defaults) GetF_Int32() int32 { - if m != nil && m.F_Int32 != nil { - return *m.F_Int32 - } - return Default_Defaults_F_Int32 -} - -func (m *Defaults) GetF_Int64() int64 { - if m != nil && m.F_Int64 != nil { - return *m.F_Int64 - } - return Default_Defaults_F_Int64 -} - -func (m *Defaults) GetF_Fixed32() uint32 { - if m != nil && m.F_Fixed32 != nil { - return *m.F_Fixed32 - } - return Default_Defaults_F_Fixed32 -} - -func (m *Defaults) GetF_Fixed64() uint64 { - if m != nil && m.F_Fixed64 != nil { - return *m.F_Fixed64 - } - return Default_Defaults_F_Fixed64 -} - -func (m *Defaults) GetF_Uint32() uint32 { - if m != nil && m.F_Uint32 != nil { - return *m.F_Uint32 - } - return Default_Defaults_F_Uint32 -} - -func (m *Defaults) GetF_Uint64() uint64 { - if m != nil && m.F_Uint64 != nil { - return *m.F_Uint64 - } - return Default_Defaults_F_Uint64 -} - -func (m *Defaults) GetF_Float() float32 { - if m != nil && m.F_Float != nil { - return *m.F_Float - } - return Default_Defaults_F_Float -} - -func (m *Defaults) GetF_Double() float64 { - if m != nil && m.F_Double != nil { - return *m.F_Double - } - return Default_Defaults_F_Double -} - -func (m *Defaults) GetF_String() string { - if m != nil && m.F_String != nil { - return *m.F_String - } - return Default_Defaults_F_String -} - -func (m *Defaults) GetF_Bytes() []byte { - if m != nil && m.F_Bytes != nil { - return m.F_Bytes - } - return append([]byte(nil), Default_Defaults_F_Bytes...) -} - -func (m *Defaults) GetF_Sint32() int32 { - if m != nil && m.F_Sint32 != nil { - return *m.F_Sint32 - } - return Default_Defaults_F_Sint32 -} - -func (m *Defaults) GetF_Sint64() int64 { - if m != nil && m.F_Sint64 != nil { - return *m.F_Sint64 - } - return Default_Defaults_F_Sint64 -} - -func (m *Defaults) GetF_Enum() Defaults_Color { - if m != nil && m.F_Enum != nil { - return *m.F_Enum - } - return Default_Defaults_F_Enum -} - -func (m *Defaults) GetF_Pinf() float32 { - if m != nil && m.F_Pinf != nil { - return *m.F_Pinf - } - return Default_Defaults_F_Pinf -} - -func (m *Defaults) GetF_Ninf() float32 { - if m != nil && m.F_Ninf != nil { - return *m.F_Ninf - } - return Default_Defaults_F_Ninf -} - -func (m *Defaults) GetF_Nan() float32 { - if m != nil && m.F_Nan != nil { - return *m.F_Nan - } - return Default_Defaults_F_Nan -} - -func (m *Defaults) GetSub() *SubDefaults { - if m != nil { - return m.Sub - } - return nil -} - -func (m *Defaults) GetStrZero() string { - if m != nil && m.StrZero != nil { - return *m.StrZero - } - return "" -} - -type SubDefaults struct { - N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SubDefaults) Reset() { *m = SubDefaults{} } -func (m *SubDefaults) String() string { return proto.CompactTextString(m) } -func (*SubDefaults) ProtoMessage() {} - -const Default_SubDefaults_N int64 = 7 - -func (m *SubDefaults) GetN() int64 { - if m != nil && m.N != nil { - return *m.N - } - return Default_SubDefaults_N -} - -type RepeatedEnum struct { - Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} } -func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) } -func (*RepeatedEnum) ProtoMessage() {} - -func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color { - if m != nil { - return m.Color - } - return nil -} - -type MoreRepeated struct { - Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"` - BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed" json:"bools_packed,omitempty"` - Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"` - IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed" json:"ints_packed,omitempty"` - Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed" json:"int64s_packed,omitempty"` - Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"` - Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MoreRepeated) Reset() { *m = MoreRepeated{} } -func (m *MoreRepeated) String() string { return proto.CompactTextString(m) } -func (*MoreRepeated) ProtoMessage() {} - -func (m *MoreRepeated) GetBools() []bool { - if m != nil { - return m.Bools - } - return nil -} - -func (m *MoreRepeated) GetBoolsPacked() []bool { - if m != nil { - return m.BoolsPacked - } - return nil -} - -func (m *MoreRepeated) GetInts() []int32 { - if m != nil { - return m.Ints - } - return nil -} - -func (m *MoreRepeated) GetIntsPacked() []int32 { - if m != nil { - return m.IntsPacked - } - return nil -} - -func (m *MoreRepeated) GetInt64SPacked() []int64 { - if m != nil { - return m.Int64SPacked - } - return nil -} - -func (m *MoreRepeated) GetStrings() []string { - if m != nil { - return m.Strings - } - return nil -} - -func (m *MoreRepeated) GetFixeds() []uint32 { - if m != nil { - return m.Fixeds - } - return nil -} - -type GroupOld struct { - G *GroupOld_G `protobuf:"group,101,opt" json:"g,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupOld) Reset() { *m = GroupOld{} } -func (m *GroupOld) String() string { return proto.CompactTextString(m) } -func (*GroupOld) ProtoMessage() {} - -func (m *GroupOld) GetG() *GroupOld_G { - if m != nil { - return m.G - } - return nil -} - -type GroupOld_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupOld_G) Reset() { *m = GroupOld_G{} } -func (m *GroupOld_G) String() string { return proto.CompactTextString(m) } -func (*GroupOld_G) ProtoMessage() {} - -func (m *GroupOld_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -type GroupNew struct { - G *GroupNew_G `protobuf:"group,101,opt" json:"g,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupNew) Reset() { *m = GroupNew{} } -func (m *GroupNew) String() string { return proto.CompactTextString(m) } -func (*GroupNew) ProtoMessage() {} - -func (m *GroupNew) GetG() *GroupNew_G { - if m != nil { - return m.G - } - return nil -} - -type GroupNew_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupNew_G) Reset() { *m = GroupNew_G{} } -func (m *GroupNew_G) String() string { return proto.CompactTextString(m) } -func (*GroupNew_G) ProtoMessage() {} - -func (m *GroupNew_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -func (m *GroupNew_G) GetY() int32 { - if m != nil && m.Y != nil { - return *m.Y - } - return 0 -} - -type FloatingPoint struct { - F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FloatingPoint) Reset() { *m = FloatingPoint{} } -func (m *FloatingPoint) String() string { return proto.CompactTextString(m) } -func (*FloatingPoint) ProtoMessage() {} - -func (m *FloatingPoint) GetF() float64 { - if m != nil && m.F != nil { - return *m.F - } - return 0 -} - -type MessageWithMap struct { - NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - StrToStr map[string]string `protobuf:"bytes,4,rep,name=str_to_str" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } -func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } -func (*MessageWithMap) ProtoMessage() {} - -func (m *MessageWithMap) GetNameMapping() map[int32]string { - if m != nil { - return m.NameMapping - } - return nil -} - -func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint { - if m != nil { - return m.MsgMapping - } - return nil -} - -func (m *MessageWithMap) GetByteMapping() map[bool][]byte { - if m != nil { - return m.ByteMapping - } - return nil -} - -func (m *MessageWithMap) GetStrToStr() map[string]string { - if m != nil { - return m.StrToStr - } - return nil -} - -var E_Greeting = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: ([]string)(nil), - Field: 106, - Name: "testdata.greeting", - Tag: "bytes,106,rep,name=greeting", -} - -var E_NoDefaultDouble = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float64)(nil), - Field: 101, - Name: "testdata.no_default_double", - Tag: "fixed64,101,opt,name=no_default_double", -} - -var E_NoDefaultFloat = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float32)(nil), - Field: 102, - Name: "testdata.no_default_float", - Tag: "fixed32,102,opt,name=no_default_float", -} - -var E_NoDefaultInt32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 103, - Name: "testdata.no_default_int32", - Tag: "varint,103,opt,name=no_default_int32", -} - -var E_NoDefaultInt64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 104, - Name: "testdata.no_default_int64", - Tag: "varint,104,opt,name=no_default_int64", -} - -var E_NoDefaultUint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 105, - Name: "testdata.no_default_uint32", - Tag: "varint,105,opt,name=no_default_uint32", -} - -var E_NoDefaultUint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 106, - Name: "testdata.no_default_uint64", - Tag: "varint,106,opt,name=no_default_uint64", -} - -var E_NoDefaultSint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 107, - Name: "testdata.no_default_sint32", - Tag: "zigzag32,107,opt,name=no_default_sint32", -} - -var E_NoDefaultSint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 108, - Name: "testdata.no_default_sint64", - Tag: "zigzag64,108,opt,name=no_default_sint64", -} - -var E_NoDefaultFixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 109, - Name: "testdata.no_default_fixed32", - Tag: "fixed32,109,opt,name=no_default_fixed32", -} - -var E_NoDefaultFixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 110, - Name: "testdata.no_default_fixed64", - Tag: "fixed64,110,opt,name=no_default_fixed64", -} - -var E_NoDefaultSfixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 111, - Name: "testdata.no_default_sfixed32", - Tag: "fixed32,111,opt,name=no_default_sfixed32", -} - -var E_NoDefaultSfixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 112, - Name: "testdata.no_default_sfixed64", - Tag: "fixed64,112,opt,name=no_default_sfixed64", -} - -var E_NoDefaultBool = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 113, - Name: "testdata.no_default_bool", - Tag: "varint,113,opt,name=no_default_bool", -} - -var E_NoDefaultString = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*string)(nil), - Field: 114, - Name: "testdata.no_default_string", - Tag: "bytes,114,opt,name=no_default_string", -} - -var E_NoDefaultBytes = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: ([]byte)(nil), - Field: 115, - Name: "testdata.no_default_bytes", - Tag: "bytes,115,opt,name=no_default_bytes", -} - -var E_NoDefaultEnum = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), - Field: 116, - Name: "testdata.no_default_enum", - Tag: "varint,116,opt,name=no_default_enum,enum=testdata.DefaultsMessage_DefaultsEnum", -} - -var E_DefaultDouble = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float64)(nil), - Field: 201, - Name: "testdata.default_double", - Tag: "fixed64,201,opt,name=default_double,def=3.1415", -} - -var E_DefaultFloat = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float32)(nil), - Field: 202, - Name: "testdata.default_float", - Tag: "fixed32,202,opt,name=default_float,def=3.14", -} - -var E_DefaultInt32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 203, - Name: "testdata.default_int32", - Tag: "varint,203,opt,name=default_int32,def=42", -} - -var E_DefaultInt64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 204, - Name: "testdata.default_int64", - Tag: "varint,204,opt,name=default_int64,def=43", -} - -var E_DefaultUint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 205, - Name: "testdata.default_uint32", - Tag: "varint,205,opt,name=default_uint32,def=44", -} - -var E_DefaultUint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 206, - Name: "testdata.default_uint64", - Tag: "varint,206,opt,name=default_uint64,def=45", -} - -var E_DefaultSint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 207, - Name: "testdata.default_sint32", - Tag: "zigzag32,207,opt,name=default_sint32,def=46", -} - -var E_DefaultSint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 208, - Name: "testdata.default_sint64", - Tag: "zigzag64,208,opt,name=default_sint64,def=47", -} - -var E_DefaultFixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 209, - Name: "testdata.default_fixed32", - Tag: "fixed32,209,opt,name=default_fixed32,def=48", -} - -var E_DefaultFixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 210, - Name: "testdata.default_fixed64", - Tag: "fixed64,210,opt,name=default_fixed64,def=49", -} - -var E_DefaultSfixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 211, - Name: "testdata.default_sfixed32", - Tag: "fixed32,211,opt,name=default_sfixed32,def=50", -} - -var E_DefaultSfixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 212, - Name: "testdata.default_sfixed64", - Tag: "fixed64,212,opt,name=default_sfixed64,def=51", -} - -var E_DefaultBool = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 213, - Name: "testdata.default_bool", - Tag: "varint,213,opt,name=default_bool,def=1", -} - -var E_DefaultString = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*string)(nil), - Field: 214, - Name: "testdata.default_string", - Tag: "bytes,214,opt,name=default_string,def=Hello, string", -} - -var E_DefaultBytes = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: ([]byte)(nil), - Field: 215, - Name: "testdata.default_bytes", - Tag: "bytes,215,opt,name=default_bytes,def=Hello, bytes", -} - -var E_DefaultEnum = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), - Field: 216, - Name: "testdata.default_enum", - Tag: "varint,216,opt,name=default_enum,enum=testdata.DefaultsMessage_DefaultsEnum,def=1", -} - -var E_X201 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 201, - Name: "testdata.x201", - Tag: "bytes,201,opt,name=x201", -} - -var E_X202 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 202, - Name: "testdata.x202", - Tag: "bytes,202,opt,name=x202", -} - -var E_X203 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 203, - Name: "testdata.x203", - Tag: "bytes,203,opt,name=x203", -} - -var E_X204 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 204, - Name: "testdata.x204", - Tag: "bytes,204,opt,name=x204", -} - -var E_X205 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 205, - Name: "testdata.x205", - Tag: "bytes,205,opt,name=x205", -} - -var E_X206 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 206, - Name: "testdata.x206", - Tag: "bytes,206,opt,name=x206", -} - -var E_X207 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 207, - Name: "testdata.x207", - Tag: "bytes,207,opt,name=x207", -} - -var E_X208 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 208, - Name: "testdata.x208", - Tag: "bytes,208,opt,name=x208", -} - -var E_X209 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 209, - Name: "testdata.x209", - Tag: "bytes,209,opt,name=x209", -} - -var E_X210 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 210, - Name: "testdata.x210", - Tag: "bytes,210,opt,name=x210", -} - -var E_X211 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 211, - Name: "testdata.x211", - Tag: "bytes,211,opt,name=x211", -} - -var E_X212 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 212, - Name: "testdata.x212", - Tag: "bytes,212,opt,name=x212", -} - -var E_X213 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 213, - Name: "testdata.x213", - Tag: "bytes,213,opt,name=x213", -} - -var E_X214 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 214, - Name: "testdata.x214", - Tag: "bytes,214,opt,name=x214", -} - -var E_X215 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 215, - Name: "testdata.x215", - Tag: "bytes,215,opt,name=x215", -} - -var E_X216 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 216, - Name: "testdata.x216", - Tag: "bytes,216,opt,name=x216", -} - -var E_X217 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 217, - Name: "testdata.x217", - Tag: "bytes,217,opt,name=x217", -} - -var E_X218 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 218, - Name: "testdata.x218", - Tag: "bytes,218,opt,name=x218", -} - -var E_X219 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 219, - Name: "testdata.x219", - Tag: "bytes,219,opt,name=x219", -} - -var E_X220 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 220, - Name: "testdata.x220", - Tag: "bytes,220,opt,name=x220", -} - -var E_X221 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 221, - Name: "testdata.x221", - Tag: "bytes,221,opt,name=x221", -} - -var E_X222 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 222, - Name: "testdata.x222", - Tag: "bytes,222,opt,name=x222", -} - -var E_X223 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 223, - Name: "testdata.x223", - Tag: "bytes,223,opt,name=x223", -} - -var E_X224 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 224, - Name: "testdata.x224", - Tag: "bytes,224,opt,name=x224", -} - -var E_X225 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 225, - Name: "testdata.x225", - Tag: "bytes,225,opt,name=x225", -} - -var E_X226 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 226, - Name: "testdata.x226", - Tag: "bytes,226,opt,name=x226", -} - -var E_X227 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 227, - Name: "testdata.x227", - Tag: "bytes,227,opt,name=x227", -} - -var E_X228 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 228, - Name: "testdata.x228", - Tag: "bytes,228,opt,name=x228", -} - -var E_X229 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 229, - Name: "testdata.x229", - Tag: "bytes,229,opt,name=x229", -} - -var E_X230 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 230, - Name: "testdata.x230", - Tag: "bytes,230,opt,name=x230", -} - -var E_X231 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 231, - Name: "testdata.x231", - Tag: "bytes,231,opt,name=x231", -} - -var E_X232 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 232, - Name: "testdata.x232", - Tag: "bytes,232,opt,name=x232", -} - -var E_X233 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 233, - Name: "testdata.x233", - Tag: "bytes,233,opt,name=x233", -} - -var E_X234 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 234, - Name: "testdata.x234", - Tag: "bytes,234,opt,name=x234", -} - -var E_X235 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 235, - Name: "testdata.x235", - Tag: "bytes,235,opt,name=x235", -} - -var E_X236 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 236, - Name: "testdata.x236", - Tag: "bytes,236,opt,name=x236", -} - -var E_X237 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 237, - Name: "testdata.x237", - Tag: "bytes,237,opt,name=x237", -} - -var E_X238 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 238, - Name: "testdata.x238", - Tag: "bytes,238,opt,name=x238", -} - -var E_X239 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 239, - Name: "testdata.x239", - Tag: "bytes,239,opt,name=x239", -} - -var E_X240 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 240, - Name: "testdata.x240", - Tag: "bytes,240,opt,name=x240", -} - -var E_X241 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 241, - Name: "testdata.x241", - Tag: "bytes,241,opt,name=x241", -} - -var E_X242 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 242, - Name: "testdata.x242", - Tag: "bytes,242,opt,name=x242", -} - -var E_X243 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 243, - Name: "testdata.x243", - Tag: "bytes,243,opt,name=x243", -} - -var E_X244 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 244, - Name: "testdata.x244", - Tag: "bytes,244,opt,name=x244", -} - -var E_X245 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 245, - Name: "testdata.x245", - Tag: "bytes,245,opt,name=x245", -} - -var E_X246 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 246, - Name: "testdata.x246", - Tag: "bytes,246,opt,name=x246", -} - -var E_X247 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 247, - Name: "testdata.x247", - Tag: "bytes,247,opt,name=x247", -} - -var E_X248 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 248, - Name: "testdata.x248", - Tag: "bytes,248,opt,name=x248", -} - -var E_X249 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 249, - Name: "testdata.x249", - Tag: "bytes,249,opt,name=x249", -} - -var E_X250 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 250, - Name: "testdata.x250", - Tag: "bytes,250,opt,name=x250", -} - -func init() { - proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value) - proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value) - proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value) - proto.RegisterEnum("testdata.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value) - proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value) - proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value) - proto.RegisterExtension(E_Ext_More) - proto.RegisterExtension(E_Ext_Text) - proto.RegisterExtension(E_Ext_Number) - proto.RegisterExtension(E_Greeting) - proto.RegisterExtension(E_NoDefaultDouble) - proto.RegisterExtension(E_NoDefaultFloat) - proto.RegisterExtension(E_NoDefaultInt32) - proto.RegisterExtension(E_NoDefaultInt64) - proto.RegisterExtension(E_NoDefaultUint32) - proto.RegisterExtension(E_NoDefaultUint64) - proto.RegisterExtension(E_NoDefaultSint32) - proto.RegisterExtension(E_NoDefaultSint64) - proto.RegisterExtension(E_NoDefaultFixed32) - proto.RegisterExtension(E_NoDefaultFixed64) - proto.RegisterExtension(E_NoDefaultSfixed32) - proto.RegisterExtension(E_NoDefaultSfixed64) - proto.RegisterExtension(E_NoDefaultBool) - proto.RegisterExtension(E_NoDefaultString) - proto.RegisterExtension(E_NoDefaultBytes) - proto.RegisterExtension(E_NoDefaultEnum) - proto.RegisterExtension(E_DefaultDouble) - proto.RegisterExtension(E_DefaultFloat) - proto.RegisterExtension(E_DefaultInt32) - proto.RegisterExtension(E_DefaultInt64) - proto.RegisterExtension(E_DefaultUint32) - proto.RegisterExtension(E_DefaultUint64) - proto.RegisterExtension(E_DefaultSint32) - proto.RegisterExtension(E_DefaultSint64) - proto.RegisterExtension(E_DefaultFixed32) - proto.RegisterExtension(E_DefaultFixed64) - proto.RegisterExtension(E_DefaultSfixed32) - proto.RegisterExtension(E_DefaultSfixed64) - proto.RegisterExtension(E_DefaultBool) - proto.RegisterExtension(E_DefaultString) - proto.RegisterExtension(E_DefaultBytes) - proto.RegisterExtension(E_DefaultEnum) - proto.RegisterExtension(E_X201) - proto.RegisterExtension(E_X202) - proto.RegisterExtension(E_X203) - proto.RegisterExtension(E_X204) - proto.RegisterExtension(E_X205) - proto.RegisterExtension(E_X206) - proto.RegisterExtension(E_X207) - proto.RegisterExtension(E_X208) - proto.RegisterExtension(E_X209) - proto.RegisterExtension(E_X210) - proto.RegisterExtension(E_X211) - proto.RegisterExtension(E_X212) - proto.RegisterExtension(E_X213) - proto.RegisterExtension(E_X214) - proto.RegisterExtension(E_X215) - proto.RegisterExtension(E_X216) - proto.RegisterExtension(E_X217) - proto.RegisterExtension(E_X218) - proto.RegisterExtension(E_X219) - proto.RegisterExtension(E_X220) - proto.RegisterExtension(E_X221) - proto.RegisterExtension(E_X222) - proto.RegisterExtension(E_X223) - proto.RegisterExtension(E_X224) - proto.RegisterExtension(E_X225) - proto.RegisterExtension(E_X226) - proto.RegisterExtension(E_X227) - proto.RegisterExtension(E_X228) - proto.RegisterExtension(E_X229) - proto.RegisterExtension(E_X230) - proto.RegisterExtension(E_X231) - proto.RegisterExtension(E_X232) - proto.RegisterExtension(E_X233) - proto.RegisterExtension(E_X234) - proto.RegisterExtension(E_X235) - proto.RegisterExtension(E_X236) - proto.RegisterExtension(E_X237) - proto.RegisterExtension(E_X238) - proto.RegisterExtension(E_X239) - proto.RegisterExtension(E_X240) - proto.RegisterExtension(E_X241) - proto.RegisterExtension(E_X242) - proto.RegisterExtension(E_X243) - proto.RegisterExtension(E_X244) - proto.RegisterExtension(E_X245) - proto.RegisterExtension(E_X246) - proto.RegisterExtension(E_X247) - proto.RegisterExtension(E_X248) - proto.RegisterExtension(E_X249) - proto.RegisterExtension(E_X250) -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto deleted file mode 100644 index 440dba3..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto +++ /dev/null @@ -1,480 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// A feature-rich test file for the protocol compiler and libraries. - -syntax = "proto2"; - -package testdata; - -enum FOO { FOO1 = 1; }; - -message GoEnum { - required FOO foo = 1; -} - -message GoTestField { - required string Label = 1; - required string Type = 2; -} - -message GoTest { - // An enum, for completeness. - enum KIND { - VOID = 0; - - // Basic types - BOOL = 1; - BYTES = 2; - FINGERPRINT = 3; - FLOAT = 4; - INT = 5; - STRING = 6; - TIME = 7; - - // Groupings - TUPLE = 8; - ARRAY = 9; - MAP = 10; - - // Table types - TABLE = 11; - - // Functions - FUNCTION = 12; // last tag - }; - - // Some typical parameters - required KIND Kind = 1; - optional string Table = 2; - optional int32 Param = 3; - - // Required, repeated and optional foreign fields. - required GoTestField RequiredField = 4; - repeated GoTestField RepeatedField = 5; - optional GoTestField OptionalField = 6; - - // Required fields of all basic types - required bool F_Bool_required = 10; - required int32 F_Int32_required = 11; - required int64 F_Int64_required = 12; - required fixed32 F_Fixed32_required = 13; - required fixed64 F_Fixed64_required = 14; - required uint32 F_Uint32_required = 15; - required uint64 F_Uint64_required = 16; - required float F_Float_required = 17; - required double F_Double_required = 18; - required string F_String_required = 19; - required bytes F_Bytes_required = 101; - required sint32 F_Sint32_required = 102; - required sint64 F_Sint64_required = 103; - - // Repeated fields of all basic types - repeated bool F_Bool_repeated = 20; - repeated int32 F_Int32_repeated = 21; - repeated int64 F_Int64_repeated = 22; - repeated fixed32 F_Fixed32_repeated = 23; - repeated fixed64 F_Fixed64_repeated = 24; - repeated uint32 F_Uint32_repeated = 25; - repeated uint64 F_Uint64_repeated = 26; - repeated float F_Float_repeated = 27; - repeated double F_Double_repeated = 28; - repeated string F_String_repeated = 29; - repeated bytes F_Bytes_repeated = 201; - repeated sint32 F_Sint32_repeated = 202; - repeated sint64 F_Sint64_repeated = 203; - - // Optional fields of all basic types - optional bool F_Bool_optional = 30; - optional int32 F_Int32_optional = 31; - optional int64 F_Int64_optional = 32; - optional fixed32 F_Fixed32_optional = 33; - optional fixed64 F_Fixed64_optional = 34; - optional uint32 F_Uint32_optional = 35; - optional uint64 F_Uint64_optional = 36; - optional float F_Float_optional = 37; - optional double F_Double_optional = 38; - optional string F_String_optional = 39; - optional bytes F_Bytes_optional = 301; - optional sint32 F_Sint32_optional = 302; - optional sint64 F_Sint64_optional = 303; - - // Default-valued fields of all basic types - optional bool F_Bool_defaulted = 40 [default=true]; - optional int32 F_Int32_defaulted = 41 [default=32]; - optional int64 F_Int64_defaulted = 42 [default=64]; - optional fixed32 F_Fixed32_defaulted = 43 [default=320]; - optional fixed64 F_Fixed64_defaulted = 44 [default=640]; - optional uint32 F_Uint32_defaulted = 45 [default=3200]; - optional uint64 F_Uint64_defaulted = 46 [default=6400]; - optional float F_Float_defaulted = 47 [default=314159.]; - optional double F_Double_defaulted = 48 [default=271828.]; - optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"]; - optional bytes F_Bytes_defaulted = 401 [default="Bignose"]; - optional sint32 F_Sint32_defaulted = 402 [default = -32]; - optional sint64 F_Sint64_defaulted = 403 [default = -64]; - - // Packed repeated fields (no string or bytes). - repeated bool F_Bool_repeated_packed = 50 [packed=true]; - repeated int32 F_Int32_repeated_packed = 51 [packed=true]; - repeated int64 F_Int64_repeated_packed = 52 [packed=true]; - repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true]; - repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true]; - repeated uint32 F_Uint32_repeated_packed = 55 [packed=true]; - repeated uint64 F_Uint64_repeated_packed = 56 [packed=true]; - repeated float F_Float_repeated_packed = 57 [packed=true]; - repeated double F_Double_repeated_packed = 58 [packed=true]; - repeated sint32 F_Sint32_repeated_packed = 502 [packed=true]; - repeated sint64 F_Sint64_repeated_packed = 503 [packed=true]; - - // Required, repeated, and optional groups. - required group RequiredGroup = 70 { - required string RequiredField = 71; - }; - - repeated group RepeatedGroup = 80 { - required string RequiredField = 81; - }; - - optional group OptionalGroup = 90 { - required string RequiredField = 91; - }; -} - -// For testing skipping of unrecognized fields. -// Numbers are all big, larger than tag numbers in GoTestField, -// the message used in the corresponding test. -message GoSkipTest { - required int32 skip_int32 = 11; - required fixed32 skip_fixed32 = 12; - required fixed64 skip_fixed64 = 13; - required string skip_string = 14; - required group SkipGroup = 15 { - required int32 group_int32 = 16; - required string group_string = 17; - } -} - -// For testing packed/non-packed decoder switching. -// A serialized instance of one should be deserializable as the other. -message NonPackedTest { - repeated int32 a = 1; -} - -message PackedTest { - repeated int32 b = 1 [packed=true]; -} - -message MaxTag { - // Maximum possible tag number. - optional string last_field = 536870911; -} - -message OldMessage { - message Nested { - optional string name = 1; - } - optional Nested nested = 1; - - optional int32 num = 2; -} - -// NewMessage is wire compatible with OldMessage; -// imagine it as a future version. -message NewMessage { - message Nested { - optional string name = 1; - optional string food_group = 2; - } - optional Nested nested = 1; - - // This is an int32 in OldMessage. - optional int64 num = 2; -} - -// Smaller tests for ASCII formatting. - -message InnerMessage { - required string host = 1; - optional int32 port = 2 [default=4000]; - optional bool connected = 3; -} - -message OtherMessage { - optional int64 key = 1; - optional bytes value = 2; - optional float weight = 3; - optional InnerMessage inner = 4; -} - -message MyMessage { - required int32 count = 1; - optional string name = 2; - optional string quote = 3; - repeated string pet = 4; - optional InnerMessage inner = 5; - repeated OtherMessage others = 6; - repeated InnerMessage rep_inner = 12; - - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - }; - optional Color bikeshed = 7; - - optional group SomeGroup = 8 { - optional int32 group_field = 9; - } - - // This field becomes [][]byte in the generated code. - repeated bytes rep_bytes = 10; - - optional double bigfloat = 11; - - extensions 100 to max; -} - -message Ext { - extend MyMessage { - optional Ext more = 103; - optional string text = 104; - optional int32 number = 105; - } - - optional string data = 1; -} - -extend MyMessage { - repeated string greeting = 106; -} - -message DefaultsMessage { - enum DefaultsEnum { - ZERO = 0; - ONE = 1; - TWO = 2; - }; - extensions 100 to max; -} - -extend DefaultsMessage { - optional double no_default_double = 101; - optional float no_default_float = 102; - optional int32 no_default_int32 = 103; - optional int64 no_default_int64 = 104; - optional uint32 no_default_uint32 = 105; - optional uint64 no_default_uint64 = 106; - optional sint32 no_default_sint32 = 107; - optional sint64 no_default_sint64 = 108; - optional fixed32 no_default_fixed32 = 109; - optional fixed64 no_default_fixed64 = 110; - optional sfixed32 no_default_sfixed32 = 111; - optional sfixed64 no_default_sfixed64 = 112; - optional bool no_default_bool = 113; - optional string no_default_string = 114; - optional bytes no_default_bytes = 115; - optional DefaultsMessage.DefaultsEnum no_default_enum = 116; - - optional double default_double = 201 [default = 3.1415]; - optional float default_float = 202 [default = 3.14]; - optional int32 default_int32 = 203 [default = 42]; - optional int64 default_int64 = 204 [default = 43]; - optional uint32 default_uint32 = 205 [default = 44]; - optional uint64 default_uint64 = 206 [default = 45]; - optional sint32 default_sint32 = 207 [default = 46]; - optional sint64 default_sint64 = 208 [default = 47]; - optional fixed32 default_fixed32 = 209 [default = 48]; - optional fixed64 default_fixed64 = 210 [default = 49]; - optional sfixed32 default_sfixed32 = 211 [default = 50]; - optional sfixed64 default_sfixed64 = 212 [default = 51]; - optional bool default_bool = 213 [default = true]; - optional string default_string = 214 [default = "Hello, string"]; - optional bytes default_bytes = 215 [default = "Hello, bytes"]; - optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE]; -} - -message MyMessageSet { - option message_set_wire_format = true; - extensions 100 to max; -} - -message Empty { -} - -extend MyMessageSet { - optional Empty x201 = 201; - optional Empty x202 = 202; - optional Empty x203 = 203; - optional Empty x204 = 204; - optional Empty x205 = 205; - optional Empty x206 = 206; - optional Empty x207 = 207; - optional Empty x208 = 208; - optional Empty x209 = 209; - optional Empty x210 = 210; - optional Empty x211 = 211; - optional Empty x212 = 212; - optional Empty x213 = 213; - optional Empty x214 = 214; - optional Empty x215 = 215; - optional Empty x216 = 216; - optional Empty x217 = 217; - optional Empty x218 = 218; - optional Empty x219 = 219; - optional Empty x220 = 220; - optional Empty x221 = 221; - optional Empty x222 = 222; - optional Empty x223 = 223; - optional Empty x224 = 224; - optional Empty x225 = 225; - optional Empty x226 = 226; - optional Empty x227 = 227; - optional Empty x228 = 228; - optional Empty x229 = 229; - optional Empty x230 = 230; - optional Empty x231 = 231; - optional Empty x232 = 232; - optional Empty x233 = 233; - optional Empty x234 = 234; - optional Empty x235 = 235; - optional Empty x236 = 236; - optional Empty x237 = 237; - optional Empty x238 = 238; - optional Empty x239 = 239; - optional Empty x240 = 240; - optional Empty x241 = 241; - optional Empty x242 = 242; - optional Empty x243 = 243; - optional Empty x244 = 244; - optional Empty x245 = 245; - optional Empty x246 = 246; - optional Empty x247 = 247; - optional Empty x248 = 248; - optional Empty x249 = 249; - optional Empty x250 = 250; -} - -message MessageList { - repeated group Message = 1 { - required string name = 2; - required int32 count = 3; - } -} - -message Strings { - optional string string_field = 1; - optional bytes bytes_field = 2; -} - -message Defaults { - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - } - - // Default-valued fields of all basic types. - // Same as GoTest, but copied here to make testing easier. - optional bool F_Bool = 1 [default=true]; - optional int32 F_Int32 = 2 [default=32]; - optional int64 F_Int64 = 3 [default=64]; - optional fixed32 F_Fixed32 = 4 [default=320]; - optional fixed64 F_Fixed64 = 5 [default=640]; - optional uint32 F_Uint32 = 6 [default=3200]; - optional uint64 F_Uint64 = 7 [default=6400]; - optional float F_Float = 8 [default=314159.]; - optional double F_Double = 9 [default=271828.]; - optional string F_String = 10 [default="hello, \"world!\"\n"]; - optional bytes F_Bytes = 11 [default="Bignose"]; - optional sint32 F_Sint32 = 12 [default=-32]; - optional sint64 F_Sint64 = 13 [default=-64]; - optional Color F_Enum = 14 [default=GREEN]; - - // More fields with crazy defaults. - optional float F_Pinf = 15 [default=inf]; - optional float F_Ninf = 16 [default=-inf]; - optional float F_Nan = 17 [default=nan]; - - // Sub-message. - optional SubDefaults sub = 18; - - // Redundant but explicit defaults. - optional string str_zero = 19 [default=""]; -} - -message SubDefaults { - optional int64 n = 1 [default=7]; -} - -message RepeatedEnum { - enum Color { - RED = 1; - } - repeated Color color = 1; -} - -message MoreRepeated { - repeated bool bools = 1; - repeated bool bools_packed = 2 [packed=true]; - repeated int32 ints = 3; - repeated int32 ints_packed = 4 [packed=true]; - repeated int64 int64s_packed = 7 [packed=true]; - repeated string strings = 5; - repeated fixed32 fixeds = 6; -} - -// GroupOld and GroupNew have the same wire format. -// GroupNew has a new field inside a group. - -message GroupOld { - optional group G = 101 { - optional int32 x = 2; - } -} - -message GroupNew { - optional group G = 101 { - optional int32 x = 2; - optional int32 y = 3; - } -} - -message FloatingPoint { - required double f = 1; -} - -message MessageWithMap { - map name_mapping = 1; - map msg_mapping = 2; - map byte_mapping = 3; - map str_to_str = 4; -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go deleted file mode 100644 index f7dc58a..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go +++ /dev/null @@ -1,769 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for writing the text protocol buffer format. - -import ( - "bufio" - "bytes" - "encoding" - "fmt" - "io" - "log" - "math" - "reflect" - "sort" - "strings" -) - -var ( - newline = []byte("\n") - spaces = []byte(" ") - gtNewline = []byte(">\n") - endBraceNewline = []byte("}\n") - backslashN = []byte{'\\', 'n'} - backslashR = []byte{'\\', 'r'} - backslashT = []byte{'\\', 't'} - backslashDQ = []byte{'\\', '"'} - backslashBS = []byte{'\\', '\\'} - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -type writer interface { - io.Writer - WriteByte(byte) error -} - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - ind int - complete bool // if the current position is a complete line - compact bool // whether to write out as a one-liner - w writer -} - -func (w *textWriter) WriteString(s string) (n int, err error) { - if !strings.Contains(s, "\n") { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - return io.WriteString(w.w, s) - } - // WriteString is typically called without newlines, so this - // codepath and its copy are rare. We copy to avoid - // duplicating all of Write's logic here. - return w.Write([]byte(s)) -} - -func (w *textWriter) Write(p []byte) (n int, err error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - n, err = w.w.Write(p) - w.complete = false - return n, err - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - if err := w.w.WriteByte(' '); err != nil { - return n, err - } - n++ - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - if i+1 < len(frags) { - if err := w.w.WriteByte('\n'); err != nil { - return n, err - } - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - err := w.w.WriteByte(c) - w.complete = c == '\n' - return err -} - -func (w *textWriter) indent() { w.ind++ } - -func (w *textWriter) unindent() { - if w.ind == 0 { - log.Printf("proto: textWriter unindented too far") - return - } - w.ind-- -} - -func writeName(w *textWriter, props *Properties) error { - if _, err := w.WriteString(props.OrigName); err != nil { - return err - } - if props.Wire != "group" { - return w.WriteByte(':') - } - return nil -} - -var ( - messageSetType = reflect.TypeOf((*MessageSet)(nil)).Elem() -) - -// raw is the interface satisfied by RawMessage. -type raw interface { - Bytes() []byte -} - -func writeStruct(w *textWriter, sv reflect.Value) error { - if sv.Type() == messageSetType { - return writeMessageSet(w, sv.Addr().Interface().(*MessageSet)) - } - - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < sv.NumField(); i++ { - fv := sv.Field(i) - props := sprops.Prop[i] - name := st.Field(i).Name - - if strings.HasPrefix(name, "XXX_") { - // There are two XXX_ fields: - // XXX_unrecognized []byte - // XXX_extensions map[int32]proto.Extension - // The first is handled here; - // the second is handled at the bottom of this function. - if name == "XXX_unrecognized" && !fv.IsNil() { - if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Field not filled in. This could be an optional field or - // a required field that wasn't filled in. Either way, there - // isn't anything we can show for it. - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - // Repeated field that is empty, or a bytes field that is unused. - continue - } - - if props.Repeated && fv.Kind() == reflect.Slice { - // Repeated field. - for j := 0; j < fv.Len(); j++ { - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - v := fv.Index(j) - if v.Kind() == reflect.Ptr && v.IsNil() { - // A nil message in a repeated field is not valid, - // but we can handle that more gracefully than panicking. - if _, err := w.Write([]byte("\n")); err != nil { - return err - } - continue - } - if err := writeAny(w, v, props); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Map { - // Map fields are rendered as a repeated struct with key/value fields. - keys := fv.MapKeys() // TODO: should we sort these for deterministic output? - sort.Sort(mapKeys(keys)) - for _, key := range keys { - val := fv.MapIndex(key) - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - // open struct - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - // key - if _, err := w.WriteString("key:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := writeAny(w, key, props.mkeyprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - // nil values aren't legal, but we can avoid panicking because of them. - if val.Kind() != reflect.Ptr || !val.IsNil() { - // value - if _, err := w.WriteString("value:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := writeAny(w, val, props.mvalprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - // close struct - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { - // empty bytes field - continue - } - if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { - // proto3 non-repeated scalar field; skip if zero value - if isProto3Zero(fv) { - continue - } - } - - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if b, ok := fv.Interface().(raw); ok { - if err := writeRaw(w, b.Bytes()); err != nil { - return err - } - continue - } - - // Enums have a String method, so writeAny will work fine. - if err := writeAny(w, fv, props); err != nil { - return err - } - - if err := w.WriteByte('\n'); err != nil { - return err - } - } - - // Extensions (the XXX_extensions field). - pv := sv.Addr() - if pv.Type().Implements(extendableProtoType) { - if err := writeExtensions(w, pv); err != nil { - return err - } - } - - return nil -} - -// writeRaw writes an uninterpreted raw message. -func writeRaw(w *textWriter, b []byte) error { - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if err := writeUnknownStruct(w, b); err != nil { - return err - } - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - return nil -} - -// writeAny writes an arbitrary field. -func writeAny(w *textWriter, v reflect.Value, props *Properties) error { - v = reflect.Indirect(v) - - // Floats have special cases. - if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { - x := v.Float() - var b []byte - switch { - case math.IsInf(x, 1): - b = posInf - case math.IsInf(x, -1): - b = negInf - case math.IsNaN(x): - b = nan - } - if b != nil { - _, err := w.Write(b) - return err - } - // Other values are handled below. - } - - // We don't attempt to serialise every possible value type; only those - // that can occur in protocol buffers. - switch v.Kind() { - case reflect.Slice: - // Should only be a []byte; repeated fields are handled in writeStruct. - if err := writeString(w, string(v.Interface().([]byte))); err != nil { - return err - } - case reflect.String: - if err := writeString(w, v.String()); err != nil { - return err - } - case reflect.Struct: - // Required/optional group/message. - var bra, ket byte = '<', '>' - if props != nil && props.Wire == "group" { - bra, ket = '{', '}' - } - if err := w.WriteByte(bra); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if tm, ok := v.Interface().(encoding.TextMarshaler); ok { - text, err := tm.MarshalText() - if err != nil { - return err - } - if _, err = w.Write(text); err != nil { - return err - } - } else if err := writeStruct(w, v); err != nil { - return err - } - w.unindent() - if err := w.WriteByte(ket); err != nil { - return err - } - default: - _, err := fmt.Fprint(w, v.Interface()) - return err - } - return nil -} - -// equivalent to C's isprint. -func isprint(c byte) bool { - return c >= 0x20 && c < 0x7f -} - -// writeString writes a string in the protocol buffer text format. -// It is similar to strconv.Quote except we don't use Go escape sequences, -// we treat the string as a byte sequence, and we use octal escapes. -// These differences are to maintain interoperability with the other -// languages' implementations of the text format. -func writeString(w *textWriter, s string) error { - // use WriteByte here to get any needed indent - if err := w.WriteByte('"'); err != nil { - return err - } - // Loop over the bytes, not the runes. - for i := 0; i < len(s); i++ { - var err error - // Divergence from C++: we don't escape apostrophes. - // There's no need to escape them, and the C++ parser - // copes with a naked apostrophe. - switch c := s[i]; c { - case '\n': - _, err = w.w.Write(backslashN) - case '\r': - _, err = w.w.Write(backslashR) - case '\t': - _, err = w.w.Write(backslashT) - case '"': - _, err = w.w.Write(backslashDQ) - case '\\': - _, err = w.w.Write(backslashBS) - default: - if isprint(c) { - err = w.w.WriteByte(c) - } else { - _, err = fmt.Fprintf(w.w, "\\%03o", c) - } - } - if err != nil { - return err - } - } - return w.WriteByte('"') -} - -func writeMessageSet(w *textWriter, ms *MessageSet) error { - for _, item := range ms.Item { - id := *item.TypeId - if msd, ok := messageSetMap[id]; ok { - // Known message set type. - if _, err := fmt.Fprintf(w, "[%s]: <\n", msd.name); err != nil { - return err - } - w.indent() - - pb := reflect.New(msd.t.Elem()) - if err := Unmarshal(item.Message, pb.Interface().(Message)); err != nil { - if _, err := fmt.Fprintf(w, "/* bad message: %v */\n", err); err != nil { - return err - } - } else { - if err := writeStruct(w, pb.Elem()); err != nil { - return err - } - } - } else { - // Unknown type. - if _, err := fmt.Fprintf(w, "[%d]: <\n", id); err != nil { - return err - } - w.indent() - if err := writeUnknownStruct(w, item.Message); err != nil { - return err - } - } - w.unindent() - if _, err := w.Write(gtNewline); err != nil { - return err - } - } - return nil -} - -func writeUnknownStruct(w *textWriter, data []byte) (err error) { - if !w.compact { - if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { - return err - } - } - b := NewBuffer(data) - for b.index < len(b.buf) { - x, err := b.DecodeVarint() - if err != nil { - _, err := fmt.Fprintf(w, "/* %v */\n", err) - return err - } - wire, tag := x&7, x>>3 - if wire == WireEndGroup { - w.unindent() - if _, err := w.Write(endBraceNewline); err != nil { - return err - } - continue - } - if _, err := fmt.Fprint(w, tag); err != nil { - return err - } - if wire != WireStartGroup { - if err := w.WriteByte(':'); err != nil { - return err - } - } - if !w.compact || wire == WireStartGroup { - if err := w.WriteByte(' '); err != nil { - return err - } - } - switch wire { - case WireBytes: - buf, e := b.DecodeRawBytes(false) - if e == nil { - _, err = fmt.Fprintf(w, "%q", buf) - } else { - _, err = fmt.Fprintf(w, "/* %v */", e) - } - case WireFixed32: - x, err = b.DecodeFixed32() - err = writeUnknownInt(w, x, err) - case WireFixed64: - x, err = b.DecodeFixed64() - err = writeUnknownInt(w, x, err) - case WireStartGroup: - err = w.WriteByte('{') - w.indent() - case WireVarint: - x, err = b.DecodeVarint() - err = writeUnknownInt(w, x, err) - default: - _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) - } - if err != nil { - return err - } - if err = w.WriteByte('\n'); err != nil { - return err - } - } - return nil -} - -func writeUnknownInt(w *textWriter, x uint64, err error) error { - if err == nil { - _, err = fmt.Fprint(w, x) - } else { - _, err = fmt.Fprintf(w, "/* %v */", err) - } - return err -} - -type int32Slice []int32 - -func (s int32Slice) Len() int { return len(s) } -func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } -func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// writeExtensions writes all the extensions in pv. -// pv is assumed to be a pointer to a protocol message struct that is extendable. -func writeExtensions(w *textWriter, pv reflect.Value) error { - emap := extensionMaps[pv.Type().Elem()] - ep := pv.Interface().(extendableProto) - - // Order the extensions by ID. - // This isn't strictly necessary, but it will give us - // canonical output, which will also make testing easier. - m := ep.ExtensionMap() - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) - - for _, extNum := range ids { - ext := m[extNum] - var desc *ExtensionDesc - if emap != nil { - desc = emap[extNum] - } - if desc == nil { - // Unknown extension. - if err := writeUnknownStruct(w, ext.enc); err != nil { - return err - } - continue - } - - pb, err := GetExtension(ep, desc) - if err != nil { - return fmt.Errorf("failed getting extension: %v", err) - } - - // Repeated extensions will appear as a slice. - if !desc.repeated() { - if err := writeExtension(w, desc.Name, pb); err != nil { - return err - } - } else { - v := reflect.ValueOf(pb) - for i := 0; i < v.Len(); i++ { - if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { - return err - } - } - } - } - return nil -} - -func writeExtension(w *textWriter, name string, pb interface{}) error { - if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := writeAny(w, reflect.ValueOf(pb), nil); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - remain := w.ind * 2 - for remain > 0 { - n := remain - if n > len(spaces) { - n = len(spaces) - } - w.w.Write(spaces[:n]) - remain -= n - } - w.complete = false -} - -func marshalText(w io.Writer, pb Message, compact bool) error { - val := reflect.ValueOf(pb) - if pb == nil || val.IsNil() { - w.Write([]byte("")) - return nil - } - var bw *bufio.Writer - ww, ok := w.(writer) - if !ok { - bw = bufio.NewWriter(w) - ww = bw - } - aw := &textWriter{ - w: ww, - complete: true, - compact: compact, - } - - if tm, ok := pb.(encoding.TextMarshaler); ok { - text, err := tm.MarshalText() - if err != nil { - return err - } - if _, err = aw.Write(text); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil - } - // Dereference the received pointer so we don't have outer < and >. - v := reflect.Indirect(val) - if err := writeStruct(aw, v); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil -} - -// MarshalText writes a given protocol buffer in text format. -// The only errors returned are from w. -func MarshalText(w io.Writer, pb Message) error { - return marshalText(w, pb, false) -} - -// MarshalTextString is the same as MarshalText, but returns the string directly. -func MarshalTextString(pb Message) string { - var buf bytes.Buffer - marshalText(&buf, pb, false) - return buf.String() -} - -// CompactText writes a given protocol buffer in compact text format (one line). -func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) } - -// CompactTextString is the same as CompactText, but returns the string directly. -func CompactTextString(pb Message) string { - var buf bytes.Buffer - marshalText(&buf, pb, true) - return buf.String() -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go deleted file mode 100644 index 7d0c757..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go +++ /dev/null @@ -1,772 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for parsing the Text protocol buffer format. -// TODO: message sets. - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -type ParseError struct { - Message string - Line int // 1-based line number - Offset int // 0-based byte offset from start of input -} - -func (p *ParseError) Error() string { - if p.Line == 1 { - // show offset only for first line - return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) - } - return fmt.Sprintf("line %d: %v", p.Line, p.Message) -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func (t *token) String() string { - if t.err == nil { - return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) - } - return fmt.Sprintf("parse error: %v", t.err) -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -// Numbers and identifiers are matched by [-+._A-Za-z0-9] -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - return false -} - -func (p *textParser) skipWhitespace() { - i := 0 - for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) - return - } - p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -var ( - errBadUTF8 = errors.New("proto: bad UTF-8") - errBadHex = errors.New("proto: bad hexadecimal") -) - -func unquoteC(s string, quote rune) (string, error) { - // This is based on C++'s tokenizer.cc. - // Despite its name, this is *not* parsing C syntax. - // For instance, "\0" is an invalid quoted string. - - // Avoid allocation in trivial cases. - simple := true - for _, r := range s { - if r == '\\' || r == quote { - simple = false - break - } - } - if simple { - return s, nil - } - - buf := make([]byte, 0, 3*len(s)/2) - for len(s) > 0 { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", errBadUTF8 - } - s = s[n:] - if r != '\\' { - if r < utf8.RuneSelf { - buf = append(buf, byte(r)) - } else { - buf = append(buf, string(r)...) - } - continue - } - - ch, tail, err := unescape(s) - if err != nil { - return "", err - } - buf = append(buf, ch...) - s = tail - } - return string(buf), nil -} - -func unescape(s string) (ch string, tail string, err error) { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", "", errBadUTF8 - } - s = s[n:] - switch r { - case 'a': - return "\a", s, nil - case 'b': - return "\b", s, nil - case 'f': - return "\f", s, nil - case 'n': - return "\n", s, nil - case 'r': - return "\r", s, nil - case 't': - return "\t", s, nil - case 'v': - return "\v", s, nil - case '?': - return "?", s, nil // trigraph workaround - case '\'', '"', '\\': - return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - base := 8 - ss := s[:2] - s = s[2:] - if r == 'x' || r == 'X' { - base = 16 - } else { - ss = string(r) + ss - } - i, err := strconv.ParseUint(ss, base, 8) - if err != nil { - return "", "", err - } - return string([]byte{byte(i)}), s, nil - case 'u', 'U': - n := 4 - if r == 'U' { - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d digits`, r, n) - } - - bs := make([]byte, n/2) - for i := 0; i < n; i += 2 { - a, ok1 := unhex(s[i]) - b, ok2 := unhex(s[i+1]) - if !ok1 || !ok2 { - return "", "", errBadHex - } - bs[i/2] = a<<4 | b - } - s = s[n:] - return string(bs), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -// Adapted from src/pkg/strconv/quote.go. -func unhex(b byte) (v byte, ok bool) { - switch { - case '0' <= b && b <= '9': - return b - '0', true - case 'a' <= b && b <= 'f': - return b - 'a' + 10, true - case 'A' <= b && b <= 'F': - return b - 'A' + 10, true - } - return 0, false -} - -// Back off the parser by one token. Can only be done between calls to next(). -// It makes the next advance() a no-op. -func (p *textParser) back() { p.backed = true } - -// Advances the parser and returns the new current token. -func (p *textParser) next() *token { - if p.backed || p.done { - p.backed = false - return &p.cur - } - p.advance() - if p.done { - p.cur.value = "" - } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' { - // Look for multiple quoted strings separated by whitespace, - // and concatenate them. - cat := p.cur - for { - p.skipWhitespace() - if p.done || p.s[0] != '"' { - break - } - p.advance() - if p.cur.err != nil { - return &p.cur - } - cat.value += " " + p.cur.value - cat.unquoted += p.cur.unquoted - } - p.done = false // parser may have seen EOF, but we want to return cat - p.cur = cat - } - return &p.cur -} - -func (p *textParser) consumeToken(s string) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != s { - p.back() - return p.errorf("expected %q, found %q", s, tok.value) - } - return nil -} - -// Return a RequiredNotSetError indicating which required field was not set. -func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < st.NumField(); i++ { - if !isNil(sv.Field(i)) { - continue - } - - props := sprops.Prop[i] - if props.Required { - return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} - } - } - return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen -} - -// Returns the index in the struct for the named field, as well as the parsed tag properties. -func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) { - sprops := GetProperties(st) - i, ok := sprops.decoderOrigNames[name] - if ok { - return i, sprops.Prop[i], true - } - return -1, nil, false -} - -// Consume a ':' from the input stream (if the next token is a colon), -// returning an error if a colon is needed but not present. -func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ":" { - // Colon is optional when the field is a group or message. - needColon := true - switch props.Wire { - case "group": - needColon = false - case "bytes": - // A "bytes" field is either a message, a string, or a repeated field; - // those three become *T, *string and []T respectively, so we can check for - // this field being a pointer to a non-string. - if typ.Kind() == reflect.Ptr { - // *T or *string - if typ.Elem().Kind() == reflect.String { - break - } - } else if typ.Kind() == reflect.Slice { - // []T or []*T - if typ.Elem().Kind() != reflect.Ptr { - break - } - } else if typ.Kind() == reflect.String { - // The proto3 exception is for a string field, - // which requires a colon. - break - } - needColon = false - } - if needColon { - return p.errorf("expected ':', found %q", tok.value) - } - p.back() - } - return nil -} - -func (p *textParser) readStruct(sv reflect.Value, terminator string) error { - st := sv.Type() - reqCount := GetProperties(st).reqCount - var reqFieldErr error - fieldSet := make(map[string]bool) - // A struct is a sequence of "name: value", terminated by one of - // '>' or '}', or the end of the input. A name may also be - // "[extension]". - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - // Looks like an extension. - // - // TODO: Check whether we need to handle - // namespace rooted names (e.g. ".something.Foo"). - tok = p.next() - if tok.err != nil { - return tok.err - } - var desc *ExtensionDesc - // This could be faster, but it's functional. - // TODO: Do something smarter than a linear scan. - for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { - if d.Name == tok.value { - desc = d - break - } - } - if desc == nil { - return p.errorf("unrecognized extension %q", tok.value) - } - // Check the extension terminator. - tok = p.next() - if tok.err != nil { - return tok.err - } - if tok.value != "]" { - return p.errorf("unrecognized extension terminator %q", tok.value) - } - - props := &Properties{} - props.Parse(desc.Tag) - - typ := reflect.TypeOf(desc.ExtensionType) - if err := p.checkForColon(props, typ); err != nil { - return err - } - - rep := desc.repeated() - - // Read the extension structure, and set it in - // the value we're constructing. - var ext reflect.Value - if !rep { - ext = reflect.New(typ).Elem() - } else { - ext = reflect.New(typ.Elem()).Elem() - } - if err := p.readAny(ext, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - ep := sv.Addr().Interface().(extendableProto) - if !rep { - SetExtension(ep, desc, ext.Interface()) - } else { - old, err := GetExtension(ep, desc) - var sl reflect.Value - if err == nil { - sl = reflect.ValueOf(old) // existing slice - } else { - sl = reflect.MakeSlice(typ, 0, 1) - } - sl = reflect.Append(sl, ext) - SetExtension(ep, desc, sl.Interface()) - } - } else { - // This is a normal, non-extension field. - name := tok.value - fi, props, ok := structFieldByName(st, name) - if !ok { - return p.errorf("unknown field name %q in %v", name, st) - } - - dst := sv.Field(fi) - - if dst.Kind() == reflect.Map { - // Consume any colon. - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Construct the map if it doesn't already exist. - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - key := reflect.New(dst.Type().Key()).Elem() - val := reflect.New(dst.Type().Elem()).Elem() - - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // Technically the "key" and "value" could come in any order, - // but in practice they won't. - - tok := p.next() - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - if err := p.consumeToken("key"); err != nil { - return err - } - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(key, props.mkeyprop); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - if err := p.consumeToken("value"); err != nil { - return err - } - if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { - return err - } - if err := p.readAny(val, props.mvalprop); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - if err := p.consumeToken(terminator); err != nil { - return err - } - - dst.SetMapIndex(key, val) - continue - } - - // Check that it's not already set if it's not a repeated field. - if !props.Repeated && fieldSet[name] { - return p.errorf("non-repeated field %q was repeated", name) - } - - if err := p.checkForColon(props, st.Field(fi).Type); err != nil { - return err - } - - // Parse into the field. - fieldSet[name] = true - if err := p.readAny(dst, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } else if props.Required { - reqCount-- - } - } - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - - } - - if reqCount > 0 { - return p.missingRequiredFieldError(sv) - } - return reqFieldErr -} - -// consumeOptionalSeparator consumes an optional semicolon or comma. -// It is used in readStruct to provide backward compatibility. -func (p *textParser) consumeOptionalSeparator() error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) readAny(v reflect.Value, props *Properties) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "" { - return p.errorf("unexpected EOF") - } - - switch fv := v; fv.Kind() { - case reflect.Slice: - at := v.Type() - if at.Elem().Kind() == reflect.Uint8 { - // Special case for []byte - if tok.value[0] != '"' && tok.value[0] != '\'' { - // Deliberately written out here, as the error after - // this switch statement would write "invalid []byte: ...", - // which is not as user-friendly. - return p.errorf("invalid string: %v", tok.value) - } - bytes := []byte(tok.unquoted) - fv.Set(reflect.ValueOf(bytes)) - return nil - } - // Repeated field. May already exist. - flen := fv.Len() - if flen == fv.Cap() { - nav := reflect.MakeSlice(at, flen, 2*flen+1) - reflect.Copy(nav, fv) - fv.Set(nav) - } - fv.SetLen(flen + 1) - - // Read one. - p.back() - return p.readAny(fv.Index(flen), props) - case reflect.Bool: - // Either "true", "false", 1 or 0. - switch tok.value { - case "true", "1": - fv.SetBool(true) - return nil - case "false", "0": - fv.SetBool(false) - return nil - } - case reflect.Float32, reflect.Float64: - v := tok.value - // Ignore 'f' for compatibility with output generated by C++, but don't - // remove 'f' when the value is "-inf" or "inf". - if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { - v = v[:len(v)-1] - } - if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { - fv.SetFloat(f) - return nil - } - case reflect.Int32: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - fv.SetInt(x) - return nil - } - - if len(props.Enum) == 0 { - break - } - m, ok := enumValueMaps[props.Enum] - if !ok { - break - } - x, ok := m[tok.value] - if !ok { - break - } - fv.SetInt(int64(x)) - return nil - case reflect.Int64: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - fv.SetInt(x) - return nil - } - - case reflect.Ptr: - // A basic field (indirected through pointer), or a repeated message/group - p.back() - fv.Set(reflect.New(fv.Type().Elem())) - return p.readAny(fv.Elem(), props) - case reflect.String: - if tok.value[0] == '"' || tok.value[0] == '\'' { - fv.SetString(tok.unquoted) - return nil - } - case reflect.Struct: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - // TODO: Handle nested messages which implement encoding.TextUnmarshaler. - return p.readStruct(fv, terminator) - case reflect.Uint32: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(uint64(x)) - return nil - } - case reflect.Uint64: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - fv.SetUint(x) - return nil - } - } - return p.errorf("invalid %v: %v", v.Type(), tok.value) -} - -// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb -// before starting to unmarshal, so any existing data in pb is always removed. -// If a required field is not set and no other error occurs, -// UnmarshalText returns *RequiredNotSetError. -func UnmarshalText(s string, pb Message) error { - if um, ok := pb.(encoding.TextUnmarshaler); ok { - err := um.UnmarshalText([]byte(s)) - return err - } - pb.Reset() - v := reflect.ValueOf(pb) - if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil { - return pe - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go deleted file mode 100644 index 0754b26..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,511 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "math" - "reflect" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - . "github.com/golang/protobuf/proto/testdata" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\xAB'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\xAB"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: `proto: required field "testdata.MyMessage.count" not set`, - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Extension - buildExtStructTest(`count: 42 [testdata.Ext.more]:`), - buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:,>` + // separating commas are okay - `msg_mapping>` + // no colon after "value" - `byte_mapping:` - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - -2: {F: Float64(4.0)}, - }, - ByteMapping: map[bool][]byte{ - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go deleted file mode 100644 index 39861d1..0000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go +++ /dev/null @@ -1,441 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[testdata.Ext.more]: < - data: "Big gobs for big rats" -> -[testdata.greeting]: "adg" -[testdata.greeting]: "easy" -[testdata.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pb := new(pb.Strings) - if err := proto.UnmarshalText(s, pb); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pb, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - &pb.MessageList_Message{ - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; current map format is the same as a repeated struct - { - &pb.MessageWithMap{NameMapping: map[int32]string{1234: "Feist"}}, - `name_mapping:`, - }, - // map with nil value; not well-defined, but we shouldn't crash - { - &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, - `msg_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/.gitignore b/Godeps/_workspace/src/github.com/jmoiron/jsonq/.gitignore deleted file mode 100644 index dbec55f..0000000 --- a/Godeps/_workspace/src/github.com/jmoiron/jsonq/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.sw[op] diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/LICENSE b/Godeps/_workspace/src/github.com/jmoiron/jsonq/LICENSE deleted file mode 100644 index 88b577e..0000000 --- a/Godeps/_workspace/src/github.com/jmoiron/jsonq/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ - Copyright (c) 2012, Jason Moiron - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation - files (the "Software"), to deal in the Software without - restriction, including without limitation the rights to use, - copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following - conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/README.md b/Godeps/_workspace/src/github.com/jmoiron/jsonq/README.md deleted file mode 100644 index 4fba5ed..0000000 --- a/Godeps/_workspace/src/github.com/jmoiron/jsonq/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# jsonq - -[![Build Status](https://drone.io/github.com/jmoiron/jsonq/status.png)](https://drone.io/github.com/jmoiron/jsonq/latest) [![Godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/jmoiron/jsonq) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/jmoiron/jsonq/master/LICENSE) - - -Simplify your golang json usage by extracting fields or items from arrays and objects with a simple, hierarchical query. [API Documentation](http://godoc.org/github.com/jmoiron/jsonq) on godoc.org. - -This package is meant to make working with complex feeds a bit more easy. If you have simple feeds you want to model with struct types, check out [jflect](http://github.com/str1ngs/jflect), which will create struct definitions given a json document. - -# installing - -``` -go get github.com/jmoiron/jsonq -``` - -# usage - -Given some json data like: - -```javascript -{ - "foo": 1, - "bar": 2, - "test": "Hello, world!", - "baz": 123.1, - "array": [ - {"foo": 1}, - {"bar": 2}, - {"baz": 3} - ], - "subobj": { - "foo": 1, - "subarray": [1,2,3], - "subsubobj": { - "bar": 2, - "baz": 3, - "array": ["hello", "world"] - } - }, - "bool": true -} -``` - -Decode it into a `map[string]interface{}`: - -```go -import ( - "strings" - "encoding/json" - "github.com/jmoiron/jsonq" -) - -data := map[string]interface{}{} -dec := json.NewDecoder(strings.NewReader(jsonstring)) -dec.Decode(&data) -jq := jsonq.NewQuery(data) -``` - -From here, you can query along different keys and indexes: - -```go -// data["foo"] -> 1 -jq.Int("foo") - -// data["subobj"]["subarray"][1] -> 2 -jq.Int("subobj", "subarray", "1") - -// data["subobj"]["subarray"]["array"][0] -> "hello" -jq.String("subobj", "subsubobj", "array", "0") - -// data["subobj"] -> map[string]interface{}{"subobj": ...} -obj, err := jq.Object("subobj") -``` - -Missing keys, out of bounds indexes, and type failures will return errors. -For simplicity, integer keys (ie, {"0": "zero"}) are inaccessible -by `jsonq` as integer strings are assumed to be array indexes. - -The `Int` and `Float` methods will attempt to parse numbers from string -values to ease the use of many real world feeds which deliver numbers as strings. - -Suggestions/comments please tweet [@jmoiron](http://twitter.com/jmoiron) - diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/autotest.sh b/Godeps/_workspace/src/github.com/jmoiron/jsonq/autotest.sh deleted file mode 100644 index b154ad3..0000000 --- a/Godeps/_workspace/src/github.com/jmoiron/jsonq/autotest.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -cur=`pwd` - -inotifywait -mqr --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' \ - -e modify ./ | while read date time dir file; do - ext="${file##*.}" - if [[ "$ext" = "go" ]]; then - echo "$file changed @ $time $date, rebuilding..." - go test - fi -done - diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/doc.go b/Godeps/_workspace/src/github.com/jmoiron/jsonq/doc.go deleted file mode 100644 index eb6918c..0000000 --- a/Godeps/_workspace/src/github.com/jmoiron/jsonq/doc.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Simplify your golang json usage with a simple hierarchical query. - -Installing - - go get github.com/jmoiron/jsonq - -Examples - -Given some json data like: - - { - "foo": 1, - "bar": 2, - "test": "Hello, world!", - "baz": 123.1, - "array": [ - {"foo": 1}, - {"bar": 2}, - {"baz": 3} - ], - "subobj": { - "foo": 1, - "subarray": [1,2,3], - "subsubobj": { - "bar": 2, - "baz": 3, - "array": ["hello", "world"] - } - }, - "bool": true - } - -Decode it into a map[string]interrface{}: - - import ( - "strings" - "encoding/json" - "github.com/jmoiron/jsonq" - ) - - data := map[string]interface{}{} - dec := json.NewDecoder(strings.NewReader(jsonstring)) - dec.Decode(&data) - jq := jsonq.NewQuery(data) - -From here, you can query along different keys and indexes: - - // data["foo"] -> 1 - jq.Int("foo") - - // data["subobj"]["subarray"][1] -> 2 - jq.Int("subobj", "subarray", "1") - - // data["subobj"]["subarray"]["array"][0] -> "hello" - jq.String("subobj", "subsubobj", "array", "0") - - // data["subobj"] -> map[string]interface{}{"subobj": ...} - obj, err := jq.Object("subobj") - -Notes - -Missing keys, out of bounds indexes, and type failures will return errors. -For simplicity, integer keys (ie, {"0": "zero"}) are inaccessible by `jsonq` -as integer strings are assumed to be array indexes. - -*/ -package jsonq diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq.go b/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq.go deleted file mode 100644 index e7880ce..0000000 --- a/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq.go +++ /dev/null @@ -1,311 +0,0 @@ -package jsonq - -import ( - "fmt" - "strconv" -) - -type JsonQuery struct { - blob map[string]interface{} -} - -/* -The following methods are identical to the routines that were originally embedded in the realted query methods. -They are seperated out here to keep the code as dry as possible. -*/ - -//stringFromInterface converts an interface{} to a string and returns an error if types don't match. -func stringFromInterface(val interface{}) (string, error) { - switch val.(type) { - case string: - return val.(string), nil - } - return "", fmt.Errorf("Expected string value for String, got \"%v\"\n", val) -} - -//boolFromInterface converts an interface{} to a bool and returns an error if types don't match. -func boolFromInterface(val interface{}) (bool, error) { - switch val.(type) { - case bool: - return val.(bool), nil - } - return false, fmt.Errorf("Expected boolean value for Bool, got \"%v\"\n", val) -} - -//floatFromInterface converts an interface{} to a float64 and returns an error if types don't match. -func floatFromInterface(val interface{}) (float64, error) { - switch val.(type) { - case float64: - return val.(float64), nil - case int: - return float64(val.(int)), nil - case string: - fval, err := strconv.ParseFloat(val.(string), 64) - if err == nil { - return fval, nil - } - } - return 0.0, fmt.Errorf("Expected numeric value for Float, got \"%v\"\n", val) -} - -//intFromInterface converts an interface{} to an int and returns an error if types don't match. -func intFromInterface(val interface{}) (int, error) { - switch val.(type) { - case float64: - return int(val.(float64)), nil - case string: - ival, err := strconv.ParseFloat(val.(string), 64) - if err == nil { - return int(ival), nil - } - case int: - return val.(int), nil - } - return 0, fmt.Errorf("Expected numeric value for Int, got \"%v\"\n", val) -} - -//objectFromInterface converts an interface{} to a map[string]interface{} and returns an error if types don't match. -func objectFromInterface(val interface{}) (map[string]interface{}, error) { - switch val.(type) { - case map[string]interface{}: - return val.(map[string]interface{}), nil - } - return map[string]interface{}{}, fmt.Errorf("Expected json object for Object, got \"%v\"\n", val) -} - -//arrayFromInterface converts an interface{} to an []interface{} and returns an error if types don't match. -func arrayFromInterface(val interface{}) ([]interface{}, error) { - switch val.(type) { - case []interface{}: - return val.([]interface{}), nil - } - return []interface{}{}, fmt.Errorf("Expected json array for Array, got \"%v\"\n", val) -} - -// Create a new JsonQuery obj from a json-decoded interface{} -func NewQuery(data interface{}) *JsonQuery { - j := new(JsonQuery) - j.blob = data.(map[string]interface{}) - return j -} - -// Extract a Bool from some json -func (j *JsonQuery) Bool(s ...string) (bool, error) { - val, err := rquery(j.blob, s...) - if err != nil { - return false, err - } - return boolFromInterface(val) -} - -// Extract a float from some json -func (j *JsonQuery) Float(s ...string) (float64, error) { - val, err := rquery(j.blob, s...) - if err != nil { - return 0.0, err - } - return floatFromInterface(val) -} - -// Extract an int from some json -func (j *JsonQuery) Int(s ...string) (int, error) { - val, err := rquery(j.blob, s...) - if err != nil { - return 0, err - } - return intFromInterface(val) -} - -// Extract a string from some json -func (j *JsonQuery) String(s ...string) (string, error) { - val, err := rquery(j.blob, s...) - if err != nil { - return "", err - } - return stringFromInterface(val) -} - -// Extract an object from some json -func (j *JsonQuery) Object(s ...string) (map[string]interface{}, error) { - val, err := rquery(j.blob, s...) - if err != nil { - return map[string]interface{}{}, err - } - return objectFromInterface(val) -} - -// Extract an array from some json -func (j *JsonQuery) Array(s ...string) ([]interface{}, error) { - val, err := rquery(j.blob, s...) - if err != nil { - return []interface{}{}, err - } - return arrayFromInterface(val) -} - -// Extract interface from some json -func (j *JsonQuery) Interface(s ...string) (interface{}, error) { - val, err := rquery(j.blob, s...) - if err != nil { - return nil, err - } - return val, nil -} - -/* -Extract typed slices. -*/ - -//ArrayOfStrings extracts an array of strings from some json -func (j *JsonQuery) ArrayOfStrings(s ...string) ([]string, error) { - array, err := j.Array(s...) - if err != nil { - return []string{}, err - } - toReturn := make([]string, len(array)) - for index, val := range array { - toReturn[index], err = stringFromInterface(val) - if err != nil { - return toReturn, err - } - } - return toReturn, nil -} - -//ArrayOfInts extracts an array of ints from some json -func (j *JsonQuery) ArrayOfInts(s ...string) ([]int, error) { - array, err := j.Array(s...) - if err != nil { - return []int{}, err - } - toReturn := make([]int, len(array)) - for index, val := range array { - toReturn[index], err = intFromInterface(val) - if err != nil { - return toReturn, err - } - } - return toReturn, nil -} - -//ArrayOfFloats extracts an array of float64s from some json -func (j *JsonQuery) ArrayOfFloats(s ...string) ([]float64, error) { - array, err := j.Array(s...) - if err != nil { - return []float64{}, err - } - toReturn := make([]float64, len(array)) - for index, val := range array { - toReturn[index], err = floatFromInterface(val) - if err != nil { - return toReturn, err - } - } - return toReturn, nil -} - -//ArrayOfBools extracts an array of bools from some json -func (j *JsonQuery) ArrayOfBools(s ...string) ([]bool, error) { - array, err := j.Array(s...) - if err != nil { - return []bool{}, err - } - toReturn := make([]bool, len(array)) - for index, val := range array { - toReturn[index], err = boolFromInterface(val) - if err != nil { - return toReturn, err - } - } - return toReturn, nil -} - -//ArrayOfObjects extracts an array of map[string]interface{} (objects) from some json -func (j *JsonQuery) ArrayOfObjects(s ...string) ([]map[string]interface{}, error) { - array, err := j.Array(s...) - if err != nil { - return []map[string]interface{}{}, err - } - toReturn := make([]map[string]interface{}, len(array)) - for index, val := range array { - toReturn[index], err = objectFromInterface(val) - if err != nil { - return toReturn, err - } - } - return toReturn, nil -} - -//ArrayOfArrays extracts an array of []interface{} (arrays) from some json -func (j *JsonQuery) ArrayOfArrays(s ...string) ([][]interface{}, error) { - array, err := j.Array(s...) - if err != nil { - return [][]interface{}{}, err - } - toReturn := make([][]interface{}, len(array)) - for index, val := range array { - toReturn[index], err = arrayFromInterface(val) - if err != nil { - return toReturn, err - } - } - return toReturn, nil -} - -//Matrix2D is an alias for ArrayOfArrays -func (j *JsonQuery) Matrix2D(s ...string) ([][]interface{}, error) { - return j.ArrayOfArrays(s...) -} - -// Recursively query a decoded json blob -func rquery(blob interface{}, s ...string) (interface{}, error) { - var ( - val interface{} - err error - ) - val = blob - for _, q := range s { - val, err = query(val, q) - if err != nil { - return nil, err - } - } - switch val.(type) { - case nil: - return nil, fmt.Errorf("Nil value found at %s\n", s[len(s)-1]) - } - return val, nil -} - -// Query a json blob for a single field or index. If query is a string, then -// the blob is treated as a json object (map[string]interface{}). If query is -// an integer, the blob is treated as a json array ([]interface{}). Any kind -// of key or index error will result in a nil return value with an error set. -func query(blob interface{}, query string) (interface{}, error) { - index, err := strconv.Atoi(query) - // if it's an integer, then we treat the current interface as an array - if err == nil { - switch blob.(type) { - case []interface{}: - default: - return nil, fmt.Errorf("Array index on non-array %v\n", blob) - } - if len(blob.([]interface{})) > index { - return blob.([]interface{})[index], nil - } - return nil, fmt.Errorf("Array index %d on array %v out of bounds\n", index, blob) - } - - // blob is likely an object, but verify first - switch blob.(type) { - case map[string]interface{}: - default: - return nil, fmt.Errorf("Object lookup \"%s\" on non-object %v\n", query, blob) - } - - val, ok := blob.(map[string]interface{})[query] - if !ok { - return nil, fmt.Errorf("Object %v does not contain field %s\n", blob, query) - } - return val, nil -} diff --git a/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq_test.go b/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq_test.go deleted file mode 100644 index 9b1835b..0000000 --- a/Godeps/_workspace/src/github.com/jmoiron/jsonq/jsonq_test.go +++ /dev/null @@ -1,186 +0,0 @@ -package jsonq - -import ( - "encoding/json" - "fmt" - "strings" - "testing" -) - -const TestData = `{ - "foo": 1, - "bar": 2, - "test": "Hello, world!", - "baz": 123.1, - "numstring": "42", - "floatstring": "42.1", - "array": [ - {"foo": 1}, - {"bar": 2}, - {"baz": 3} - ], - "subobj": { - "foo": 1, - "subarray": [1,2,3], - "subsubobj": { - "bar": 2, - "baz": 3, - "array": ["hello", "world"] - } - }, - "collections": { - "bools": [false, true, false], - "strings": ["hello", "strings"], - "numbers": [1,2,3,4], - "arrays": [[1.0,2.0],[2.0,3.0],[4.0,3.0]], - "objects": [ - {"obj1": 1}, - {"obj2": 2} - ] - }, - "bool": true -}` - -func tErr(t *testing.T, err error) { - if err != nil { - t.Errorf("Error: %v\n", err) - } -} - -func TestQuery(t *testing.T) { - data := map[string]interface{}{} - dec := json.NewDecoder(strings.NewReader(TestData)) - err := dec.Decode(&data) - tErr(t, err) - q := NewQuery(data) - - ival, err := q.Int("foo") - if ival != 1 { - t.Errorf("Expecting 1, got %v\n", ival) - } - tErr(t, err) - ival, err = q.Int("bar") - if ival != 2 { - t.Errorf("Expecting 2, got %v\n", ival) - } - tErr(t, err) - - ival, err = q.Int("subobj", "foo") - if ival != 1 { - t.Errorf("Expecting 1, got %v\n", ival) - } - tErr(t, err) - - // test that strings can get int-ed - ival, err = q.Int("numstring") - if ival != 42 { - t.Errorf("Expecting 42, got %v\n", ival) - } - tErr(t, err) - - for i := 0; i < 3; i++ { - ival, err := q.Int("subobj", "subarray", fmt.Sprintf("%d", i)) - if ival != i+1 { - t.Errorf("Expecting %d, got %v\n", i+1, ival) - } - tErr(t, err) - } - - fval, err := q.Float("baz") - if fval != 123.1 { - t.Errorf("Expecting 123.1, got %f\n", fval) - } - tErr(t, err) - - // test that strings can get float-ed - fval, err = q.Float("floatstring") - if fval != 42.1 { - t.Errorf("Expecting 42.1, got %v\n", fval) - } - tErr(t, err) - - sval, err := q.String("test") - if sval != "Hello, world!" { - t.Errorf("Expecting \"Hello, World!\", got \"%v\"\n", sval) - } - - sval, err = q.String("subobj", "subsubobj", "array", "0") - if sval != "hello" { - t.Errorf("Expecting \"hello\", got \"%s\"\n", sval) - } - tErr(t, err) - - bval, err := q.Bool("bool") - if !bval { - t.Errorf("Expecting true, got %v\n", bval) - } - tErr(t, err) - - obj, err := q.Object("subobj", "subsubobj") - tErr(t, err) - q2 := NewQuery(obj) - sval, err = q2.String("array", "1") - if sval != "world" { - t.Errorf("Expecting \"world\", got \"%s\"\n", sval) - } - tErr(t, err) - - aobj, err := q.Array("subobj", "subarray") - tErr(t, err) - if aobj[0].(float64) != 1 { - t.Errorf("Expecting 1, got %v\n", aobj[0]) - } - - iobj, err := q.Interface("numstring") - tErr(t, err) - if _, ok := iobj.(string); !ok { - t.Errorf("Expecting type string got: %s", iobj) - } - - /* - Test Extraction of typed slices - */ - - //test array of strings - astrings, err := q.ArrayOfStrings("collections", "strings") - tErr(t, err) - if astrings[0] != "hello" { - t.Errorf("Expecting hello, got %v\n", astrings[0]) - } - - //test array of ints - aints, err := q.ArrayOfInts("collections", "numbers") - tErr(t, err) - if aints[0] != 1 { - t.Errorf("Expecting 1, got %v\n", aints[0]) - } - - //test array of floats - afloats, err := q.ArrayOfFloats("collections", "numbers") - tErr(t, err) - if afloats[0] != 1.0 { - t.Errorf("Expecting 1.0, got %v\n", afloats[0]) - } - - //test array of bools - abools, err := q.ArrayOfBools("collections", "bools") - tErr(t, err) - if abools[0] { - t.Errorf("Expecting true, got %v\n", abools[0]) - } - - //test array of arrays - aa, err := q.ArrayOfArrays("collections", "arrays") - tErr(t, err) - if aa[0][0].(float64) != 1 { - t.Errorf("Expecting 1, got %v\n", aa[0][0]) - } - - //test array of objs - aobjs, err := q.ArrayOfObjects("collections", "objects") - tErr(t, err) - if aobjs[0]["obj1"].(float64) != 1 { - t.Errorf("Expecting 1, got %v\n", aobjs[0]["obj1"]) - } - -} diff --git a/Godeps/_workspace/src/github.com/layeh/gopus/LICENSE b/Godeps/_workspace/src/github.com/layeh/gopus/LICENSE deleted file mode 100644 index 45385d1..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gopus/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014 Tim Cooper - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Godeps/_workspace/src/github.com/layeh/gopus/README.md b/Godeps/_workspace/src/github.com/layeh/gopus/README.md deleted file mode 100644 index 99ec9e9..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gopus/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# gopus - -gopus is a Go binding for the [Opus](http://www.opus-codec.org/) audio codec. - -## Documentation - -- [API Reference](https://godoc.org/github.com/layeh/gopus) - -## Requirements - -- cgo -- [opus](http://www.opus-codec.org/) - -## License - -MIT - -## Author - -Tim Cooper () diff --git a/Godeps/_workspace/src/github.com/layeh/gopus/decoder.go b/Godeps/_workspace/src/github.com/layeh/gopus/decoder.go deleted file mode 100644 index 76ce8d5..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gopus/decoder.go +++ /dev/null @@ -1,71 +0,0 @@ -package gopus - -// #cgo !nopkgconfig pkg-config: opus -// #include -// -// void gopus_decoder_resetstate(OpusDecoder *decoder) { -// opus_decoder_ctl(decoder, OPUS_RESET_STATE); -// } -import "C" - -import ( - "unsafe" -) - -type Decoder struct { - data []byte - cDecoder *C.struct_OpusDecoder - channels int -} - -func NewDecoder(sampleRate, channels int) (*Decoder, error) { - decoder := &Decoder{} - decoder.data = make([]byte, int(C.opus_decoder_get_size(C.int(channels)))) - decoder.cDecoder = (*C.struct_OpusDecoder)(unsafe.Pointer(&decoder.data[0])) - - ret := C.opus_decoder_init(decoder.cDecoder, C.opus_int32(sampleRate), C.int(channels)) - if err := getErr(ret); err != nil { - return nil, err - } - decoder.channels = channels - - return decoder, nil -} - -func (d *Decoder) Decode(data []byte, frameSize int, fec bool) ([]int16, error) { - dataPtr := (*C.uchar)(unsafe.Pointer(&data[0])) - dataLen := C.opus_int32(len(data)) - - output := make([]int16, d.channels * frameSize) - outputPtr := (*C.opus_int16)(unsafe.Pointer(&output[0])) - - var cFec C.int - if fec { - cFec = 1 - } else { - cFec = 0 - } - - cRet := C.opus_decode(d.cDecoder, dataPtr, dataLen, outputPtr, C.int(frameSize), cFec) - ret := int(cRet) - - if ret < 0 { - return nil, getErr(cRet) - } - return output[:ret], nil -} - -func (d *Decoder) ResetState() { - C.gopus_decoder_resetstate(d.cDecoder) -} - -func CountFrames(data []byte) (int, error) { - dataPtr := (*C.uchar)(unsafe.Pointer(&data[0])) - cLen := C.opus_int32(len(data)) - - cRet := C.opus_packet_get_nb_frames(dataPtr, cLen) - if err := getErr(cRet); err != nil { - return 0, err - } - return int(cRet), nil -} diff --git a/Godeps/_workspace/src/github.com/layeh/gopus/encoder.go b/Godeps/_workspace/src/github.com/layeh/gopus/encoder.go deleted file mode 100644 index d39b36c..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gopus/encoder.go +++ /dev/null @@ -1,119 +0,0 @@ -package gopus - -// #cgo !nopkgconfig pkg-config: opus -// #include -// -// enum { -// gopus_application_voip = OPUS_APPLICATION_VOIP, -// gopus_application_audio = OPUS_APPLICATION_AUDIO, -// gopus_restricted_lowdelay = OPUS_APPLICATION_RESTRICTED_LOWDELAY, -// gopus_bitrate_max = OPUS_BITRATE_MAX, -// }; -// -// -// void gopus_setvbr(OpusEncoder *encoder, int vbr) { -// opus_encoder_ctl(encoder, OPUS_SET_VBR(vbr)); -// } -// -// void gopus_setbitrate(OpusEncoder *encoder, int bitrate) { -// opus_encoder_ctl(encoder, OPUS_SET_BITRATE(bitrate)); -// } -// -// opus_int32 gopus_bitrate(OpusEncoder *encoder) { -// opus_int32 bitrate; -// opus_encoder_ctl(encoder, OPUS_GET_BITRATE(&bitrate)); -// return bitrate; -// } -// -// void gopus_setapplication(OpusEncoder *encoder, int application) { -// opus_encoder_ctl(encoder, OPUS_SET_APPLICATION(application)); -// } -// -// opus_int32 gopus_application(OpusEncoder *encoder) { -// opus_int32 application; -// opus_encoder_ctl(encoder, OPUS_GET_APPLICATION(&application)); -// return application; -// } -// -// void gopus_encoder_resetstate(OpusEncoder *encoder) { -// opus_encoder_ctl(encoder, OPUS_RESET_STATE); -// } -import "C" - -import ( - "unsafe" -) - -type Application int - -const ( - Voip Application = C.gopus_application_voip - Audio Application = C.gopus_application_audio - RestrictedLowDelay Application = C.gopus_restricted_lowdelay -) - -const ( - BitrateMaximum = C.gopus_bitrate_max -) - -type Encoder struct { - data []byte - cEncoder *C.struct_OpusEncoder -} - -func NewEncoder(sampleRate, channels int, application Application) (*Encoder, error) { - encoder := &Encoder{} - encoder.data = make([]byte, int(C.opus_encoder_get_size(C.int(channels)))) - encoder.cEncoder = (*C.struct_OpusEncoder)(unsafe.Pointer(&encoder.data[0])) - - ret := C.opus_encoder_init(encoder.cEncoder, C.opus_int32(sampleRate), C.int(channels), C.int(application)) - if err := getErr(ret); err != nil { - return nil, err - } - return encoder, nil -} - -func (e *Encoder) Encode(pcm []int16, frameSize, maxDataBytes int) ([]byte, error) { - pcmPtr := (*C.opus_int16)(unsafe.Pointer(&pcm[0])) - - data := make([]byte, maxDataBytes) - dataPtr := (*C.uchar)(unsafe.Pointer(&data[0])) - - encodedC := C.opus_encode(e.cEncoder, pcmPtr, C.int(frameSize), dataPtr, C.opus_int32(len(data))) - encoded := int(encodedC) - - if encoded < 0 { - return nil, getErr(C.int(encodedC)) - } - return data[0:encoded], nil -} - -func (e *Encoder) SetVbr(vbr bool) { - var cVbr C.int - if vbr { - cVbr = 1 - } else { - cVbr = 0 - } - C.gopus_setvbr(e.cEncoder, cVbr) -} - -func (e *Encoder) SetBitrate(bitrate int) { - C.gopus_setbitrate(e.cEncoder, C.int(bitrate)) -} - -func (e *Encoder) Bitrate() int { - return int(C.gopus_bitrate(e.cEncoder)) -} - -func (e *Encoder) SetApplication(application Application) { - C.gopus_setapplication(e.cEncoder, C.int(application)) -} - -func (e *Encoder) Application() Application { - return Application(C.gopus_application(e.cEncoder)) -} - -func (e *Encoder) ResetState() { - C.gopus_encoder_resetstate(e.cEncoder) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gopus/gopus.go b/Godeps/_workspace/src/github.com/layeh/gopus/gopus.go deleted file mode 100644 index 9fde581..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gopus/gopus.go +++ /dev/null @@ -1,53 +0,0 @@ -package gopus - -// #include -// -// enum { -// gopus_ok = OPUS_OK, -// gopus_bad_arg = OPUS_BAD_ARG, -// gopus_small_buffer = OPUS_BUFFER_TOO_SMALL, -// gopus_internal = OPUS_INTERNAL_ERROR, -// gopus_invalid_packet = OPUS_INVALID_PACKET, -// gopus_unimplemented = OPUS_UNIMPLEMENTED, -// gopus_invalid_state = OPUS_INVALID_STATE, -// gopus_alloc_fail = OPUS_ALLOC_FAIL, -// }; -import "C" - -import ( - "errors" -) - -var ( - ErrBadArgument = errors.New("bad argument") - ErrSmallBuffer = errors.New("buffer is too small") - ErrInternal = errors.New("internal error") - ErrInvalidPacket = errors.New("invalid packet") - ErrUnimplemented = errors.New("unimplemented") - ErrInvalidState = errors.New("invalid state") - ErrAllocFail = errors.New("allocation failed") - ErrUnknown = errors.New("unknown error") -) - -func getErr(code C.int) error { - switch code { - case C.gopus_ok: - return nil - case C.gopus_bad_arg: - return ErrBadArgument - case C.gopus_small_buffer: - return ErrSmallBuffer - case C.gopus_internal: - return ErrInternal - case C.gopus_invalid_packet: - return ErrInvalidPacket - case C.gopus_unimplemented: - return ErrUnimplemented - case C.gopus_invalid_state: - return ErrInvalidState - case C.gopus_alloc_fail: - return ErrAllocFail - default: - return ErrUnknown - } -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/LICENSE b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/LICENSE deleted file mode 100644 index c3ffe8f..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/LICENSE +++ /dev/null @@ -1,37 +0,0 @@ -Copyright (C) 2005-2013, Thorvald Natvig -Copyright (C) 2007, Stefan Gehn -Copyright (C) 2007, Sebastian Schlingmann -Copyright (C) 2008-2013, Mikkel Krautz -Copyright (C) 2008, Andreas Messer -Copyright (C) 2007, Trenton Schulz -Copyright (C) 2008-2013, Stefan Hacker -Copyright (C) 2008-2011, Snares -Copyright (C) 2009-2013, Benjamin Jemlich -Copyright (C) 2009-2013, Kissaki - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -- Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. -- Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. -- Neither the name of the Mumble Developers nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -`AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.pb.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.pb.go deleted file mode 100644 index a9f4ad9..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.pb.go +++ /dev/null @@ -1,2092 +0,0 @@ -// Code generated by protoc-gen-go. -// source: Mumble.proto -// DO NOT EDIT! - -/* -Package MumbleProto is a generated protocol buffer package. - -It is generated from these files: - Mumble.proto - -It has these top-level messages: - Version - UDPTunnel - Authenticate - Ping - Reject - ServerSync - ChannelRemove - ChannelState - UserRemove - UserState - BanList - TextMessage - PermissionDenied - ACL - QueryUsers - CryptSetup - ContextActionModify - ContextAction - UserList - VoiceTarget - PermissionQuery - CodecVersion - UserStats - RequestBlob - ServerConfig - SuggestConfig -*/ -package MumbleProto - -import proto "github.com/golang/protobuf/proto" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = math.Inf - -type Reject_RejectType int32 - -const ( - // TODO ?? - Reject_None Reject_RejectType = 0 - // The client attempted to connect with an incompatible version. - Reject_WrongVersion Reject_RejectType = 1 - // The user name supplied by the client was invalid. - Reject_InvalidUsername Reject_RejectType = 2 - // The client attempted to authenticate as a user with a password but it - // was wrong. - Reject_WrongUserPW Reject_RejectType = 3 - // The client attempted to connect to a passworded server but the password - // was wrong. - Reject_WrongServerPW Reject_RejectType = 4 - // Supplied username is already in use. - Reject_UsernameInUse Reject_RejectType = 5 - // Server is currently full and cannot accept more users. - Reject_ServerFull Reject_RejectType = 6 - // The user did not provide a certificate but one is required. - Reject_NoCertificate Reject_RejectType = 7 - Reject_AuthenticatorFail Reject_RejectType = 8 -) - -var Reject_RejectType_name = map[int32]string{ - 0: "None", - 1: "WrongVersion", - 2: "InvalidUsername", - 3: "WrongUserPW", - 4: "WrongServerPW", - 5: "UsernameInUse", - 6: "ServerFull", - 7: "NoCertificate", - 8: "AuthenticatorFail", -} -var Reject_RejectType_value = map[string]int32{ - "None": 0, - "WrongVersion": 1, - "InvalidUsername": 2, - "WrongUserPW": 3, - "WrongServerPW": 4, - "UsernameInUse": 5, - "ServerFull": 6, - "NoCertificate": 7, - "AuthenticatorFail": 8, -} - -func (x Reject_RejectType) Enum() *Reject_RejectType { - p := new(Reject_RejectType) - *p = x - return p -} -func (x Reject_RejectType) String() string { - return proto.EnumName(Reject_RejectType_name, int32(x)) -} -func (x *Reject_RejectType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Reject_RejectType_value, data, "Reject_RejectType") - if err != nil { - return err - } - *x = Reject_RejectType(value) - return nil -} - -type PermissionDenied_DenyType int32 - -const ( - // Operation denied for other reason, see reason field. - PermissionDenied_Text PermissionDenied_DenyType = 0 - // Permissions were denied. - PermissionDenied_Permission PermissionDenied_DenyType = 1 - // Cannot modify SuperUser. - PermissionDenied_SuperUser PermissionDenied_DenyType = 2 - // Invalid channel name. - PermissionDenied_ChannelName PermissionDenied_DenyType = 3 - // Text message too long. - PermissionDenied_TextTooLong PermissionDenied_DenyType = 4 - // The flux capacitor was spelled wrong. - PermissionDenied_H9K PermissionDenied_DenyType = 5 - // Operation not permitted in temporary channel. - PermissionDenied_TemporaryChannel PermissionDenied_DenyType = 6 - // Operation requires certificate. - PermissionDenied_MissingCertificate PermissionDenied_DenyType = 7 - // Invalid username. - PermissionDenied_UserName PermissionDenied_DenyType = 8 - // Channel is full. - PermissionDenied_ChannelFull PermissionDenied_DenyType = 9 - PermissionDenied_NestingLimit PermissionDenied_DenyType = 10 -) - -var PermissionDenied_DenyType_name = map[int32]string{ - 0: "Text", - 1: "Permission", - 2: "SuperUser", - 3: "ChannelName", - 4: "TextTooLong", - 5: "H9K", - 6: "TemporaryChannel", - 7: "MissingCertificate", - 8: "UserName", - 9: "ChannelFull", - 10: "NestingLimit", -} -var PermissionDenied_DenyType_value = map[string]int32{ - "Text": 0, - "Permission": 1, - "SuperUser": 2, - "ChannelName": 3, - "TextTooLong": 4, - "H9K": 5, - "TemporaryChannel": 6, - "MissingCertificate": 7, - "UserName": 8, - "ChannelFull": 9, - "NestingLimit": 10, -} - -func (x PermissionDenied_DenyType) Enum() *PermissionDenied_DenyType { - p := new(PermissionDenied_DenyType) - *p = x - return p -} -func (x PermissionDenied_DenyType) String() string { - return proto.EnumName(PermissionDenied_DenyType_name, int32(x)) -} -func (x *PermissionDenied_DenyType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(PermissionDenied_DenyType_value, data, "PermissionDenied_DenyType") - if err != nil { - return err - } - *x = PermissionDenied_DenyType(value) - return nil -} - -type ContextActionModify_Context int32 - -const ( - // Action is applicable to the server. - ContextActionModify_Server ContextActionModify_Context = 1 - // Action can target a Channel. - ContextActionModify_Channel ContextActionModify_Context = 2 - // Action can target a User. - ContextActionModify_User ContextActionModify_Context = 4 -) - -var ContextActionModify_Context_name = map[int32]string{ - 1: "Server", - 2: "Channel", - 4: "User", -} -var ContextActionModify_Context_value = map[string]int32{ - "Server": 1, - "Channel": 2, - "User": 4, -} - -func (x ContextActionModify_Context) Enum() *ContextActionModify_Context { - p := new(ContextActionModify_Context) - *p = x - return p -} -func (x ContextActionModify_Context) String() string { - return proto.EnumName(ContextActionModify_Context_name, int32(x)) -} -func (x *ContextActionModify_Context) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(ContextActionModify_Context_value, data, "ContextActionModify_Context") - if err != nil { - return err - } - *x = ContextActionModify_Context(value) - return nil -} - -type ContextActionModify_Operation int32 - -const ( - ContextActionModify_Add ContextActionModify_Operation = 0 - ContextActionModify_Remove ContextActionModify_Operation = 1 -) - -var ContextActionModify_Operation_name = map[int32]string{ - 0: "Add", - 1: "Remove", -} -var ContextActionModify_Operation_value = map[string]int32{ - "Add": 0, - "Remove": 1, -} - -func (x ContextActionModify_Operation) Enum() *ContextActionModify_Operation { - p := new(ContextActionModify_Operation) - *p = x - return p -} -func (x ContextActionModify_Operation) String() string { - return proto.EnumName(ContextActionModify_Operation_name, int32(x)) -} -func (x *ContextActionModify_Operation) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(ContextActionModify_Operation_value, data, "ContextActionModify_Operation") - if err != nil { - return err - } - *x = ContextActionModify_Operation(value) - return nil -} - -type Version struct { - // 2-byte Major, 1-byte Minor and 1-byte Patch version number. - Version *uint32 `protobuf:"varint,1,opt,name=version" json:"version,omitempty"` - // Client release name. - Release *string `protobuf:"bytes,2,opt,name=release" json:"release,omitempty"` - // Client OS name. - Os *string `protobuf:"bytes,3,opt,name=os" json:"os,omitempty"` - // Client OS version. - OsVersion *string `protobuf:"bytes,4,opt,name=os_version" json:"os_version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Version) Reset() { *m = Version{} } -func (m *Version) String() string { return proto.CompactTextString(m) } -func (*Version) ProtoMessage() {} - -func (m *Version) GetVersion() uint32 { - if m != nil && m.Version != nil { - return *m.Version - } - return 0 -} - -func (m *Version) GetRelease() string { - if m != nil && m.Release != nil { - return *m.Release - } - return "" -} - -func (m *Version) GetOs() string { - if m != nil && m.Os != nil { - return *m.Os - } - return "" -} - -func (m *Version) GetOsVersion() string { - if m != nil && m.OsVersion != nil { - return *m.OsVersion - } - return "" -} - -// Not used. Not even for tunneling UDP through TCP. -type UDPTunnel struct { - // Not used. - Packet []byte `protobuf:"bytes,1,req,name=packet" json:"packet,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UDPTunnel) Reset() { *m = UDPTunnel{} } -func (m *UDPTunnel) String() string { return proto.CompactTextString(m) } -func (*UDPTunnel) ProtoMessage() {} - -func (m *UDPTunnel) GetPacket() []byte { - if m != nil { - return m.Packet - } - return nil -} - -// Used by the client to send the authentication credentials to the server. -type Authenticate struct { - // UTF-8 encoded username. - Username *string `protobuf:"bytes,1,opt,name=username" json:"username,omitempty"` - // Server or user password. - Password *string `protobuf:"bytes,2,opt,name=password" json:"password,omitempty"` - // Additional access tokens for server ACL groups. - Tokens []string `protobuf:"bytes,3,rep,name=tokens" json:"tokens,omitempty"` - // A list of CELT bitstream version constants supported by the client. - CeltVersions []int32 `protobuf:"varint,4,rep,name=celt_versions" json:"celt_versions,omitempty"` - Opus *bool `protobuf:"varint,5,opt,name=opus,def=0" json:"opus,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Authenticate) Reset() { *m = Authenticate{} } -func (m *Authenticate) String() string { return proto.CompactTextString(m) } -func (*Authenticate) ProtoMessage() {} - -const Default_Authenticate_Opus bool = false - -func (m *Authenticate) GetUsername() string { - if m != nil && m.Username != nil { - return *m.Username - } - return "" -} - -func (m *Authenticate) GetPassword() string { - if m != nil && m.Password != nil { - return *m.Password - } - return "" -} - -func (m *Authenticate) GetTokens() []string { - if m != nil { - return m.Tokens - } - return nil -} - -func (m *Authenticate) GetCeltVersions() []int32 { - if m != nil { - return m.CeltVersions - } - return nil -} - -func (m *Authenticate) GetOpus() bool { - if m != nil && m.Opus != nil { - return *m.Opus - } - return Default_Authenticate_Opus -} - -// Sent by the client to notify the server that the client is still alive. -// Server must reply to the packet with the same timestamp and its own -// good/late/lost/resync numbers. None of the fields is strictly required. -type Ping struct { - // Client timestamp. Server should not attempt to decode. - Timestamp *uint64 `protobuf:"varint,1,opt,name=timestamp" json:"timestamp,omitempty"` - // The amount of good packets received. - Good *uint32 `protobuf:"varint,2,opt,name=good" json:"good,omitempty"` - // The amount of late packets received. - Late *uint32 `protobuf:"varint,3,opt,name=late" json:"late,omitempty"` - // The amount of packets never received. - Lost *uint32 `protobuf:"varint,4,opt,name=lost" json:"lost,omitempty"` - // The amount of nonce resyncs. - Resync *uint32 `protobuf:"varint,5,opt,name=resync" json:"resync,omitempty"` - // The total amount of UDP packets received. - UdpPackets *uint32 `protobuf:"varint,6,opt,name=udp_packets" json:"udp_packets,omitempty"` - // The total amount of TCP packets received. - TcpPackets *uint32 `protobuf:"varint,7,opt,name=tcp_packets" json:"tcp_packets,omitempty"` - // UDP ping average. - UdpPingAvg *float32 `protobuf:"fixed32,8,opt,name=udp_ping_avg" json:"udp_ping_avg,omitempty"` - // UDP ping variance. - UdpPingVar *float32 `protobuf:"fixed32,9,opt,name=udp_ping_var" json:"udp_ping_var,omitempty"` - // TCP ping average. - TcpPingAvg *float32 `protobuf:"fixed32,10,opt,name=tcp_ping_avg" json:"tcp_ping_avg,omitempty"` - // TCP ping variance. - TcpPingVar *float32 `protobuf:"fixed32,11,opt,name=tcp_ping_var" json:"tcp_ping_var,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Ping) Reset() { *m = Ping{} } -func (m *Ping) String() string { return proto.CompactTextString(m) } -func (*Ping) ProtoMessage() {} - -func (m *Ping) GetTimestamp() uint64 { - if m != nil && m.Timestamp != nil { - return *m.Timestamp - } - return 0 -} - -func (m *Ping) GetGood() uint32 { - if m != nil && m.Good != nil { - return *m.Good - } - return 0 -} - -func (m *Ping) GetLate() uint32 { - if m != nil && m.Late != nil { - return *m.Late - } - return 0 -} - -func (m *Ping) GetLost() uint32 { - if m != nil && m.Lost != nil { - return *m.Lost - } - return 0 -} - -func (m *Ping) GetResync() uint32 { - if m != nil && m.Resync != nil { - return *m.Resync - } - return 0 -} - -func (m *Ping) GetUdpPackets() uint32 { - if m != nil && m.UdpPackets != nil { - return *m.UdpPackets - } - return 0 -} - -func (m *Ping) GetTcpPackets() uint32 { - if m != nil && m.TcpPackets != nil { - return *m.TcpPackets - } - return 0 -} - -func (m *Ping) GetUdpPingAvg() float32 { - if m != nil && m.UdpPingAvg != nil { - return *m.UdpPingAvg - } - return 0 -} - -func (m *Ping) GetUdpPingVar() float32 { - if m != nil && m.UdpPingVar != nil { - return *m.UdpPingVar - } - return 0 -} - -func (m *Ping) GetTcpPingAvg() float32 { - if m != nil && m.TcpPingAvg != nil { - return *m.TcpPingAvg - } - return 0 -} - -func (m *Ping) GetTcpPingVar() float32 { - if m != nil && m.TcpPingVar != nil { - return *m.TcpPingVar - } - return 0 -} - -// Sent by the server when it rejects the user connection. -type Reject struct { - // Rejection type. - Type *Reject_RejectType `protobuf:"varint,1,opt,name=type,enum=MumbleProto.Reject_RejectType" json:"type,omitempty"` - // Human readable rejection reason. - Reason *string `protobuf:"bytes,2,opt,name=reason" json:"reason,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Reject) Reset() { *m = Reject{} } -func (m *Reject) String() string { return proto.CompactTextString(m) } -func (*Reject) ProtoMessage() {} - -func (m *Reject) GetType() Reject_RejectType { - if m != nil && m.Type != nil { - return *m.Type - } - return Reject_None -} - -func (m *Reject) GetReason() string { - if m != nil && m.Reason != nil { - return *m.Reason - } - return "" -} - -// ServerSync message is sent by the server when it has authenticated the user -// and finished synchronizing the server state. -type ServerSync struct { - // The session of the current user. - Session *uint32 `protobuf:"varint,1,opt,name=session" json:"session,omitempty"` - // Maximum bandwidth that the user should use. - MaxBandwidth *uint32 `protobuf:"varint,2,opt,name=max_bandwidth" json:"max_bandwidth,omitempty"` - // Server welcome text. - WelcomeText *string `protobuf:"bytes,3,opt,name=welcome_text" json:"welcome_text,omitempty"` - // Current user permissions TODO: Confirm?? - Permissions *uint64 `protobuf:"varint,4,opt,name=permissions" json:"permissions,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ServerSync) Reset() { *m = ServerSync{} } -func (m *ServerSync) String() string { return proto.CompactTextString(m) } -func (*ServerSync) ProtoMessage() {} - -func (m *ServerSync) GetSession() uint32 { - if m != nil && m.Session != nil { - return *m.Session - } - return 0 -} - -func (m *ServerSync) GetMaxBandwidth() uint32 { - if m != nil && m.MaxBandwidth != nil { - return *m.MaxBandwidth - } - return 0 -} - -func (m *ServerSync) GetWelcomeText() string { - if m != nil && m.WelcomeText != nil { - return *m.WelcomeText - } - return "" -} - -func (m *ServerSync) GetPermissions() uint64 { - if m != nil && m.Permissions != nil { - return *m.Permissions - } - return 0 -} - -// Sent by the client when it wants a channel removed. Sent by the server when -// a channel has been removed and clients should be notified. -type ChannelRemove struct { - ChannelId *uint32 `protobuf:"varint,1,req,name=channel_id" json:"channel_id,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ChannelRemove) Reset() { *m = ChannelRemove{} } -func (m *ChannelRemove) String() string { return proto.CompactTextString(m) } -func (*ChannelRemove) ProtoMessage() {} - -func (m *ChannelRemove) GetChannelId() uint32 { - if m != nil && m.ChannelId != nil { - return *m.ChannelId - } - return 0 -} - -// Used to communicate channel properties between the client and the server. -// Sent by the server during the login process or when channel properties are -// updated. Client may use this message to update said channel properties. -type ChannelState struct { - // Unique ID for the channel within the server. - ChannelId *uint32 `protobuf:"varint,1,opt,name=channel_id" json:"channel_id,omitempty"` - // channel_id of the parent channel. - Parent *uint32 `protobuf:"varint,2,opt,name=parent" json:"parent,omitempty"` - // UTF-8 encoded channel name. - Name *string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"` - // A collection of channel id values of the linked channels. Absent during - // the first channel listing. - Links []uint32 `protobuf:"varint,4,rep,name=links" json:"links,omitempty"` - // UTF-8 encoded channel description. Only if the description is less than - // 128 bytes - Description *string `protobuf:"bytes,5,opt,name=description" json:"description,omitempty"` - // A collection of channel_id values that should be added to links. - LinksAdd []uint32 `protobuf:"varint,6,rep,name=links_add" json:"links_add,omitempty"` - // A collection of channel_id values that should be removed from links. - LinksRemove []uint32 `protobuf:"varint,7,rep,name=links_remove" json:"links_remove,omitempty"` - // True if the channel is temporary. - Temporary *bool `protobuf:"varint,8,opt,name=temporary,def=0" json:"temporary,omitempty"` - // Position weight to tweak the channel position in the channel list. - Position *int32 `protobuf:"varint,9,opt,name=position,def=0" json:"position,omitempty"` - // SHA1 hash of the description if the description is 128 bytes or more. - DescriptionHash []byte `protobuf:"bytes,10,opt,name=description_hash" json:"description_hash,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ChannelState) Reset() { *m = ChannelState{} } -func (m *ChannelState) String() string { return proto.CompactTextString(m) } -func (*ChannelState) ProtoMessage() {} - -const Default_ChannelState_Temporary bool = false -const Default_ChannelState_Position int32 = 0 - -func (m *ChannelState) GetChannelId() uint32 { - if m != nil && m.ChannelId != nil { - return *m.ChannelId - } - return 0 -} - -func (m *ChannelState) GetParent() uint32 { - if m != nil && m.Parent != nil { - return *m.Parent - } - return 0 -} - -func (m *ChannelState) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *ChannelState) GetLinks() []uint32 { - if m != nil { - return m.Links - } - return nil -} - -func (m *ChannelState) GetDescription() string { - if m != nil && m.Description != nil { - return *m.Description - } - return "" -} - -func (m *ChannelState) GetLinksAdd() []uint32 { - if m != nil { - return m.LinksAdd - } - return nil -} - -func (m *ChannelState) GetLinksRemove() []uint32 { - if m != nil { - return m.LinksRemove - } - return nil -} - -func (m *ChannelState) GetTemporary() bool { - if m != nil && m.Temporary != nil { - return *m.Temporary - } - return Default_ChannelState_Temporary -} - -func (m *ChannelState) GetPosition() int32 { - if m != nil && m.Position != nil { - return *m.Position - } - return Default_ChannelState_Position -} - -func (m *ChannelState) GetDescriptionHash() []byte { - if m != nil { - return m.DescriptionHash - } - return nil -} - -// Used to communicate user leaving or being kicked. May be sent by the client -// when it attempts to kick a user. Sent by the server when it informs the -// clients that a user is not present anymore. -type UserRemove struct { - // The user who is being kicked, identified by their session, not present - // when no one is being kicked. - Session *uint32 `protobuf:"varint,1,req,name=session" json:"session,omitempty"` - // The user who initiated the removal. Either the user who performs the kick - // or the user who is currently leaving. - Actor *uint32 `protobuf:"varint,2,opt,name=actor" json:"actor,omitempty"` - // Reason for the kick, stored as the ban reason if the user is banned. - Reason *string `protobuf:"bytes,3,opt,name=reason" json:"reason,omitempty"` - // True if the kick should result in a ban. - Ban *bool `protobuf:"varint,4,opt,name=ban" json:"ban,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UserRemove) Reset() { *m = UserRemove{} } -func (m *UserRemove) String() string { return proto.CompactTextString(m) } -func (*UserRemove) ProtoMessage() {} - -func (m *UserRemove) GetSession() uint32 { - if m != nil && m.Session != nil { - return *m.Session - } - return 0 -} - -func (m *UserRemove) GetActor() uint32 { - if m != nil && m.Actor != nil { - return *m.Actor - } - return 0 -} - -func (m *UserRemove) GetReason() string { - if m != nil && m.Reason != nil { - return *m.Reason - } - return "" -} - -func (m *UserRemove) GetBan() bool { - if m != nil && m.Ban != nil { - return *m.Ban - } - return false -} - -// Sent by the server when it communicates new and changed users to client. -// First seen during login procedure. May be sent by the client when it wishes -// to alter its state. -type UserState struct { - // Unique user session ID of the user whose state this is, may change on - // reconnect. - Session *uint32 `protobuf:"varint,1,opt,name=session" json:"session,omitempty"` - // The session of the user who is updating this user. - Actor *uint32 `protobuf:"varint,2,opt,name=actor" json:"actor,omitempty"` - // User name, UTF-8 encoded. - Name *string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"` - // Registered user ID if the user is registered. - UserId *uint32 `protobuf:"varint,4,opt,name=user_id" json:"user_id,omitempty"` - // Channel on which the user is. - ChannelId *uint32 `protobuf:"varint,5,opt,name=channel_id" json:"channel_id,omitempty"` - // True if the user is muted by admin. - Mute *bool `protobuf:"varint,6,opt,name=mute" json:"mute,omitempty"` - // True if the user is deafened by admin. - Deaf *bool `protobuf:"varint,7,opt,name=deaf" json:"deaf,omitempty"` - // True if the user has been suppressed from talking by a reason other than - // being muted. - Suppress *bool `protobuf:"varint,8,opt,name=suppress" json:"suppress,omitempty"` - // True if the user has muted self. - SelfMute *bool `protobuf:"varint,9,opt,name=self_mute" json:"self_mute,omitempty"` - // True if the user has deafened self. - SelfDeaf *bool `protobuf:"varint,10,opt,name=self_deaf" json:"self_deaf,omitempty"` - // User image if it is less than 128 bytes. - Texture []byte `protobuf:"bytes,11,opt,name=texture" json:"texture,omitempty"` - // TODO ?? - PluginContext []byte `protobuf:"bytes,12,opt,name=plugin_context" json:"plugin_context,omitempty"` - // TODO ?? - PluginIdentity *string `protobuf:"bytes,13,opt,name=plugin_identity" json:"plugin_identity,omitempty"` - // User comment if it is less than 128 bytes. - Comment *string `protobuf:"bytes,14,opt,name=comment" json:"comment,omitempty"` - // The hash of the user certificate. - Hash *string `protobuf:"bytes,15,opt,name=hash" json:"hash,omitempty"` - // SHA1 hash of the user comment if it 128 bytes or more. - CommentHash []byte `protobuf:"bytes,16,opt,name=comment_hash" json:"comment_hash,omitempty"` - // SHA1 hash of the user picture if it 128 bytes or more. - TextureHash []byte `protobuf:"bytes,17,opt,name=texture_hash" json:"texture_hash,omitempty"` - // True if the user is a priority speaker. - PrioritySpeaker *bool `protobuf:"varint,18,opt,name=priority_speaker" json:"priority_speaker,omitempty"` - // True if the user is currently recording. - Recording *bool `protobuf:"varint,19,opt,name=recording" json:"recording,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UserState) Reset() { *m = UserState{} } -func (m *UserState) String() string { return proto.CompactTextString(m) } -func (*UserState) ProtoMessage() {} - -func (m *UserState) GetSession() uint32 { - if m != nil && m.Session != nil { - return *m.Session - } - return 0 -} - -func (m *UserState) GetActor() uint32 { - if m != nil && m.Actor != nil { - return *m.Actor - } - return 0 -} - -func (m *UserState) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *UserState) GetUserId() uint32 { - if m != nil && m.UserId != nil { - return *m.UserId - } - return 0 -} - -func (m *UserState) GetChannelId() uint32 { - if m != nil && m.ChannelId != nil { - return *m.ChannelId - } - return 0 -} - -func (m *UserState) GetMute() bool { - if m != nil && m.Mute != nil { - return *m.Mute - } - return false -} - -func (m *UserState) GetDeaf() bool { - if m != nil && m.Deaf != nil { - return *m.Deaf - } - return false -} - -func (m *UserState) GetSuppress() bool { - if m != nil && m.Suppress != nil { - return *m.Suppress - } - return false -} - -func (m *UserState) GetSelfMute() bool { - if m != nil && m.SelfMute != nil { - return *m.SelfMute - } - return false -} - -func (m *UserState) GetSelfDeaf() bool { - if m != nil && m.SelfDeaf != nil { - return *m.SelfDeaf - } - return false -} - -func (m *UserState) GetTexture() []byte { - if m != nil { - return m.Texture - } - return nil -} - -func (m *UserState) GetPluginContext() []byte { - if m != nil { - return m.PluginContext - } - return nil -} - -func (m *UserState) GetPluginIdentity() string { - if m != nil && m.PluginIdentity != nil { - return *m.PluginIdentity - } - return "" -} - -func (m *UserState) GetComment() string { - if m != nil && m.Comment != nil { - return *m.Comment - } - return "" -} - -func (m *UserState) GetHash() string { - if m != nil && m.Hash != nil { - return *m.Hash - } - return "" -} - -func (m *UserState) GetCommentHash() []byte { - if m != nil { - return m.CommentHash - } - return nil -} - -func (m *UserState) GetTextureHash() []byte { - if m != nil { - return m.TextureHash - } - return nil -} - -func (m *UserState) GetPrioritySpeaker() bool { - if m != nil && m.PrioritySpeaker != nil { - return *m.PrioritySpeaker - } - return false -} - -func (m *UserState) GetRecording() bool { - if m != nil && m.Recording != nil { - return *m.Recording - } - return false -} - -// Relays information on the bans. The client may send the BanList message to -// either modify the list of bans or query them from the server. The server -// sends this list only after a client queries for it. -type BanList struct { - // List of ban entries currently in place. - Bans []*BanList_BanEntry `protobuf:"bytes,1,rep,name=bans" json:"bans,omitempty"` - // True if the server should return the list, false if it should replace old - // ban list with the one provided. - Query *bool `protobuf:"varint,2,opt,name=query,def=0" json:"query,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *BanList) Reset() { *m = BanList{} } -func (m *BanList) String() string { return proto.CompactTextString(m) } -func (*BanList) ProtoMessage() {} - -const Default_BanList_Query bool = false - -func (m *BanList) GetBans() []*BanList_BanEntry { - if m != nil { - return m.Bans - } - return nil -} - -func (m *BanList) GetQuery() bool { - if m != nil && m.Query != nil { - return *m.Query - } - return Default_BanList_Query -} - -type BanList_BanEntry struct { - // Banned IP address. - Address []byte `protobuf:"bytes,1,req,name=address" json:"address,omitempty"` - // The length of the subnet mask for the ban. - Mask *uint32 `protobuf:"varint,2,req,name=mask" json:"mask,omitempty"` - // User name for identification purposes (does not affect the ban). - Name *string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"` - // TODO ?? - Hash *string `protobuf:"bytes,4,opt,name=hash" json:"hash,omitempty"` - // Reason for the ban (does not affect the ban). - Reason *string `protobuf:"bytes,5,opt,name=reason" json:"reason,omitempty"` - // Ban start time. - Start *string `protobuf:"bytes,6,opt,name=start" json:"start,omitempty"` - // Ban duration in seconds. - Duration *uint32 `protobuf:"varint,7,opt,name=duration" json:"duration,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *BanList_BanEntry) Reset() { *m = BanList_BanEntry{} } -func (m *BanList_BanEntry) String() string { return proto.CompactTextString(m) } -func (*BanList_BanEntry) ProtoMessage() {} - -func (m *BanList_BanEntry) GetAddress() []byte { - if m != nil { - return m.Address - } - return nil -} - -func (m *BanList_BanEntry) GetMask() uint32 { - if m != nil && m.Mask != nil { - return *m.Mask - } - return 0 -} - -func (m *BanList_BanEntry) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *BanList_BanEntry) GetHash() string { - if m != nil && m.Hash != nil { - return *m.Hash - } - return "" -} - -func (m *BanList_BanEntry) GetReason() string { - if m != nil && m.Reason != nil { - return *m.Reason - } - return "" -} - -func (m *BanList_BanEntry) GetStart() string { - if m != nil && m.Start != nil { - return *m.Start - } - return "" -} - -func (m *BanList_BanEntry) GetDuration() uint32 { - if m != nil && m.Duration != nil { - return *m.Duration - } - return 0 -} - -// Used to send and broadcast text messages. -type TextMessage struct { - // The message sender, identified by its session. - Actor *uint32 `protobuf:"varint,1,opt,name=actor" json:"actor,omitempty"` - // Target users for the message, identified by their session. - Session []uint32 `protobuf:"varint,2,rep,name=session" json:"session,omitempty"` - // The channels to which the message is sent, identified by their - // channel_ids. - ChannelId []uint32 `protobuf:"varint,3,rep,name=channel_id" json:"channel_id,omitempty"` - // The root channels when sending message recursively to several channels, - // identified by their channel_ids. - TreeId []uint32 `protobuf:"varint,4,rep,name=tree_id" json:"tree_id,omitempty"` - // The UTF-8 encoded message. May be HTML if the server allows. - Message *string `protobuf:"bytes,5,req,name=message" json:"message,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *TextMessage) Reset() { *m = TextMessage{} } -func (m *TextMessage) String() string { return proto.CompactTextString(m) } -func (*TextMessage) ProtoMessage() {} - -func (m *TextMessage) GetActor() uint32 { - if m != nil && m.Actor != nil { - return *m.Actor - } - return 0 -} - -func (m *TextMessage) GetSession() []uint32 { - if m != nil { - return m.Session - } - return nil -} - -func (m *TextMessage) GetChannelId() []uint32 { - if m != nil { - return m.ChannelId - } - return nil -} - -func (m *TextMessage) GetTreeId() []uint32 { - if m != nil { - return m.TreeId - } - return nil -} - -func (m *TextMessage) GetMessage() string { - if m != nil && m.Message != nil { - return *m.Message - } - return "" -} - -type PermissionDenied struct { - // The denied permission when type is Permission. - Permission *uint32 `protobuf:"varint,1,opt,name=permission" json:"permission,omitempty"` - // channel_id for the channel where the permission was denied when type is - // Permission. - ChannelId *uint32 `protobuf:"varint,2,opt,name=channel_id" json:"channel_id,omitempty"` - // The user who was denied permissions, identified by session. - Session *uint32 `protobuf:"varint,3,opt,name=session" json:"session,omitempty"` - // Textual reason for the denial. - Reason *string `protobuf:"bytes,4,opt,name=reason" json:"reason,omitempty"` - // Type of the denial. - Type *PermissionDenied_DenyType `protobuf:"varint,5,opt,name=type,enum=MumbleProto.PermissionDenied_DenyType" json:"type,omitempty"` - // The name that is invalid when type is UserName. - Name *string `protobuf:"bytes,6,opt,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PermissionDenied) Reset() { *m = PermissionDenied{} } -func (m *PermissionDenied) String() string { return proto.CompactTextString(m) } -func (*PermissionDenied) ProtoMessage() {} - -func (m *PermissionDenied) GetPermission() uint32 { - if m != nil && m.Permission != nil { - return *m.Permission - } - return 0 -} - -func (m *PermissionDenied) GetChannelId() uint32 { - if m != nil && m.ChannelId != nil { - return *m.ChannelId - } - return 0 -} - -func (m *PermissionDenied) GetSession() uint32 { - if m != nil && m.Session != nil { - return *m.Session - } - return 0 -} - -func (m *PermissionDenied) GetReason() string { - if m != nil && m.Reason != nil { - return *m.Reason - } - return "" -} - -func (m *PermissionDenied) GetType() PermissionDenied_DenyType { - if m != nil && m.Type != nil { - return *m.Type - } - return PermissionDenied_Text -} - -func (m *PermissionDenied) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -type ACL struct { - // Channel ID of the channel this message affects. - ChannelId *uint32 `protobuf:"varint,1,req,name=channel_id" json:"channel_id,omitempty"` - // True if the channel inherits its parent's ACLs. - InheritAcls *bool `protobuf:"varint,2,opt,name=inherit_acls,def=1" json:"inherit_acls,omitempty"` - // User group specifications. - Groups []*ACL_ChanGroup `protobuf:"bytes,3,rep,name=groups" json:"groups,omitempty"` - // ACL specifications. - Acls []*ACL_ChanACL `protobuf:"bytes,4,rep,name=acls" json:"acls,omitempty"` - // True if the message is a query for ACLs instead of setting them. - Query *bool `protobuf:"varint,5,opt,name=query,def=0" json:"query,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ACL) Reset() { *m = ACL{} } -func (m *ACL) String() string { return proto.CompactTextString(m) } -func (*ACL) ProtoMessage() {} - -const Default_ACL_InheritAcls bool = true -const Default_ACL_Query bool = false - -func (m *ACL) GetChannelId() uint32 { - if m != nil && m.ChannelId != nil { - return *m.ChannelId - } - return 0 -} - -func (m *ACL) GetInheritAcls() bool { - if m != nil && m.InheritAcls != nil { - return *m.InheritAcls - } - return Default_ACL_InheritAcls -} - -func (m *ACL) GetGroups() []*ACL_ChanGroup { - if m != nil { - return m.Groups - } - return nil -} - -func (m *ACL) GetAcls() []*ACL_ChanACL { - if m != nil { - return m.Acls - } - return nil -} - -func (m *ACL) GetQuery() bool { - if m != nil && m.Query != nil { - return *m.Query - } - return Default_ACL_Query -} - -type ACL_ChanGroup struct { - // Name of the channel group, UTF-8 encoded. - Name *string `protobuf:"bytes,1,req,name=name" json:"name,omitempty"` - // True if the group has been inherited from the parent (Read only). - Inherited *bool `protobuf:"varint,2,opt,name=inherited,def=1" json:"inherited,omitempty"` - // True if the group members are inherited. - Inherit *bool `protobuf:"varint,3,opt,name=inherit,def=1" json:"inherit,omitempty"` - // True if the group can be inherited by sub channels. - Inheritable *bool `protobuf:"varint,4,opt,name=inheritable,def=1" json:"inheritable,omitempty"` - // Users explicitly included in this group, identified by user_id. - Add []uint32 `protobuf:"varint,5,rep,name=add" json:"add,omitempty"` - // Users explicitly removed from this group in this channel if the group - // has been inherited, identified by user_id. - Remove []uint32 `protobuf:"varint,6,rep,name=remove" json:"remove,omitempty"` - // Users inherited, identified by user_id. - InheritedMembers []uint32 `protobuf:"varint,7,rep,name=inherited_members" json:"inherited_members,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ACL_ChanGroup) Reset() { *m = ACL_ChanGroup{} } -func (m *ACL_ChanGroup) String() string { return proto.CompactTextString(m) } -func (*ACL_ChanGroup) ProtoMessage() {} - -const Default_ACL_ChanGroup_Inherited bool = true -const Default_ACL_ChanGroup_Inherit bool = true -const Default_ACL_ChanGroup_Inheritable bool = true - -func (m *ACL_ChanGroup) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *ACL_ChanGroup) GetInherited() bool { - if m != nil && m.Inherited != nil { - return *m.Inherited - } - return Default_ACL_ChanGroup_Inherited -} - -func (m *ACL_ChanGroup) GetInherit() bool { - if m != nil && m.Inherit != nil { - return *m.Inherit - } - return Default_ACL_ChanGroup_Inherit -} - -func (m *ACL_ChanGroup) GetInheritable() bool { - if m != nil && m.Inheritable != nil { - return *m.Inheritable - } - return Default_ACL_ChanGroup_Inheritable -} - -func (m *ACL_ChanGroup) GetAdd() []uint32 { - if m != nil { - return m.Add - } - return nil -} - -func (m *ACL_ChanGroup) GetRemove() []uint32 { - if m != nil { - return m.Remove - } - return nil -} - -func (m *ACL_ChanGroup) GetInheritedMembers() []uint32 { - if m != nil { - return m.InheritedMembers - } - return nil -} - -type ACL_ChanACL struct { - // True if this ACL applies to the current channel. - ApplyHere *bool `protobuf:"varint,1,opt,name=apply_here,def=1" json:"apply_here,omitempty"` - // True if this ACL applies to the sub channels. - ApplySubs *bool `protobuf:"varint,2,opt,name=apply_subs,def=1" json:"apply_subs,omitempty"` - // True if the ACL has been inherited from the parent. - Inherited *bool `protobuf:"varint,3,opt,name=inherited,def=1" json:"inherited,omitempty"` - // ID of the user that is affected by this ACL. - UserId *uint32 `protobuf:"varint,4,opt,name=user_id" json:"user_id,omitempty"` - // ID of the group that is affected by this ACL. - Group *string `protobuf:"bytes,5,opt,name=group" json:"group,omitempty"` - // Bit flag field of the permissions granted by this ACL. - Grant *uint32 `protobuf:"varint,6,opt,name=grant" json:"grant,omitempty"` - // Bit flag field of the permissions denied by this ACL. - Deny *uint32 `protobuf:"varint,7,opt,name=deny" json:"deny,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ACL_ChanACL) Reset() { *m = ACL_ChanACL{} } -func (m *ACL_ChanACL) String() string { return proto.CompactTextString(m) } -func (*ACL_ChanACL) ProtoMessage() {} - -const Default_ACL_ChanACL_ApplyHere bool = true -const Default_ACL_ChanACL_ApplySubs bool = true -const Default_ACL_ChanACL_Inherited bool = true - -func (m *ACL_ChanACL) GetApplyHere() bool { - if m != nil && m.ApplyHere != nil { - return *m.ApplyHere - } - return Default_ACL_ChanACL_ApplyHere -} - -func (m *ACL_ChanACL) GetApplySubs() bool { - if m != nil && m.ApplySubs != nil { - return *m.ApplySubs - } - return Default_ACL_ChanACL_ApplySubs -} - -func (m *ACL_ChanACL) GetInherited() bool { - if m != nil && m.Inherited != nil { - return *m.Inherited - } - return Default_ACL_ChanACL_Inherited -} - -func (m *ACL_ChanACL) GetUserId() uint32 { - if m != nil && m.UserId != nil { - return *m.UserId - } - return 0 -} - -func (m *ACL_ChanACL) GetGroup() string { - if m != nil && m.Group != nil { - return *m.Group - } - return "" -} - -func (m *ACL_ChanACL) GetGrant() uint32 { - if m != nil && m.Grant != nil { - return *m.Grant - } - return 0 -} - -func (m *ACL_ChanACL) GetDeny() uint32 { - if m != nil && m.Deny != nil { - return *m.Deny - } - return 0 -} - -// Client may use this message to refresh its registered user information. The -// client should fill the IDs or Names of the users it wants to refresh. The -// server fills the missing parts and sends the message back. -type QueryUsers struct { - // user_ids. - Ids []uint32 `protobuf:"varint,1,rep,name=ids" json:"ids,omitempty"` - // User names in the same order as ids. - Names []string `protobuf:"bytes,2,rep,name=names" json:"names,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *QueryUsers) Reset() { *m = QueryUsers{} } -func (m *QueryUsers) String() string { return proto.CompactTextString(m) } -func (*QueryUsers) ProtoMessage() {} - -func (m *QueryUsers) GetIds() []uint32 { - if m != nil { - return m.Ids - } - return nil -} - -func (m *QueryUsers) GetNames() []string { - if m != nil { - return m.Names - } - return nil -} - -// Used to initialize and resync the UDP encryption. Either side may request a -// resync by sending the message without any values filled. The resync is -// performed by sending the message with only the client or server nonce -// filled. -type CryptSetup struct { - // Encryption key. - Key []byte `protobuf:"bytes,1,opt,name=key" json:"key,omitempty"` - // Client nonce. - ClientNonce []byte `protobuf:"bytes,2,opt,name=client_nonce" json:"client_nonce,omitempty"` - // Server nonce. - ServerNonce []byte `protobuf:"bytes,3,opt,name=server_nonce" json:"server_nonce,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CryptSetup) Reset() { *m = CryptSetup{} } -func (m *CryptSetup) String() string { return proto.CompactTextString(m) } -func (*CryptSetup) ProtoMessage() {} - -func (m *CryptSetup) GetKey() []byte { - if m != nil { - return m.Key - } - return nil -} - -func (m *CryptSetup) GetClientNonce() []byte { - if m != nil { - return m.ClientNonce - } - return nil -} - -func (m *CryptSetup) GetServerNonce() []byte { - if m != nil { - return m.ServerNonce - } - return nil -} - -type ContextActionModify struct { - // The action name. - Action *string `protobuf:"bytes,1,req,name=action" json:"action,omitempty"` - // The display name of the action. - Text *string `protobuf:"bytes,2,opt,name=text" json:"text,omitempty"` - // Context bit flags defining where the action should be displayed. - Context *uint32 `protobuf:"varint,3,opt,name=context" json:"context,omitempty"` - Operation *ContextActionModify_Operation `protobuf:"varint,4,opt,name=operation,enum=MumbleProto.ContextActionModify_Operation" json:"operation,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ContextActionModify) Reset() { *m = ContextActionModify{} } -func (m *ContextActionModify) String() string { return proto.CompactTextString(m) } -func (*ContextActionModify) ProtoMessage() {} - -func (m *ContextActionModify) GetAction() string { - if m != nil && m.Action != nil { - return *m.Action - } - return "" -} - -func (m *ContextActionModify) GetText() string { - if m != nil && m.Text != nil { - return *m.Text - } - return "" -} - -func (m *ContextActionModify) GetContext() uint32 { - if m != nil && m.Context != nil { - return *m.Context - } - return 0 -} - -func (m *ContextActionModify) GetOperation() ContextActionModify_Operation { - if m != nil && m.Operation != nil { - return *m.Operation - } - return ContextActionModify_Add -} - -// Sent by the client when it wants to initiate a Context action. -type ContextAction struct { - // The target User for the action, identified by session. - Session *uint32 `protobuf:"varint,1,opt,name=session" json:"session,omitempty"` - // The target Channel for the action, identified by channel_id. - ChannelId *uint32 `protobuf:"varint,2,opt,name=channel_id" json:"channel_id,omitempty"` - // The action that should be executed. - Action *string `protobuf:"bytes,3,req,name=action" json:"action,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ContextAction) Reset() { *m = ContextAction{} } -func (m *ContextAction) String() string { return proto.CompactTextString(m) } -func (*ContextAction) ProtoMessage() {} - -func (m *ContextAction) GetSession() uint32 { - if m != nil && m.Session != nil { - return *m.Session - } - return 0 -} - -func (m *ContextAction) GetChannelId() uint32 { - if m != nil && m.ChannelId != nil { - return *m.ChannelId - } - return 0 -} - -func (m *ContextAction) GetAction() string { - if m != nil && m.Action != nil { - return *m.Action - } - return "" -} - -// Lists the registered users. -type UserList struct { - // A list of registered users. - Users []*UserList_User `protobuf:"bytes,1,rep,name=users" json:"users,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UserList) Reset() { *m = UserList{} } -func (m *UserList) String() string { return proto.CompactTextString(m) } -func (*UserList) ProtoMessage() {} - -func (m *UserList) GetUsers() []*UserList_User { - if m != nil { - return m.Users - } - return nil -} - -type UserList_User struct { - // Registered user ID. - UserId *uint32 `protobuf:"varint,1,req,name=user_id" json:"user_id,omitempty"` - // Registered user name. - Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` - LastSeen *string `protobuf:"bytes,3,opt,name=last_seen" json:"last_seen,omitempty"` - LastChannel *uint32 `protobuf:"varint,4,opt,name=last_channel" json:"last_channel,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UserList_User) Reset() { *m = UserList_User{} } -func (m *UserList_User) String() string { return proto.CompactTextString(m) } -func (*UserList_User) ProtoMessage() {} - -func (m *UserList_User) GetUserId() uint32 { - if m != nil && m.UserId != nil { - return *m.UserId - } - return 0 -} - -func (m *UserList_User) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *UserList_User) GetLastSeen() string { - if m != nil && m.LastSeen != nil { - return *m.LastSeen - } - return "" -} - -func (m *UserList_User) GetLastChannel() uint32 { - if m != nil && m.LastChannel != nil { - return *m.LastChannel - } - return 0 -} - -// Sent by the client when it wants to register or clear whisper targets. -// -// Note: The first available target ID is 1 as 0 is reserved for normal -// talking. Maximum target ID is 30. -type VoiceTarget struct { - // Voice target ID. - Id *uint32 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"` - // The receivers that this voice target includes. - Targets []*VoiceTarget_Target `protobuf:"bytes,2,rep,name=targets" json:"targets,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *VoiceTarget) Reset() { *m = VoiceTarget{} } -func (m *VoiceTarget) String() string { return proto.CompactTextString(m) } -func (*VoiceTarget) ProtoMessage() {} - -func (m *VoiceTarget) GetId() uint32 { - if m != nil && m.Id != nil { - return *m.Id - } - return 0 -} - -func (m *VoiceTarget) GetTargets() []*VoiceTarget_Target { - if m != nil { - return m.Targets - } - return nil -} - -type VoiceTarget_Target struct { - // Users that are included as targets. - Session []uint32 `protobuf:"varint,1,rep,name=session" json:"session,omitempty"` - // Channels that are included as targets. - ChannelId *uint32 `protobuf:"varint,2,opt,name=channel_id" json:"channel_id,omitempty"` - // TODO ?? - Group *string `protobuf:"bytes,3,opt,name=group" json:"group,omitempty"` - // True if the voice should follow links from the specified channel. - Links *bool `protobuf:"varint,4,opt,name=links,def=0" json:"links,omitempty"` - // True if the voice should also be sent to children of the specific - // channel. - Children *bool `protobuf:"varint,5,opt,name=children,def=0" json:"children,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *VoiceTarget_Target) Reset() { *m = VoiceTarget_Target{} } -func (m *VoiceTarget_Target) String() string { return proto.CompactTextString(m) } -func (*VoiceTarget_Target) ProtoMessage() {} - -const Default_VoiceTarget_Target_Links bool = false -const Default_VoiceTarget_Target_Children bool = false - -func (m *VoiceTarget_Target) GetSession() []uint32 { - if m != nil { - return m.Session - } - return nil -} - -func (m *VoiceTarget_Target) GetChannelId() uint32 { - if m != nil && m.ChannelId != nil { - return *m.ChannelId - } - return 0 -} - -func (m *VoiceTarget_Target) GetGroup() string { - if m != nil && m.Group != nil { - return *m.Group - } - return "" -} - -func (m *VoiceTarget_Target) GetLinks() bool { - if m != nil && m.Links != nil { - return *m.Links - } - return Default_VoiceTarget_Target_Links -} - -func (m *VoiceTarget_Target) GetChildren() bool { - if m != nil && m.Children != nil { - return *m.Children - } - return Default_VoiceTarget_Target_Children -} - -// Sent by the client when it wants permissions for a certain channel. Sent by -// the server when it replies to the query or wants the user to resync all -// channel permissions. -type PermissionQuery struct { - // channel_id of the channel for which the permissions are queried. - ChannelId *uint32 `protobuf:"varint,1,opt,name=channel_id" json:"channel_id,omitempty"` - // Channel permissions. - Permissions *uint32 `protobuf:"varint,2,opt,name=permissions" json:"permissions,omitempty"` - // True if the client should drop its current permission information for all - // channels. - Flush *bool `protobuf:"varint,3,opt,name=flush,def=0" json:"flush,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PermissionQuery) Reset() { *m = PermissionQuery{} } -func (m *PermissionQuery) String() string { return proto.CompactTextString(m) } -func (*PermissionQuery) ProtoMessage() {} - -const Default_PermissionQuery_Flush bool = false - -func (m *PermissionQuery) GetChannelId() uint32 { - if m != nil && m.ChannelId != nil { - return *m.ChannelId - } - return 0 -} - -func (m *PermissionQuery) GetPermissions() uint32 { - if m != nil && m.Permissions != nil { - return *m.Permissions - } - return 0 -} - -func (m *PermissionQuery) GetFlush() bool { - if m != nil && m.Flush != nil { - return *m.Flush - } - return Default_PermissionQuery_Flush -} - -// Sent by the server to notify the users of the version of the CELT codec they -// should use. This may change during the connection when new users join. -type CodecVersion struct { - // The version of the CELT Alpha codec. - Alpha *int32 `protobuf:"varint,1,req,name=alpha" json:"alpha,omitempty"` - // The version of the CELT Beta codec. - Beta *int32 `protobuf:"varint,2,req,name=beta" json:"beta,omitempty"` - // True if the user should prefer Alpha over Beta. - PreferAlpha *bool `protobuf:"varint,3,req,name=prefer_alpha,def=1" json:"prefer_alpha,omitempty"` - Opus *bool `protobuf:"varint,4,opt,name=opus,def=0" json:"opus,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CodecVersion) Reset() { *m = CodecVersion{} } -func (m *CodecVersion) String() string { return proto.CompactTextString(m) } -func (*CodecVersion) ProtoMessage() {} - -const Default_CodecVersion_PreferAlpha bool = true -const Default_CodecVersion_Opus bool = false - -func (m *CodecVersion) GetAlpha() int32 { - if m != nil && m.Alpha != nil { - return *m.Alpha - } - return 0 -} - -func (m *CodecVersion) GetBeta() int32 { - if m != nil && m.Beta != nil { - return *m.Beta - } - return 0 -} - -func (m *CodecVersion) GetPreferAlpha() bool { - if m != nil && m.PreferAlpha != nil { - return *m.PreferAlpha - } - return Default_CodecVersion_PreferAlpha -} - -func (m *CodecVersion) GetOpus() bool { - if m != nil && m.Opus != nil { - return *m.Opus - } - return Default_CodecVersion_Opus -} - -// Used to communicate user stats between the server and clients. -type UserStats struct { - // User whose stats these are. - Session *uint32 `protobuf:"varint,1,opt,name=session" json:"session,omitempty"` - // True if the message contains only mutable stats (packets, ping). - StatsOnly *bool `protobuf:"varint,2,opt,name=stats_only,def=0" json:"stats_only,omitempty"` - // Full user certificate chain of the user certificate in DER format. - Certificates [][]byte `protobuf:"bytes,3,rep,name=certificates" json:"certificates,omitempty"` - // Packet statistics for packets received from the client. - FromClient *UserStats_Stats `protobuf:"bytes,4,opt,name=from_client" json:"from_client,omitempty"` - // Packet statistics for packets sent by the server. - FromServer *UserStats_Stats `protobuf:"bytes,5,opt,name=from_server" json:"from_server,omitempty"` - // Amount of UDP packets sent. - UdpPackets *uint32 `protobuf:"varint,6,opt,name=udp_packets" json:"udp_packets,omitempty"` - // Amount of TCP packets sent. - TcpPackets *uint32 `protobuf:"varint,7,opt,name=tcp_packets" json:"tcp_packets,omitempty"` - // UDP ping average. - UdpPingAvg *float32 `protobuf:"fixed32,8,opt,name=udp_ping_avg" json:"udp_ping_avg,omitempty"` - // UDP ping variance. - UdpPingVar *float32 `protobuf:"fixed32,9,opt,name=udp_ping_var" json:"udp_ping_var,omitempty"` - // TCP ping average. - TcpPingAvg *float32 `protobuf:"fixed32,10,opt,name=tcp_ping_avg" json:"tcp_ping_avg,omitempty"` - // TCP ping variance. - TcpPingVar *float32 `protobuf:"fixed32,11,opt,name=tcp_ping_var" json:"tcp_ping_var,omitempty"` - // Client version. - Version *Version `protobuf:"bytes,12,opt,name=version" json:"version,omitempty"` - // A list of CELT bitstream version constants supported by the client of this - // user. - CeltVersions []int32 `protobuf:"varint,13,rep,name=celt_versions" json:"celt_versions,omitempty"` - // Client IP address. - Address []byte `protobuf:"bytes,14,opt,name=address" json:"address,omitempty"` - // Bandwith used by this client. - Bandwidth *uint32 `protobuf:"varint,15,opt,name=bandwidth" json:"bandwidth,omitempty"` - // Connection duration. - Onlinesecs *uint32 `protobuf:"varint,16,opt,name=onlinesecs" json:"onlinesecs,omitempty"` - // Duration since last activity. - Idlesecs *uint32 `protobuf:"varint,17,opt,name=idlesecs" json:"idlesecs,omitempty"` - // True if the user has a strong certificate. - StrongCertificate *bool `protobuf:"varint,18,opt,name=strong_certificate,def=0" json:"strong_certificate,omitempty"` - Opus *bool `protobuf:"varint,19,opt,name=opus,def=0" json:"opus,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UserStats) Reset() { *m = UserStats{} } -func (m *UserStats) String() string { return proto.CompactTextString(m) } -func (*UserStats) ProtoMessage() {} - -const Default_UserStats_StatsOnly bool = false -const Default_UserStats_StrongCertificate bool = false -const Default_UserStats_Opus bool = false - -func (m *UserStats) GetSession() uint32 { - if m != nil && m.Session != nil { - return *m.Session - } - return 0 -} - -func (m *UserStats) GetStatsOnly() bool { - if m != nil && m.StatsOnly != nil { - return *m.StatsOnly - } - return Default_UserStats_StatsOnly -} - -func (m *UserStats) GetCertificates() [][]byte { - if m != nil { - return m.Certificates - } - return nil -} - -func (m *UserStats) GetFromClient() *UserStats_Stats { - if m != nil { - return m.FromClient - } - return nil -} - -func (m *UserStats) GetFromServer() *UserStats_Stats { - if m != nil { - return m.FromServer - } - return nil -} - -func (m *UserStats) GetUdpPackets() uint32 { - if m != nil && m.UdpPackets != nil { - return *m.UdpPackets - } - return 0 -} - -func (m *UserStats) GetTcpPackets() uint32 { - if m != nil && m.TcpPackets != nil { - return *m.TcpPackets - } - return 0 -} - -func (m *UserStats) GetUdpPingAvg() float32 { - if m != nil && m.UdpPingAvg != nil { - return *m.UdpPingAvg - } - return 0 -} - -func (m *UserStats) GetUdpPingVar() float32 { - if m != nil && m.UdpPingVar != nil { - return *m.UdpPingVar - } - return 0 -} - -func (m *UserStats) GetTcpPingAvg() float32 { - if m != nil && m.TcpPingAvg != nil { - return *m.TcpPingAvg - } - return 0 -} - -func (m *UserStats) GetTcpPingVar() float32 { - if m != nil && m.TcpPingVar != nil { - return *m.TcpPingVar - } - return 0 -} - -func (m *UserStats) GetVersion() *Version { - if m != nil { - return m.Version - } - return nil -} - -func (m *UserStats) GetCeltVersions() []int32 { - if m != nil { - return m.CeltVersions - } - return nil -} - -func (m *UserStats) GetAddress() []byte { - if m != nil { - return m.Address - } - return nil -} - -func (m *UserStats) GetBandwidth() uint32 { - if m != nil && m.Bandwidth != nil { - return *m.Bandwidth - } - return 0 -} - -func (m *UserStats) GetOnlinesecs() uint32 { - if m != nil && m.Onlinesecs != nil { - return *m.Onlinesecs - } - return 0 -} - -func (m *UserStats) GetIdlesecs() uint32 { - if m != nil && m.Idlesecs != nil { - return *m.Idlesecs - } - return 0 -} - -func (m *UserStats) GetStrongCertificate() bool { - if m != nil && m.StrongCertificate != nil { - return *m.StrongCertificate - } - return Default_UserStats_StrongCertificate -} - -func (m *UserStats) GetOpus() bool { - if m != nil && m.Opus != nil { - return *m.Opus - } - return Default_UserStats_Opus -} - -type UserStats_Stats struct { - // The amount of good packets received. - Good *uint32 `protobuf:"varint,1,opt,name=good" json:"good,omitempty"` - // The amount of late packets received. - Late *uint32 `protobuf:"varint,2,opt,name=late" json:"late,omitempty"` - // The amount of packets never received. - Lost *uint32 `protobuf:"varint,3,opt,name=lost" json:"lost,omitempty"` - // The amount of nonce resyncs. - Resync *uint32 `protobuf:"varint,4,opt,name=resync" json:"resync,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UserStats_Stats) Reset() { *m = UserStats_Stats{} } -func (m *UserStats_Stats) String() string { return proto.CompactTextString(m) } -func (*UserStats_Stats) ProtoMessage() {} - -func (m *UserStats_Stats) GetGood() uint32 { - if m != nil && m.Good != nil { - return *m.Good - } - return 0 -} - -func (m *UserStats_Stats) GetLate() uint32 { - if m != nil && m.Late != nil { - return *m.Late - } - return 0 -} - -func (m *UserStats_Stats) GetLost() uint32 { - if m != nil && m.Lost != nil { - return *m.Lost - } - return 0 -} - -func (m *UserStats_Stats) GetResync() uint32 { - if m != nil && m.Resync != nil { - return *m.Resync - } - return 0 -} - -// Used by the client to request binary data from the server. By default large -// comments or textures are not sent within standard messages but instead the -// hash is. If the client does not recognize the hash it may request the -// resource when it needs it. The client does so by sending a RequestBlob -// message with the correct fields filled with the user sessions or channel_ids -// it wants to receive. The server replies to this by sending a new -// UserState/ChannelState message with the resources filled even if they would -// normally be transmitted as hashes. -type RequestBlob struct { - // sessions of the requested UserState textures. - SessionTexture []uint32 `protobuf:"varint,1,rep,name=session_texture" json:"session_texture,omitempty"` - // sessions of the requested UserState comments. - SessionComment []uint32 `protobuf:"varint,2,rep,name=session_comment" json:"session_comment,omitempty"` - // channel_ids of the requested ChannelState descriptions. - ChannelDescription []uint32 `protobuf:"varint,3,rep,name=channel_description" json:"channel_description,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RequestBlob) Reset() { *m = RequestBlob{} } -func (m *RequestBlob) String() string { return proto.CompactTextString(m) } -func (*RequestBlob) ProtoMessage() {} - -func (m *RequestBlob) GetSessionTexture() []uint32 { - if m != nil { - return m.SessionTexture - } - return nil -} - -func (m *RequestBlob) GetSessionComment() []uint32 { - if m != nil { - return m.SessionComment - } - return nil -} - -func (m *RequestBlob) GetChannelDescription() []uint32 { - if m != nil { - return m.ChannelDescription - } - return nil -} - -// Sent by the server when it informs the clients on server configuration -// details. -type ServerConfig struct { - // The maximum bandwidth the clients should use. - MaxBandwidth *uint32 `protobuf:"varint,1,opt,name=max_bandwidth" json:"max_bandwidth,omitempty"` - // Server welcome text. - WelcomeText *string `protobuf:"bytes,2,opt,name=welcome_text" json:"welcome_text,omitempty"` - // True if the server allows HTML. - AllowHtml *bool `protobuf:"varint,3,opt,name=allow_html" json:"allow_html,omitempty"` - // Maximum text message length. - MessageLength *uint32 `protobuf:"varint,4,opt,name=message_length" json:"message_length,omitempty"` - // Maximum image message length. - ImageMessageLength *uint32 `protobuf:"varint,5,opt,name=image_message_length" json:"image_message_length,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ServerConfig) Reset() { *m = ServerConfig{} } -func (m *ServerConfig) String() string { return proto.CompactTextString(m) } -func (*ServerConfig) ProtoMessage() {} - -func (m *ServerConfig) GetMaxBandwidth() uint32 { - if m != nil && m.MaxBandwidth != nil { - return *m.MaxBandwidth - } - return 0 -} - -func (m *ServerConfig) GetWelcomeText() string { - if m != nil && m.WelcomeText != nil { - return *m.WelcomeText - } - return "" -} - -func (m *ServerConfig) GetAllowHtml() bool { - if m != nil && m.AllowHtml != nil { - return *m.AllowHtml - } - return false -} - -func (m *ServerConfig) GetMessageLength() uint32 { - if m != nil && m.MessageLength != nil { - return *m.MessageLength - } - return 0 -} - -func (m *ServerConfig) GetImageMessageLength() uint32 { - if m != nil && m.ImageMessageLength != nil { - return *m.ImageMessageLength - } - return 0 -} - -// Sent by the server to inform the clients of suggested client configuration -// specified by the server administrator. -type SuggestConfig struct { - // Suggested client version. - Version *uint32 `protobuf:"varint,1,opt,name=version" json:"version,omitempty"` - // True if the administrator suggests positional audio to be used on this - // server. - Positional *bool `protobuf:"varint,2,opt,name=positional" json:"positional,omitempty"` - // True if the administrator suggests push to talk to be used on this server. - PushToTalk *bool `protobuf:"varint,3,opt,name=push_to_talk" json:"push_to_talk,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SuggestConfig) Reset() { *m = SuggestConfig{} } -func (m *SuggestConfig) String() string { return proto.CompactTextString(m) } -func (*SuggestConfig) ProtoMessage() {} - -func (m *SuggestConfig) GetVersion() uint32 { - if m != nil && m.Version != nil { - return *m.Version - } - return 0 -} - -func (m *SuggestConfig) GetPositional() bool { - if m != nil && m.Positional != nil { - return *m.Positional - } - return false -} - -func (m *SuggestConfig) GetPushToTalk() bool { - if m != nil && m.PushToTalk != nil { - return *m.PushToTalk - } - return false -} - -func init() { - proto.RegisterEnum("MumbleProto.Reject_RejectType", Reject_RejectType_name, Reject_RejectType_value) - proto.RegisterEnum("MumbleProto.PermissionDenied_DenyType", PermissionDenied_DenyType_name, PermissionDenied_DenyType_value) - proto.RegisterEnum("MumbleProto.ContextActionModify_Context", ContextActionModify_Context_name, ContextActionModify_Context_value) - proto.RegisterEnum("MumbleProto.ContextActionModify_Operation", ContextActionModify_Operation_name, ContextActionModify_Operation_value) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.proto b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.proto deleted file mode 100644 index 92b8737..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/Mumble.proto +++ /dev/null @@ -1,544 +0,0 @@ -package MumbleProto; - -option optimize_for = SPEED; - -message Version { - // 2-byte Major, 1-byte Minor and 1-byte Patch version number. - optional uint32 version = 1; - // Client release name. - optional string release = 2; - // Client OS name. - optional string os = 3; - // Client OS version. - optional string os_version = 4; -} - -// Not used. Not even for tunneling UDP through TCP. -message UDPTunnel { - // Not used. - required bytes packet = 1; -} - -// Used by the client to send the authentication credentials to the server. -message Authenticate { - // UTF-8 encoded username. - optional string username = 1; - // Server or user password. - optional string password = 2; - // Additional access tokens for server ACL groups. - repeated string tokens = 3; - // A list of CELT bitstream version constants supported by the client. - repeated int32 celt_versions = 4; - optional bool opus = 5 [default = false]; -} - -// Sent by the client to notify the server that the client is still alive. -// Server must reply to the packet with the same timestamp and its own -// good/late/lost/resync numbers. None of the fields is strictly required. -message Ping { - // Client timestamp. Server should not attempt to decode. - optional uint64 timestamp = 1; - // The amount of good packets received. - optional uint32 good = 2; - // The amount of late packets received. - optional uint32 late = 3; - // The amount of packets never received. - optional uint32 lost = 4; - // The amount of nonce resyncs. - optional uint32 resync = 5; - // The total amount of UDP packets received. - optional uint32 udp_packets = 6; - // The total amount of TCP packets received. - optional uint32 tcp_packets = 7; - // UDP ping average. - optional float udp_ping_avg = 8; - // UDP ping variance. - optional float udp_ping_var = 9; - // TCP ping average. - optional float tcp_ping_avg = 10; - // TCP ping variance. - optional float tcp_ping_var = 11; -} - -// Sent by the server when it rejects the user connection. -message Reject { - enum RejectType { - // TODO ?? - None = 0; - // The client attempted to connect with an incompatible version. - WrongVersion = 1; - // The user name supplied by the client was invalid. - InvalidUsername = 2; - // The client attempted to authenticate as a user with a password but it - // was wrong. - WrongUserPW = 3; - // The client attempted to connect to a passworded server but the password - // was wrong. - WrongServerPW = 4; - // Supplied username is already in use. - UsernameInUse = 5; - // Server is currently full and cannot accept more users. - ServerFull = 6; - // The user did not provide a certificate but one is required. - NoCertificate = 7; - AuthenticatorFail = 8; - } - // Rejection type. - optional RejectType type = 1; - // Human readable rejection reason. - optional string reason = 2; -} - -// ServerSync message is sent by the server when it has authenticated the user -// and finished synchronizing the server state. -message ServerSync { - // The session of the current user. - optional uint32 session = 1; - // Maximum bandwidth that the user should use. - optional uint32 max_bandwidth = 2; - // Server welcome text. - optional string welcome_text = 3; - // Current user permissions TODO: Confirm?? - optional uint64 permissions = 4; -} - -// Sent by the client when it wants a channel removed. Sent by the server when -// a channel has been removed and clients should be notified. -message ChannelRemove { - required uint32 channel_id = 1; -} - -// Used to communicate channel properties between the client and the server. -// Sent by the server during the login process or when channel properties are -// updated. Client may use this message to update said channel properties. -message ChannelState { - // Unique ID for the channel within the server. - optional uint32 channel_id = 1; - // channel_id of the parent channel. - optional uint32 parent = 2; - // UTF-8 encoded channel name. - optional string name = 3; - // A collection of channel id values of the linked channels. Absent during - // the first channel listing. - repeated uint32 links = 4; - // UTF-8 encoded channel description. Only if the description is less than - // 128 bytes - optional string description = 5; - // A collection of channel_id values that should be added to links. - repeated uint32 links_add = 6; - // A collection of channel_id values that should be removed from links. - repeated uint32 links_remove = 7; - // True if the channel is temporary. - optional bool temporary = 8 [default = false]; - // Position weight to tweak the channel position in the channel list. - optional int32 position = 9 [default = 0]; - // SHA1 hash of the description if the description is 128 bytes or more. - optional bytes description_hash = 10; -} - -// Used to communicate user leaving or being kicked. May be sent by the client -// when it attempts to kick a user. Sent by the server when it informs the -// clients that a user is not present anymore. -message UserRemove { - // The user who is being kicked, identified by their session, not present - // when no one is being kicked. - required uint32 session = 1; - // The user who initiated the removal. Either the user who performs the kick - // or the user who is currently leaving. - optional uint32 actor = 2; - // Reason for the kick, stored as the ban reason if the user is banned. - optional string reason = 3; - // True if the kick should result in a ban. - optional bool ban = 4; -} - -// Sent by the server when it communicates new and changed users to client. -// First seen during login procedure. May be sent by the client when it wishes -// to alter its state. -message UserState { - // Unique user session ID of the user whose state this is, may change on - // reconnect. - optional uint32 session = 1; - // The session of the user who is updating this user. - optional uint32 actor = 2; - // User name, UTF-8 encoded. - optional string name = 3; - // Registered user ID if the user is registered. - optional uint32 user_id = 4; - // Channel on which the user is. - optional uint32 channel_id = 5; - // True if the user is muted by admin. - optional bool mute = 6; - // True if the user is deafened by admin. - optional bool deaf = 7; - // True if the user has been suppressed from talking by a reason other than - // being muted. - optional bool suppress = 8; - // True if the user has muted self. - optional bool self_mute = 9; - // True if the user has deafened self. - optional bool self_deaf = 10; - // User image if it is less than 128 bytes. - optional bytes texture = 11; - // TODO ?? - optional bytes plugin_context = 12; - // TODO ?? - optional string plugin_identity = 13; - // User comment if it is less than 128 bytes. - optional string comment = 14; - // The hash of the user certificate. - optional string hash = 15; - // SHA1 hash of the user comment if it 128 bytes or more. - optional bytes comment_hash = 16; - // SHA1 hash of the user picture if it 128 bytes or more. - optional bytes texture_hash = 17; - // True if the user is a priority speaker. - optional bool priority_speaker = 18; - // True if the user is currently recording. - optional bool recording = 19; -} - -// Relays information on the bans. The client may send the BanList message to -// either modify the list of bans or query them from the server. The server -// sends this list only after a client queries for it. -message BanList { - message BanEntry { - // Banned IP address. - required bytes address = 1; - // The length of the subnet mask for the ban. - required uint32 mask = 2; - // User name for identification purposes (does not affect the ban). - optional string name = 3; - // TODO ?? - optional string hash = 4; - // Reason for the ban (does not affect the ban). - optional string reason = 5; - // Ban start time. - optional string start = 6; - // Ban duration in seconds. - optional uint32 duration = 7; - } - // List of ban entries currently in place. - repeated BanEntry bans = 1; - // True if the server should return the list, false if it should replace old - // ban list with the one provided. - optional bool query = 2 [default = false]; -} - -// Used to send and broadcast text messages. -message TextMessage { - // The message sender, identified by its session. - optional uint32 actor = 1; - // Target users for the message, identified by their session. - repeated uint32 session = 2; - // The channels to which the message is sent, identified by their - // channel_ids. - repeated uint32 channel_id = 3; - // The root channels when sending message recursively to several channels, - // identified by their channel_ids. - repeated uint32 tree_id = 4; - // The UTF-8 encoded message. May be HTML if the server allows. - required string message = 5; -} - -message PermissionDenied { - enum DenyType { - // Operation denied for other reason, see reason field. - Text = 0; - // Permissions were denied. - Permission = 1; - // Cannot modify SuperUser. - SuperUser = 2; - // Invalid channel name. - ChannelName = 3; - // Text message too long. - TextTooLong = 4; - // The flux capacitor was spelled wrong. - H9K = 5; - // Operation not permitted in temporary channel. - TemporaryChannel = 6; - // Operation requires certificate. - MissingCertificate = 7; - // Invalid username. - UserName = 8; - // Channel is full. - ChannelFull = 9; - NestingLimit = 10; - } - // The denied permission when type is Permission. - optional uint32 permission = 1; - // channel_id for the channel where the permission was denied when type is - // Permission. - optional uint32 channel_id = 2; - // The user who was denied permissions, identified by session. - optional uint32 session = 3; - // Textual reason for the denial. - optional string reason = 4; - // Type of the denial. - optional DenyType type = 5; - // The name that is invalid when type is UserName. - optional string name = 6; -} - -message ACL { - message ChanGroup { - // Name of the channel group, UTF-8 encoded. - required string name = 1; - // True if the group has been inherited from the parent (Read only). - optional bool inherited = 2 [default = true]; - // True if the group members are inherited. - optional bool inherit = 3 [default = true]; - // True if the group can be inherited by sub channels. - optional bool inheritable = 4 [default = true]; - // Users explicitly included in this group, identified by user_id. - repeated uint32 add = 5; - // Users explicitly removed from this group in this channel if the group - // has been inherited, identified by user_id. - repeated uint32 remove = 6; - // Users inherited, identified by user_id. - repeated uint32 inherited_members = 7; - } - message ChanACL { - // True if this ACL applies to the current channel. - optional bool apply_here = 1 [default = true]; - // True if this ACL applies to the sub channels. - optional bool apply_subs = 2 [default = true]; - // True if the ACL has been inherited from the parent. - optional bool inherited = 3 [default = true]; - // ID of the user that is affected by this ACL. - optional uint32 user_id = 4; - // ID of the group that is affected by this ACL. - optional string group = 5; - // Bit flag field of the permissions granted by this ACL. - optional uint32 grant = 6; - // Bit flag field of the permissions denied by this ACL. - optional uint32 deny = 7; - } - // Channel ID of the channel this message affects. - required uint32 channel_id = 1; - // True if the channel inherits its parent's ACLs. - optional bool inherit_acls = 2 [default = true]; - // User group specifications. - repeated ChanGroup groups = 3; - // ACL specifications. - repeated ChanACL acls = 4; - // True if the message is a query for ACLs instead of setting them. - optional bool query = 5 [default = false]; -} - -// Client may use this message to refresh its registered user information. The -// client should fill the IDs or Names of the users it wants to refresh. The -// server fills the missing parts and sends the message back. -message QueryUsers { - // user_ids. - repeated uint32 ids = 1; - // User names in the same order as ids. - repeated string names = 2; -} - -// Used to initialize and resync the UDP encryption. Either side may request a -// resync by sending the message without any values filled. The resync is -// performed by sending the message with only the client or server nonce -// filled. -message CryptSetup { - // Encryption key. - optional bytes key = 1; - // Client nonce. - optional bytes client_nonce = 2; - // Server nonce. - optional bytes server_nonce = 3; -} - -message ContextActionModify { - enum Context { - // Action is applicable to the server. - Server = 0x01; - // Action can target a Channel. - Channel = 0x02; - // Action can target a User. - User = 0x04; - } - enum Operation { - Add = 0; - Remove = 1; - } - // The action name. - required string action = 1; - // The display name of the action. - optional string text = 2; - // Context bit flags defining where the action should be displayed. - optional uint32 context = 3; - optional Operation operation = 4; -} - -// Sent by the client when it wants to initiate a Context action. -message ContextAction { - // The target User for the action, identified by session. - optional uint32 session = 1; - // The target Channel for the action, identified by channel_id. - optional uint32 channel_id = 2; - // The action that should be executed. - required string action = 3; -} - -// Lists the registered users. -message UserList { - message User { - // Registered user ID. - required uint32 user_id = 1; - // Registered user name. - optional string name = 2; - optional string last_seen = 3; - optional uint32 last_channel = 4; - } - // A list of registered users. - repeated User users = 1; -} - -// Sent by the client when it wants to register or clear whisper targets. -// -// Note: The first available target ID is 1 as 0 is reserved for normal -// talking. Maximum target ID is 30. -message VoiceTarget { - message Target { - // Users that are included as targets. - repeated uint32 session = 1; - // Channels that are included as targets. - optional uint32 channel_id = 2; - // TODO ?? - optional string group = 3; - // True if the voice should follow links from the specified channel. - optional bool links = 4 [default = false]; - // True if the voice should also be sent to children of the specific - // channel. - optional bool children = 5 [default = false]; - } - // Voice target ID. - optional uint32 id = 1; - // The receivers that this voice target includes. - repeated Target targets = 2; -} - -// Sent by the client when it wants permissions for a certain channel. Sent by -// the server when it replies to the query or wants the user to resync all -// channel permissions. -message PermissionQuery { - // channel_id of the channel for which the permissions are queried. - optional uint32 channel_id = 1; - // Channel permissions. - optional uint32 permissions = 2; - // True if the client should drop its current permission information for all - // channels. - optional bool flush = 3 [default = false]; -} - -// Sent by the server to notify the users of the version of the CELT codec they -// should use. This may change during the connection when new users join. -message CodecVersion { - // The version of the CELT Alpha codec. - required int32 alpha = 1; - // The version of the CELT Beta codec. - required int32 beta = 2; - // True if the user should prefer Alpha over Beta. - required bool prefer_alpha = 3 [default = true]; - optional bool opus = 4 [default = false]; -} - -// Used to communicate user stats between the server and clients. -message UserStats { - message Stats { - // The amount of good packets received. - optional uint32 good = 1; - // The amount of late packets received. - optional uint32 late = 2; - // The amount of packets never received. - optional uint32 lost = 3; - // The amount of nonce resyncs. - optional uint32 resync = 4; - } - - // User whose stats these are. - optional uint32 session = 1; - // True if the message contains only mutable stats (packets, ping). - optional bool stats_only = 2 [default = false]; - // Full user certificate chain of the user certificate in DER format. - repeated bytes certificates = 3; - // Packet statistics for packets received from the client. - optional Stats from_client = 4; - // Packet statistics for packets sent by the server. - optional Stats from_server = 5; - - // Amount of UDP packets sent. - optional uint32 udp_packets = 6; - // Amount of TCP packets sent. - optional uint32 tcp_packets = 7; - // UDP ping average. - optional float udp_ping_avg = 8; - // UDP ping variance. - optional float udp_ping_var = 9; - // TCP ping average. - optional float tcp_ping_avg = 10; - // TCP ping variance. - optional float tcp_ping_var = 11; - - // Client version. - optional Version version = 12; - // A list of CELT bitstream version constants supported by the client of this - // user. - repeated int32 celt_versions = 13; - // Client IP address. - optional bytes address = 14; - // Bandwith used by this client. - optional uint32 bandwidth = 15; - // Connection duration. - optional uint32 onlinesecs = 16; - // Duration since last activity. - optional uint32 idlesecs = 17; - // True if the user has a strong certificate. - optional bool strong_certificate = 18 [default = false]; - optional bool opus = 19 [default = false]; -} - -// Used by the client to request binary data from the server. By default large -// comments or textures are not sent within standard messages but instead the -// hash is. If the client does not recognize the hash it may request the -// resource when it needs it. The client does so by sending a RequestBlob -// message with the correct fields filled with the user sessions or channel_ids -// it wants to receive. The server replies to this by sending a new -// UserState/ChannelState message with the resources filled even if they would -// normally be transmitted as hashes. -message RequestBlob { - // sessions of the requested UserState textures. - repeated uint32 session_texture = 1; - // sessions of the requested UserState comments. - repeated uint32 session_comment = 2; - // channel_ids of the requested ChannelState descriptions. - repeated uint32 channel_description = 3; -} - -// Sent by the server when it informs the clients on server configuration -// details. -message ServerConfig { - // The maximum bandwidth the clients should use. - optional uint32 max_bandwidth = 1; - // Server welcome text. - optional string welcome_text = 2; - // True if the server allows HTML. - optional bool allow_html = 3; - // Maximum text message length. - optional uint32 message_length = 4; - // Maximum image message length. - optional uint32 image_message_length = 5; -} - -// Sent by the server to inform the clients of suggested client configuration -// specified by the server administrator. -message SuggestConfig { - // Suggested client version. - optional uint32 version = 1; - // True if the administrator suggests positional audio to be used on this - // server. - optional bool positional = 2; - // True if the administrator suggests push to talk to be used on this server. - optional bool push_to_talk = 3; -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/generate.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/generate.go deleted file mode 100644 index 88da886..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/MumbleProto/generate.go +++ /dev/null @@ -1,2 +0,0 @@ -//go:generate protoc --go_out=. Mumble.proto -package MumbleProto diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/acl.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/acl.go deleted file mode 100644 index 993be1c..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/acl.go +++ /dev/null @@ -1,58 +0,0 @@ -package gumble - -// ACL contains a list of ACLGroups and ACLRules linked to a channel. -type ACL struct { - // The channel to which the ACL belongs. - Channel *Channel - // The ACL's groups. - Groups []*ACLGroup - // The ACL's rules. - Rules []*ACLRule - // Does the ACL inherits the parent channel's ACL?s - Inherits bool -} - -// ACLUser is a registered user who is part of or can be part of an ACL group -// or rule. -type ACLUser struct { - // The user ID of the user. - UserID uint32 - // The name of the user. - Name string -} - -// ACLGroup is a named group of registered users which can be used in an -// ACLRule. -type ACLGroup struct { - // The ACL group name. - Name string - // Is the group inherited from the parent channel's ACL? - Inherited bool - // Are group members are inherited from the parent channel's ACL? - InheritUsers bool - // Can the group be inherited by child channels? - Inheritable bool - usersAdd, usersRemove, usersInherited map[uint32]*ACLUser -} - -// ACLRule is a set of granted and denied permissions given to an ACLUser or -// ACLGroup. -type ACLRule struct { - // Does the rule apply to the channel in which the rule is defined? - AppliesCurrent bool - // Does the rule apply to the children of the channel in which the rule is - // defined? - AppliesChildren bool - // Is the rule inherited from the parent channel's ACL? - Inherited bool - - // The permissions granted by the rule. - Granted Permission - // The permissions denied by the rule. - Denied Permission - - // The ACL user the rule applies to. Can be nil. - User *ACLUser - // The ACL group the rule applies to. Can be nil. - Group *ACLGroup -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audio.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audio.go deleted file mode 100644 index d8f4591..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audio.go +++ /dev/null @@ -1,85 +0,0 @@ -package gumble - -import ( - "math" - "time" -) - -const ( - // AudioSampleRate is the audio sample rate (in hertz) for incoming and - // outgoing audio. - AudioSampleRate = 48000 - - // AudioDefaultInterval is the default interval that audio packets are sent - // at. - AudioDefaultInterval = 10 * time.Millisecond - - // AudioDefaultFrameSize is the number of audio frames that should be sent in - // a 10ms window. - AudioDefaultFrameSize = AudioSampleRate / 100 - - // AudioMaximumFrameSize is the maximum audio frame size from another user - // that will be processed. - AudioMaximumFrameSize = AudioDefaultFrameSize * 10 - - // AudioDefaultDataBytes is the default number of bytes that an audio frame - // can use. - AudioDefaultDataBytes = 40 -) - -// AudioListener is the interface that must be implemented by types wishing to -// receive incoming audio data from the server. -type AudioListener interface { - OnAudioPacket(e *AudioPacketEvent) -} - -// AudioPacketEvent is event that is passed to AudioListener.OnAudioPacket. -type AudioPacketEvent struct { - Client *Client - AudioPacket AudioPacket -} - -// AudioBuffer is a slice of PCM samples. -type AudioBuffer []int16 - -// PositionalAudioBuffer is an AudioBuffer that has a position in 3D space -// associated with it. -type PositionalAudioBuffer struct { - X, Y, Z float32 - AudioBuffer -} - -func (pab PositionalAudioBuffer) writeMessage(client *Client) error { - return writeAudioTo(client, pab.AudioBuffer, &pab) -} - -// AudioPacket contains incoming audio data and information. -type AudioPacket struct { - Sender *User - Target int - Sequence int - PositionalAudioBuffer -} - -func (ab AudioBuffer) writeMessage(client *Client) error { - return writeAudioTo(client, ab, nil) -} - -func writeAudioTo(client *Client, ab AudioBuffer, pab *PositionalAudioBuffer) error { - dataBytes := client.Config.GetAudioDataBytes() - opus, err := client.AudioEncoder.Encode(ab, len(ab), dataBytes) - if err != nil { - return err - } - - var targetID int - if target := client.VoiceTarget; target != nil { - targetID = int(target.ID) - } - seq := client.audioSequence - client.audioSequence = (client.audioSequence + 1) % math.MaxInt32 - if pab == nil { - return client.Conn.WriteAudio(4, targetID, seq, opus, nil, nil, nil) - } - return client.Conn.WriteAudio(4, targetID, seq, opus, &pab.X, &pab.Y, &pab.Z) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audiomultiplexer.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audiomultiplexer.go deleted file mode 100644 index 23983a4..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/audiomultiplexer.go +++ /dev/null @@ -1,47 +0,0 @@ -package gumble - -type audioEventMultiplexerItem struct { - mux *audioEventMultiplexer - prev, next *audioEventMultiplexerItem - listener AudioListener -} - -func (emi *audioEventMultiplexerItem) Detach() { - if emi.prev == nil { - emi.mux.head = emi.next - } else { - emi.prev.next = emi.next - } - if emi.next == nil { - emi.mux.tail = emi.prev - } else { - emi.next.prev = emi.prev - } -} - -type audioEventMultiplexer struct { - head, tail *audioEventMultiplexerItem -} - -func (aem *audioEventMultiplexer) Attach(listener AudioListener) Detacher { - item := &audioEventMultiplexerItem{ - mux: aem, - prev: aem.tail, - listener: listener, - } - if aem.head == nil { - aem.head = item - } - if aem.tail == nil { - aem.tail = item - } else { - aem.tail.next = item - } - return item -} - -func (aem audioEventMultiplexer) OnAudioPacket(event *AudioPacketEvent) { - for item := aem.head; item != nil; item = item.next { - item.listener.OnAudioPacket(event) - } -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/bans.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/bans.go deleted file mode 100644 index 833100e..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/bans.go +++ /dev/null @@ -1,102 +0,0 @@ -package gumble - -import ( - "net" - "time" - - "github.com/golang/protobuf/proto" - "github.com/layeh/gumble/gumble/MumbleProto" -) - -// BanList is a list of server ban entries. -// -// Whenever a ban is changed, it does not come into effect until the ban list -// is sent back to the server. -type BanList []*Ban - -// Add creates a new ban list entry with the given parameters. -func (bl *BanList) Add(address net.IP, mask net.IPMask, reason string, duration time.Duration) *Ban { - ban := &Ban{ - Address: address, - Mask: mask, - Reason: reason, - Duration: duration, - } - *bl = append(*bl, ban) - return ban -} - -// Ban represents an entry in the server ban list. -// -// This type should not be initialized manually. Instead, create new ban -// entries using BanList.Add(). -type Ban struct { - // The banned IP address. - Address net.IP - // The IP mask that the ban applies to. - Mask net.IPMask - // The name of the banned user. - Name string - // The certificate hash of the banned user. - Hash string - // The reason for the ban. - Reason string - // The start time from which the ban applies. - Start time.Time - // How long the ban is for. - Duration time.Duration - - unban bool -} - -// SetAddress sets the banned IP address. -func (b *Ban) SetAddress(address net.IP) { - b.Address = address -} - -// SetMask sets the IP mask that the ban applies to. -func (b *Ban) SetMask(mask net.IPMask) { - b.Mask = mask -} - -// SetReason changes the reason for the ban. -func (b *Ban) SetReason(reason string) { - b.Reason = reason -} - -// SetDuration changes the duration of the ban. -func (b *Ban) SetDuration(duration time.Duration) { - b.Duration = duration -} - -// Unban will unban the user from the server. -func (b *Ban) Unban() { - b.unban = true -} - -// Ban will ban the user from the server. This is only useful if Unban() was -// called on the ban entry. -func (b *Ban) Ban() { - b.unban = false -} - -func (bl BanList) writeMessage(client *Client) error { - packet := MumbleProto.BanList{ - Query: proto.Bool(false), - } - - for _, ban := range bl { - if !ban.unban { - maskSize, _ := ban.Mask.Size() - packet.Bans = append(packet.Bans, &MumbleProto.BanList_BanEntry{ - Address: ban.Address, - Mask: proto.Uint32(uint32(maskSize)), - Reason: &ban.Reason, - Duration: proto.Uint32(uint32(ban.Duration / time.Second)), - }) - } - } - - proto := protoMessage{&packet} - return proto.writeMessage(client) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channel.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channel.go deleted file mode 100644 index 606b4ef..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channel.go +++ /dev/null @@ -1,147 +0,0 @@ -package gumble - -import ( - "github.com/golang/protobuf/proto" - "github.com/layeh/gumble/gumble/MumbleProto" -) - -// Channel represents a channel in the server's channel tree. -type Channel struct { - // The channel's unique ID. - ID uint32 - // The channel's name. - Name string - // The channel's parent. Contains nil if the channel is the root channel. - Parent *Channel - // The channels directly underneath the channel. - Children Channels - // The users currently in the channel. - Users Users - // The channel's description. Contains the empty string if the channel does - // not have a description, or if it needs to be requested. - Description string - // The channel's description hash. Contains nil if Channel.Description has - // been populated. - DescriptionHash []byte - // The position at which the channel should be displayed in an ordered list. - Position int32 - // Is the channel temporary? - Temporary bool - - client *Client -} - -// IsRoot returns true if the channel is the server's root channel. -func (c *Channel) IsRoot() bool { - return c.ID == 0 -} - -// Add will add a sub-channel to the given channel. -func (c *Channel) Add(name string, temporary bool) { - packet := MumbleProto.ChannelState{ - Parent: &c.ID, - Name: &name, - Temporary: &temporary, - } - c.client.Send(protoMessage{&packet}) -} - -// Remove will remove the given channel and all sub-channels from the server's -// channel tree. -func (c *Channel) Remove() { - packet := MumbleProto.ChannelRemove{ - ChannelId: &c.ID, - } - c.client.Send(protoMessage{&packet}) -} - -// SetName will set the name of the channel. This will have no effect if the -// channel is the server's root channel. -func (c *Channel) SetName(name string) { - packet := MumbleProto.ChannelState{ - ChannelId: &c.ID, - Name: &name, - } - c.client.Send(protoMessage{&packet}) -} - -// SetDescription will set the description of the channel. -func (c *Channel) SetDescription(description string) { - packet := MumbleProto.ChannelState{ - ChannelId: &c.ID, - Description: &description, - } - c.client.Send(protoMessage{&packet}) -} - -// Find returns a channel whose path (by channel name) from the current channel -// is equal to the arguments passed. -// -// For example, given the following server channel tree: -// Root -// Child 1 -// Child 2 -// Child 2.1 -// Child 2.2 -// Child 2.2.1 -// Child 3 -// To get the "Child 2.2.1" channel: -// root.Find("Child 2", "Child 2.2", "Child 2.2.1") -func (c *Channel) Find(names ...string) *Channel { - if len(names) == 0 { - return c - } - for _, child := range c.Children { - if child.Name == names[0] { - return child.Find(names[1:]...) - } - } - return nil -} - -// Request requests channel information that has not yet been sent to the -// client. The supported request types are: RequestACL, RequestDescription, -// RequestPermission. -// -// Note: the server will not reply to a RequestPermission request if the client -// has up-to-date permission information. -func (c *Channel) Request(request Request) { - if (request & RequestDescription) != 0 { - packet := MumbleProto.RequestBlob{ - ChannelDescription: []uint32{c.ID}, - } - c.client.Send(protoMessage{&packet}) - } - if (request & RequestACL) != 0 { - packet := MumbleProto.ACL{ - ChannelId: &c.ID, - Query: proto.Bool(true), - } - c.client.Send(protoMessage{&packet}) - } - if (request & RequestPermission) != 0 { - packet := MumbleProto.PermissionQuery{ - ChannelId: &c.ID, - } - c.client.Send(protoMessage{&packet}) - } -} - -// Send will send a text message to the channel. -func (c *Channel) Send(message string, recursive bool) { - textMessage := TextMessage{ - Message: message, - } - if recursive { - textMessage.Trees = []*Channel{c} - } else { - textMessage.Channels = []*Channel{c} - } - c.client.Send(&textMessage) -} - -// Permission returns the permissions the user has in the channel, or nil if -// the permissions are unknown. -func (c *Channel) Permission() *Permission { - return c.client.permissions[c.ID] -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channels.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channels.go deleted file mode 100644 index 9963651..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/channels.go +++ /dev/null @@ -1,32 +0,0 @@ -package gumble - -// Channels is a map of server channels. -// -// When accessed through Client.Channels, it contains all channels on the -// server. When accessed through a specific channel -// (e.g. client.Channels[0].Children), it contains only the children of the -// channel. -type Channels map[uint32]*Channel - -// create adds a new channel with the given id to the collection. If a channel -// with the given id already exists, it is overwritten. -func (c Channels) create(id uint32) *Channel { - channel := &Channel{ - ID: id, - Children: Channels{}, - Users: Users{}, - } - c[id] = channel - return channel -} - -// Find returns a channel whose path (by channel name) from the server root -// channel is equal to the arguments passed. If the root channel does not -// exist, nil is returned. -func (c Channels) Find(names ...string) *Channel { - root := c[0] - if names == nil || root == nil { - return root - } - return root.Find(names...) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/client.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/client.go deleted file mode 100644 index c6d4118..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/client.go +++ /dev/null @@ -1,230 +0,0 @@ -package gumble - -import ( - "crypto/tls" - "errors" - "runtime" - "time" - - "github.com/golang/protobuf/proto" - "github.com/layeh/gopus" - "github.com/layeh/gumble/gumble/MumbleProto" -) - -// State is the current state of the client's connection to the server. -type State int - -const ( - // StateDisconnected means the client is not connected to a server. - StateDisconnected State = iota - - // StateConnected means the client is connected to a server, but has yet to - // receive the initial server state. - StateConnected - - // StateSynced means the client is connected to a server and has been sent - // the server state. - StateSynced -) - -// ClientVersion is the protocol version that Client implements. -const ClientVersion = 1<<16 | 2<<8 | 4 - -// Client is the type used to create a connection to a server. -type Client struct { - // The current state of the client. - State State - // The User associated with the client (nil if the client has not yet been - // synced). - Self *User - // The client's configuration. - Config *Config - // The underlying Conn to the server. - *Conn - - listeners eventMultiplexer - audioListeners audioEventMultiplexer - - // The users currently connected to the server. - Users Users - // The connected server's channels. - Channels Channels - permissions map[uint32]*Permission - tmpACL *ACL - - pingStats pingStats - - // A collection containing the server's context actions. - ContextActions ContextActions - - // The audio encoder used when sending audio to the server. - AudioEncoder *gopus.Encoder - audioSequence int - // To whom transmitted audio will be sent. The VoiceTarget must have already - // been sent to the server for targeting to work correctly. Setting to nil - // will disable voice targeting (i.e. switch back to regular speaking). - VoiceTarget *VoiceTarget - - end chan bool - disconnectEvent DisconnectEvent -} - -// NewClient creates a new gumble client. Returns nil if config is nil. -func NewClient(config *Config) *Client { - if config == nil { - return nil - } - client := &Client{ - Config: config, - end: make(chan bool), - } - return client -} - -// Connect connects to the server. -func (c *Client) Connect() error { - if c.State != StateDisconnected { - return errors.New("client is already connected") - } - encoder, err := gopus.NewEncoder(AudioSampleRate, 1, gopus.Voip) - if err != nil { - return err - } - encoder.SetBitrate(gopus.BitrateMaximum) - c.audioSequence = 0 - c.VoiceTarget = nil - - tlsConn, err := tls.DialWithDialer(&c.Config.Dialer, "tcp", c.Config.Address, &c.Config.TLSConfig) - if err != nil { - return err - } - if verify := c.Config.TLSVerify; verify != nil { - state := tlsConn.ConnectionState() - if err := verify(&state); err != nil { - tlsConn.Close() - return err - } - } - c.Conn = NewConn(tlsConn) - - c.AudioEncoder = encoder - c.Users = Users{} - c.Channels = Channels{} - c.permissions = make(map[uint32]*Permission) - c.ContextActions = ContextActions{} - c.State = StateConnected - - // Channels and goroutines - go c.readRoutine() - go c.pingRoutine() - - // Initial packets - versionPacket := MumbleProto.Version{ - Version: proto.Uint32(ClientVersion), - Release: proto.String("gumble"), - Os: proto.String(runtime.GOOS), - OsVersion: proto.String(runtime.GOARCH), - } - authenticationPacket := MumbleProto.Authenticate{ - Username: &c.Config.Username, - Password: &c.Config.Password, - Opus: proto.Bool(true), - Tokens: c.Config.Tokens, - } - c.Send(protoMessage{&versionPacket}) - c.Send(protoMessage{&authenticationPacket}) - return nil -} - -// Attach adds an event listener that will receive incoming connection events. -func (c *Client) Attach(listener EventListener) Detacher { - return c.listeners.Attach(listener) -} - -// AttachAudio adds an audio event listener that will receive incoming audio -// packets. -func (c *Client) AttachAudio(listener AudioListener) Detacher { - return c.audioListeners.Attach(listener) -} - -// pingRoutine sends ping packets to the server at regular intervals. -func (c *Client) pingRoutine() { - ticker := time.NewTicker(time.Second * 10) - defer ticker.Stop() - - pingPacket := MumbleProto.Ping{ - Timestamp: proto.Uint64(0), - TcpPackets: &c.pingStats.TCPPackets, - } - pingProto := protoMessage{&pingPacket} - - for { - select { - case <-c.end: - return - case time := <-ticker.C: - *pingPacket.Timestamp = uint64(time.Unix()) - c.Send(pingProto) - } - } -} - -// readRoutine reads protocol buffer messages from the server. -func (c *Client) readRoutine() { - c.disconnectEvent = DisconnectEvent{ - Client: c, - Type: DisconnectError, - } - - for { - pType, data, err := c.Conn.ReadPacket() - if err != nil { - break - } - if handle, ok := handlers[pType]; ok { - handle(c, data) - } - } - - c.end <- true - c.Conn = nil - c.State = StateDisconnected - c.tmpACL = nil - c.pingStats = pingStats{} - c.listeners.OnDisconnect(&c.disconnectEvent) -} - -// Request requests that specific server information be sent to the client. The -// supported request types are: RequestUserList, and RequestBanList. -func (c *Client) Request(request Request) { - if (request & RequestUserList) != 0 { - packet := MumbleProto.UserList{} - proto := protoMessage{&packet} - c.Send(proto) - } - if (request & RequestBanList) != 0 { - packet := MumbleProto.BanList{ - Query: proto.Bool(true), - } - proto := protoMessage{&packet} - c.Send(proto) - } -} - -// Disconnect disconnects the client from the server. -func (c *Client) Disconnect() error { - if c.State == StateDisconnected { - return errors.New("client is already disconnected") - } - c.disconnectEvent.Type = DisconnectUser - c.Conn.Close() - return nil -} - -// Send will send a message to the server. -func (c *Client) Send(message Message) error { - if err := message.writeMessage(c); err != nil { - return err - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/config.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/config.go deleted file mode 100644 index 0bb454b..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/config.go +++ /dev/null @@ -1,72 +0,0 @@ -package gumble - -import ( - "crypto/tls" - "net" - "time" - - "github.com/layeh/gumble/gumble/MumbleProto" -) - -// Config holds the configuration data used by Client. -type Config struct { - // User name used when authenticating with the server. - Username string - // Password used when authenticating with the server. A password is not - // usually required to connect to a server. - Password string - // Server address, including port (e.g. localhost:64738). - Address string - Tokens AccessTokens - - // AudioInterval is the interval at which audio packets are sent. Valid - // values are 10ms, 20ms, 40ms, and 60ms. - AudioInterval time.Duration - - // AudioDataBytes is the number of bytes that an audio frame can use. - AudioDataBytes int - - TLSConfig tls.Config - // If non-nil, this function will be called after the connection to the - // server has been made. If it returns nil, the connection will stay alive, - // otherwise, it will be closed and Client.Connect will return the returned - // error. - TLSVerify func(state *tls.ConnectionState) error - Dialer net.Dialer -} - -// GetAudioInterval returns c.AudioInterval if it is valid, else returns -// AudioDefaultInterval. -func (c *Config) GetAudioInterval() time.Duration { - if c.AudioInterval <= 0 { - return AudioDefaultInterval - } - return c.AudioInterval -} - -// GetAudioDataBytes returns c.AudioDataBytes if it is valid, else returns -// AudioDefaultDataBytes. -func (c *Config) GetAudioDataBytes() int { - if c.AudioDataBytes <= 0 { - return AudioDefaultDataBytes - } - return c.AudioDataBytes -} - -// GetAudioFrameSize returns the appropriate audio frame size, based off of the -// audio interval. -func (c *Config) GetAudioFrameSize() int { - return int(c.GetAudioInterval()/AudioDefaultInterval) * AudioDefaultFrameSize -} - -// AccessTokens are additional passwords that can be provided to the server to -// gain access to restricted channels. -type AccessTokens []string - -func (at AccessTokens) writeMessage(client *Client) error { - packet := MumbleProto.Authenticate{ - Tokens: at, - } - proto := protoMessage{&packet} - return proto.writeMessage(client) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/conn.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/conn.go deleted file mode 100644 index 9b4a7ee..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/conn.go +++ /dev/null @@ -1,197 +0,0 @@ -package gumble - -import ( - "bytes" - "encoding/binary" - "errors" - "io" - "net" - "sync" - "time" - - "github.com/golang/protobuf/proto" - "github.com/layeh/gumble/gumble/MumbleProto" - "github.com/layeh/gumble/gumble/varint" -) - -// Conn represents a connection to a Mumble client/server. -type Conn struct { - sync.Mutex - net.Conn - - MaximumPacketBytes int - Timeout time.Duration - - buffer []byte -} - -// NewConn creates a new Conn with the given net.Conn. -func NewConn(conn net.Conn) *Conn { - return &Conn{ - Conn: conn, - Timeout: time.Second * 20, - MaximumPacketBytes: 1024 * 1024 * 10, - } -} - -// ReadPacket reads a packet from the server. Returns the packet type, the -// packet data, and nil on success. -// -// This function should only be called by a single go routine. -func (c *Conn) ReadPacket() (uint16, []byte, error) { - var pType uint16 - var pLength uint32 - - c.Conn.SetReadDeadline(time.Now().Add(c.Timeout)) - if err := binary.Read(c.Conn, binary.BigEndian, &pType); err != nil { - return 0, nil, err - } - if err := binary.Read(c.Conn, binary.BigEndian, &pLength); err != nil { - return 0, nil, err - } - pLengthInt := int(pLength) - if pLengthInt > c.MaximumPacketBytes { - return 0, nil, errors.New("packet larger than maximum allowed size") - } - if pLengthInt > cap(c.buffer) { - c.buffer = make([]byte, pLengthInt) - } - if _, err := io.ReadFull(c.Conn, c.buffer[:pLengthInt]); err != nil { - return 0, nil, err - } - return pType, c.buffer[:pLengthInt], nil -} - -// WriteAudio writes an audio packet to the connection. -func (c *Conn) WriteAudio(format, target, sequence int, data []byte, X, Y, Z *float32) error { - var header bytes.Buffer - formatTarget := byte(format)<<5 | byte(target) - if err := header.WriteByte(formatTarget); err != nil { - return err - } - if _, err := varint.WriteTo(&header, int64(sequence)); err != nil { - return err - } - if _, err := varint.WriteTo(&header, int64(len(data))); err != nil { - return err - } - - var positionalLength int - if X != nil { - positionalLength = 3 * 4 - } - - c.Lock() - defer c.Unlock() - - if err := c.writeHeader(1, uint32(header.Len()+len(data)+positionalLength)); err != nil { - return err - } - if _, err := header.WriteTo(c.Conn); err != nil { - return err - } - if _, err := c.Conn.Write(data); err != nil { - return err - } - - if positionalLength > 0 { - if err := binary.Write(c.Conn, binary.LittleEndian, *X); err != nil { - return err - } - if err := binary.Write(c.Conn, binary.LittleEndian, *Y); err != nil { - return err - } - if err := binary.Write(c.Conn, binary.LittleEndian, *Z); err != nil { - return err - } - } - - return nil -} - -// WritePacket writes a data packet of the given type to the connection. -func (c *Conn) WritePacket(ptype uint16, data []byte) error { - c.Lock() - defer c.Unlock() - if err := c.writeHeader(uint16(ptype), uint32(len(data))); err != nil { - return err - } - if _, err := c.Conn.Write(data); err != nil { - return err - } - return nil -} - -func (c *Conn) writeHeader(pType uint16, pLength uint32) error { - if err := binary.Write(c.Conn, binary.BigEndian, pType); err != nil { - return err - } - if err := binary.Write(c.Conn, binary.BigEndian, pLength); err != nil { - return err - } - return nil -} - -// WriteProto writes a protocol buffer message to the connection. -func (c *Conn) WriteProto(message proto.Message) error { - var protoType uint16 - switch message.(type) { - case *MumbleProto.Version: - protoType = 0 - case *MumbleProto.Authenticate: - protoType = 2 - case *MumbleProto.Ping: - protoType = 3 - case *MumbleProto.Reject: - protoType = 4 - case *MumbleProto.ServerSync: - protoType = 5 - case *MumbleProto.ChannelRemove: - protoType = 6 - case *MumbleProto.ChannelState: - protoType = 7 - case *MumbleProto.UserRemove: - protoType = 8 - case *MumbleProto.UserState: - protoType = 9 - case *MumbleProto.BanList: - protoType = 10 - case *MumbleProto.TextMessage: - protoType = 11 - case *MumbleProto.PermissionDenied: - protoType = 12 - case *MumbleProto.ACL: - protoType = 13 - case *MumbleProto.QueryUsers: - protoType = 14 - case *MumbleProto.CryptSetup: - protoType = 15 - case *MumbleProto.ContextActionModify: - protoType = 16 - case *MumbleProto.ContextAction: - protoType = 17 - case *MumbleProto.UserList: - protoType = 18 - case *MumbleProto.VoiceTarget: - protoType = 19 - case *MumbleProto.PermissionQuery: - protoType = 20 - case *MumbleProto.CodecVersion: - protoType = 21 - case *MumbleProto.UserStats: - protoType = 22 - case *MumbleProto.RequestBlob: - protoType = 23 - case *MumbleProto.ServerConfig: - protoType = 24 - case *MumbleProto.SuggestConfig: - protoType = 25 - default: - return errors.New("unknown message type") - } - data, err := proto.Marshal(message) - if err != nil { - return err - } - return c.WritePacket(protoType, data) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextaction.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextaction.go deleted file mode 100644 index 7706e16..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextaction.go +++ /dev/null @@ -1,57 +0,0 @@ -package gumble - -import ( - "github.com/layeh/gumble/gumble/MumbleProto" -) - -// ContextActionType is a bitmask of contexts where a ContextAction can be -// triggered. -type ContextActionType int - -// Supported ContextAction contexts. -const ( - ContextActionServer ContextActionType = ContextActionType(MumbleProto.ContextActionModify_Server) - ContextActionChannel ContextActionType = ContextActionType(MumbleProto.ContextActionModify_Channel) - ContextActionUser ContextActionType = ContextActionType(MumbleProto.ContextActionModify_User) -) - -// ContextAction is an triggerable item that has been added by a server-side -// plugin. -type ContextAction struct { - client *Client - - // The context action type. - Type ContextActionType - // The name of the context action. - Name string - // The user-friendly description of the context action. - Label string -} - -// Trigger will trigger the context action in the context of the server. -func (ca *ContextAction) Trigger() { - packet := MumbleProto.ContextAction{ - Action: &ca.Name, - } - ca.client.Send(protoMessage{&packet}) -} - -// TriggerUser will trigger the context action in the context of the given -// user. -func (ca *ContextAction) TriggerUser(user *User) { - packet := MumbleProto.ContextAction{ - Session: &user.Session, - Action: &ca.Name, - } - ca.client.Send(protoMessage{&packet}) -} - -// TriggerChannel will trigger the context action in the context of the given -// channel. -func (ca *ContextAction) TriggerChannel(channel *Channel) { - packet := MumbleProto.ContextAction{ - ChannelId: &channel.ID, - Action: &ca.Name, - } - ca.client.Send(protoMessage{&packet}) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextactions.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextactions.go deleted file mode 100644 index c1defee..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/contextactions.go +++ /dev/null @@ -1,12 +0,0 @@ -package gumble - -// ContextActions is a map of ContextActions. -type ContextActions map[string]*ContextAction - -func (ca ContextActions) create(action string) *ContextAction { - contextAction := &ContextAction{ - Name: action, - } - ca[action] = contextAction - return contextAction -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/doc.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/doc.go deleted file mode 100644 index fae0daa..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/doc.go +++ /dev/null @@ -1,39 +0,0 @@ -// Package gumble is a client for the Mumble voice chat software. -// -// Getting started -// -//1. Create a new Config to hold your connection settings: -// -// config := gumble.Config{ -// Username: "gumble-test", -// Address: "example.com:64738", -// } -// -//2. Create a new Client: -// -// client := gumble.NewClient(&config) -// -//3. Implement EventListener (or use gumbleutil.Listener) and attach it to the client: -// -// client.Attach(gumbleutil.Listener{ -// TextMessage: func(e *gumble.TextMessageEvent) { -// fmt.Printf("Received text message: %s\n", e.Message) -// }, -// }) -// -//4. Connect to the server: -// -// if err := client.Connect(); err != nil { -// panic(err) -// } -// -// Audio codecs -// -// Currently, only the Opus codec (https://www.opus-codec.org/) is supported -// for transmitting and receiving audio. -// -// To ensure that gumble clients can always transmit and receive audio to and -// from your server, add the following line to your murmur configuration file: -// -// opusthreshold=0 -package gumble diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/event.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/event.go deleted file mode 100644 index d279582..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/event.go +++ /dev/null @@ -1,202 +0,0 @@ -package gumble - -import ( - "github.com/layeh/gumble/gumble/MumbleProto" -) - -// EventListener is the interface that must be implemented by a type if it -// wishes to be notified of Client events. -type EventListener interface { - OnConnect(e *ConnectEvent) - OnDisconnect(e *DisconnectEvent) - OnTextMessage(e *TextMessageEvent) - OnUserChange(e *UserChangeEvent) - OnChannelChange(e *ChannelChangeEvent) - OnPermissionDenied(e *PermissionDeniedEvent) - OnUserList(e *UserListEvent) - OnACL(e *ACLEvent) - OnBanList(e *BanListEvent) - OnContextActionChange(e *ContextActionChangeEvent) -} - -// ConnectEvent is the event that is passed to EventListener.OnConnect. -type ConnectEvent struct { - Client *Client - WelcomeMessage string - MaximumBitrate int -} - -// DisconnectType specifies why a Client disconnected from a server. -type DisconnectType int - -// Client disconnect reasons. -const ( - DisconnectError DisconnectType = 0xFE - iota - DisconnectKicked - DisconnectBanned - DisconnectUser - - DisconnectOther DisconnectType = DisconnectType(MumbleProto.Reject_None) - DisconnectVersion DisconnectType = DisconnectType(MumbleProto.Reject_WrongVersion) - DisconnectUserName DisconnectType = DisconnectType(MumbleProto.Reject_InvalidUsername) - DisconnectUserCredentials DisconnectType = DisconnectType(MumbleProto.Reject_WrongUserPW) - DisconnectServerPassword DisconnectType = DisconnectType(MumbleProto.Reject_WrongServerPW) - DisconnectUsernameInUse DisconnectType = DisconnectType(MumbleProto.Reject_UsernameInUse) - DisconnectServerFull DisconnectType = DisconnectType(MumbleProto.Reject_ServerFull) - DisconnectNoCertificate DisconnectType = DisconnectType(MumbleProto.Reject_NoCertificate) - DisconnectAuthenticatorFail DisconnectType = DisconnectType(MumbleProto.Reject_AuthenticatorFail) -) - -// Has returns true if the DisconnectType has changeType part of its bitmask. -func (dt DisconnectType) Has(changeType DisconnectType) bool { - return (dt & changeType) != 0 -} - -// DisconnectEvent is the event that is passed to EventListener.OnDisconnect. -type DisconnectEvent struct { - Client *Client - Type DisconnectType - - String string -} - -// TextMessageEvent is the event that is passed to EventListener.OnTextMessage. -type TextMessageEvent struct { - Client *Client - TextMessage -} - -// UserChangeType is a bitmask of items that changed for a user. -type UserChangeType int - -// User change items. -const ( - UserChangeConnected UserChangeType = 1 << iota - UserChangeDisconnected - UserChangeKicked - UserChangeBanned - UserChangeRegistered - UserChangeUnregistered - UserChangeName - UserChangeChannel - UserChangeComment - UserChangeAudio - UserChangeTexture - UserChangePrioritySpeaker - UserChangeRecording - UserChangeStats -) - -// Has returns true if the UserChangeType has changeType part of its bitmask. -func (uct UserChangeType) Has(changeType UserChangeType) bool { - return (uct & changeType) != 0 -} - -// UserChangeEvent is the event that is passed to EventListener.OnUserChange. -type UserChangeEvent struct { - Client *Client - Type UserChangeType - User *User - Actor *User - - String string -} - -// ChannelChangeType is a bitmask of items that changed for a channel. -type ChannelChangeType int - -// Channel change items. -const ( - ChannelChangeCreated ChannelChangeType = 1 << iota - ChannelChangeRemoved - ChannelChangeMoved - ChannelChangeName - ChannelChangeDescription - ChannelChangePosition - ChannelChangePermission -) - -// Has returns true if the ChannelChangeType has changeType part of its -// bitmask. -func (cct ChannelChangeType) Has(changeType ChannelChangeType) bool { - return (cct & changeType) != 0 -} - -// ChannelChangeEvent is the event that is passed to -// EventListener.OnChannelChange. -type ChannelChangeEvent struct { - Client *Client - Type ChannelChangeType - Channel *Channel -} - -// PermissionDeniedType specifies why a Client was denied permission to perform -// a particular action. -type PermissionDeniedType int - -// Permission denied types. -const ( - PermissionDeniedOther PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_Text) - PermissionDeniedPermission PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_Permission) - PermissionDeniedSuperUser PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_SuperUser) - PermissionDeniedInvalidChannelName PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelName) - PermissionDeniedTextTooLong PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_TextTooLong) - PermissionDeniedTemporaryChannel PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_TemporaryChannel) - PermissionDeniedMissingCertificate PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_MissingCertificate) - PermissionDeniedInvalidUserName PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_UserName) - PermissionDeniedChannelFull PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelFull) - PermissionDeniedNestingLimit PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_NestingLimit) -) - -// Has returns true if the PermissionDeniedType has changeType part of its -// bitmask. -func (pdt PermissionDeniedType) Has(changeType PermissionDeniedType) bool { - return (pdt & changeType) != 0 -} - -// PermissionDeniedEvent is the event that is passed to -// EventListener.OnPermissionDenied. -type PermissionDeniedEvent struct { - Client *Client - Type PermissionDeniedType - Channel *Channel - User *User - - Permission Permission - String string -} - -// UserListEvent is the event that is passed to EventListener.OnUserList. -type UserListEvent struct { - Client *Client - UserList RegisteredUsers -} - -// ACLEvent is the event that is passed to EventListener.OnACL. -type ACLEvent struct { - Client *Client - ACL *ACL -} - -// BanListEvent is the event that is passed to EventListener.OnBanList. -type BanListEvent struct { - Client *Client - BanList BanList -} - -// ContextActionChangeType specifies how a ContextAction changed. -type ContextActionChangeType int - -// ContextAction change types. -const ( - ContextActionAdd ContextActionChangeType = ContextActionChangeType(MumbleProto.ContextActionModify_Add) - ContextActionRemove ContextActionChangeType = ContextActionChangeType(MumbleProto.ContextActionModify_Remove) -) - -// ContextActionChangeEvent is the event that is passed to -// EventListener.OnContextActionChange. -type ContextActionChangeEvent struct { - Client *Client - Type ContextActionChangeType - ContextAction *ContextAction -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/eventmultiplexer.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/eventmultiplexer.go deleted file mode 100644 index 3ee5915..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/eventmultiplexer.go +++ /dev/null @@ -1,106 +0,0 @@ -package gumble - -// Detacher is an interface that event listeners implement. After the Detach -// method is called, the listener will no longer receive events. -type Detacher interface { - Detach() -} - -type eventMultiplexerItem struct { - mux *eventMultiplexer - prev, next *eventMultiplexerItem - listener EventListener -} - -func (emi *eventMultiplexerItem) Detach() { - if emi.prev == nil { - emi.mux.head = emi.next - } else { - emi.prev.next = emi.next - } - if emi.next == nil { - emi.mux.tail = emi.prev - } else { - emi.next.prev = emi.prev - } -} - -type eventMultiplexer struct { - head, tail *eventMultiplexerItem -} - -func (em *eventMultiplexer) Attach(listener EventListener) Detacher { - item := &eventMultiplexerItem{ - mux: em, - prev: em.tail, - listener: listener, - } - if em.head == nil { - em.head = item - } - if em.tail != nil { - em.tail.next = item - } - em.tail = item - return item -} - -func (em eventMultiplexer) OnConnect(event *ConnectEvent) { - for item := em.head; item != nil; item = item.next { - item.listener.OnConnect(event) - } -} - -func (em eventMultiplexer) OnDisconnect(event *DisconnectEvent) { - for item := em.head; item != nil; item = item.next { - item.listener.OnDisconnect(event) - } -} - -func (em eventMultiplexer) OnTextMessage(event *TextMessageEvent) { - for item := em.head; item != nil; item = item.next { - item.listener.OnTextMessage(event) - } -} - -func (em eventMultiplexer) OnUserChange(event *UserChangeEvent) { - for item := em.head; item != nil; item = item.next { - item.listener.OnUserChange(event) - } -} - -func (em eventMultiplexer) OnChannelChange(event *ChannelChangeEvent) { - for item := em.head; item != nil; item = item.next { - item.listener.OnChannelChange(event) - } -} - -func (em eventMultiplexer) OnPermissionDenied(event *PermissionDeniedEvent) { - for item := em.head; item != nil; item = item.next { - item.listener.OnPermissionDenied(event) - } -} - -func (em eventMultiplexer) OnUserList(event *UserListEvent) { - for item := em.head; item != nil; item = item.next { - item.listener.OnUserList(event) - } -} - -func (em eventMultiplexer) OnACL(event *ACLEvent) { - for item := em.head; item != nil; item = item.next { - item.listener.OnACL(event) - } -} - -func (em eventMultiplexer) OnBanList(event *BanListEvent) { - for item := em.head; item != nil; item = item.next { - item.listener.OnBanList(event) - } -} - -func (em eventMultiplexer) OnContextActionChange(event *ContextActionChangeEvent) { - for item := em.head; item != nil; item = item.next { - item.listener.OnContextActionChange(event) - } -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/handlers.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/handlers.go deleted file mode 100644 index e2e25c8..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/handlers.go +++ /dev/null @@ -1,962 +0,0 @@ -package gumble - -import ( - "bytes" - "crypto/x509" - "encoding/binary" - "errors" - "math" - "net" - "time" - - "github.com/golang/protobuf/proto" - "github.com/layeh/gopus" - "github.com/layeh/gumble/gumble/MumbleProto" - "github.com/layeh/gumble/gumble/varint" -) - -type handlerFunc func(*Client, []byte) error - -var ( - errUnimplementedHandler = errors.New("the handler has not been implemented") - errIncompleteProtobuf = errors.New("protobuf message is missing a required field") - errInvalidProtobuf = errors.New("protobuf message has an invalid field") - errUnsupportedAudio = errors.New("unsupported audio codec") -) - -var handlers = map[uint16]handlerFunc{ - 0: (*Client).handleVersion, - 1: (*Client).handleUdpTunnel, - 2: (*Client).handleAuthenticate, - 3: (*Client).handlePing, - 4: (*Client).handleReject, - 5: (*Client).handleServerSync, - 6: (*Client).handleChannelRemove, - 7: (*Client).handleChannelState, - 8: (*Client).handleUserRemove, - 9: (*Client).handleUserState, - 10: (*Client).handleBanList, - 11: (*Client).handleTextMessage, - 12: (*Client).handlePermissionDenied, - 13: (*Client).handleACL, - 14: (*Client).handleQueryUsers, - 15: (*Client).handleCryptSetup, - 16: (*Client).handleContextActionModify, - 17: (*Client).handleContextAction, - 18: (*Client).handleUserList, - 19: (*Client).handleVoiceTarget, - 20: (*Client).handlePermissionQuery, - 21: (*Client).handleCodecVersion, - 22: (*Client).handleUserStats, - 23: (*Client).handleRequestBlob, - 24: (*Client).handleServerConfig, - 25: (*Client).handleSuggestConfig, -} - -func parseVersion(packet *MumbleProto.Version) Version { - var version Version - if packet.Version != nil { - version.Version = *packet.Version - } - if packet.Release != nil { - version.Release = *packet.Release - } - if packet.Os != nil { - version.OS = *packet.Os - } - if packet.OsVersion != nil { - version.OSVersion = *packet.OsVersion - } - return version -} - -func (c *Client) handleVersion(buffer []byte) error { - var packet MumbleProto.Version - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - return nil -} - -func (c *Client) handleUdpTunnel(buffer []byte) error { - reader := bytes.NewReader(buffer) - var bytesRead int64 - - var audioType byte - var audioTarget byte - var user *User - var audioLength int - - // Header byte - typeTarget, err := varint.ReadByte(reader) - if err != nil { - return err - } - audioType = (typeTarget >> 5) & 0x7 - audioTarget = typeTarget & 0x1F - // Opus only - if audioType != 4 { - return errUnsupportedAudio - } - bytesRead++ - - // Session - session, n, err := varint.ReadFrom(reader) - if err != nil { - return err - } - user = c.Users[uint32(session)] - if user == nil { - return errInvalidProtobuf - } - bytesRead += n - - // Sequence - sequence, n, err := varint.ReadFrom(reader) - if err != nil { - return err - } - bytesRead += n - - // Length - length, n, err := varint.ReadFrom(reader) - if err != nil { - return err - } - // Opus audio packets set the 13th bit in the size field as the terminator. - audioLength = int(length) &^ 0x2000 - if audioLength > reader.Len() { - return errInvalidProtobuf - } - audioLength64 := int64(audioLength) - bytesRead += n - - opus := buffer[bytesRead : bytesRead+audioLength64] - pcm, err := user.decoder.Decode(opus, AudioMaximumFrameSize, false) - if err != nil { - return err - } - event := AudioPacketEvent{ - Client: c, - } - event.AudioPacket.Sender = user - event.AudioPacket.Target = int(audioTarget) - event.AudioPacket.Sequence = int(sequence) - event.AudioPacket.PositionalAudioBuffer.AudioBuffer = pcm - - reader.Seek(audioLength64, 1) - binary.Read(reader, binary.LittleEndian, &event.AudioPacket.PositionalAudioBuffer.X) - binary.Read(reader, binary.LittleEndian, &event.AudioPacket.PositionalAudioBuffer.Y) - binary.Read(reader, binary.LittleEndian, &event.AudioPacket.PositionalAudioBuffer.Z) - - c.audioListeners.OnAudioPacket(&event) - return nil -} - -func (c *Client) handleAuthenticate(buffer []byte) error { - return errUnimplementedHandler -} - -func (c *Client) handlePing(buffer []byte) error { - var packet MumbleProto.Ping - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - c.pingStats.TCPPackets++ - return nil -} - -func (c *Client) handleReject(buffer []byte) error { - var packet MumbleProto.Reject - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - if packet.Type != nil { - c.disconnectEvent.Type = DisconnectType(*packet.Type) - } - if packet.Reason != nil { - c.disconnectEvent.String = *packet.Reason - } - c.Conn.Close() - return nil -} - -func (c *Client) handleServerSync(buffer []byte) error { - var packet MumbleProto.ServerSync - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - event := ConnectEvent{ - Client: c, - } - - if packet.Session != nil { - c.Self = c.Users[*packet.Session] - } - if packet.WelcomeText != nil { - event.WelcomeMessage = *packet.WelcomeText - } - if packet.MaxBandwidth != nil { - event.MaximumBitrate = int(*packet.MaxBandwidth) - } - c.State = StateSynced - - c.listeners.OnConnect(&event) - return nil -} - -func (c *Client) handleChannelRemove(buffer []byte) error { - var packet MumbleProto.ChannelRemove - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - if packet.ChannelId == nil { - return errIncompleteProtobuf - } - var channel *Channel - { - channelID := *packet.ChannelId - channel = c.Channels[channelID] - if channel == nil { - return errInvalidProtobuf - } - delete(c.Channels, channelID) - delete(c.permissions, channelID) - if parent := channel.Parent; parent != nil { - delete(parent.Children, channel.ID) - } - } - - if c.State == StateSynced { - event := ChannelChangeEvent{ - Client: c, - Type: ChannelChangeRemoved, - Channel: channel, - } - c.listeners.OnChannelChange(&event) - } - return nil -} - -func (c *Client) handleChannelState(buffer []byte) error { - var packet MumbleProto.ChannelState - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - if packet.ChannelId == nil { - return errIncompleteProtobuf - } - event := ChannelChangeEvent{ - Client: c, - } - channelID := *packet.ChannelId - channel := c.Channels[channelID] - if channel == nil { - channel = c.Channels.create(channelID) - channel.client = c - - event.Type |= ChannelChangeCreated - } - event.Channel = channel - if packet.Parent != nil { - if channel.Parent != nil { - delete(channel.Parent.Children, channelID) - } - newParent := c.Channels[*packet.Parent] - if newParent != channel.Parent { - event.Type |= ChannelChangeMoved - } - channel.Parent = newParent - if channel.Parent != nil { - channel.Parent.Children[channel.ID] = channel - } - } - if packet.Name != nil { - if *packet.Name != channel.Name { - event.Type |= ChannelChangeName - } - channel.Name = *packet.Name - } - if packet.Description != nil { - if *packet.Description != channel.Description { - event.Type |= ChannelChangeDescription - } - channel.Description = *packet.Description - channel.DescriptionHash = nil - } - if packet.Temporary != nil { - channel.Temporary = *packet.Temporary - } - if packet.Position != nil { - if *packet.Position != channel.Position { - event.Type |= ChannelChangePosition - } - channel.Position = *packet.Position - } - if packet.DescriptionHash != nil { - event.Type |= ChannelChangeDescription - channel.DescriptionHash = packet.DescriptionHash - channel.Description = "" - } - - if c.State == StateSynced { - c.listeners.OnChannelChange(&event) - } - return nil -} - -func (c *Client) handleUserRemove(buffer []byte) error { - var packet MumbleProto.UserRemove - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - if packet.Session == nil { - return errIncompleteProtobuf - } - event := UserChangeEvent{ - Client: c, - Type: UserChangeDisconnected, - } - { - session := *packet.Session - event.User = c.Users[session] - if event.User == nil { - return errInvalidProtobuf - } - if event.User.Channel != nil { - delete(event.User.Channel.Users, session) - } - delete(c.Users, session) - } - if packet.Actor != nil { - event.Actor = c.Users[*packet.Actor] - if event.Actor == nil { - return errInvalidProtobuf - } - event.Type |= UserChangeKicked - } - if packet.Reason != nil { - event.String = *packet.Reason - } - if packet.Ban != nil && *packet.Ban { - event.Type |= UserChangeBanned - } - if event.User == c.Self { - if packet.Ban != nil && *packet.Ban { - c.disconnectEvent.Type = DisconnectBanned - } else { - c.disconnectEvent.Type = DisconnectKicked - } - } - - if c.State == StateSynced { - c.listeners.OnUserChange(&event) - } - return nil -} - -func (c *Client) handleUserState(buffer []byte) error { - var packet MumbleProto.UserState - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - if packet.Session == nil { - return errIncompleteProtobuf - } - event := UserChangeEvent{ - Client: c, - } - var user, actor *User - { - session := *packet.Session - user = c.Users[session] - if user == nil { - user = c.Users.create(session) - user.Channel = c.Channels[0] - user.client = c - - event.Type |= UserChangeConnected - - decoder, _ := gopus.NewDecoder(AudioSampleRate, 1) - user.decoder = decoder - - if user.Channel == nil { - return errInvalidProtobuf - } - event.Type |= UserChangeChannel - user.Channel.Users[session] = user - } - } - event.User = user - if packet.Actor != nil { - actor = c.Users[*packet.Actor] - if actor == nil { - return errInvalidProtobuf - } - event.Actor = actor - } - if packet.Name != nil { - if *packet.Name != user.Name { - event.Type |= UserChangeName - } - user.Name = *packet.Name - } - if packet.UserId != nil { - if *packet.UserId != user.UserID && !event.Type.Has(UserChangeConnected) { - if *packet.UserId != math.MaxUint32 { - event.Type |= UserChangeRegistered - user.UserID = *packet.UserId - } else { - event.Type |= UserChangeUnregistered - user.UserID = 0 - } - } else { - user.UserID = *packet.UserId - } - } - if packet.ChannelId != nil { - if user.Channel != nil { - delete(user.Channel.Users, user.Session) - } - newChannel := c.Channels[*packet.ChannelId] - if newChannel == nil { - return errInvalidProtobuf - } - if newChannel != user.Channel { - event.Type |= UserChangeChannel - user.Channel = newChannel - } - user.Channel.Users[user.Session] = user - } - if packet.Mute != nil { - if *packet.Mute != user.Muted { - event.Type |= UserChangeAudio - } - user.Muted = *packet.Mute - } - if packet.Deaf != nil { - if *packet.Deaf != user.Deafened { - event.Type |= UserChangeAudio - } - user.Deafened = *packet.Deaf - } - if packet.Suppress != nil { - if *packet.Suppress != user.Suppressed { - event.Type |= UserChangeAudio - } - user.Suppressed = *packet.Suppress - } - if packet.SelfMute != nil { - if *packet.SelfMute != user.SelfMuted { - event.Type |= UserChangeAudio - } - user.SelfMuted = *packet.SelfMute - } - if packet.SelfDeaf != nil { - if *packet.SelfDeaf != user.SelfDeafened { - event.Type |= UserChangeAudio - } - user.SelfDeafened = *packet.SelfDeaf - } - if packet.Texture != nil { - event.Type |= UserChangeTexture - user.Texture = packet.Texture - user.TextureHash = nil - } - if packet.Comment != nil { - if *packet.Comment != user.Comment { - event.Type |= UserChangeComment - } - user.Comment = *packet.Comment - user.CommentHash = nil - } - if packet.Hash != nil { - user.Hash = *packet.Hash - } - if packet.CommentHash != nil { - event.Type |= UserChangeComment - user.CommentHash = packet.CommentHash - user.Comment = "" - } - if packet.TextureHash != nil { - event.Type |= UserChangeTexture - user.TextureHash = packet.TextureHash - user.Texture = nil - } - if packet.PrioritySpeaker != nil { - if *packet.PrioritySpeaker != user.PrioritySpeaker { - event.Type |= UserChangePrioritySpeaker - } - user.PrioritySpeaker = *packet.PrioritySpeaker - } - if packet.Recording != nil { - if *packet.Recording != user.Recording { - event.Type |= UserChangeRecording - } - user.Recording = *packet.Recording - } - - if c.State == StateSynced { - c.listeners.OnUserChange(&event) - } - return nil -} - -func (c *Client) handleBanList(buffer []byte) error { - var packet MumbleProto.BanList - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - event := BanListEvent{ - Client: c, - BanList: make(BanList, 0, len(packet.Bans)), - } - - for _, banPacket := range packet.Bans { - ban := &Ban{ - Address: net.IP(banPacket.Address), - } - if banPacket.Mask != nil { - size := net.IPv4len * 8 - if len(ban.Address) == net.IPv6len { - size = net.IPv6len * 8 - } - ban.Mask = net.CIDRMask(int(*banPacket.Mask), size) - } - if banPacket.Name != nil { - ban.Name = *banPacket.Name - } - if banPacket.Hash != nil { - ban.Hash = *banPacket.Hash - } - if banPacket.Reason != nil { - ban.Reason = *banPacket.Reason - } - if banPacket.Start != nil { - ban.Start, _ = time.Parse(time.RFC3339, *banPacket.Start) - } - if banPacket.Duration != nil { - ban.Duration = time.Duration(*banPacket.Duration) * time.Second - } - event.BanList = append(event.BanList, ban) - } - - c.listeners.OnBanList(&event) - return nil -} - -func (c *Client) handleTextMessage(buffer []byte) error { - var packet MumbleProto.TextMessage - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - event := TextMessageEvent{ - Client: c, - } - if packet.Actor != nil { - event.Sender = c.Users[*packet.Actor] - } - if packet.Session != nil { - event.Users = make([]*User, 0, len(packet.Session)) - for _, session := range packet.Session { - if user := c.Users[session]; user != nil { - event.Users = append(event.Users, user) - } - } - } - if packet.ChannelId != nil { - event.Channels = make([]*Channel, 0, len(packet.ChannelId)) - for _, id := range packet.ChannelId { - if channel := c.Channels[id]; channel != nil { - event.Channels = append(event.Channels, channel) - } - } - } - if packet.TreeId != nil { - event.Trees = make([]*Channel, 0, len(packet.TreeId)) - for _, id := range packet.TreeId { - if channel := c.Channels[id]; channel != nil { - event.Trees = append(event.Trees, channel) - } - } - } - if packet.Message != nil { - event.Message = *packet.Message - } - - c.listeners.OnTextMessage(&event) - return nil -} - -func (c *Client) handlePermissionDenied(buffer []byte) error { - var packet MumbleProto.PermissionDenied - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - if packet.Type == nil || *packet.Type == MumbleProto.PermissionDenied_H9K { - return errInvalidProtobuf - } - - event := PermissionDeniedEvent{ - Client: c, - Type: PermissionDeniedType(*packet.Type), - } - if packet.Reason != nil { - event.String = *packet.Reason - } - if packet.Name != nil { - event.String = *packet.Name - } - if packet.Session != nil { - event.User = c.Users[*packet.Session] - if event.User == nil { - return errInvalidProtobuf - } - } - if packet.ChannelId != nil { - event.Channel = c.Channels[*packet.ChannelId] - if event.Channel == nil { - return errInvalidProtobuf - } - } - if packet.Permission != nil { - event.Permission = Permission(*packet.Permission) - } - - c.listeners.OnPermissionDenied(&event) - return nil -} - -func (c *Client) handleACL(buffer []byte) error { - var packet MumbleProto.ACL - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - acl := &ACL{ - Inherits: packet.GetInheritAcls(), - } - if packet.ChannelId == nil { - return errInvalidProtobuf - } - acl.Channel = c.Channels[*packet.ChannelId] - if acl.Channel == nil { - return errInvalidProtobuf - } - - if packet.Groups != nil { - acl.Groups = make([]*ACLGroup, 0, len(packet.Groups)) - for _, group := range packet.Groups { - aclGroup := &ACLGroup{ - Name: *group.Name, - Inherited: group.GetInherited(), - InheritUsers: group.GetInherit(), - Inheritable: group.GetInheritable(), - } - if group.Add != nil { - aclGroup.usersAdd = make(map[uint32]*ACLUser) - for _, userID := range group.Add { - aclGroup.usersAdd[userID] = &ACLUser{ - UserID: userID, - } - } - } - if group.Remove != nil { - aclGroup.usersRemove = make(map[uint32]*ACLUser) - for _, userID := range group.Remove { - aclGroup.usersRemove[userID] = &ACLUser{ - UserID: userID, - } - } - } - if group.InheritedMembers != nil { - aclGroup.usersInherited = make(map[uint32]*ACLUser) - for _, userID := range group.InheritedMembers { - aclGroup.usersInherited[userID] = &ACLUser{ - UserID: userID, - } - } - } - acl.Groups = append(acl.Groups, aclGroup) - } - } - if packet.Acls != nil { - acl.Rules = make([]*ACLRule, 0, len(packet.Acls)) - for _, rule := range packet.Acls { - aclRule := &ACLRule{ - AppliesCurrent: rule.GetApplyHere(), - AppliesChildren: rule.GetApplySubs(), - Inherited: rule.GetInherited(), - Granted: Permission(rule.GetGrant()), - Denied: Permission(rule.GetDeny()), - } - if rule.UserId != nil { - aclRule.User = &ACLUser{ - UserID: *rule.UserId, - } - } else if rule.Group != nil { - var group *ACLGroup - for _, g := range acl.Groups { - if g.Name == *rule.Group { - group = g - break - } - } - if group == nil { - group = &ACLGroup{ - Name: *rule.Group, - } - } - aclRule.Group = group - } - acl.Rules = append(acl.Rules, aclRule) - } - } - c.tmpACL = acl - return nil -} - -func (c *Client) handleQueryUsers(buffer []byte) error { - var packet MumbleProto.QueryUsers - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - acl := c.tmpACL - if acl == nil { - return errIncompleteProtobuf - } - c.tmpACL = nil - - userMap := make(map[uint32]string) - for i := 0; i < len(packet.Ids) && i < len(packet.Names); i++ { - userMap[packet.Ids[i]] = packet.Names[i] - } - - for _, group := range acl.Groups { - for _, user := range group.usersAdd { - user.Name = userMap[user.UserID] - } - for _, user := range group.usersRemove { - user.Name = userMap[user.UserID] - } - for _, user := range group.usersInherited { - user.Name = userMap[user.UserID] - } - } - for _, rule := range acl.Rules { - if rule.User != nil { - rule.User.Name = userMap[rule.User.UserID] - } - } - - event := ACLEvent{ - Client: c, - ACL: acl, - } - c.listeners.OnACL(&event) - return nil -} - -func (c *Client) handleCryptSetup(buffer []byte) error { - return errUnimplementedHandler -} - -func (c *Client) handleContextActionModify(buffer []byte) error { - var packet MumbleProto.ContextActionModify - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - if packet.Action == nil || packet.Operation == nil { - return errInvalidProtobuf - } - - event := ContextActionChangeEvent{ - Client: c, - } - - switch *packet.Operation { - case MumbleProto.ContextActionModify_Add: - if ca := c.ContextActions[*packet.Action]; ca != nil { - return nil - } - event.Type = ContextActionAdd - contextAction := c.ContextActions.create(*packet.Action) - if packet.Text != nil { - contextAction.Label = *packet.Text - } - if packet.Context != nil { - contextAction.Type = ContextActionType(*packet.Context) - } - event.ContextAction = contextAction - case MumbleProto.ContextActionModify_Remove: - contextAction := c.ContextActions[*packet.Action] - if contextAction == nil { - return nil - } - event.Type = ContextActionRemove - delete(c.ContextActions, *packet.Action) - event.ContextAction = contextAction - default: - return errInvalidProtobuf - } - - c.listeners.OnContextActionChange(&event) - return nil -} - -func (c *Client) handleContextAction(buffer []byte) error { - return errUnimplementedHandler -} - -func (c *Client) handleUserList(buffer []byte) error { - var packet MumbleProto.UserList - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - event := UserListEvent{ - Client: c, - UserList: make(RegisteredUsers, 0, len(packet.Users)), - } - - for _, user := range packet.Users { - registeredUser := &RegisteredUser{ - UserID: *user.UserId, - } - if user.Name != nil { - registeredUser.Name = *user.Name - } - event.UserList = append(event.UserList, registeredUser) - } - - c.listeners.OnUserList(&event) - return nil -} - -func (c *Client) handleVoiceTarget(buffer []byte) error { - return errUnimplementedHandler -} - -func (c *Client) handlePermissionQuery(buffer []byte) error { - var packet MumbleProto.PermissionQuery - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - if packet.Flush != nil && *packet.Flush { - oldPermissions := c.permissions - c.permissions = make(map[uint32]*Permission) - for channelID := range oldPermissions { - channel := c.Channels[channelID] - event := ChannelChangeEvent{ - Client: c, - Type: ChannelChangePermission, - Channel: channel, - } - c.listeners.OnChannelChange(&event) - } - } - if packet.ChannelId != nil { - channel := c.Channels[*packet.ChannelId] - if packet.Permissions != nil { - p := Permission(*packet.Permissions) - c.permissions[channel.ID] = &p - event := ChannelChangeEvent{ - Client: c, - Type: ChannelChangePermission, - Channel: channel, - } - c.listeners.OnChannelChange(&event) - } - } - return nil -} - -func (c *Client) handleCodecVersion(buffer []byte) error { - return errUnimplementedHandler -} - -func (c *Client) handleUserStats(buffer []byte) error { - var packet MumbleProto.UserStats - if err := proto.Unmarshal(buffer, &packet); err != nil { - return err - } - - if packet.Session == nil { - return errIncompleteProtobuf - } - user := c.Users[*packet.Session] - if user == nil { - return errInvalidProtobuf - } - - if user.Stats == nil { - user.Stats = &UserStats{} - } - *user.Stats = UserStats{ - User: user, - } - stats := user.Stats - - if packet.Version != nil { - stats.Version = parseVersion(packet.Version) - } - if packet.Onlinesecs != nil { - stats.Connected = time.Now().Add(time.Duration(*packet.Onlinesecs) * -time.Second) - } - if packet.Idlesecs != nil { - stats.Idle = time.Duration(*packet.Idlesecs) * time.Second - } - if packet.Bandwidth != nil { - stats.Bandwidth = int(*packet.Bandwidth) - } - if packet.Address != nil { - stats.IP = net.IP(packet.Address) - } - if packet.Certificates != nil { - stats.Certificates = make([]*x509.Certificate, 0, len(packet.Certificates)) - for _, data := range packet.Certificates { - if data != nil { - if cert, err := x509.ParseCertificate(data); err == nil { - stats.Certificates = append(stats.Certificates, cert) - } - } - } - } - stats.StrongCertificate = packet.GetStrongCertificate() - stats.CELTVersions = packet.GetCeltVersions() - if packet.Opus != nil { - stats.Opus = *packet.Opus - } - - event := UserChangeEvent{ - Client: c, - Type: UserChangeStats, - User: user, - } - - c.listeners.OnUserChange(&event) - return nil -} - -func (c *Client) handleRequestBlob(buffer []byte) error { - return errUnimplementedHandler -} - -func (c *Client) handleServerConfig(buffer []byte) error { - return errUnimplementedHandler -} - -func (c *Client) handleSuggestConfig(buffer []byte) error { - return errUnimplementedHandler -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/message.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/message.go deleted file mode 100644 index a84d8c1..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/message.go +++ /dev/null @@ -1,8 +0,0 @@ -package gumble - -// Message is data that be encoded and sent to the server. The following -// types implement this interface: AudioBuffer, AccessTokens, BanList, -// RegisteredUsers, TextMessage, and VoiceTarget. -type Message interface { - writeMessage(client *Client) error -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/permission.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/permission.go deleted file mode 100644 index 91a84e5..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/permission.go +++ /dev/null @@ -1,27 +0,0 @@ -package gumble - -// Permission is a bitmask of permissions given to a certain user. -type Permission int - -// Permissions that can be applied in any channel. -const ( - PermissionWrite Permission = 1 << iota - PermissionTraverse - PermissionEnter - PermissionSpeak - PermissionMuteDeafen - PermissionMove - PermissionMakeChannel - PermissionLinkChannel - PermissionWhisper - PermissionTextMessage - PermissionMakeTemporaryChannel -) - -// Permissions that can only be applied in the root channel. -const ( - PermissionKick Permission = 0x10000 << iota - PermissionBan - PermissionRegister - PermissionRegisterSelf -) diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/ping.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/ping.go deleted file mode 100644 index 719cb3b..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/ping.go +++ /dev/null @@ -1,73 +0,0 @@ -package gumble - -import ( - "bytes" - "crypto/rand" - "encoding/binary" - "io" - "net" - "time" -) - -// PingResponse contains information about a server that responded to a UDP -// ping packet. -type PingResponse struct { - // The address of the pinged server. - Address *net.UDPAddr - // The round-trip time from the client to the server. - Ping time.Duration - // The server's version. Only the Version field and SemanticVersion method of - // the value will be valid. - Version Version - // The number users currently connected to the server. - ConnectedUsers int - // The maximum number of users that can connect to the server. - MaximumUsers int - // The maximum audio bitrate per user for the server. - MaximumBitrate int -} - -// Ping sends a UDP ping packet to the given server. Returns a PingResponse and -// nil on success. The function will return nil and an error if a valid -// response is not received after the given timeout. -func Ping(address string, timeout time.Duration) (*PingResponse, error) { - addr, err := net.ResolveUDPAddr("udp", address) - if err != nil { - return nil, err - } - conn, err := net.DialUDP("udp", nil, addr) - if err != nil { - return nil, err - } - - var packet [12]byte - if _, err := rand.Read(packet[4:]); err != nil { - return nil, err - } - start := time.Now() - if _, err := conn.Write(packet[:]); err != nil { - return nil, err - } - - conn.SetReadDeadline(time.Now().Add(timeout)) - for { - var incoming [24]byte - if _, err := io.ReadFull(conn, incoming[:]); err != nil { - return nil, err - } - if !bytes.Equal(incoming[4:12], packet[4:]) { - continue - } - - return &PingResponse{ - Address: addr, - Ping: time.Since(start), - Version: Version{ - Version: binary.BigEndian.Uint32(incoming[0:]), - }, - ConnectedUsers: int(binary.BigEndian.Uint32(incoming[12:])), - MaximumUsers: int(binary.BigEndian.Uint32(incoming[16:])), - MaximumBitrate: int(binary.BigEndian.Uint32(incoming[20:])), - }, nil - } -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/pingstats.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/pingstats.go deleted file mode 100644 index 5748a82..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/pingstats.go +++ /dev/null @@ -1,5 +0,0 @@ -package gumble - -type pingStats struct { - TCPPackets uint32 -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/protomessage.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/protomessage.go deleted file mode 100644 index 3b1c5a7..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/protomessage.go +++ /dev/null @@ -1,16 +0,0 @@ -package gumble - -import ( - "github.com/golang/protobuf/proto" -) - -type protoMessage struct { - proto.Message -} - -func (pm protoMessage) writeMessage(client *Client) error { - if err := client.Conn.WriteProto(pm.Message); err != nil { - return err - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/request.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/request.go deleted file mode 100644 index f38ef1b..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/request.go +++ /dev/null @@ -1,18 +0,0 @@ -package gumble - -// Request is a mask of items that the client can ask the server to send. -type Request int - -// Items that can be requested from the server. See the documentation for -// Channel.Request, Client.Request, and User.Request to see which request types -// each one supports. -const ( - RequestDescription Request = 1 << iota - RequestComment - RequestTexture - RequestStats - RequestUserList - RequestACL - RequestBanList - RequestPermission -) diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/textmessage.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/textmessage.go deleted file mode 100644 index 264d9a3..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/textmessage.go +++ /dev/null @@ -1,50 +0,0 @@ -package gumble - -import ( - "github.com/layeh/gumble/gumble/MumbleProto" -) - -// TextMessage is a chat message that can be received from and sent to the -// server. -type TextMessage struct { - // User who sent the message (can be nil). - Sender *User - - // Users that receive the message. - Users []*User - - // Channels that receive the message. - Channels []*Channel - - // Channels that receive the message and send it recursively to sub-channels. - Trees []*Channel - - // Chat message. - Message string -} - -func (tm *TextMessage) writeMessage(client *Client) error { - packet := MumbleProto.TextMessage{ - Message: &tm.Message, - } - if tm.Users != nil { - packet.Session = make([]uint32, len(tm.Users)) - for i, user := range tm.Users { - packet.Session[i] = user.Session - } - } - if tm.Channels != nil { - packet.ChannelId = make([]uint32, len(tm.Channels)) - for i, channel := range tm.Channels { - packet.ChannelId[i] = channel.ID - } - } - if tm.Trees != nil { - packet.TreeId = make([]uint32, len(tm.Trees)) - for i, channel := range tm.Trees { - packet.TreeId[i] = channel.ID - } - } - proto := protoMessage{&packet} - return proto.writeMessage(client) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/user.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/user.go deleted file mode 100644 index c03c3e5..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/user.go +++ /dev/null @@ -1,231 +0,0 @@ -package gumble - -import ( - "github.com/golang/protobuf/proto" - "github.com/layeh/gopus" - "github.com/layeh/gumble/gumble/MumbleProto" -) - -// User represents a user that is currently connected to the server. -type User struct { - // The user's unique session ID. - Session uint32 - // The user's ID. Contains an invalid value if the user is not registered. - UserID uint32 - // The user's name. - Name string - // The channel that the user is currently in. - Channel *Channel - - // Has the user has been muted? - Muted bool - // Has the user been deafened? - Deafened bool - // Has the user been suppressed? - Suppressed bool - // Has the user been muted by him/herself? - SelfMuted bool - // Has the user been deafened by him/herself? - SelfDeafened bool - // Is the user a priority speaker in the channel? - PrioritySpeaker bool - // Is the user recording audio? - Recording bool - - // The user's comment. Contains the empty string if the user does not have a - // comment, or if the comment needs to be requested. - Comment string - // The user's comment hash. Contains nil if User.Comment has been populated. - CommentHash []byte - // The hash of the user's certificate (can be empty). - Hash string - // The user's texture (avatar). Contains nil if the user does not have a - // texture, or if the texture needs to be requested. - Texture []byte - // The user's texture hash. Contains nil if User.Texture has been populated. - TextureHash []byte - - // The user's stats. Containts nil if the stats have not yet been requested. - Stats *UserStats - - client *Client - decoder *gopus.Decoder -} - -// SetTexture sets the user's texture. -func (u *User) SetTexture(texture []byte) { - packet := MumbleProto.UserState{ - Session: &u.Session, - Texture: texture, - } - u.client.Send(protoMessage{&packet}) -} - -// SetPrioritySpeaker sets if the user is a priority speaker in the channel. -func (u *User) SetPrioritySpeaker(prioritySpeaker bool) { - packet := MumbleProto.UserState{ - Session: &u.Session, - PrioritySpeaker: &prioritySpeaker, - } - u.client.Send(protoMessage{&packet}) -} - -// SetRecording sets if the user is recording audio. -func (u *User) SetRecording(recording bool) { - packet := MumbleProto.UserState{ - Session: &u.Session, - Recording: &recording, - } - u.client.Send(protoMessage{&packet}) -} - -// IsRegistered returns true if the user's certificate has been registered with -// the server. A registered user will have a valid user ID. -func (u *User) IsRegistered() bool { - return u.UserID > 0 -} - -// Register will register the user with the server. If the client has -// permission to do so, the user will shortly be given a UserID. -func (u *User) Register() { - packet := MumbleProto.UserState{ - Session: &u.Session, - UserId: proto.Uint32(0), - } - u.client.Send(protoMessage{&packet}) -} - -// SetComment will set the user's comment to the given string. The user's -// comment will be erased if the comment is set to the empty string. -func (u *User) SetComment(comment string) { - packet := MumbleProto.UserState{ - Session: &u.Session, - Comment: &comment, - } - u.client.Send(protoMessage{&packet}) -} - -// Move will move the user to the given channel. -func (u *User) Move(channel *Channel) { - packet := MumbleProto.UserState{ - Session: &u.Session, - ChannelId: &channel.ID, - } - u.client.Send(protoMessage{&packet}) -} - -// Kick will kick the user from the server. -func (u *User) Kick(reason string) { - packet := MumbleProto.UserRemove{ - Session: &u.Session, - Reason: &reason, - } - u.client.Send(protoMessage{&packet}) -} - -// Ban will ban the user from the server. -func (u *User) Ban(reason string) { - packet := MumbleProto.UserRemove{ - Session: &u.Session, - Reason: &reason, - Ban: proto.Bool(true), - } - u.client.Send(protoMessage{&packet}) -} - -// SetMuted sets whether the user can transmit audio or not. -func (u *User) SetMuted(muted bool) { - packet := MumbleProto.UserState{ - Session: &u.Session, - Mute: &muted, - } - u.client.Send(protoMessage{&packet}) -} - -// SetSuppressed sets whether the user is suppressed by the server or not. -func (u *User) SetSuppressed(supressed bool) { - packet := MumbleProto.UserState{ - Session: &u.Session, - Suppress: &supressed, - } - u.client.Send(protoMessage{&packet}) -} - -// SetDeafened sets whether the user can receive audio or not. -func (u *User) SetDeafened(muted bool) { - packet := MumbleProto.UserState{ - Session: &u.Session, - Deaf: &muted, - } - u.client.Send(protoMessage{&packet}) -} - -// SetSelfMuted sets whether the user can transmit audio or not. -// -// This method should only be called on Client.Self(). -func (u *User) SetSelfMuted(muted bool) { - packet := MumbleProto.UserState{ - Session: &u.Session, - SelfMute: &muted, - } - u.client.Send(protoMessage{&packet}) -} - -// SetSelfDeafened sets whether the user can receive audio or not. -// -// This method should only be called on Client.Self(). -func (u *User) SetSelfDeafened(muted bool) { - packet := MumbleProto.UserState{ - Session: &u.Session, - SelfDeaf: &muted, - } - u.client.Send(protoMessage{&packet}) -} - -// Request requests user information that has not yet been sent to the client. -// The supported request types are: RequestStats, RequestTexture, and -// RequestComment. -func (u *User) Request(request Request) { - if (request & RequestStats) != 0 { - packet := MumbleProto.UserStats{ - Session: &u.Session, - } - u.client.Send(protoMessage{&packet}) - } - - packet := MumbleProto.RequestBlob{} - if (request & RequestTexture) != 0 { - packet.SessionTexture = []uint32{u.Session} - } - if (request & RequestComment) != 0 { - packet.SessionComment = []uint32{u.Session} - } - if packet.SessionTexture != nil || packet.SessionComment != nil { - u.client.Send(protoMessage{&packet}) - } -} - -// Send will send a text message to the user. -func (u *User) Send(message string) { - textMessage := TextMessage{ - Users: []*User{u}, - Message: message, - } - u.client.Send(&textMessage) -} - -// SetPlugin sets the user's plugin data. -// -// Plugins are currently only used for positional audio. Clients will receive -// positional audio information from other users if their plugin context is the -// same. The official Mumble client sets the context to: -// -// PluginShortName + "\x00" + AdditionalContextInformation -func (u *User) SetPlugin(context []byte, identity string) { - packet := MumbleProto.UserState{ - Session: &u.Session, - PluginContext: context, - PluginIdentity: &identity, - } - u.client.Send(protoMessage{&packet}) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userlist.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userlist.go deleted file mode 100644 index b915ca6..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userlist.go +++ /dev/null @@ -1,69 +0,0 @@ -package gumble - -import ( - "github.com/layeh/gumble/gumble/MumbleProto" -) - -// RegisteredUser represents a registered user on the server. -type RegisteredUser struct { - // The registered user's ID. - UserID uint32 - // The registered user's name. - Name string - - changed bool - deregister bool -} - -// SetName sets the new name for the user. -func (ru *RegisteredUser) SetName(name string) { - ru.Name = name - ru.changed = true -} - -// Deregister will remove the registered user from the server. -func (ru *RegisteredUser) Deregister() { - ru.deregister = true -} - -// Register will keep the user registered on the server. This is only useful if -// Deregister() was called on the registered user. -func (ru *RegisteredUser) Register() { - ru.deregister = false -} - -// ACLUser returns an ACLUser for the given registered user. -func (ru *RegisteredUser) ACLUser() *ACLUser { - return &ACLUser{ - UserID: ru.UserID, - Name: ru.Name, - } -} - -// RegisteredUsers is a list of users who are registered on the server. -// -// Whenever a registered user is changed, it does not come into effect until -// the registered user list is sent back to the server. -type RegisteredUsers []*RegisteredUser - -func (pm RegisteredUsers) writeMessage(client *Client) error { - packet := MumbleProto.UserList{} - - for _, user := range pm { - if user.deregister || user.changed { - userListUser := &MumbleProto.UserList_User{ - UserId: &user.UserID, - } - if !user.deregister { - userListUser.Name = &user.Name - } - packet.Users = append(packet.Users, userListUser) - } - } - - if len(packet.Users) <= 0 { - return nil - } - proto := protoMessage{&packet} - return proto.writeMessage(client) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/users.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/users.go deleted file mode 100644 index 83845a9..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/users.go +++ /dev/null @@ -1,30 +0,0 @@ -package gumble - -// Users is a map of server users. -// -// When accessed through client.Users, it contains all users currently on the -// server. When accessed through a specific channel -// (e.g. client.Channels[0].Users), it contains only the users in the -// channel. -type Users map[uint32]*User - -// create adds a new user with the given session to the collection. If a user -// with the given session already exists, it is overwritten. -func (u Users) create(session uint32) *User { - user := &User{ - Session: session, - } - u[session] = user - return user -} - -// Find returns the user with the given name. Nil is returned if no user exists -// with the given name. -func (u Users) Find(name string) *User { - for _, user := range u { - if user.Name == name { - return user - } - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userstats.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userstats.go deleted file mode 100644 index 3da4988..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/userstats.go +++ /dev/null @@ -1,34 +0,0 @@ -package gumble - -import ( - "crypto/x509" - "net" - "time" -) - -// UserStats contains additional information about a user. -type UserStats struct { - // The owner of the stats. - User *User - - // The user's version. - Version Version - // When the user connected to the server. - Connected time.Time - // How long the user has been idle. - Idle time.Duration - // How much bandwidth the user is current using. - Bandwidth int - // The user's certificate chain. - Certificates []*x509.Certificate - // Does the user have a strong certificate? A strong certificate is one that - // is not self signed, nor expired, etc. - StrongCertificate bool - // A list of CELT versions supported by the user's client. - CELTVersions []int32 - // Does the user's client supports the Opus audio codec? - Opus bool - - // The user's IP address. - IP net.IP -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/read.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/read.go deleted file mode 100644 index f7141a0..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/read.go +++ /dev/null @@ -1,48 +0,0 @@ -package varint - -import ( - "io" -) - -// ReadFrom reads a varint encoded from the given io.Reader. -// -// On success, the function returns the varint as a int64, the number of bytes -// consumed, and nil. -func ReadFrom(r io.Reader) (int64, int64, error) { - var buffer [3]byte - b, err := ReadByte(r) - if err != nil { - return 0, 0, err - } - if (b & 0x80) == 0 { - return int64(b), 1, nil - } - if (b & 0xC0) == 0x80 { - if n, err := io.ReadFull(r, buffer[0:1]); err != nil { - return 0, int64(n + 1), err - } - return int64(b&0x3F)<<8 | int64(buffer[0]), 2, nil - } - if (b & 0xE0) == 0xC0 { - if n, err := io.ReadFull(r, buffer[0:2]); err != nil { - return 0, int64(n + 1), err - } - return int64(b&0x1F)<<16 | int64(buffer[0])<<8 | int64(buffer[1]), 3, nil - } - if (b & 0xF0) == 0xE0 { - if n, err := io.ReadFull(r, buffer[0:3]); err != nil { - return 0, int64(n + 1), err - } - return int64(b&0xF)<<24 | int64(buffer[0])<<16 | int64(buffer[1])<<8 | int64(buffer[2]), 4, nil - } - return 0, 1, ErrOutOfRange -} - -// ReadBytes reads a single byte from the given io.Reader. -func ReadByte(r io.Reader) (byte, error) { - var buff [1]byte - if _, err := io.ReadFull(r, buff[:]); err != nil { - return 0, err - } - return buff[0], nil -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/varint.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/varint.go deleted file mode 100644 index 185ecd6..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/varint.go +++ /dev/null @@ -1,9 +0,0 @@ -package varint - -import ( - "errors" -) - -var ( - ErrOutOfRange = errors.New("out of range") -) diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/write.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/write.go deleted file mode 100644 index 6d9bbff..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/varint/write.go +++ /dev/null @@ -1,51 +0,0 @@ -package varint - -import ( - "encoding/binary" - "io" - "math" -) - -// WriteTo writes the given value to the given io.Writer as a varint encoded -// byte array. -// -// On success, the function returns the number of bytes written to the writer, -// and nil. -func WriteTo(w io.Writer, value int64) (int64, error) { - var length int - var buff [5]byte - if value < 0 { - return 0, ErrOutOfRange - } - if value <= 0x7F { - buff[0] = byte(value) - length = 1 - } else if value <= 0x3FFF { - buff[0] = byte(((value >> 8) & 0x3F) | 0x80) - buff[1] = byte(value & 0xFF) - length = 2 - } else if value <= 0x1FFFFF { - buff[0] = byte((value>>16)&0x1F | 0xC0) - buff[1] = byte((value >> 8) & 0xFF) - buff[2] = byte(value & 0xFF) - length = 3 - } else if value <= 0xFFFFFFF { - buff[0] = byte((value>>24)&0xF | 0xE0) - buff[1] = byte((value >> 16) & 0xFF) - buff[2] = byte((value >> 8) & 0xFF) - buff[3] = byte(value & 0xFF) - length = 4 - } else if value <= math.MaxInt32 { - buff[0] = 0xF0 - binary.BigEndian.PutUint32(buff[1:], uint32(value)) - length = 5 - } - if length > 0 { - if n, err := w.Write(buff[:length]); err != nil { - return int64(n), err - } else { - return int64(n), nil - } - } - return 0, ErrOutOfRange -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/version.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/version.go deleted file mode 100644 index 7270e57..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/version.go +++ /dev/null @@ -1,24 +0,0 @@ -package gumble - -// Version represents a Mumble client or server version. -type Version struct { - // The semantic version information as a single unsigned integer. - // - // Bits 0-15 are the major version, bits 16-23 are the minor version, and - // bits 24-31 are the patch version. - Version uint32 - // The name of the client. - Release string - // The operating system name. - OS string - // The operating system version. - OSVersion string -} - -// SemanticVersion returns the version's semantic version components. -func (v *Version) SemanticVersion() (major, minor, patch uint) { - major = uint(v.Version>>16) & 0xFFFF - minor = uint(v.Version>>8) & 0xFF - patch = uint(v.Version) & 0xFF - return -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/voicetarget.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble/voicetarget.go deleted file mode 100644 index d1f9a78..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble/voicetarget.go +++ /dev/null @@ -1,81 +0,0 @@ -package gumble - -import ( - "github.com/layeh/gumble/gumble/MumbleProto" -) - -// VoiceTargetLoopback is a special voice target which causes any audio sent to -// the server to be returned to the client. -// -// Its ID should not be modified, and it does not have to to be sent to the -// server before use. -var VoiceTargetLoopback *VoiceTarget - -func init() { - VoiceTargetLoopback = &VoiceTarget{ - ID: 31, - } -} - -type voiceTargetChannel struct { - channel *Channel - links, recursive bool - group string -} - -// VoiceTarget represents a set of users and/or channels that the client can -// whisper to. -type VoiceTarget struct { - // The voice target ID. This value must be in the range [1, 30]. - ID uint32 - users []*User - channels []*voiceTargetChannel -} - -// Clear removes all users and channels from the voice target. -func (vt *VoiceTarget) Clear() { - vt.users = nil - vt.channels = nil -} - -// AddUser adds a user to the voice target. -func (vt *VoiceTarget) AddUser(user *User) { - vt.users = append(vt.users, user) -} - -// AddChannel adds a user to the voice target. If group is non-empty, only -// users belonging to that ACL group will be targeted. -func (vt *VoiceTarget) AddChannel(channel *Channel, recursive, links bool, group string) { - vt.channels = append(vt.channels, &voiceTargetChannel{ - channel: channel, - links: links, - recursive: recursive, - group: group, - }) -} - -func (vt *VoiceTarget) writeMessage(client *Client) error { - packet := MumbleProto.VoiceTarget{ - Id: &vt.ID, - Targets: make([]*MumbleProto.VoiceTarget_Target, 0, len(vt.users)+len(vt.channels)), - } - for _, user := range vt.users { - packet.Targets = append(packet.Targets, &MumbleProto.VoiceTarget_Target{ - Session: []uint32{user.Session}, - }) - } - for _, vtChannel := range vt.channels { - target := &MumbleProto.VoiceTarget_Target{ - ChannelId: &vtChannel.channel.ID, - Links: &vtChannel.links, - Children: &vtChannel.recursive, - } - if vtChannel.group != "" { - target.Group = &vtChannel.group - } - packet.Targets = append(packet.Targets, target) - } - - proto := protoMessage{&packet} - return proto.writeMessage(client) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/gumble_ffmpeg.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/gumble_ffmpeg.go deleted file mode 100644 index cdf70a0..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/gumble_ffmpeg.go +++ /dev/null @@ -1,134 +0,0 @@ -package gumble_ffmpeg - -import ( - "encoding/binary" - "errors" - "io" - "os/exec" - "strconv" - "sync" - "time" - - "github.com/layeh/gumble/gumble" -) - -const ( - DefaultCommand = "ffmpeg" -) - -type Stream struct { - // Command to execute to play the file. Defaults to "ffmpeg". - Command string - // Playback volume. This value can be changed while the source is playing. - Volume float32 - // Audio source. This value should not be closed until the stream is done - // playing. - Source Source - // Starting offset. - Offset time.Duration - - client *gumble.Client - cmd *exec.Cmd - pipe io.ReadCloser - - stop chan bool - stopWaitGroup sync.WaitGroup -} - -// New creates a new stream on the given gumble client. -func New(client *gumble.Client) *Stream { - stream := &Stream{ - client: client, - Volume: 1.0, - Command: DefaultCommand, - stop: make(chan bool), - } - return stream -} - -// Play starts playing the stream to the gumble client. Returns non-nil if the -// stream could not be started. -func (s *Stream) Play() error { - if s.IsPlaying() { - return errors.New("already playing") - } - if s.Source == nil { - return errors.New("nil source") - } - args := s.Source.arguments() - if secs := int(s.Offset.Seconds()); secs > 0 { - args = append([]string{"-ss", strconv.Itoa(secs)}, args...) - } - args = append(args, []string{"-ac", "1", "-ar", strconv.Itoa(gumble.AudioSampleRate), "-f", "s16le", "-"}...) - cmd := exec.Command(s.Command, args...) - if pipe, err := cmd.StdoutPipe(); err != nil { - return err - } else { - s.pipe = pipe - } - s.Source.start(cmd) - if err := cmd.Start(); err != nil { - s.Source.done() - return err - } - s.stopWaitGroup.Add(1) - s.cmd = cmd - go s.sourceRoutine() - return nil -} - -// IsPlaying returns if a stream is playing. -func (s *Stream) IsPlaying() bool { - return s.cmd != nil -} - -// Wait returns once the stream has finished playing. -func (s *Stream) Wait() { - s.stopWaitGroup.Wait() -} - -// Stop stops the currently playing stream. -func (s *Stream) Stop() error { - if !s.IsPlaying() { - return errors.New("nothing playing") - } - - s.stop <- true - s.stopWaitGroup.Wait() - return nil -} - -func (s *Stream) sourceRoutine() { - interval := s.client.Config.GetAudioInterval() - frameSize := s.client.Config.GetAudioFrameSize() - - ticker := time.NewTicker(interval) - - defer func() { - ticker.Stop() - s.cmd.Process.Kill() - s.cmd.Wait() - s.cmd = nil - s.Source.done() - s.stopWaitGroup.Done() - }() - - int16Buffer := make([]int16, frameSize) - byteBuffer := make([]byte, frameSize*2) - - for { - select { - case <-s.stop: - return - case <-ticker.C: - if _, err := io.ReadFull(s.pipe, byteBuffer); err != nil { - return - } - for i := range int16Buffer { - float := float32(int16(binary.LittleEndian.Uint16(byteBuffer[i*2 : (i+1)*2]))) - int16Buffer[i] = int16(s.Volume * float) - } - s.client.Send(gumble.AudioBuffer(int16Buffer)) - } - } -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/source.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/source.go deleted file mode 100644 index 4824d41..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumble_ffmpeg/source.go +++ /dev/null @@ -1,55 +0,0 @@ -package gumble_ffmpeg - -import ( - "io" - "os/exec" -) - -type Source interface { - // must include the -i - arguments() []string - start(*exec.Cmd) - done() -} - -// sourceFile - -type sourceFile string - -// SourceFile is standard file source. -func SourceFile(filename string) Source { - return sourceFile(filename) -} - -func (s sourceFile) arguments() []string { - return []string{"-i", string(s)} -} - -func (sourceFile) start(*exec.Cmd) { -} - -func (sourceFile) done() { -} - -// sourceReader - -type sourceReader struct { - r io.ReadCloser -} - -// SourceReader is a ReadCloser source. -func SourceReader(r io.ReadCloser) Source { - return &sourceReader{r} -} - -func (*sourceReader) arguments() []string { - return []string{"-i", "-"} -} - -func (s *sourceReader) start(cmd *exec.Cmd) { - cmd.Stdin = s.r -} - -func (s *sourceReader) done() { - s.r.Close() -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/bitrate.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/bitrate.go deleted file mode 100644 index ecf6d8f..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/bitrate.go +++ /dev/null @@ -1,25 +0,0 @@ -package gumbleutil - -import ( - "time" - - "github.com/layeh/gopus" - "github.com/layeh/gumble/gumble" -) - -var autoBitrate = &Listener{ - Connect: func(e *gumble.ConnectEvent) { - if e.MaximumBitrate > 0 { - const safety = 5 - interval := e.Client.Config.GetAudioInterval() - dataBytes := (e.MaximumBitrate / (8 * (int(time.Second/interval) + safety))) - 32 - 10 - - e.Client.Config.AudioDataBytes = dataBytes - e.Client.AudioEncoder.SetBitrate(gopus.BitrateMaximum) - } - }, -} - -// AutoBitrate is a gumble.EventListener that automatically sets the client's -// AudioDataBytes to suitable value, based on the server's bitrate. -var AutoBitrate gumble.EventListener = autoBitrate diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/certificatelock.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/certificatelock.go deleted file mode 100644 index 2364aca..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/certificatelock.go +++ /dev/null @@ -1,75 +0,0 @@ -package gumbleutil - -import ( - "crypto/tls" - "crypto/x509" - "encoding/pem" - "errors" - "io/ioutil" - "os" - - "github.com/layeh/gumble/gumble" -) - -// CertificateLockFile adds a new certificate lock on the given Client that -// ensures that a server's certificate chain is the same from -// connection-to-connection. This is helpful when connecting to servers with -// self-signed certificates. -// -// If filename does not exist, the server's certificate chain will be written -// to that file. If it does exist, certificates will be read from the file and -// checked against the server's certificate chain upon connection. -// -// Example: -// -// if allowSelfSignedCertificates { -// config.TLSConfig.InsecureSkipVerify = true -// } -// gumbleutil.CertificateLockFile(client, filename) -// -// if err := client.Connect(); err != nil { -// panic(err) -// } -func CertificateLockFile(client *gumble.Client, filename string) { - client.Config.TLSVerify = func(state *tls.ConnectionState) error { - if file, err := os.Open(filename); err == nil { - defer file.Close() - data, err := ioutil.ReadAll(file) - if err != nil { - return err - } - i := 0 - for block, data := pem.Decode(data); block != nil; block, data = pem.Decode(data) { - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return err - } - if i >= len(state.PeerCertificates) { - return errors.New("gumbleutil: invalid certificate chain length") - } - if !cert.Equal(state.PeerCertificates[i]) { - return errors.New("gumbleutil: certificate verification failure") - } - i++ - } - if i != len(state.PeerCertificates) { - return errors.New("gumbleutil: invalid certificate chain length") - } - return nil - } - - file, err := os.Create(filename) - if err != nil { - return err - } - defer file.Close() - block := pem.Block{ - Type: "CERTIFICATE", - } - for _, cert := range state.PeerCertificates { - block.Bytes = cert.Raw - pem.Encode(file, &block) - } - return nil - } -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/doc.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/doc.go deleted file mode 100644 index 864a3b8..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package gumbleutil provides extras that can make working with gumble easier. -package gumbleutil diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listener.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listener.go deleted file mode 100644 index c1112a7..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listener.go +++ /dev/null @@ -1,90 +0,0 @@ -package gumbleutil - -import ( - "github.com/layeh/gumble/gumble" -) - -// Listener is a struct that implements the gumble.EventListener interface. The -// corresponding event function in the struct is called if it is non-nil. -type Listener struct { - Connect func(e *gumble.ConnectEvent) - Disconnect func(e *gumble.DisconnectEvent) - TextMessage func(e *gumble.TextMessageEvent) - UserChange func(e *gumble.UserChangeEvent) - ChannelChange func(e *gumble.ChannelChangeEvent) - PermissionDenied func(e *gumble.PermissionDeniedEvent) - UserList func(e *gumble.UserListEvent) - ACL func(e *gumble.ACLEvent) - BanList func(e *gumble.BanListEvent) - ContextActionChange func(e *gumble.ContextActionChangeEvent) -} - -// OnConnect implements gumble.EventListener.OnConnect. -func (l Listener) OnConnect(e *gumble.ConnectEvent) { - if l.Connect != nil { - l.Connect(e) - } -} - -// OnDisconnect implements gumble.EventListener.OnDisconnect. -func (l Listener) OnDisconnect(e *gumble.DisconnectEvent) { - if l.Disconnect != nil { - l.Disconnect(e) - } -} - -// OnTextMessage implements gumble.EventListener.OnTextMessage. -func (l Listener) OnTextMessage(e *gumble.TextMessageEvent) { - if l.TextMessage != nil { - l.TextMessage(e) - } -} - -// OnUserChange implements gumble.EventListener.OnUserChange. -func (l Listener) OnUserChange(e *gumble.UserChangeEvent) { - if l.UserChange != nil { - l.UserChange(e) - } -} - -// OnChannelChange implements gumble.EventListener.OnChannelChange. -func (l Listener) OnChannelChange(e *gumble.ChannelChangeEvent) { - if l.ChannelChange != nil { - l.ChannelChange(e) - } -} - -// OnPermissionDenied implements gumble.EventListener.OnPermissionDenied. -func (l Listener) OnPermissionDenied(e *gumble.PermissionDeniedEvent) { - if l.PermissionDenied != nil { - l.PermissionDenied(e) - } -} - -// OnUserList implements gumble.EventListener.OnUserList. -func (l Listener) OnUserList(e *gumble.UserListEvent) { - if l.UserList != nil { - l.UserList(e) - } -} - -// OnACL implements gumble.EventListener.OnACL. -func (l Listener) OnACL(e *gumble.ACLEvent) { - if l.ACL != nil { - l.ACL(e) - } -} - -// OnBanList implements gumble.EventListener.OnBanList. -func (l Listener) OnBanList(e *gumble.BanListEvent) { - if l.BanList != nil { - l.BanList(e) - } -} - -// OnContextActionChange implements gumble.EventListener.OnContextActionChange. -func (l Listener) OnContextActionChange(e *gumble.ContextActionChangeEvent) { - if l.ContextActionChange != nil { - l.ContextActionChange(e) - } -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listenerfunc.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listenerfunc.go deleted file mode 100644 index 60e42db..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/listenerfunc.go +++ /dev/null @@ -1,73 +0,0 @@ -package gumbleutil - -import ( - "github.com/layeh/gumble/gumble" -) - -// ListenerFunc is a single listener function that implements the -// gumble.EventListener interface. This is useful if you would like to use a -// type-switch for handling the different event types. -// -// Example: -// handler := func(e interface{}) { -// switch e.(type) { -// case *gumble.ConnectEvent: -// println("Connected") -// case *gumble.DisconnectEvent: -// println("Disconnected") -// // ... -// } -// } -// -// client.Attach(gumbleutil.ListenerFunc(handler)) -type ListenerFunc func(e interface{}) - -// OnConnect implements gumble.EventListener.OnConnect. -func (lf ListenerFunc) OnConnect(e *gumble.ConnectEvent) { - lf(e) -} - -// OnDisconnect implements gumble.EventListener.OnDisconnect. -func (lf ListenerFunc) OnDisconnect(e *gumble.DisconnectEvent) { - lf(e) -} - -// OnTextMessage implements gumble.EventListener.OnTextMessage. -func (lf ListenerFunc) OnTextMessage(e *gumble.TextMessageEvent) { - lf(e) -} - -// OnUserChange implements gumble.EventListener.OnUserChange. -func (lf ListenerFunc) OnUserChange(e *gumble.UserChangeEvent) { - lf(e) -} - -// OnChannelChange implements gumble.EventListener.OnChannelChange. -func (lf ListenerFunc) OnChannelChange(e *gumble.ChannelChangeEvent) { - lf(e) -} - -// OnPermissionDenied implements gumble.EventListener.OnPermissionDenied. -func (lf ListenerFunc) OnPermissionDenied(e *gumble.PermissionDeniedEvent) { - lf(e) -} - -// OnUserList implements gumble.EventListener.OnUserList. -func (lf ListenerFunc) OnUserList(e *gumble.UserListEvent) { - lf(e) -} - -// OnACL implements gumble.EventListener.OnACL. -func (lf ListenerFunc) OnACL(e *gumble.ACLEvent) { - lf(e) -} - -// OnBanList implements gumble.EventListener.OnBanList. -func (lf ListenerFunc) OnBanList(e *gumble.BanListEvent) { - lf(e) -} - -// OnContextActionChange implements gumble.EventListener.OnContextActionChange. -func (lf ListenerFunc) OnContextActionChange(e *gumble.ContextActionChangeEvent) { - lf(e) -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/main.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/main.go deleted file mode 100644 index fa1d2dd..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/main.go +++ /dev/null @@ -1,67 +0,0 @@ -package gumbleutil - -import ( - "crypto/tls" - "flag" - "fmt" - "os" - - "github.com/layeh/gumble/gumble" -) - -// Main aids in the creation of a basic command line gumble bot. It accepts the -// following flag arguments: --server, --username, --password, --insecure, -// --certificate, and --key. -// -// If init is non-nil, it is called before attempting to connect to the server. -func Main(init func(client *gumble.Client), listener gumble.EventListener) { - server := flag.String("server", "localhost:64738", "Mumble server address") - username := flag.String("username", "gumble-bot", "client username") - password := flag.String("password", "", "client password") - insecure := flag.Bool("insecure", false, "skip server certificate verification") - certificateFile := flag.String("certificate", "", "user certificate file (PEM)") - keyFile := flag.String("key", "", "user certificate key file (PEM)") - - if !flag.Parsed() { - flag.Parse() - } - - keepAlive := make(chan bool) - - // client - config := gumble.Config{ - Username: *username, - Password: *password, - Address: *server, - } - client := gumble.NewClient(&config) - if *insecure { - config.TLSConfig.InsecureSkipVerify = true - } - if *certificateFile != "" { - if *keyFile == "" { - keyFile = certificateFile - } - if certificate, err := tls.LoadX509KeyPair(*certificateFile, *keyFile); err != nil { - fmt.Printf("%s: %s\n", os.Args[0], err) - os.Exit(1) - } else { - config.TLSConfig.Certificates = append(config.TLSConfig.Certificates, certificate) - } - } - client.Attach(listener) - client.Attach(Listener{ - Disconnect: func(e *gumble.DisconnectEvent) { - keepAlive <- true - }, - }) - if init != nil { - init(client) - } - if err := client.Connect(); err != nil { - fmt.Printf("%s: %s\n", os.Args[0], err) - os.Exit(1) - } - - <-keepAlive -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/path.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/path.go deleted file mode 100644 index 6b60afa..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/path.go +++ /dev/null @@ -1,18 +0,0 @@ -package gumbleutil - -import ( - "github.com/layeh/gumble/gumble" -) - -// ChannelPath returns a slice of channel names, starting from the root channel -// to the given channel. -func ChannelPath(channel *gumble.Channel) []string { - var pieces []string - for ; channel != nil; channel = channel.Parent { - pieces = append(pieces, channel.Name) - } - for i := 0; i < (len(pieces) / 2); i++ { - pieces[len(pieces)-1-i], pieces[i] = pieces[i], pieces[len(pieces)-1-i] - } - return pieces -} diff --git a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/textmessage.go b/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/textmessage.go deleted file mode 100644 index 3c94b9c..0000000 --- a/Godeps/_workspace/src/github.com/layeh/gumble/gumbleutil/textmessage.go +++ /dev/null @@ -1,45 +0,0 @@ -package gumbleutil - -import ( - "bytes" - "encoding/xml" - "strings" - - "github.com/layeh/gumble/gumble" -) - -// PlainText returns the Message string without HTML tags or entities. -func PlainText(tm *gumble.TextMessage) string { - d := xml.NewDecoder(strings.NewReader(tm.Message)) - d.Strict = false - d.AutoClose = xml.HTMLAutoClose - d.Entity = xml.HTMLEntity - - var b bytes.Buffer - newline := false - for { - t, _ := d.Token() - if t == nil { - break - } - switch node := t.(type) { - case xml.CharData: - if len(node) > 0 { - b.Write(node) - newline = false - } - case xml.StartElement: - switch node.Name.Local { - case "address", "article", "aside", "audio", "blockquote", "canvas", "dd", "div", "dl", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "noscript", "ol", "output", "p", "pre", "section", "table", "tfoot", "ul", "video": - if !newline { - b.WriteByte('\n') - newline = true - } - case "br": - b.WriteByte('\n') - newline = true - } - } - } - return b.String() -} From acc55bad30f00aab17a32f232d137f7cf23507a2 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 18:52:44 +0100 Subject: [PATCH 138/297] Fixing build issues --- service_youtube.go | 1 - 1 file changed, 1 deletion(-) diff --git a/service_youtube.go b/service_youtube.go index aa8561c..a8c2b44 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -161,7 +161,6 @@ func (yt YouTube) NewSong(user, id, offset string, playlist Playlist) (Song, err title: title, id: id, offset: int((offsetDays * 86400) + (offsetHours * 3600) + (offsetMinutes * 60) + offsetSeconds), - filename: id + ".m4a", duration: durationString, thumbnail: thumbnail, skippers: make([]string, 0), From 068323e9b8cf4c6059dd4b7224dbd824f7501256 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 18:57:01 +0100 Subject: [PATCH 139/297] Fixing panic on launch --- main.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index f59a93c..d315ebc 100644 --- a/main.go +++ b/main.go @@ -253,11 +253,11 @@ func main() { if isNil(web) { Verbose("WEB IS NIL") } - - <-dj.keepAlive - + if test { Test(password, address, port) kill() } + + <-dj.keepAlive } From a48d10a1ccc5e62f0230589021904918c4a25e93 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 19:05:20 +0100 Subject: [PATCH 140/297] Fixed parseConfig.go to include new Web section --- config.gcfg | 2 +- parseconfig.go | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/config.gcfg b/config.gcfg index 02393e6..0e1e47a 100644 --- a/config.gcfg +++ b/config.gcfg @@ -162,7 +162,7 @@ AdminsEnabled = true # SYNTAX: In order to specify multiple admins, repeat the Admins="username" # line of code. Each line has one username, and an unlimited amount of usernames may # be entered in this matter. -Admins = "Matt" +Admins = "" # Make add an admin command? # DEFAULT VALUE: false diff --git a/parseconfig.go b/parseconfig.go index 4b4a16a..fcb80f6 100644 --- a/parseconfig.go +++ b/parseconfig.go @@ -33,6 +33,12 @@ type DjConfig struct { LowestVolume float32 HighestVolume float32 } + Web struct { + WebBrowser bool + WebPort int + WebAddress string + CustomWebPage bool + } Aliases struct { AddAlias string SkipAlias string From edba4d447a47de0a5f287b350dbc75e86934fc3f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 19:08:11 +0100 Subject: [PATCH 141/297] Put quotation marks around WebAddress string in config.gcfg --- config.gcfg | 2 +- parseconfig.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/config.gcfg b/config.gcfg index 0e1e47a..b88e838 100644 --- a/config.gcfg +++ b/config.gcfg @@ -68,7 +68,7 @@ WebPort: 9563 # Web address to provide links for # DEFAULT VALUE: http://{{IP}}:{{PORT}}/ -WebAddress: http://{{IP}}:{{PORT}}/ +WebAddress: "http://{{IP}}:{{PORT}}/" # Can users have their own web page # DEFAULT VALUE: false diff --git a/parseconfig.go b/parseconfig.go index fcb80f6..e308548 100644 --- a/parseconfig.go +++ b/parseconfig.go @@ -34,9 +34,9 @@ type DjConfig struct { HighestVolume float32 } Web struct { - WebBrowser bool - WebPort int - WebAddress string + WebBrowser bool + WebPort int + WebAddress string CustomWebPage bool } Aliases struct { From d1c3255ed9e0dce59c8d6df9afef2b9a7672e1d0 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 19:14:01 +0100 Subject: [PATCH 142/297] Deleted web section from config.gcfg until I can work out what went wrong --- config.gcfg | 18 ------------------ parseconfig.go | 6 ------ 2 files changed, 24 deletions(-) diff --git a/config.gcfg b/config.gcfg index b88e838..cf36a98 100644 --- a/config.gcfg +++ b/config.gcfg @@ -55,24 +55,6 @@ LowestVolume = 0.01 # DEFAULT VALUE: 0.8 HighestVolume = 0.8 - -[Web] - -# Enable web browser control -# DEFAULT VALUE: true -WebBrowser: true - -# Port for web browser, 80 provides links with no port -# DEFAULT VALUE: 9563 -WebPort: 9563 - -# Web address to provide links for -# DEFAULT VALUE: http://{{IP}}:{{PORT}}/ -WebAddress: "http://{{IP}}:{{PORT}}/" - -# Can users have their own web page -# DEFAULT VALUE: false -CustomWebPage: false [Aliases] diff --git a/parseconfig.go b/parseconfig.go index e308548..4b4a16a 100644 --- a/parseconfig.go +++ b/parseconfig.go @@ -33,12 +33,6 @@ type DjConfig struct { LowestVolume float32 HighestVolume float32 } - Web struct { - WebBrowser bool - WebPort int - WebAddress string - CustomWebPage bool - } Aliases struct { AddAlias string SkipAlias string From af9b4d840581136b2ec8b0e4b79a37eb7d37731c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 19:17:16 +0100 Subject: [PATCH 143/297] Trying to get tests to run --- .travis.yml | 2 +- main.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 16ee276..88a86ce 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,4 +21,4 @@ script: - make install after_success: - - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=travis -password=$MUMBLE_PASSWORD -test=true \ No newline at end of file + - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=travis -password=$MUMBLE_PASSWORD -verbose=true -test=true \ No newline at end of file diff --git a/main.go b/main.go index d315ebc..f59a93c 100644 --- a/main.go +++ b/main.go @@ -253,11 +253,11 @@ func main() { if isNil(web) { Verbose("WEB IS NIL") } - + + <-dj.keepAlive + if test { Test(password, address, port) kill() } - - <-dj.keepAlive } From 46820b68eae647c825e4dba63e8b6ba56fd779ca Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 19:29:58 +0100 Subject: [PATCH 144/297] Added more error messages --- commands.go | 6 +++++- service.go | 1 + service_soundcloud.go | 7 ++++++- service_youtube.go | 7 ++++++- test.go | 5 ++++- 5 files changed, 22 insertions(+), 4 deletions(-) diff --git a/commands.go b/commands.go index 5dde0c4..22121e2 100644 --- a/commands.go +++ b/commands.go @@ -171,7 +171,11 @@ func add(user *gumble.User, url string) error { dj.SendPrivateMessage(user, NO_ARGUMENT_MSG) return errors.New("NO_ARGUMENT") } else { - return findServiceAndAdd(user, url) + err := findServiceAndAdd(user, url) + if err != nil { + dj.SendPrivateMessage(user, err.Error()) + } + return err } } diff --git a/service.go b/service.go index a83ddba..15a5947 100644 --- a/service.go +++ b/service.go @@ -65,6 +65,7 @@ func findServiceAndAdd(user *gumble.User, url string) error { } if urlService == nil { + Verbose("Invalid_URL") return errors.New("INVALID_URL") } else { oldLength := dj.queue.Len() diff --git a/service_soundcloud.go b/service_soundcloud.go index 01def80..aa43e2f 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -58,7 +58,12 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { for _, t := range tracks { sc.NewSong(user.Name, jsonq.NewQuery(t), playlist) } - return playlist.Title(), err + if err == nil { + return playlist.Title(), nil + } else { + Verbose("soundcloud.NewRequest: " + err.Error()) + return nil, err + } } else { return "", errors.New("NO_PLAYLIST_PERMISSION") } diff --git a/service_youtube.go b/service_youtube.go index a8c2b44..ff1b9ec 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -73,7 +73,12 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { startOffset = matches[0][2] } song, err := yt.NewSong(user.Name, shortURL, startOffset, nil) - return song.Title(), err + if err == nil { + return song.Title(), nil + } else { + Verbose("youtube.NewRequest: " + err.Error()) + return nil, err + } } } else { return "", err diff --git a/test.go b/test.go index ba8067c..e5ae017 100644 --- a/test.go +++ b/test.go @@ -3,10 +3,11 @@ package main import ( "fmt" "github.com/layeh/gumble/gumble" + "time" ) func Test(password, ip, port string) { - + testYoutubeSong(password, ip, port) } func createClient(uname, password, ip, port string) *gumble.Client { @@ -40,6 +41,8 @@ func testYoutubeSong(password, ip, port string) { } else if dj.queue.CurrentSong().Title() != title { fmt.Printf("For: %s; Expected: %s; Got: %s", url, title, dj.queue.CurrentSong().Title()) } + + sleep(time.Second * 5) skip(dummyUser, false, false) } From d3407816111d60a895c174a9becb36393b11c408 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 19:31:12 +0100 Subject: [PATCH 145/297] Fixing build errors --- service_soundcloud.go | 2 +- service_youtube.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index aa43e2f..9784468 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -62,7 +62,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { return playlist.Title(), nil } else { Verbose("soundcloud.NewRequest: " + err.Error()) - return nil, err + return "", err } } else { return "", errors.New("NO_PLAYLIST_PERMISSION") diff --git a/service_youtube.go b/service_youtube.go index ff1b9ec..542baa0 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -77,7 +77,7 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { return song.Title(), nil } else { Verbose("youtube.NewRequest: " + err.Error()) - return nil, err + return "", err } } } else { From d494642e27f00ec467baeecf2f451b38cc7023da Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Mon, 10 Aug 2015 19:32:24 +0100 Subject: [PATCH 146/297] Fixing build errors --- test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test.go b/test.go index e5ae017..c9b40ec 100644 --- a/test.go +++ b/test.go @@ -42,7 +42,7 @@ func testYoutubeSong(password, ip, port string) { fmt.Printf("For: %s; Expected: %s; Got: %s", url, title, dj.queue.CurrentSong().Title()) } - sleep(time.Second * 5) + time.Sleep(time.Second * 5) skip(dummyUser, false, false) } From 2df36136361c1942e21b5517b1162f73b0c4f124 Mon Sep 17 00:00:00 2001 From: Connor Mahaffey Date: Wed, 12 Aug 2015 11:46:09 -0400 Subject: [PATCH 147/297] Fixed cache clearing earlier than expected By default, the date on a file downloaded by youtube-dl is the date the video was originally uploaded to youtube. As a result, items will always be cleared from the cache because they appear to be years old - even though they were just downloaded. Adding the directive "--no-mtime" will make the date on files the date the file was downloaded. See this issue on youtube-dl: https://github.com/rg3/youtube-dl/issues/4667 --- service_youtube.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_youtube.go b/service_youtube.go index b93b30a..450c2f0 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -140,7 +140,7 @@ func NewYouTubeSong(user, id, offset string, playlist *YouTubePlaylist) (*YouTub // All downloaded songs are stored in ~/.mumbledj/songs and should be automatically cleaned. func (s *YouTubeSong) Download() error { if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, s.Filename())); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, s.Filename()), "--format", "m4a", "--", s.ID()) + cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, s.Filename()), "--format", "m4a", "--", s.ID()) if err := cmd.Run(); err == nil { if dj.conf.Cache.Enabled { dj.cache.CheckMaximumDirectorySize() From f8a0940ae1c08f96e5ad4dd3f33c8d7877b631c2 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 19:19:28 +0100 Subject: [PATCH 148/297] Added circle.yml to build on circleci --- circle.yml | 27 +++++++++++++++++++++++++++ config.gcfg | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 circle.yml diff --git a/circle.yml b/circle.yml new file mode 100644 index 0000000..26ee0d9 --- /dev/null +++ b/circle.yml @@ -0,0 +1,27 @@ +machine: + golang: + version: + 1.4.2 + environment: + PATH: $PATH:$HOME/bin/ + LD_RUN_PATH: $LD_RUN_PATH:$HOME/opus/lib + LD_LIBRARY_PATH: $LD_LIBRARY_PATH:$HOME/opus/lib + PKG_CONFIG_PATH: $PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig + +dependencies: + pre: + - bash install-dependencies.sh + override: + - make + - make install + cache: + directories: + - $HOME/opus + - $HOME/bin + - $HOME/gopath/bin + - $HOME/gopath/pkg + - $HOME/gopath/src/github.com/nitrous-io + - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor +test: + override: + - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=travis -password=$MUMBLE_PASSWORD -verbose=true -test=true \ No newline at end of file diff --git a/config.gcfg b/config.gcfg index cf36a98..eea2750 100644 --- a/config.gcfg +++ b/config.gcfg @@ -144,7 +144,7 @@ AdminsEnabled = true # SYNTAX: In order to specify multiple admins, repeat the Admins="username" # line of code. Each line has one username, and an unlimited amount of usernames may # be entered in this matter. -Admins = "" +Admins = "BottleOToast" # Make add an admin command? # DEFAULT VALUE: false From 5f9e778ac193f6a4263e6817b66ca4a5e0c6b806 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 19:29:22 +0100 Subject: [PATCH 149/297] Modified circle.yml to make it work --- circle.yml | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/circle.yml b/circle.yml index 26ee0d9..baa1a4b 100644 --- a/circle.yml +++ b/circle.yml @@ -1,5 +1,5 @@ machine: - golang: + go: version: 1.4.2 environment: @@ -14,14 +14,14 @@ dependencies: override: - make - make install - cache: - directories: - - $HOME/opus - - $HOME/bin - - $HOME/gopath/bin - - $HOME/gopath/pkg - - $HOME/gopath/src/github.com/nitrous-io - - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor + cache_directories: + - $HOME/opus + - $HOME/bin + - $HOME/gopath/bin + - $HOME/gopath/pkg + - $HOME/gopath/src/github.com/nitrous-io + - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor test: override: - - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=travis -password=$MUMBLE_PASSWORD -verbose=true -test=true \ No newline at end of file + - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: + timeout: 180 \ No newline at end of file From dbc458379412c8a46bc13337484c79a081eb45ab Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 19:49:03 +0100 Subject: [PATCH 150/297] Trying to work out why music can not be downloaded --- circle.yml | 3 --- commands.go | 7 +++++++ test.go | 26 +++++++++++++++++++------- youtube_dl.go | 19 +++++++++---------- 4 files changed, 35 insertions(+), 20 deletions(-) diff --git a/circle.yml b/circle.yml index baa1a4b..fa81c7e 100644 --- a/circle.yml +++ b/circle.yml @@ -1,7 +1,4 @@ machine: - go: - version: - 1.4.2 environment: PATH: $PATH:$HOME/bin/ LD_RUN_PATH: $LD_RUN_PATH:$HOME/opus/lib diff --git a/commands.go b/commands.go index 22121e2..5dc19b7 100644 --- a/commands.go +++ b/commands.go @@ -159,6 +159,13 @@ func parseCommand(user *gumble.User, username, command string) { } else { dj.SendPrivateMessage(user, NO_PERMISSION_MSG) } + // Test command (WORKAROUND) + case "test": + if dj.HasPermission(username, dj.conf.Permissions.AdminKill) && test != nil { + test.testYoutubeSong() + } else { + dj.SendPrivateMessage(user, NO_PERMISSION_MSG) + } default: dj.SendPrivateMessage(user, COMMAND_DOESNT_EXIST_MSG) } diff --git a/test.go b/test.go index c9b40ec..8b41a8a 100644 --- a/test.go +++ b/test.go @@ -6,19 +6,31 @@ import ( "time" ) -func Test(password, ip, port string) { - testYoutubeSong(password, ip, port) +type Test struct { + password string + ip string + port string } -func createClient(uname, password, ip, port string) *gumble.Client { +var test Test + +func Test(password, ip, port string) { + test = Test{ + password: password, + ip: ip, + port: port, + } +} + +func (t Test) createClient(uname) *gumble.Client { return gumble.NewClient(&gumble.Config{ Username: uname, - Password: password, - Address: ip + ":" + port}) + Password: t.password, + Address: t.ip + ":" + t.port}) } -func testYoutubeSong(password, ip, port string) { - dummyClient := createClient("dummy", password, ip, port) +func (t Test) testYoutubeSong() { + dummyClient := t.createClient("dummy") dummyClient.Connect() dummyUser := dj.client.Users.Find("dummy") diff --git a/youtube_dl.go b/youtube_dl.go index b7afff2..a661df4 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -38,14 +38,15 @@ type YouTubeDLPlaylist struct { func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded - if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.id+".m4a")); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, dl.id+".m4a"), "--format", "m4a", "--", dl.url) + if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { + cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, dl.Filename()), "--format", "m4a", dl.url) if err := cmd.Run(); err == nil { if dj.conf.Cache.Enabled { dj.cache.CheckMaximumDirectorySize() } return nil } + Verbose("youtube-dl: " + err.Error()) return errors.New("Song download failed.") } return nil @@ -58,18 +59,16 @@ func (dl *YouTubeDLSong) Play() { offsetDuration, _ := time.ParseDuration(fmt.Sprintf("%ds", dl.offset)) dj.audioStream.Offset = offsetDuration } - dj.audioStream.Source = gumble_ffmpeg.SourceFile(fmt.Sprintf("%s/.mumbledj/songs/%s.m4a", dj.homeDir, dl.id)) + dj.audioStream.Source = gumble_ffmpeg.SourceFile(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())) if err := dj.audioStream.Play(); err != nil { panic(err) } else { - message := `` + message := `
%s (%s)
Added by %s
` message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.duration, dl.submitter) - if isNil(dl.playlist) { - dj.client.Self.Channel.Send(message+`
%s (%s)
Added by %s
`, false) - } else { - message += `From playlist "%s"` - dj.client.Self.Channel.Send(fmt.Sprintf(message, dl.playlist.Title()), false) + if !isNil(dl.playlist) { + message = fmt.Sprintf(message+`From playlist "%s"`, dl.playlist.Title()) } + dj.client.Self.Channel.Send(message+``, false) Verbose("Now playing " + dl.title) go func() { @@ -82,7 +81,7 @@ func (dl *YouTubeDLSong) Play() { // Delete deletes the song from ~/.mumbledj/songs if the cache is disabled. func (dl *YouTubeDLSong) Delete() error { if dj.conf.Cache.Enabled == false { - filePath := fmt.Sprintf("%s/.mumbledj/songs/%s.m4a", dj.homeDir, dl.id) + filePath := fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()) if _, err := os.Stat(filePath); err == nil { if err := os.Remove(filePath); err == nil { return nil From 43f412e722d11d05cedcd2b2abc02d3c47a559fd Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 19:52:38 +0100 Subject: [PATCH 151/297] Fixing build errors --- test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test.go b/test.go index 8b41a8a..de8813e 100644 --- a/test.go +++ b/test.go @@ -6,30 +6,30 @@ import ( "time" ) -type Test struct { +type TestSettings struct { password string ip string port string } -var test Test +var test TestSettings func Test(password, ip, port string) { - test = Test{ + test = TestSettings{ password: password, ip: ip, port: port, } } -func (t Test) createClient(uname) *gumble.Client { +func (t TestSettings) createClient(uname string) *gumble.Client { return gumble.NewClient(&gumble.Config{ Username: uname, Password: t.password, Address: t.ip + ":" + t.port}) } -func (t Test) testYoutubeSong() { +func (t TestSettings) testYoutubeSong() { dummyClient := t.createClient("dummy") dummyClient.Connect() dummyUser := dj.client.Users.Find("dummy") From 77723f494191787db2ea090f01754006f41e1908 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 19:54:56 +0100 Subject: [PATCH 152/297] Fixing build errors --- circle.yml | 12 ++++++------ commands.go | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/circle.yml b/circle.yml index fa81c7e..937a4af 100644 --- a/circle.yml +++ b/circle.yml @@ -12,12 +12,12 @@ dependencies: - make - make install cache_directories: - - $HOME/opus - - $HOME/bin - - $HOME/gopath/bin - - $HOME/gopath/pkg - - $HOME/gopath/src/github.com/nitrous-io - - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor + - "$HOME/opus" + - "$HOME/bin" + - "$HOME/gopath/bin" + - "$HOME/gopath/pkg" + - "$HOME/gopath/src/github.com/nitrous-io" + - "$HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor" test: override: - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: diff --git a/commands.go b/commands.go index 5dc19b7..e0413cc 100644 --- a/commands.go +++ b/commands.go @@ -161,7 +161,7 @@ func parseCommand(user *gumble.User, username, command string) { } // Test command (WORKAROUND) case "test": - if dj.HasPermission(username, dj.conf.Permissions.AdminKill) && test != nil { + if dj.HasPermission(username, dj.conf.Permissions.AdminKill) { test.testYoutubeSong() } else { dj.SendPrivateMessage(user, NO_PERMISSION_MSG) From fb16dc1db329b80a3b3a97f6f92643bbd06af219 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 20:23:51 +0100 Subject: [PATCH 153/297] Fixing build errors --- circle.yml | 12 ++++++------ main.go | 15 ++++++++------- test.go | 3 ++- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/circle.yml b/circle.yml index 937a4af..09d7ee0 100644 --- a/circle.yml +++ b/circle.yml @@ -12,12 +12,12 @@ dependencies: - make - make install cache_directories: - - "$HOME/opus" - - "$HOME/bin" - - "$HOME/gopath/bin" - - "$HOME/gopath/pkg" - - "$HOME/gopath/src/github.com/nitrous-io" - - "$HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor" + - "opus" + - "bin" + - "gopath/bin" + - "gopath/pkg" + - "gopath/src/github.com/nitrous-io" + - "gopath/src/github.com/MichaelOultram/mumbledj/.vendor" test: override: - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: diff --git a/main.go b/main.go index f59a93c..9151d79 100644 --- a/main.go +++ b/main.go @@ -193,7 +193,7 @@ func main() { } var address, port, username, password, channel, pemCert, pemKey, accesstokens string - var insecure, verbose, test bool + var insecure, verbose, testcode bool flag.StringVar(&address, "server", "localhost", "address for Mumble server") flag.StringVar(&port, "port", "64738", "port for Mumble server") @@ -205,7 +205,7 @@ func main() { flag.StringVar(&accesstokens, "accesstokens", "", "list of access tokens for channel auth") flag.BoolVar(&insecure, "insecure", false, "skip certificate checking") flag.BoolVar(&verbose, "verbose", false, "[debug] prints out debug messages to the console") - flag.BoolVar(&test, "test", false, "[debug] tests the features of mumbledj") + flag.BoolVar(&testcode, "test", false, "[debug] tests the features of mumbledj") flag.Parse() dj.config = gumble.Config{ @@ -247,6 +247,12 @@ func main() { os.Exit(1) } + if testcode { + Verbose("Testing is enabled") + Test(password, address, port) + kill() + } + web = NewWebServer(9563) web.makeWeb() @@ -255,9 +261,4 @@ func main() { } <-dj.keepAlive - - if test { - Test(password, address, port) - kill() - } } diff --git a/test.go b/test.go index de8813e..4dcb63b 100644 --- a/test.go +++ b/test.go @@ -32,7 +32,8 @@ func (t TestSettings) createClient(uname string) *gumble.Client { func (t TestSettings) testYoutubeSong() { dummyClient := t.createClient("dummy") dummyClient.Connect() - dummyUser := dj.client.Users.Find("dummy") + time.Sleep(time.Second * 5) // Give dummy time to connect + dummyUser := dj.client.Users.Find("dummy") // May be nil // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist songs := map[string]string{ From d9527a40937b976fc7b71ebcc3dd0a3b055e7e93 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 20:26:27 +0100 Subject: [PATCH 154/297] Getting tests to run --- main.go | 1 - test.go | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/main.go b/main.go index 9151d79..a26aad8 100644 --- a/main.go +++ b/main.go @@ -250,7 +250,6 @@ func main() { if testcode { Verbose("Testing is enabled") Test(password, address, port) - kill() } web = NewWebServer(9563) diff --git a/test.go b/test.go index 4dcb63b..f1a8284 100644 --- a/test.go +++ b/test.go @@ -20,6 +20,7 @@ func Test(password, ip, port string) { ip: ip, port: port, } + test.testYoutubeSong() } func (t TestSettings) createClient(uname string) *gumble.Client { From c6c58c4d1131daa024b4ac4126a12574a766a4e1 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 20:31:12 +0100 Subject: [PATCH 155/297] Trying to work out why dummy won't connect --- main.go | 2 +- test.go | 22 +++++++++++++--------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/main.go b/main.go index a26aad8..ba758c4 100644 --- a/main.go +++ b/main.go @@ -249,7 +249,7 @@ func main() { if testcode { Verbose("Testing is enabled") - Test(password, address, port) + Test(password, address, port, accesstokens) } web = NewWebServer(9563) diff --git a/test.go b/test.go index f1a8284..39201e7 100644 --- a/test.go +++ b/test.go @@ -7,18 +7,20 @@ import ( ) type TestSettings struct { - password string - ip string - port string + password string + ip string + port string + accesstokens []string } var test TestSettings -func Test(password, ip, port string) { +func Test(password, ip, port, accesstokens string) { test = TestSettings{ - password: password, - ip: ip, - port: port, + password: password, + ip: ip, + port: port, + accesstokens: strings.Split(accesstokens, " "), } test.testYoutubeSong() } @@ -27,13 +29,15 @@ func (t TestSettings) createClient(uname string) *gumble.Client { return gumble.NewClient(&gumble.Config{ Username: uname, Password: t.password, - Address: t.ip + ":" + t.port}) + Address: t.ip + ":" + t.port, + Tokens: t.accesstokens, + }) } func (t TestSettings) testYoutubeSong() { dummyClient := t.createClient("dummy") dummyClient.Connect() - time.Sleep(time.Second * 5) // Give dummy time to connect + time.Sleep(time.Second * 5) // Give dummy time to connect dummyUser := dj.client.Users.Find("dummy") // May be nil // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist From 5fcec92929e571f6b06b5ca4bb39e8c3dfd0aca7 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 20:34:32 +0100 Subject: [PATCH 156/297] Trying to work out why dummy won't connect --- circle.yml | 12 ++++++------ main.go | 2 +- test.go | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/circle.yml b/circle.yml index 09d7ee0..b2ab77f 100644 --- a/circle.yml +++ b/circle.yml @@ -12,12 +12,12 @@ dependencies: - make - make install cache_directories: - - "opus" - - "bin" - - "gopath/bin" - - "gopath/pkg" - - "gopath/src/github.com/nitrous-io" - - "gopath/src/github.com/MichaelOultram/mumbledj/.vendor" + - "~/opus" + - "~/bin" + - "~/gopath/bin" + - "~/gopath/pkg" + - "~/gopath/src/github.com/nitrous-io" + - "~/gopath/src/github.com/MichaelOultram/mumbledj/.vendor" test: override: - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: diff --git a/main.go b/main.go index ba758c4..3a2ae5f 100644 --- a/main.go +++ b/main.go @@ -249,7 +249,7 @@ func main() { if testcode { Verbose("Testing is enabled") - Test(password, address, port, accesstokens) + Test(password, address, port, strings.Split(accesstokens, " ")) } web = NewWebServer(9563) diff --git a/test.go b/test.go index 39201e7..01b4915 100644 --- a/test.go +++ b/test.go @@ -15,12 +15,12 @@ type TestSettings struct { var test TestSettings -func Test(password, ip, port, accesstokens string) { +func Test(password, ip, port string, accesstokens []string) { test = TestSettings{ password: password, ip: ip, port: port, - accesstokens: strings.Split(accesstokens, " "), + accesstokens: accesstokens, } test.testYoutubeSong() } From ee8578119fac91fbcca701f1aea797abab44dfb0 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 20:39:49 +0100 Subject: [PATCH 157/297] Fixing build errors --- circle.yml | 8 ++++---- test.go | 5 +++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/circle.yml b/circle.yml index b2ab77f..f60f592 100644 --- a/circle.yml +++ b/circle.yml @@ -14,10 +14,10 @@ dependencies: cache_directories: - "~/opus" - "~/bin" - - "~/gopath/bin" - - "~/gopath/pkg" - - "~/gopath/src/github.com/nitrous-io" - - "~/gopath/src/github.com/MichaelOultram/mumbledj/.vendor" + - "/usr/local/go/bin" + - "/usr/local/go/pkg" + - "/usr/local/go/src/github.com/nitrous-io" + - "~/.vendor" test: override: - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: diff --git a/test.go b/test.go index 01b4915..8574e79 100644 --- a/test.go +++ b/test.go @@ -36,8 +36,9 @@ func (t TestSettings) createClient(uname string) *gumble.Client { func (t TestSettings) testYoutubeSong() { dummyClient := t.createClient("dummy") - dummyClient.Connect() - time.Sleep(time.Second * 5) // Give dummy time to connect + if err := dummyClient.Connect(); err != nil { + panic(err) + } dummyUser := dj.client.Users.Find("dummy") // May be nil // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist From 48377ece099302bda1bce2e000363da35142fe1f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 20:46:32 +0100 Subject: [PATCH 158/297] Fixing build errors --- test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test.go b/test.go index 8574e79..f3f3c56 100644 --- a/test.go +++ b/test.go @@ -3,6 +3,7 @@ package main import ( "fmt" "github.com/layeh/gumble/gumble" + "github.com/layeh/gumble/gumbleutil" "time" ) @@ -26,12 +27,14 @@ func Test(password, ip, port string, accesstokens []string) { } func (t TestSettings) createClient(uname string) *gumble.Client { - return gumble.NewClient(&gumble.Config{ + client := gumble.NewClient(&gumble.Config{ Username: uname, Password: t.password, Address: t.ip + ":" + t.port, Tokens: t.accesstokens, }) + gumbleutil.CertificateLockFile(client, fmt.Sprintf("%s/.mumbledj/cert.lock", dj.homeDir)) + return client } func (t TestSettings) testYoutubeSong() { From ab95cfb9bcde614f61e7cf057cc2d662e6d20637 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 20:52:20 +0100 Subject: [PATCH 159/297] Fixing build errors --- test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test.go b/test.go index f3f3c56..20a9d3a 100644 --- a/test.go +++ b/test.go @@ -38,11 +38,11 @@ func (t TestSettings) createClient(uname string) *gumble.Client { } func (t TestSettings) testYoutubeSong() { - dummyClient := t.createClient("dummy") - if err := dummyClient.Connect(); err != nil { - panic(err) - } - dummyUser := dj.client.Users.Find("dummy") // May be nil +// dummyClient := t.createClient("dummy") +// if err := dummyClient.Connect(); err != nil { +// panic(err) +// } + dummyUser := dj.client.Users.Find("BottleOToast") // May be nil // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist songs := map[string]string{ From 14aebb85d3ae6ca9723db44af325dde79ed9e880 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 20:53:44 +0100 Subject: [PATCH 160/297] Fixing build errors --- circle.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/circle.yml b/circle.yml index f60f592..7e326b2 100644 --- a/circle.yml +++ b/circle.yml @@ -15,7 +15,6 @@ dependencies: - "~/opus" - "~/bin" - "/usr/local/go/bin" - - "/usr/local/go/pkg" - "/usr/local/go/src/github.com/nitrous-io" - "~/.vendor" test: From f8d9100e93821f68e4aa79da4fbe4d623235172e Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 20:56:01 +0100 Subject: [PATCH 161/297] Fixing build errors --- test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test.go b/test.go index 20a9d3a..76b9b15 100644 --- a/test.go +++ b/test.go @@ -38,10 +38,10 @@ func (t TestSettings) createClient(uname string) *gumble.Client { } func (t TestSettings) testYoutubeSong() { -// dummyClient := t.createClient("dummy") -// if err := dummyClient.Connect(); err != nil { -// panic(err) -// } + // dummyClient := t.createClient("dummy") + // if err := dummyClient.Connect(); err != nil { + // panic(err) + // } dummyUser := dj.client.Users.Find("BottleOToast") // May be nil // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist @@ -68,5 +68,5 @@ func (t TestSettings) testYoutubeSong() { skip(dummyUser, false, false) } - dummyClient.Disconnect() + //dummyClient.Disconnect() } From a5fd3459591cbb2ea5fad52175d919d9f4b81a5b Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 21:22:55 +0100 Subject: [PATCH 162/297] Fixing build errors --- test.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test.go b/test.go index 76b9b15..4c989c1 100644 --- a/test.go +++ b/test.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/layeh/gumble/gumble" "github.com/layeh/gumble/gumbleutil" + "os" "time" ) @@ -42,7 +43,10 @@ func (t TestSettings) testYoutubeSong() { // if err := dummyClient.Connect(); err != nil { // panic(err) // } - dummyUser := dj.client.Users.Find("BottleOToast") // May be nil + if dummyUser := dj.client.Users.Find("BottleOToast"); dummyUser == nil { + fmt.Printf("User does not exist") + os.Exit(1) + } // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist songs := map[string]string{ From aaa4694980cc38a75665835e55c78fca0450b792 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 21:28:54 +0100 Subject: [PATCH 163/297] Fixing build errors --- circle.yml | 4 ++-- test.go | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/circle.yml b/circle.yml index 7e326b2..02c2058 100644 --- a/circle.yml +++ b/circle.yml @@ -14,9 +14,9 @@ dependencies: cache_directories: - "~/opus" - "~/bin" - - "/usr/local/go/bin" - - "/usr/local/go/src/github.com/nitrous-io" + - "$(GOPATH)/src/github.com/nitrous-io" - "~/.vendor" + - "$(GOPATH)/bin/goop" test: override: - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: diff --git a/test.go b/test.go index 4c989c1..7a3c81f 100644 --- a/test.go +++ b/test.go @@ -43,7 +43,8 @@ func (t TestSettings) testYoutubeSong() { // if err := dummyClient.Connect(); err != nil { // panic(err) // } - if dummyUser := dj.client.Users.Find("BottleOToast"); dummyUser == nil { + dummyUser := dj.client.Users.Find("BottleOToast") + if dummyUser == nil { fmt.Printf("User does not exist") os.Exit(1) } From 16ae6685c188fe5b919b3014b409408ab6a56d72 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 21:34:03 +0100 Subject: [PATCH 164/297] Changed how things are cached on circleci --- circle.yml | 3 +-- install-dependencies.sh | 12 +++++++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/circle.yml b/circle.yml index 02c2058..203f232 100644 --- a/circle.yml +++ b/circle.yml @@ -14,9 +14,8 @@ dependencies: cache_directories: - "~/opus" - "~/bin" - - "$(GOPATH)/src/github.com/nitrous-io" - "~/.vendor" - - "$(GOPATH)/bin/goop" + - "$(GOPATH)/src/github.com/nitrous-io" test: override: - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: diff --git a/install-dependencies.sh b/install-dependencies.sh index 6bf067a..4c9c3a8 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -3,6 +3,7 @@ set -e # check to see if ffmpeg is installed if [ ! -f "$HOME/bin/ffmpeg" ]; then + echo 'Installing ffmpeg' wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe chmod a+rx ffmpeg ffprobe @@ -13,6 +14,7 @@ fi # check to see if opus is installed if [ ! -d "$HOME/opus/lib" ]; then + echo 'Installing opus' wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz tar xzvf opus-1.0.3.tar.gz cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install @@ -22,10 +24,18 @@ fi # check to see if youtube-dl is installed if [ ! -f "$HOME/bin/youtube-dl" ]; then + echo 'Installing youtube-dl' curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o ~/bin/youtube-dl chmod a+rx ~/bin/youtube-dl else echo 'Using cached version of youtube-dl.'; fi -ls -lR $HOME/opus \ No newline at end of file +# check to see if goop is installed +if [ ! -f "$HOME/bin/goop" ]; then + echo 'Installing goop' + go get github.com/nitrous-io/goop + mv $GOPATH/bin/goop ~/goop +else + echo 'Using cached version of goop.'; +fi \ No newline at end of file From 373d87b556e4d0ee81cdae732418e3a657ef5dd8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 21:35:58 +0100 Subject: [PATCH 165/297] Changed how things are cached on circleci --- install-dependencies.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install-dependencies.sh b/install-dependencies.sh index 4c9c3a8..78ffafc 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -35,7 +35,7 @@ fi if [ ! -f "$HOME/bin/goop" ]; then echo 'Installing goop' go get github.com/nitrous-io/goop - mv $GOPATH/bin/goop ~/goop + mv "$GOPATH/bin/goop" "~/bin/goop" else echo 'Using cached version of goop.'; fi \ No newline at end of file From 7f1182815357789dd6997e47e1334c7a71e6d3ce Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 21:39:48 +0100 Subject: [PATCH 166/297] Changed how things are cached on circleci --- install-dependencies.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install-dependencies.sh b/install-dependencies.sh index 78ffafc..86942eb 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -35,7 +35,7 @@ fi if [ ! -f "$HOME/bin/goop" ]; then echo 'Installing goop' go get github.com/nitrous-io/goop - mv "$GOPATH/bin/goop" "~/bin/goop" + mv "/usr/local/bin/goop" "~/bin/goop" else echo 'Using cached version of goop.'; fi \ No newline at end of file From 11544fae216e13aa1cf29bd9ffc77b4c0be86e80 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 21:42:17 +0100 Subject: [PATCH 167/297] Changed how things are cached on circleci --- install-dependencies.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/install-dependencies.sh b/install-dependencies.sh index 86942eb..63668b9 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -1,6 +1,9 @@ #!/bin/sh set -e +echo "Gopath: $GOPATH" +ls -lR $GOPATH + # check to see if ffmpeg is installed if [ ! -f "$HOME/bin/ffmpeg" ]; then echo 'Installing ffmpeg' From 02b46e6a9640ac978a33e50008d605d392195ccc Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 21:44:04 +0100 Subject: [PATCH 168/297] Changed how things are cached on circleci --- circle.yml | 4 +++- install-dependencies.sh | 12 ------------ 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/circle.yml b/circle.yml index 203f232..26bda34 100644 --- a/circle.yml +++ b/circle.yml @@ -15,7 +15,9 @@ dependencies: - "~/opus" - "~/bin" - "~/.vendor" - - "$(GOPATH)/src/github.com/nitrous-io" + - "/home/ubuntu/.go_workspace/bin" + - "/home/ubuntu/.go_workspace/pkg" + - "/home/ubuntu/.go_workspace/src/github.com/nitrous-io" test: override: - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: diff --git a/install-dependencies.sh b/install-dependencies.sh index 63668b9..a03870b 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -1,9 +1,6 @@ #!/bin/sh set -e -echo "Gopath: $GOPATH" -ls -lR $GOPATH - # check to see if ffmpeg is installed if [ ! -f "$HOME/bin/ffmpeg" ]; then echo 'Installing ffmpeg' @@ -32,13 +29,4 @@ if [ ! -f "$HOME/bin/youtube-dl" ]; then chmod a+rx ~/bin/youtube-dl else echo 'Using cached version of youtube-dl.'; -fi - -# check to see if goop is installed -if [ ! -f "$HOME/bin/goop" ]; then - echo 'Installing goop' - go get github.com/nitrous-io/goop - mv "/usr/local/bin/goop" "~/bin/goop" -else - echo 'Using cached version of goop.'; fi \ No newline at end of file From 13fc08ad6946cc0c7be91725d8b9df8719cfd2df Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 21:46:58 +0100 Subject: [PATCH 169/297] Trying to work out why it cannot find user --- test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test.go b/test.go index 7a3c81f..d2ee80e 100644 --- a/test.go +++ b/test.go @@ -43,7 +43,7 @@ func (t TestSettings) testYoutubeSong() { // if err := dummyClient.Connect(); err != nil { // panic(err) // } - dummyUser := dj.client.Users.Find("BottleOToast") + dummyUser := dj.client.Users.Find("bottleotoast") if dummyUser == nil { fmt.Printf("User does not exist") os.Exit(1) From 4ae529de85e77e8d811f2e6ff2a839393bee42fa Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 21:51:47 +0100 Subject: [PATCH 170/297] Trying to work out why it cannot find user --- test.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test.go b/test.go index d2ee80e..5eb6697 100644 --- a/test.go +++ b/test.go @@ -45,7 +45,11 @@ func (t TestSettings) testYoutubeSong() { // } dummyUser := dj.client.Users.Find("bottleotoast") if dummyUser == nil { - fmt.Printf("User does not exist") + fmt.Printf("User does not exist, printing users\n") + for _, user := range dj.client.Users { + fmt.Printf(user.Name + "\n") + } + fmt.Printf("End of user list\n") os.Exit(1) } From 945974670c307ade03ec906bbfac925ce623088a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 21:59:15 +0100 Subject: [PATCH 171/297] Added request for user list --- test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test.go b/test.go index 5eb6697..3acb89b 100644 --- a/test.go +++ b/test.go @@ -43,7 +43,8 @@ func (t TestSettings) testYoutubeSong() { // if err := dummyClient.Connect(); err != nil { // panic(err) // } - dummyUser := dj.client.Users.Find("bottleotoast") + dj.client.Request(gumble.Request.RequestUserList) + dummyUser := dj.client.Users.Find("BottleOToast") if dummyUser == nil { fmt.Printf("User does not exist, printing users\n") for _, user := range dj.client.Users { From b0d3f78ee4028a991d234ce74d5be4c20bb3a2ec Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:01:34 +0100 Subject: [PATCH 172/297] Fixing build issues --- test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test.go b/test.go index 3acb89b..4697308 100644 --- a/test.go +++ b/test.go @@ -43,7 +43,7 @@ func (t TestSettings) testYoutubeSong() { // if err := dummyClient.Connect(); err != nil { // panic(err) // } - dj.client.Request(gumble.Request.RequestUserList) + dj.client.Request(gumble.RequestUserList) dummyUser := dj.client.Users.Find("BottleOToast") if dummyUser == nil { fmt.Printf("User does not exist, printing users\n") From 83c0857f4357034f57adb4473d1ee1e02d29d08c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:06:03 +0100 Subject: [PATCH 173/297] Fixing build issues --- circle.yml | 2 +- test.go | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 26bda34..7cb9265 100644 --- a/circle.yml +++ b/circle.yml @@ -14,7 +14,7 @@ dependencies: cache_directories: - "~/opus" - "~/bin" - - "~/.vendor" + - "~/mumbledj/.vendor" - "/home/ubuntu/.go_workspace/bin" - "/home/ubuntu/.go_workspace/pkg" - "/home/ubuntu/.go_workspace/src/github.com/nitrous-io" diff --git a/test.go b/test.go index 4697308..d56813e 100644 --- a/test.go +++ b/test.go @@ -43,7 +43,9 @@ func (t TestSettings) testYoutubeSong() { // if err := dummyClient.Connect(); err != nil { // panic(err) // } + dj.client.Request(gumble.RequestUserList) + time.Sleep(time.Second * 5) dummyUser := dj.client.Users.Find("BottleOToast") if dummyUser == nil { fmt.Printf("User does not exist, printing users\n") From 4955a806fa65b845f63c847add299b9c55ca9d05 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:18:22 +0100 Subject: [PATCH 174/297] Fixing issue downloading songs --- test.go | 4 ++-- youtube_dl.go | 8 +++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/test.go b/test.go index d56813e..fcc1857 100644 --- a/test.go +++ b/test.go @@ -71,9 +71,9 @@ func (t TestSettings) testYoutubeSong() { for url, title := range songs { err := add(dummyUser, url) if err != nil { - fmt.Printf("For: %s; Expected: %s; Got: %s", url, title, err.Error()) + fmt.Printf("For: %s; Expected: %s; Got: %s\n", url, title, err.Error()) } else if dj.queue.CurrentSong().Title() != title { - fmt.Printf("For: %s; Expected: %s; Got: %s", url, title, dj.queue.CurrentSong().Title()) + fmt.Printf("For: %s; Expected: %s; Got: %s\n", url, title, dj.queue.CurrentSong().Title()) } time.Sleep(time.Second * 5) diff --git a/youtube_dl.go b/youtube_dl.go index a661df4..3d6b8ad 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -40,14 +40,16 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, dl.Filename()), "--format", "m4a", dl.url) - if err := cmd.Run(); err == nil { + err = cmd.Run() + if err == nil { if dj.conf.Cache.Enabled { dj.cache.CheckMaximumDirectorySize() } return nil + } else { + Verbose("youtube-dl: " + err.Error()) + return errors.New("Song download failed.") } - Verbose("youtube-dl: " + err.Error()) - return errors.New("Song download failed.") } return nil } From 06cc7056d0e2eec1a5f3fa3174b48ad84e31cf07 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:26:25 +0100 Subject: [PATCH 175/297] Fixing issue downloading songs --- circle.yml | 1 + youtube_dl.go | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 7cb9265..6051378 100644 --- a/circle.yml +++ b/circle.yml @@ -20,5 +20,6 @@ dependencies: - "/home/ubuntu/.go_workspace/src/github.com/nitrous-io" test: override: + - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: timeout: 180 \ No newline at end of file diff --git a/youtube_dl.go b/youtube_dl.go index 3d6b8ad..57c6957 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -39,7 +39,7 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, dl.Filename()), "--format", "m4a", dl.url) + cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", dl.url) err = cmd.Run() if err == nil { if dj.conf.Cache.Enabled { From cc32db2688f8d7a07d44febc2a22e2011209cc3e Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:29:46 +0100 Subject: [PATCH 176/297] Fixing issue downloading songs --- circle.yml | 2 +- youtube_dl.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/circle.yml b/circle.yml index 6051378..4c2b6c4 100644 --- a/circle.yml +++ b/circle.yml @@ -20,6 +20,6 @@ dependencies: - "/home/ubuntu/.go_workspace/src/github.com/nitrous-io" test: override: - - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a http://www.youtube.com/watch?v=QcIy9NiNbmo + - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: timeout: 180 \ No newline at end of file diff --git a/youtube_dl.go b/youtube_dl.go index 57c6957..83a120c 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -39,7 +39,7 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", dl.url) + cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", dl.url) err = cmd.Run() if err == nil { if dj.conf.Cache.Enabled { From 82d2faa1a4d0e12b4a37af3098db6d39689f7566 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:33:08 +0100 Subject: [PATCH 177/297] Fixing issue downloading songs --- circle.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/circle.yml b/circle.yml index 4c2b6c4..3c44885 100644 --- a/circle.yml +++ b/circle.yml @@ -7,10 +7,13 @@ machine: dependencies: pre: + - sudo apt-get update; sudo apt-get upgrade - bash install-dependencies.sh + override: - make - make install + cache_directories: - "~/opus" - "~/bin" @@ -18,6 +21,7 @@ dependencies: - "/home/ubuntu/.go_workspace/bin" - "/home/ubuntu/.go_workspace/pkg" - "/home/ubuntu/.go_workspace/src/github.com/nitrous-io" + test: override: - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg http://www.youtube.com/watch?v=QcIy9NiNbmo From 41a2b587f6cffbd304935d9c19ba7648e2baf646 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:35:21 +0100 Subject: [PATCH 178/297] Fixing issue downloading songs --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 3c44885..d8a5af7 100644 --- a/circle.yml +++ b/circle.yml @@ -7,7 +7,7 @@ machine: dependencies: pre: - - sudo apt-get update; sudo apt-get upgrade + - sudo apt-get remove -y ffmpeg - bash install-dependencies.sh override: From 9d80bcd1f664ce51386b00dca1acadafb250cba8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:38:10 +0100 Subject: [PATCH 179/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/circle.yml b/circle.yml index d8a5af7..af8cb2c 100644 --- a/circle.yml +++ b/circle.yml @@ -24,6 +24,7 @@ dependencies: test: override: + - ffmpeg -version - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: timeout: 180 \ No newline at end of file From 82f00aaf130c71bc2cdb1107803d1f100c60894d Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:46:09 +0100 Subject: [PATCH 180/297] Fixing issue with youtube-dl and ffmpeg --- test.go | 1 + youtube_dl.go | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/test.go b/test.go index fcc1857..2258187 100644 --- a/test.go +++ b/test.go @@ -80,5 +80,6 @@ func (t TestSettings) testYoutubeSong() { skip(dummyUser, false, false) } + os.Exit(0) //dummyClient.Disconnect() } diff --git a/youtube_dl.go b/youtube_dl.go index 83a120c..cb1ce8d 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -39,7 +39,7 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", dl.url) + cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", "--", dl.ID()) err = cmd.Run() if err == nil { if dj.conf.Cache.Enabled { From e45a3e1a9bb7052a4e370a9622e87f406992292f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:51:18 +0100 Subject: [PATCH 181/297] Fixing issue with youtube-dl and ffmpeg --- youtube_dl.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/youtube_dl.go b/youtube_dl.go index cb1ce8d..9c02206 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -48,6 +48,9 @@ func (dl *YouTubeDLSong) Download() error { return nil } else { Verbose("youtube-dl: " + err.Error()) + for s := range cmd.Args { + Verbose("youtube-dl args: " + s) + } return errors.New("Song download failed.") } } From 4e9e303cb85cca32ea22eb1b098c5b0dc03c273a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:52:41 +0100 Subject: [PATCH 182/297] Fixing issue with youtube-dl and ffmpeg --- youtube_dl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/youtube_dl.go b/youtube_dl.go index 9c02206..fedfc28 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -49,7 +49,7 @@ func (dl *YouTubeDLSong) Download() error { } else { Verbose("youtube-dl: " + err.Error()) for s := range cmd.Args { - Verbose("youtube-dl args: " + s) + Verbose("youtube-dl args: " + cmd.Args[s]) } return errors.New("Song download failed.") } From 3f0a5ae6f9922a8d90a8445e016fa98684124bf1 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 22:59:01 +0100 Subject: [PATCH 183/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index af8cb2c..e5d0b0e 100644 --- a/circle.yml +++ b/circle.yml @@ -7,7 +7,9 @@ machine: dependencies: pre: - - sudo apt-get remove -y ffmpeg + - sudo apt-get -qqy remove ffmpeg + - sudo apt-get -qq update + - sudo apt-get -qqy upgrade - bash install-dependencies.sh override: From 5a4e149c7e852bec79831ca5a83e827336c199b8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:12:56 +0100 Subject: [PATCH 184/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/circle.yml b/circle.yml index e5d0b0e..5c4c59d 100644 --- a/circle.yml +++ b/circle.yml @@ -8,8 +8,6 @@ machine: dependencies: pre: - sudo apt-get -qqy remove ffmpeg - - sudo apt-get -qq update - - sudo apt-get -qqy upgrade - bash install-dependencies.sh override: @@ -27,6 +25,7 @@ dependencies: test: override: - ffmpeg -version - - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg http://www.youtube.com/watch?v=QcIy9NiNbmo + - avconf -version + - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -v http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: timeout: 180 \ No newline at end of file From dc91d47ae09ac1578fb61ac9578d4400223de301 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:22:45 +0100 Subject: [PATCH 185/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 3 ++- install-dependencies.sh | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/circle.yml b/circle.yml index 5c4c59d..468b65c 100644 --- a/circle.yml +++ b/circle.yml @@ -7,7 +7,8 @@ machine: dependencies: pre: - - sudo apt-get -qqy remove ffmpeg + - sudo apt-get -y remove ffmpeg + - sudo apt-get -y install libavconf - bash install-dependencies.sh override: diff --git a/install-dependencies.sh b/install-dependencies.sh index a03870b..a02e6a5 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -2,22 +2,22 @@ set -e # check to see if ffmpeg is installed -if [ ! -f "$HOME/bin/ffmpeg" ]; then - echo 'Installing ffmpeg' - wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz - tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe - chmod a+rx ffmpeg ffprobe - mv ff* $HOME/bin -else - echo 'Using cached version of ffmpeg.'; -fi +#if [ ! -f "$HOME/bin/ffmpeg" ]; then +# echo 'Installing ffmpeg' +# wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz +# tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe +# chmod a+rx ffmpeg ffprobe +# mv ff* ~/bin +#else +# echo 'Using cached version of ffmpeg.'; +#fi # check to see if opus is installed if [ ! -d "$HOME/opus/lib" ]; then echo 'Installing opus' wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz tar xzvf opus-1.0.3.tar.gz - cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install + cd opus-1.0.3 && ./configure --prefix=~/opus && make && make install else echo 'Using cached version of opus.'; fi From 51cad774615a2295529e0fbb2721525a2473465f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:25:08 +0100 Subject: [PATCH 186/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/circle.yml b/circle.yml index 468b65c..9b3b05d 100644 --- a/circle.yml +++ b/circle.yml @@ -8,7 +8,6 @@ machine: dependencies: pre: - sudo apt-get -y remove ffmpeg - - sudo apt-get -y install libavconf - bash install-dependencies.sh override: From bfae7caa0af3a33d3b08746e35c3cc0cf408c894 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:28:21 +0100 Subject: [PATCH 187/297] Fixing issue with youtube-dl and ffmpeg --- install-dependencies.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install-dependencies.sh b/install-dependencies.sh index a02e6a5..d055fde 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -17,7 +17,7 @@ if [ ! -d "$HOME/opus/lib" ]; then echo 'Installing opus' wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz tar xzvf opus-1.0.3.tar.gz - cd opus-1.0.3 && ./configure --prefix=~/opus && make && make install + cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install else echo 'Using cached version of opus.'; fi From c3f48e01cfdcd546279cb8101fb49600b637dc50 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:33:09 +0100 Subject: [PATCH 188/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 9b3b05d..824902c 100644 --- a/circle.yml +++ b/circle.yml @@ -25,7 +25,7 @@ dependencies: test: override: - ffmpeg -version - - avconf -version + - ls -lR /usr/local - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -v http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: timeout: 180 \ No newline at end of file From b0cc12c2765ee3b2bf417143bac6297929e79053 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:35:38 +0100 Subject: [PATCH 189/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 824902c..e8d7231 100644 --- a/circle.yml +++ b/circle.yml @@ -25,7 +25,7 @@ dependencies: test: override: - ffmpeg -version - - ls -lR /usr/local + - ls -lR /usr/local/bin - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -v http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: timeout: 180 \ No newline at end of file From e8ad824c22c402fce28d6435a9601d4e41116dee Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:37:19 +0100 Subject: [PATCH 190/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/circle.yml b/circle.yml index e8d7231..4d0b6b6 100644 --- a/circle.yml +++ b/circle.yml @@ -26,6 +26,7 @@ test: override: - ffmpeg -version - ls -lR /usr/local/bin + - echo "$PATH" - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -v http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: timeout: 180 \ No newline at end of file From ff5b11f966c228f0c4126a10be7c982b135bd679 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:42:42 +0100 Subject: [PATCH 191/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 4d0b6b6..ecc1055 100644 --- a/circle.yml +++ b/circle.yml @@ -7,7 +7,9 @@ machine: dependencies: pre: - - sudo apt-get -y remove ffmpeg + - sudo apt-get -qq update + - sudo apt-get -qqy remove --purge ffmpeg + - sudo apt-get clean - bash install-dependencies.sh override: From dd6c7c2d3cc18db92eec266311b2c74d20162230 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:44:41 +0100 Subject: [PATCH 192/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/circle.yml b/circle.yml index ecc1055..27c2595 100644 --- a/circle.yml +++ b/circle.yml @@ -7,9 +7,6 @@ machine: dependencies: pre: - - sudo apt-get -qq update - - sudo apt-get -qqy remove --purge ffmpeg - - sudo apt-get clean - bash install-dependencies.sh override: From 0fde6178827064b9987df43bc749376a48cb65ef Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:46:46 +0100 Subject: [PATCH 193/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/circle.yml b/circle.yml index 27c2595..efaf07a 100644 --- a/circle.yml +++ b/circle.yml @@ -7,6 +7,8 @@ machine: dependencies: pre: + - sudo apt-get -qq update + - sudo apt-get -qqy upgrade ffmpeg - bash install-dependencies.sh override: From 0f96078a36c7f6037cbe5b5591c3dcf8aab04451 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:49:09 +0100 Subject: [PATCH 194/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index efaf07a..3dc319d 100644 --- a/circle.yml +++ b/circle.yml @@ -8,7 +8,7 @@ machine: dependencies: pre: - sudo apt-get -qq update - - sudo apt-get -qqy upgrade ffmpeg + - sudo apt-get -qqy install ffmpeg - bash install-dependencies.sh override: From 03dbb36361386b9c82dbf0a49a98cfc0b7408360 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:54:01 +0100 Subject: [PATCH 195/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 4 +--- install-dependencies.sh | 18 +++++++++--------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/circle.yml b/circle.yml index 3dc319d..6630d03 100644 --- a/circle.yml +++ b/circle.yml @@ -1,14 +1,12 @@ machine: environment: - PATH: $PATH:$HOME/bin/ + PATH: $HOME/bin/:$PATH LD_RUN_PATH: $LD_RUN_PATH:$HOME/opus/lib LD_LIBRARY_PATH: $LD_LIBRARY_PATH:$HOME/opus/lib PKG_CONFIG_PATH: $PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig dependencies: pre: - - sudo apt-get -qq update - - sudo apt-get -qqy install ffmpeg - bash install-dependencies.sh override: diff --git a/install-dependencies.sh b/install-dependencies.sh index d055fde..2331fb7 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -2,15 +2,15 @@ set -e # check to see if ffmpeg is installed -#if [ ! -f "$HOME/bin/ffmpeg" ]; then -# echo 'Installing ffmpeg' -# wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz -# tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe -# chmod a+rx ffmpeg ffprobe -# mv ff* ~/bin -#else -# echo 'Using cached version of ffmpeg.'; -#fi +if [ ! -f "$HOME/bin/ffmpeg" ]; then + echo 'Installing ffmpeg' + wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz + tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe + chmod a+rx ffmpeg ffprobe + mv ff* ~/bin +else + echo 'Using cached version of ffmpeg.'; +fi # check to see if opus is installed if [ ! -d "$HOME/opus/lib" ]; then From 5129c0e8f4a7b87ac7ba92c65654ac96d41b6315 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 12 Aug 2015 23:59:34 +0100 Subject: [PATCH 196/297] Fixing issue with youtube-dl and ffmpeg --- circle.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/circle.yml b/circle.yml index 6630d03..d8c0f8f 100644 --- a/circle.yml +++ b/circle.yml @@ -7,6 +7,7 @@ machine: dependencies: pre: + - sudo apt-get purge -y ffmpeg - bash install-dependencies.sh override: From 4d87a6c6d085ec3032884e15901271bb793a6367 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 00:02:55 +0100 Subject: [PATCH 197/297] Deleted circle.yml --- circle.yml | 32 -------------------------------- 1 file changed, 32 deletions(-) delete mode 100644 circle.yml diff --git a/circle.yml b/circle.yml deleted file mode 100644 index d8c0f8f..0000000 --- a/circle.yml +++ /dev/null @@ -1,32 +0,0 @@ -machine: - environment: - PATH: $HOME/bin/:$PATH - LD_RUN_PATH: $LD_RUN_PATH:$HOME/opus/lib - LD_LIBRARY_PATH: $LD_LIBRARY_PATH:$HOME/opus/lib - PKG_CONFIG_PATH: $PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig - -dependencies: - pre: - - sudo apt-get purge -y ffmpeg - - bash install-dependencies.sh - - override: - - make - - make install - - cache_directories: - - "~/opus" - - "~/bin" - - "~/mumbledj/.vendor" - - "/home/ubuntu/.go_workspace/bin" - - "/home/ubuntu/.go_workspace/pkg" - - "/home/ubuntu/.go_workspace/src/github.com/nitrous-io" - -test: - override: - - ffmpeg -version - - ls -lR /usr/local/bin - - echo "$PATH" - - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -v http://www.youtube.com/watch?v=QcIy9NiNbmo - - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: - timeout: 180 \ No newline at end of file From cfa0842aa3d1cd2974fb8547e90aa19ca9cf54fe Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 00:04:49 +0100 Subject: [PATCH 198/297] Fixing issue with youtube-dl and ffmpeg --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index 88a86ce..ed5b900 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,4 +21,6 @@ script: - make install after_success: + - ffmpeg -version + - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -v http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=travis -password=$MUMBLE_PASSWORD -verbose=true -test=true \ No newline at end of file From fa3ea6e17b64c81ba2e21cc3d5c7d96dc914ea79 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 00:07:23 +0100 Subject: [PATCH 199/297] Fixing issue with youtube-dl and ffmpeg --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ed5b900..b307804 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,5 +22,5 @@ script: after_success: - ffmpeg -version - - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -v http://www.youtube.com/watch?v=QcIy9NiNbmo + - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg --verbose http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=travis -password=$MUMBLE_PASSWORD -verbose=true -test=true \ No newline at end of file From 9ccedc06a71853f37d520cd1e862ce793f73f241 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 00:16:21 +0100 Subject: [PATCH 200/297] Using IPV4 for youtube-dl due to HTTP Error 429 using travis-ci --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index b307804..defd123 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,5 +22,5 @@ script: after_success: - ffmpeg -version - - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg --verbose http://www.youtube.com/watch?v=QcIy9NiNbmo + - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -4 --verbose http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=travis -password=$MUMBLE_PASSWORD -verbose=true -test=true \ No newline at end of file From 5ff177aa8df3f4b67bf41e4b02bb5e63f7fefbb6 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 00:26:52 +0100 Subject: [PATCH 201/297] Added circle.yml --- circle.yml | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 circle.yml diff --git a/circle.yml b/circle.yml new file mode 100644 index 0000000..d8c0f8f --- /dev/null +++ b/circle.yml @@ -0,0 +1,32 @@ +machine: + environment: + PATH: $HOME/bin/:$PATH + LD_RUN_PATH: $LD_RUN_PATH:$HOME/opus/lib + LD_LIBRARY_PATH: $LD_LIBRARY_PATH:$HOME/opus/lib + PKG_CONFIG_PATH: $PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig + +dependencies: + pre: + - sudo apt-get purge -y ffmpeg + - bash install-dependencies.sh + + override: + - make + - make install + + cache_directories: + - "~/opus" + - "~/bin" + - "~/mumbledj/.vendor" + - "/home/ubuntu/.go_workspace/bin" + - "/home/ubuntu/.go_workspace/pkg" + - "/home/ubuntu/.go_workspace/src/github.com/nitrous-io" + +test: + override: + - ffmpeg -version + - ls -lR /usr/local/bin + - echo "$PATH" + - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -v http://www.youtube.com/watch?v=QcIy9NiNbmo + - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: + timeout: 180 \ No newline at end of file From 314134432e0cbb899502033bd510bb84629050eb Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 00:33:51 +0100 Subject: [PATCH 202/297] Checking version of ffmpeg at every stage --- circle.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/circle.yml b/circle.yml index d8c0f8f..ac8b93e 100644 --- a/circle.yml +++ b/circle.yml @@ -7,8 +7,11 @@ machine: dependencies: pre: - - sudo apt-get purge -y ffmpeg + - ffmpeg --version + - sudo apt-get remove -y ffmpeg + - ffmpeg --version - bash install-dependencies.sh + - ffmpeg --version override: - make @@ -24,9 +27,6 @@ dependencies: test: override: - - ffmpeg -version - - ls -lR /usr/local/bin - - echo "$PATH" - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -v http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: timeout: 180 \ No newline at end of file From b3b1d9c3f40baceda0ab894deb92948ca8a5f8be Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 00:34:35 +0100 Subject: [PATCH 203/297] Checking version of ffmpeg at every stage --- circle.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/circle.yml b/circle.yml index ac8b93e..936fb68 100644 --- a/circle.yml +++ b/circle.yml @@ -7,11 +7,11 @@ machine: dependencies: pre: - - ffmpeg --version + - ffmpeg -version - sudo apt-get remove -y ffmpeg - - ffmpeg --version + - ffmpeg -version - bash install-dependencies.sh - - ffmpeg --version + - ffmpeg -version override: - make From 9928986bfe38df365c536db3f3206bcd9162fe83 Mon Sep 17 00:00:00 2001 From: Matthieu Grieger Date: Wed, 12 Aug 2015 21:24:41 -0700 Subject: [PATCH 204/297] Update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac1421a..2493d8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ MumbleDJ Changelog ================== +### August 12, 2015 -- `v2.7.5` +* Fixed cache clearing earlier than expected (thanks [@CMahaff](https://github.com/CMahaff)). + ### May 19, 2015 -- `v2.7.4` * Fixed a panic that occurred when certain YouTube playlists were added to the queue. From 99b6abdd2cff8a3781e2264246048aaf51380d82 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 13:44:38 +0100 Subject: [PATCH 205/297] Checking output of youtube-dl when downloading --- service_soundcloud.go | 15 ++++++++++----- service_youtube.go | 11 +++++------ youtube_dl.go | 8 +++++--- 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 9784468..6c3a5ef 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -44,7 +44,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { // PLAYLIST if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { // Check duration of playlist - // duration, _ := apiResponse.Int("duration") + duration, _ := apiResponse.Int("duration") // Create playlist title, _ := apiResponse.String("title") @@ -56,7 +56,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { // Add all tracks for _, t := range tracks { - sc.NewSong(user.Name, jsonq.NewQuery(t), playlist) + sc.NewSong(user, jsonq.NewQuery(t), playlist) } if err == nil { return playlist.Title(), nil @@ -69,12 +69,12 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { } } else { // SONG - return sc.NewSong(user.Name, apiResponse, nil) + return sc.NewSong(user, apiResponse, nil) } } // Creates a track and adds to the queue -func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist Playlist) (string, error) { +func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, playlist Playlist) (string, error) { title, err := trackData.String("title") if err != nil { return "", err @@ -83,7 +83,7 @@ func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist P if err != nil { return "", err } - duration, err := trackData.String("duration") + duration, err := trackData.Int("duration") if err != nil { return "", err } @@ -91,10 +91,15 @@ func (sc SoundCloud) NewSong(user string, trackData *jsonq.JsonQuery, playlist P if err != nil { return "", err } + url, err := trackData.String("permalink_url") + if err != nil { + return "", err + } song := &YouTubeDLSong{ id: id, title: title, + url: url, thumbnail: thumbnail, submitter: user, duration: duration, diff --git a/service_youtube.go b/service_youtube.go index 542baa0..4f86ca7 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -60,7 +60,7 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { if re.MatchString(url) { if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { shortURL = re.FindStringSubmatch(url)[1] - playlist, err := yt.NewPlaylist(user.Name, shortURL) + playlist, err := yt.NewPlaylist(user, shortURL) return playlist.Title(), err } else { return "", errors.New("NO_PLAYLIST_PERMISSION") @@ -72,7 +72,7 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { if len(matches[0]) == 3 { startOffset = matches[0][2] } - song, err := yt.NewSong(user.Name, shortURL, startOffset, nil) + song, err := yt.NewSong(user, shortURL, startOffset, nil) if err == nil { return song.Title(), nil } else { @@ -87,7 +87,7 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { // NewSong gathers the metadata for a song extracted from a YouTube video, and returns // the song. -func (yt YouTube) NewSong(user, id, offset string, playlist Playlist) (Song, error) { +func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlist) (Song, error) { var apiResponse *jsonq.JsonQuery var err error url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s", @@ -181,12 +181,11 @@ func (yt YouTube) NewSong(user, id, offset string, playlist Playlist) (Song, err } // NewPlaylist gathers the metadata for a YouTube playlist and returns it. -func (yt YouTube) NewPlaylist(user, id string) (Playlist, error) { +func (yt YouTube) NewPlaylist(user *gumble.User, id string) (Playlist, error) { var apiResponse *jsonq.JsonQuery var err error // Retrieve title of playlist - url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=%s&key=%s", - id, os.Getenv("YOUTUBE_API_KEY")) + url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=%s&key=%s", id, os.Getenv("YOUTUBE_API_KEY")) if apiResponse, err = PerformGetRequest(url); err != nil { return nil, err } diff --git a/youtube_dl.go b/youtube_dl.go index fedfc28..618581d 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -15,8 +15,8 @@ type YouTubeDLSong struct { id string title string thumbnail string - submitter string - duration string + submitter *gumble.User + duration int url string offset int playlist Playlist @@ -39,7 +39,7 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", "--", dl.ID()) + cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", "--", dl.url) err = cmd.Run() if err == nil { if dj.conf.Cache.Enabled { @@ -51,6 +51,8 @@ func (dl *YouTubeDLSong) Download() error { for s := range cmd.Args { Verbose("youtube-dl args: " + cmd.Args[s]) } + b, _ := ioutil.ReadAll(cmd.Stdout) + Verbose(string(b)) return errors.New("Song download failed.") } } From 988a23cbd31b6ccaa26e278b3bbeb1c723b8f1ff Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 13:46:28 +0100 Subject: [PATCH 206/297] Checking output of youtube-dl when downloading --- youtube_dl.go | 1 + 1 file changed, 1 insertion(+) diff --git a/youtube_dl.go b/youtube_dl.go index 618581d..5198680 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -7,6 +7,7 @@ import ( "os/exec" "time" + "github.com/layeh/gumble/gumble" "github.com/layeh/gumble/gumble_ffmpeg" ) From a8a9c1f231a9c8d4bee7d60c8c146cdfb3a5ee6f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 13:51:51 +0100 Subject: [PATCH 207/297] Checking output of youtube-dl when downloading[ci skip] --- youtube_dl.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/youtube_dl.go b/youtube_dl.go index 5198680..cd17f8f 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -52,8 +52,7 @@ func (dl *YouTubeDLSong) Download() error { for s := range cmd.Args { Verbose("youtube-dl args: " + cmd.Args[s]) } - b, _ := ioutil.ReadAll(cmd.Stdout) - Verbose(string(b)) + Verbose(string(cmd.Output())) return errors.New("Song download failed.") } } @@ -137,7 +136,7 @@ func (dl *YouTubeDLSong) SkipReached(channelUsers int) bool { // Submitter returns the name of the submitter of the Song. func (dl *YouTubeDLSong) Submitter() string { - return dl.submitter + return dl.submitter.Name } // Title returns the title of the Song. @@ -156,7 +155,7 @@ func (dl *YouTubeDLSong) Filename() string { } // Duration returns the duration of the Song. -func (dl *YouTubeDLSong) Duration() string { +func (dl *YouTubeDLSong) Duration() int { return dl.duration } From 255c516967f76d21e453800147b0cf04d6e87d39 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 13:54:19 +0100 Subject: [PATCH 208/297] Checking output of youtube-dl when downloading[ci skip] --- service.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service.go b/service.go index 15a5947..08c7404 100644 --- a/service.go +++ b/service.go @@ -34,7 +34,7 @@ type Song interface { Title() string ID() string Filename() string - Duration() string + Duration() int Thumbnail() string Playlist() Playlist DontSkip() bool From fa0dd246774fa3989deb6fe2b7552243c4f5f04a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 13:57:45 +0100 Subject: [PATCH 209/297] Checking output of youtube-dl when downloading[ci skip] --- service.go | 2 +- service_soundcloud.go | 2 +- youtube_dl.go | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/service.go b/service.go index 08c7404..15a5947 100644 --- a/service.go +++ b/service.go @@ -34,7 +34,7 @@ type Song interface { Title() string ID() string Filename() string - Duration() int + Duration() string Thumbnail() string Playlist() Playlist DontSkip() bool diff --git a/service_soundcloud.go b/service_soundcloud.go index 6c3a5ef..1c3c77c 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -102,7 +102,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play url: url, thumbnail: thumbnail, submitter: user, - duration: duration, + duration: string(duration), playlist: playlist, skippers: make([]string, 0), dontSkip: false, diff --git a/youtube_dl.go b/youtube_dl.go index cd17f8f..cd77416 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -17,7 +17,7 @@ type YouTubeDLSong struct { title string thumbnail string submitter *gumble.User - duration int + duration string url string offset int playlist Playlist @@ -52,7 +52,7 @@ func (dl *YouTubeDLSong) Download() error { for s := range cmd.Args { Verbose("youtube-dl args: " + cmd.Args[s]) } - Verbose(string(cmd.Output())) + Verbose(string(cmd.CombinedOutput())) return errors.New("Song download failed.") } } @@ -155,7 +155,7 @@ func (dl *YouTubeDLSong) Filename() string { } // Duration returns the duration of the Song. -func (dl *YouTubeDLSong) Duration() int { +func (dl *YouTubeDLSong) Duration() string { return dl.duration } From 4a2238571e1353e71eca3402de7ee0da482845ee Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 13:59:24 +0100 Subject: [PATCH 210/297] Checking output of youtube-dl when downloading[ci skip] --- youtube_dl.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/youtube_dl.go b/youtube_dl.go index cd77416..81373ec 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -52,7 +52,8 @@ func (dl *YouTubeDLSong) Download() error { for s := range cmd.Args { Verbose("youtube-dl args: " + cmd.Args[s]) } - Verbose(string(cmd.CombinedOutput())) + output, _ := cmd.CombinedOutput() + Verbose(string(output)) return errors.New("Song download failed.") } } From 488391c9da346bda904231551cd503bdd7aa826b Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:00:12 +0100 Subject: [PATCH 211/297] Checking output of youtube-dl when downloading[ci skip] --- service_soundcloud.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 1c3c77c..5b423d6 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -44,7 +44,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { // PLAYLIST if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { // Check duration of playlist - duration, _ := apiResponse.Int("duration") + //duration, _ := apiResponse.Int("duration") // Create playlist title, _ := apiResponse.String("title") From a5bebd06c8f436bb3b056d0ff8e615ac8319d64a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:07:04 +0100 Subject: [PATCH 212/297] Checking output of youtube-dl when downloading[ci skip] --- service_youtube.go | 1 + youtube_dl.go | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/service_youtube.go b/service_youtube.go index 4f86ca7..08dc01a 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -165,6 +165,7 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis submitter: user, title: title, id: id, + url: "https://youtu.be/" + id, offset: int((offsetDays * 86400) + (offsetHours * 3600) + (offsetMinutes * 60) + offsetSeconds), duration: durationString, thumbnail: thumbnail, diff --git a/youtube_dl.go b/youtube_dl.go index 81373ec..7546fa4 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -40,7 +40,7 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", "--", dl.url) + cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", "--", dl.url) err = cmd.Run() if err == nil { if dj.conf.Cache.Enabled { From d0f06f7543403bb213b772d41fd302a4bca0f5c5 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:08:59 +0100 Subject: [PATCH 213/297] Checking output of youtube-dl when downloading[ci skip] --- youtube_dl.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/youtube_dl.go b/youtube_dl.go index 7546fa4..7ba5e73 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -40,7 +40,7 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", "--", dl.url) + cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", dl.url) err = cmd.Run() if err == nil { if dj.conf.Cache.Enabled { @@ -52,7 +52,7 @@ func (dl *YouTubeDLSong) Download() error { for s := range cmd.Args { Verbose("youtube-dl args: " + cmd.Args[s]) } - output, _ := cmd.CombinedOutput() + output, _ := cmd.Output() Verbose(string(output)) return errors.New("Song download failed.") } From 549669bef88df2a35236a8ec03999c694457e36d Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:11:44 +0100 Subject: [PATCH 214/297] Checking output of youtube-dl when downloading[ci skip] --- youtube_dl.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/youtube_dl.go b/youtube_dl.go index 7ba5e73..809c252 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -41,7 +41,7 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", dl.url) - err = cmd.Run() + output, err = cmd.CombinedOutput() if err == nil { if dj.conf.Cache.Enabled { dj.cache.CheckMaximumDirectorySize() @@ -52,7 +52,6 @@ func (dl *YouTubeDLSong) Download() error { for s := range cmd.Args { Verbose("youtube-dl args: " + cmd.Args[s]) } - output, _ := cmd.Output() Verbose(string(output)) return errors.New("Song download failed.") } From 1024c9e9af742baca2f063e902683429b90981a4 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:12:28 +0100 Subject: [PATCH 215/297] Checking output of youtube-dl when downloading[ci skip] --- youtube_dl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/youtube_dl.go b/youtube_dl.go index 809c252..1d065a2 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -41,7 +41,7 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", dl.url) - output, err = cmd.CombinedOutput() + output, err := cmd.CombinedOutput() if err == nil { if dj.conf.Cache.Enabled { dj.cache.CheckMaximumDirectorySize() From 04fc569a9bb00c43ab03e56579d5feca8ac79049 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:15:25 +0100 Subject: [PATCH 216/297] Checking output of youtube-dl when downloading[ci skip] --- youtube_dl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/youtube_dl.go b/youtube_dl.go index 1d065a2..2170123 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -40,7 +40,7 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format m4a", "--prefer-ffmpeg", dl.url) + cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format", "m4a", "--prefer-ffmpeg", dl.url) output, err := cmd.CombinedOutput() if err == nil { if dj.conf.Cache.Enabled { From 6ef0f7f5bca4971bed07510438fedcb4c60792de Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:26:39 +0100 Subject: [PATCH 217/297] Getting soundcloud to work [ci skip] --- service_soundcloud.go | 4 ++-- youtube_dl.go | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 5b423d6..8f26bd8 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -79,7 +79,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play if err != nil { return "", err } - id, err := trackData.String("id") + id, err := trackData.Int("id") if err != nil { return "", err } @@ -97,7 +97,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play } song := &YouTubeDLSong{ - id: id, + id: string(id), title: title, url: url, thumbnail: thumbnail, diff --git a/youtube_dl.go b/youtube_dl.go index 2170123..b9053b9 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -48,11 +48,13 @@ func (dl *YouTubeDLSong) Download() error { } return nil } else { - Verbose("youtube-dl: " + err.Error()) + args := "youtube-dl " for s := range cmd.Args { - Verbose("youtube-dl args: " + cmd.Args[s]) + args += cmd.Args[s] } + Verbose(args) Verbose(string(output)) + Verbose("youtube-dl: " + err.Error()) return errors.New("Song download failed.") } } From 9d29d77dfa6c03036037b04b18998bb8be872c60 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:30:11 +0100 Subject: [PATCH 218/297] Getting soundcloud to work [ci skip] --- service_soundcloud.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 8f26bd8..2f80980 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -87,7 +87,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play if err != nil { return "", err } - thumbnail, err := trackData.String("artwork_uri") + thumbnail, err := trackData.String("artwork_url") if err != nil { return "", err } From 67c8b696a4bbf0f9cced8233f28470d243fb7170 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:33:37 +0100 Subject: [PATCH 219/297] Getting soundcloud to work [ci skip] --- service_soundcloud.go | 1 + service_youtube.go | 1 + youtube_dl.go | 9 +++++---- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 2f80980..ba36ccc 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -103,6 +103,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play thumbnail: thumbnail, submitter: user, duration: string(duration), + format: "mp3", playlist: playlist, skippers: make([]string, 0), dontSkip: false, diff --git a/service_youtube.go b/service_youtube.go index 08dc01a..1cac086 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -169,6 +169,7 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis offset: int((offsetDays * 86400) + (offsetHours * 3600) + (offsetMinutes * 60) + offsetSeconds), duration: durationString, thumbnail: thumbnail, + format: "m4a", skippers: make([]string, 0), playlist: playlist, dontSkip: false, diff --git a/youtube_dl.go b/youtube_dl.go index b9053b9..abb294e 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -20,6 +20,7 @@ type YouTubeDLSong struct { duration string url string offset int + format string playlist Playlist skippers []string dontSkip bool @@ -40,7 +41,7 @@ func (dl *YouTubeDLSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format", "m4a", "--prefer-ffmpeg", dl.url) + cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format", dl.format, "--prefer-ffmpeg", dl.url) output, err := cmd.CombinedOutput() if err == nil { if dj.conf.Cache.Enabled { @@ -48,9 +49,9 @@ func (dl *YouTubeDLSong) Download() error { } return nil } else { - args := "youtube-dl " + args := "" for s := range cmd.Args { - args += cmd.Args[s] + args += cmd.Args[s] + " " } Verbose(args) Verbose(string(output)) @@ -153,7 +154,7 @@ func (dl *YouTubeDLSong) ID() string { // Filename returns the filename of the Song. func (dl *YouTubeDLSong) Filename() string { - return dl.id + ".m4a" + return dl.id + dl.format } // Duration returns the duration of the Song. From d4b54bfa79c6b5ea4d5e628c0fcf9271acc0f931 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:36:30 +0100 Subject: [PATCH 220/297] Getting soundcloud to work [ci skip] --- service_soundcloud.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index ba36ccc..d98774d 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -10,8 +10,8 @@ import ( ) // Regular expressions for soundcloud urls -var soundcloudSongPattern = `https?:\/\/(www)?\.soundcloud\.com\/([\w-]+)\/([\w-]+)` -var soundcloudPlaylistPattern = `https?:\/\/(www)?\.soundcloud\.com\/([\w-]+)\/sets\/([\w-]+)` +var soundcloudSongPattern = `https?:\/\/(www\.)?soundcloud\.com\/([\w-]+)\/([\w-]+)` +var soundcloudPlaylistPattern = `https?:\/\/(www\.)?soundcloud\.com\/([\w-]+)\/sets\/([\w-]+)` // SoundCloud implements the Service interface type SoundCloud struct{} From 4520bac5140fe4684c5d4cf691e5e6e328724232 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 14:57:12 +0100 Subject: [PATCH 221/297] Soundcloud API works, just no music [ci skip] --- youtube_dl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/youtube_dl.go b/youtube_dl.go index abb294e..c1685ee 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -74,7 +74,7 @@ func (dl *YouTubeDLSong) Play() { panic(err) } else { message := `` - message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.duration, dl.submitter) + message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.duration, dl.submitter.Name) if !isNil(dl.playlist) { message = fmt.Sprintf(message+``, dl.playlist.Title()) } From c4ffe8810b5bad40eb8dbaf95ff9dd641fdd4f1f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 15:07:34 +0100 Subject: [PATCH 222/297] Soundcloud API works, just no music [ci skip] --- service_soundcloud.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index d98774d..0ba4b5d 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "os" + "strconv" "github.com/jmoiron/jsonq" "github.com/layeh/gumble/gumble" @@ -97,12 +98,12 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play } song := &YouTubeDLSong{ - id: string(id), + id: strconv.Itoa(id), title: title, url: url, thumbnail: thumbnail, submitter: user, - duration: string(duration), + duration: strconv.Itoa(duration), format: "mp3", playlist: playlist, skippers: make([]string, 0), From c3d733ae355e8625751a4f1c08f6c1d5554222a7 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 15:16:10 +0100 Subject: [PATCH 223/297] Fixed webpages so they now load [ci skip] --- index.html | 2 +- web.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 0922733..9fbb722 100644 --- a/index.html +++ b/index.html @@ -32,7 +32,7 @@ } - +

Add Song Form

Date: Thu, 13 Aug 2015 15:20:37 +0100 Subject: [PATCH 224/297] Fixed error in javascript on webpage [ci skip] --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 9fbb722..7bd1999 100644 --- a/index.html +++ b/index.html @@ -21,7 +21,7 @@ }); } - function apiCompete(jqXHR, textStatus) { + function apiComplete(jqXHR, textStatus) { alert(textStatus); } From bceaa27085d70210b5bcaef0ec698a89bb5c444f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 13 Aug 2015 15:32:20 +0100 Subject: [PATCH 225/297] Soundcloud uses avatar if song has no artwork [ci skip] --- service_soundcloud.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 0ba4b5d..4e47e8d 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -80,18 +80,30 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play if err != nil { return "", err } + id, err := trackData.Int("id") if err != nil { return "", err } + duration, err := trackData.Int("duration") if err != nil { return "", err } thumbnail, err := trackData.String("artwork_url") if err != nil { - return "", err + // Song has no artwork, using profile avatar instead + userObj, err := trackData.Object("user") + if err != nil { + return "", err + } + + thumbnail, err = jsonq.NewQuery(userObj).String("avatar_url") + if err != nil { + return "", err + } } + url, err := trackData.String("permalink_url") if err != nil { return "", err From d71257422c2fee448e3008c2b952ca7a8be68c7c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 14 Aug 2015 10:48:40 +0100 Subject: [PATCH 226/297] Using pip to install youtube-dl --- circle.yml | 4 +--- install-dependencies.sh | 9 --------- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/circle.yml b/circle.yml index 936fb68..a0c815b 100644 --- a/circle.yml +++ b/circle.yml @@ -7,10 +7,8 @@ machine: dependencies: pre: - - ffmpeg -version - - sudo apt-get remove -y ffmpeg - - ffmpeg -version - bash install-dependencies.sh + - pip install youtube-dl - ffmpeg -version override: diff --git a/install-dependencies.sh b/install-dependencies.sh index 2331fb7..a42e213 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -20,13 +20,4 @@ if [ ! -d "$HOME/opus/lib" ]; then cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install else echo 'Using cached version of opus.'; -fi - -# check to see if youtube-dl is installed -if [ ! -f "$HOME/bin/youtube-dl" ]; then - echo 'Installing youtube-dl' - curl https://yt-dl.org/downloads/2015.07.28/youtube-dl -o ~/bin/youtube-dl - chmod a+rx ~/bin/youtube-dl -else - echo 'Using cached version of youtube-dl.'; fi \ No newline at end of file From 9b6956f13d017067a0de456496e4369a14475049 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 14 Aug 2015 10:50:56 +0100 Subject: [PATCH 227/297] Giving pip sudo to install youtube-dl --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index a0c815b..62e5a76 100644 --- a/circle.yml +++ b/circle.yml @@ -8,7 +8,7 @@ machine: dependencies: pre: - bash install-dependencies.sh - - pip install youtube-dl + - sudo pip install youtube-dl - ffmpeg -version override: From 536bdbe921948a7bb8b7850ab940a842bb237a22 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 14 Aug 2015 10:57:42 +0100 Subject: [PATCH 228/297] Removing old ffmpeg --- circle.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/circle.yml b/circle.yml index 62e5a76..f536fd2 100644 --- a/circle.yml +++ b/circle.yml @@ -7,6 +7,7 @@ machine: dependencies: pre: + - sudo apt-get --qqy remove ffmpeg - bash install-dependencies.sh - sudo pip install youtube-dl - ffmpeg -version From 75bc9502905e5abf3726ab89f655dddff23c109d Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 14 Aug 2015 10:58:38 +0100 Subject: [PATCH 229/297] Removing old ffmpeg --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index f536fd2..4aad8d7 100644 --- a/circle.yml +++ b/circle.yml @@ -7,7 +7,7 @@ machine: dependencies: pre: - - sudo apt-get --qqy remove ffmpeg + - sudo apt-get -qqy remove ffmpeg - bash install-dependencies.sh - sudo pip install youtube-dl - ffmpeg -version From bcf96af96454aa2ec02ab0330663c8646e4c46bb Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 14 Aug 2015 11:01:57 +0100 Subject: [PATCH 230/297] Removing old ffmpeg --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 4aad8d7..79b9eaa 100644 --- a/circle.yml +++ b/circle.yml @@ -7,7 +7,7 @@ machine: dependencies: pre: - - sudo apt-get -qqy remove ffmpeg + - sudo apt-get -qqy remove avconv avprobe ffmpeg ffprobe - bash install-dependencies.sh - sudo pip install youtube-dl - ffmpeg -version From 3efcb43ed78027b8b93736e7141ce6fe2d01d2f5 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 14 Aug 2015 11:02:55 +0100 Subject: [PATCH 231/297] Removing old ffmpeg --- circle.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/circle.yml b/circle.yml index 79b9eaa..9f7cda9 100644 --- a/circle.yml +++ b/circle.yml @@ -7,9 +7,9 @@ machine: dependencies: pre: - - sudo apt-get -qqy remove avconv avprobe ffmpeg ffprobe + - sudo apt-get -qqy remove ffmpeg ffprobe - bash install-dependencies.sh - - sudo pip install youtube-dl + - sudo pip install youtube-dlS - ffmpeg -version override: From c35b95e9f732ddfee8f6fe9edb25d2ba388ab337 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 14 Aug 2015 11:04:09 +0100 Subject: [PATCH 232/297] Removing old ffmpeg --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 9f7cda9..190de2c 100644 --- a/circle.yml +++ b/circle.yml @@ -9,7 +9,7 @@ dependencies: pre: - sudo apt-get -qqy remove ffmpeg ffprobe - bash install-dependencies.sh - - sudo pip install youtube-dlS + - sudo pip install youtube-dl - ffmpeg -version override: From 2571d60045ca66edfb928803b18349ca2e37fa48 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 15:24:29 +0100 Subject: [PATCH 233/297] Using whereis and type to find ffmpeg location --- circle.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 190de2c..be5177c 100644 --- a/circle.yml +++ b/circle.yml @@ -7,7 +7,9 @@ machine: dependencies: pre: - - sudo apt-get -qqy remove ffmpeg ffprobe + - sudo apt-get remove -y ffmpeg ffprobe + - sudo type ffmpeg + - sudo whereis ffmpeg - bash install-dependencies.sh - sudo pip install youtube-dl - ffmpeg -version From 38bf1e68bae90ee92f4011fd551244b745e3e819 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 15:26:11 +0100 Subject: [PATCH 234/297] Using whereis and type to find ffmpeg location --- circle.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/circle.yml b/circle.yml index be5177c..67b4886 100644 --- a/circle.yml +++ b/circle.yml @@ -8,6 +8,7 @@ machine: dependencies: pre: - sudo apt-get remove -y ffmpeg ffprobe + - sudo apt-get install -y type whereis - sudo type ffmpeg - sudo whereis ffmpeg - bash install-dependencies.sh From ac364a95493c4f8a65870b8eabcd4e3cce47d878 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 15:27:10 +0100 Subject: [PATCH 235/297] Using whereis and type to find ffmpeg location --- circle.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/circle.yml b/circle.yml index 67b4886..54ec01d 100644 --- a/circle.yml +++ b/circle.yml @@ -8,8 +8,7 @@ machine: dependencies: pre: - sudo apt-get remove -y ffmpeg ffprobe - - sudo apt-get install -y type whereis - - sudo type ffmpeg + - sudo apt-get install -y whereis - sudo whereis ffmpeg - bash install-dependencies.sh - sudo pip install youtube-dl From 50d67127b5a63c85824d30b9f0d95d14acf2209d Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 15:28:37 +0100 Subject: [PATCH 236/297] Using whereis and type to find ffmpeg location --- circle.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/circle.yml b/circle.yml index 54ec01d..65be379 100644 --- a/circle.yml +++ b/circle.yml @@ -8,7 +8,6 @@ machine: dependencies: pre: - sudo apt-get remove -y ffmpeg ffprobe - - sudo apt-get install -y whereis - sudo whereis ffmpeg - bash install-dependencies.sh - sudo pip install youtube-dl From 264087a2484ca098e4dace239d17803749cebe07 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 15:32:42 +0100 Subject: [PATCH 237/297] Removing all old ffmpeg locations --- install-dependencies.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/install-dependencies.sh b/install-dependencies.sh index a42e213..074d819 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -1,6 +1,11 @@ #!/bin/sh set -e +# removing old ffmpeg +sudo rm -rf /usr/bin/ffmpeg +sudo rm -rf /usr/bin/X11/ffmpeg +sudo rm -rf /usr/share/man/man1/ffmpeg.1.gz + # check to see if ffmpeg is installed if [ ! -f "$HOME/bin/ffmpeg" ]; then echo 'Installing ffmpeg' From 644fe0ac24a5ee3f7f4dde29fe45369ef24247c8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 15:43:56 +0100 Subject: [PATCH 238/297] Cleaned up circleci files --- .travis.yml | 26 -------------------------- circle.yml | 5 ----- install-dependencies.sh | 9 +++++++++ 3 files changed, 9 insertions(+), 31 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index defd123..0000000 --- a/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: go - -cache: - directories: - - $HOME/opus - - $HOME/bin - - $HOME/gopath/bin - - $HOME/gopath/pkg - - $HOME/gopath/src/github.com/nitrous-io - - $HOME/gopath/src/github.com/MichaelOultram/mumbledj/.vendor - -before_script: - - export PATH=$PATH:$HOME/bin/ - - export LD_RUN_PATH=$LD_RUN_PATH:$HOME/opus/lib - - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/opus/lib - - export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig - - bash install-dependencies.sh - -script: - - make - - make install - -after_success: - - ffmpeg -version - - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -4 --verbose http://www.youtube.com/watch?v=QcIy9NiNbmo - - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=travis -password=$MUMBLE_PASSWORD -verbose=true -test=true \ No newline at end of file diff --git a/circle.yml b/circle.yml index 65be379..aeeb361 100644 --- a/circle.yml +++ b/circle.yml @@ -7,11 +7,7 @@ machine: dependencies: pre: - - sudo apt-get remove -y ffmpeg ffprobe - - sudo whereis ffmpeg - bash install-dependencies.sh - - sudo pip install youtube-dl - - ffmpeg -version override: - make @@ -27,6 +23,5 @@ dependencies: test: override: - - youtube-dl --output ~/.mumbledj/songs/QcIy9NiNbmo.m4a --format m4a --prefer-ffmpeg -v http://www.youtube.com/watch?v=QcIy9NiNbmo - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: timeout: 180 \ No newline at end of file diff --git a/install-dependencies.sh b/install-dependencies.sh index 074d819..cb03750 100644 --- a/install-dependencies.sh +++ b/install-dependencies.sh @@ -17,6 +17,15 @@ else echo 'Using cached version of ffmpeg.'; fi +# check to see if youtube-dl is installed +if [ ! -f "$HOME/bin/youtube-dl" ]; then + echo 'Installing youtube-dl' + curl https://yt-dl.org/latest/youtube-dl -o ~/bin/youtube-dl + chmod a+rx ~/bin/youtube-dl +else + echo 'Using cached version of youtube-dl.'; +fi + # check to see if opus is installed if [ ! -d "$HOME/opus/lib" ]; then echo 'Installing opus' From 0383202304ae614dd7f093b2d6c54199d92f58d8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 15:57:55 +0100 Subject: [PATCH 239/297] Getting tests to use dummy client --- test.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test.go b/test.go index 2258187..0e203c8 100644 --- a/test.go +++ b/test.go @@ -39,14 +39,14 @@ func (t TestSettings) createClient(uname string) *gumble.Client { } func (t TestSettings) testYoutubeSong() { - // dummyClient := t.createClient("dummy") - // if err := dummyClient.Connect(); err != nil { - // panic(err) - // } + dummyClient := t.createClient("dummy") + if err := dummyClient.Connect(); err != nil { + panic(err) + } dj.client.Request(gumble.RequestUserList) time.Sleep(time.Second * 5) - dummyUser := dj.client.Users.Find("BottleOToast") + dummyUser := dj.client.Users.Find("dummy") if dummyUser == nil { fmt.Printf("User does not exist, printing users\n") for _, user := range dj.client.Users { @@ -76,10 +76,10 @@ func (t TestSettings) testYoutubeSong() { fmt.Printf("For: %s; Expected: %s; Got: %s\n", url, title, dj.queue.CurrentSong().Title()) } - time.Sleep(time.Second * 5) + time.Sleep(time.Second * 10) skip(dummyUser, false, false) } os.Exit(0) - //dummyClient.Disconnect() + dummyClient.Disconnect() } From 4ae3052684dcef95b779612d0ab5dd00f73a07df Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 16:03:24 +0100 Subject: [PATCH 240/297] Getting tests to use dummy client --- test.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test.go b/test.go index 0e203c8..7365005 100644 --- a/test.go +++ b/test.go @@ -28,13 +28,14 @@ func Test(password, ip, port string, accesstokens []string) { } func (t TestSettings) createClient(uname string) *gumble.Client { - client := gumble.NewClient(&gumble.Config{ + config := gumble.Config{ Username: uname, Password: t.password, Address: t.ip + ":" + t.port, Tokens: t.accesstokens, - }) - gumbleutil.CertificateLockFile(client, fmt.Sprintf("%s/.mumbledj/cert.lock", dj.homeDir)) + } + config.TLSConfig.InsecureSkipVerify = true + client := gumble.NewClient(&config) return client } From 2396adfdf3615177af6aea4349b9d6b5cad991ca Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 16:04:09 +0100 Subject: [PATCH 241/297] Getting tests to use dummy client --- test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/test.go b/test.go index 7365005..4edbe03 100644 --- a/test.go +++ b/test.go @@ -3,7 +3,6 @@ package main import ( "fmt" "github.com/layeh/gumble/gumble" - "github.com/layeh/gumble/gumbleutil" "os" "time" ) From 03cb8a9ab513ec5110c11a9e89b735cf296adf90 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 18:04:40 +0100 Subject: [PATCH 242/297] Removed web interface as it is unfinshed --- Makefile | 4 +- commands.go | 7 -- config.gcfg | 8 -- index.html | 49 ------------ main.go | 3 - parseconfig.go | 2 - web.go | 197 ------------------------------------------------- 7 files changed, 1 insertion(+), 269 deletions(-) delete mode 100644 index.html delete mode 100644 web.go diff --git a/Makefile b/Makefile index 8c48293..97d8a23 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ all: mumbledj -mumbledj: main.go commands.go parseconfig.go strings.go service.go service_youtube.go songqueue.go cache.go web.go +mumbledj: main.go commands.go parseconfig.go strings.go service.go youtube_dl.go service_youtube.go service_soundcloud.go songqueue.go cache.go if [ ! -f $(GOPATH)/bin/goop ]; then go get github.com/nitrous-io/goop; fi; rm -rf Goopfile.lock goop install @@ -12,10 +12,8 @@ clean: install: mkdir -p ~/.mumbledj/config mkdir -p ~/.mumbledj/songs - mkdir -p ~/.mumbledj/web if [ -f ~/.mumbledj/config/mumbledj.gcfg ]; then mv ~/.mumbledj/config/mumbledj.gcfg ~/.mumbledj/config/mumbledj_backup.gcfg; fi; cp -u config.gcfg ~/.mumbledj/config/mumbledj.gcfg - cp -u index.html ~/.mumbledj/web/index.html if [ -d ~/bin ]; then cp -f mumbledj* ~/bin/mumbledj; else sudo cp -f mumbledj* /usr/local/bin/mumbledj; fi; build: diff --git a/commands.go b/commands.go index e0413cc..5c52bb0 100644 --- a/commands.go +++ b/commands.go @@ -82,13 +82,6 @@ func parseCommand(user *gumble.User, username, command string) { } else { dj.SendPrivateMessage(user, NO_PERMISSION_MSG) } - // Web command - case dj.conf.Aliases.WebAlias: - if dj.HasPermission(username, dj.conf.Permissions.AdminWeb) { - web.GetWebAddress(user) - } else { - dj.SendPrivateMessage(user, NO_PERMISSION_MSG) - } // Move command case dj.conf.Aliases.MoveAlias: if dj.HasPermission(username, dj.conf.Permissions.AdminMove) { diff --git a/config.gcfg b/config.gcfg index eea2750..c55e52c 100644 --- a/config.gcfg +++ b/config.gcfg @@ -86,10 +86,6 @@ HelpAlias = "help" # DEFAULT VALUE: "volume" VolumeAlias = "volume" -# Alias used for web address command -# DEFAULT VALUE: "web" -WebAlias = "web" - # Alias used for move command # DEFAULT VALUE: "move" MoveAlias = "move" @@ -166,10 +162,6 @@ AdminHelp = false # DEFAULT VALUE: false AdminVolume = false -# Make web an admin command? -# DEFAULT VALUE: false -AdminWeb = false - # Make move an admin command? # DEFAULT VALUE: true AdminMove = true diff --git a/index.html b/index.html deleted file mode 100644 index 7bd1999..0000000 --- a/index.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - -{{.User}} - mumbledj - - - - -

Add Song Form

- - - - - -
- - - \ No newline at end of file diff --git a/main.go b/main.go index 3a2ae5f..b918974 100644 --- a/main.go +++ b/main.go @@ -252,9 +252,6 @@ func main() { Test(password, address, port, strings.Split(accesstokens, " ")) } - web = NewWebServer(9563) - web.makeWeb() - if isNil(web) { Verbose("WEB IS NIL") } diff --git a/parseconfig.go b/parseconfig.go index 4b4a16a..9da7ec2 100644 --- a/parseconfig.go +++ b/parseconfig.go @@ -51,7 +51,6 @@ type DjConfig struct { NumCachedAlias string CacheSizeAlias string KillAlias string - WebAlias string } Permissions struct { AdminsEnabled bool @@ -71,7 +70,6 @@ type DjConfig struct { AdminNumCached bool AdminCacheSize bool AdminKill bool - AdminWeb bool } } diff --git a/web.go b/web.go deleted file mode 100644 index 84ee1d2..0000000 --- a/web.go +++ /dev/null @@ -1,197 +0,0 @@ -package main - -import ( - //"encoding/json" - "fmt" - "html" - "html/template" - "io/ioutil" - "math/rand" - "net/http" - "os" - "strconv" - "strings" - "time" - - "github.com/layeh/gumble/gumble" -) - -type WebServer struct { - port int - client_token map[*gumble.User]string - token_client map[string]*gumble.User -} - -type Page struct { - Site string - Token string - User string -} - -type Status struct { - Error bool - ErrorMsg string - Queue []SongInfo -} -type SongInfo struct { - TitleID string - PlaylistID string - Title string - Playlist string - Submitter string - Duration string - Thumbnail string -} - -var external_ip = "" - -func NewWebServer(port int) *WebServer { - rand.Seed(time.Now().UnixNano()) - return &WebServer{ - port: port, - client_token: make(map[*gumble.User]string), - token_client: make(map[string]*gumble.User), - } -} - -func (web *WebServer) makeWeb() { - http.HandleFunc("/", web.homepage) - http.HandleFunc("/api/add", web.add) - http.HandleFunc("/api/volume", web.volume) - http.HandleFunc("/api/skip", web.skip) - //http.HandleFunc("/api/status", web.status) - http.ListenAndServe(":"+strconv.Itoa(web.port), nil) -} - -func (web *WebServer) homepage(w http.ResponseWriter, r *http.Request) { - var uname = web.token_client[r.URL.Path[1:]] - if uname == nil { - fmt.Fprintf(w, "Invalid Token") - } else { - var webpage = uname.Name - - // Check to see if user has a custom webpage - if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/web/%s.html", dj.homeDir, uname.Name)); os.IsNotExist(err) { - webpage = "index" - } - - t, err := template.ParseFiles(fmt.Sprintf("%s/.mumbledj/web/%s.html", dj.homeDir, webpage)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - err = t.Execute(w, Page{getIP() + ":" + strconv.Itoa(web.port), r.URL.Path[1:], uname.Name}) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - } -} - -func (web *WebServer) add(w http.ResponseWriter, r *http.Request) { - var uname = web.token_client[r.FormValue("token")] - if uname == nil { - fmt.Fprintf(w, "Invalid Token") - } else { - add(uname, html.UnescapeString(r.FormValue("value"))) - fmt.Fprintf(w, "Success") - } -} - -func (web *WebServer) volume(w http.ResponseWriter, r *http.Request) { - var uname = web.token_client[r.FormValue("token")] - if uname == nil { - fmt.Fprintf(w, "Invalid Token") - } else { - var vol = html.UnescapeString(r.FormValue("value")) - volume(uname, vol) - fmt.Fprintf(w, "Success") - } -} - -func (web *WebServer) skip(w http.ResponseWriter, r *http.Request) { - var uname = web.token_client[r.FormValue("token")] - if uname == nil { - fmt.Fprintf(w, "Invalid Token") - } else { - value := html.UnescapeString(r.FormValue("value")) - playlist, err := strconv.ParseBool(value) - if err == nil { - skip(uname, false, playlist) - fmt.Fprintf(w, "Success") - } else { - fmt.Fprintf(w, "Invalid Value") - } - } -} - -//func (web *WebServer) status(w http.ResponseWriter, r *http.Request) { -// var uname = web.token_client[r.FormValue("token")] -// if uname == nil { -// str, ok := json.Marshal(&Status{true, "Invalid Token"}).(string) -// fmt.Fprintf(w, str) -// } else { -// // Generate song queue -// queueLength := dj.queue.Len() -// var songsInQueue [queueLength]SongInfo -// for i := 0; i < dj.queue.Len(); i++ { -// songItem := dj.queue.Get(i) -// songsInQueue[i] = &SongInfo{ -// TitleID: songItem.ID(), -// Title: songItem.Title(), -// Submitter: songItem.Submitter(), -// Duration: songItem.Duration(), -// Thumbnail: songItem.Thumbnail(), -// } -// if !isNil(songItem.Playlist()) { -// songsInQueue[i].PlaylistID = songItem.Playlist().ID() -// songsInQueue[i].Playlist = songItem.Playlist().Title() -// } -// } -// -// // Output status -// fmt.Fprintf(w, string(json.MarshalIndent(&Status{false, "", songsInQueue}))) -// } -//} - -func (website *WebServer) GetWebAddress(user *gumble.User) { - Verbose("Port number: " + strconv.Itoa(web.port)) - if web.client_token[user] != "" { - web.token_client[web.client_token[user]] = nil - } - // dealing with collisions - var firstLoop = true - for firstLoop || web.token_client[web.client_token[user]] != nil || web.client_token[user] == "api" { - web.client_token[user] = randSeq(10) - firstLoop = false - } - web.token_client[web.client_token[user]] = user - dj.SendPrivateMessage(user, fmt.Sprintf(WEB_ADDRESS, getIP(), web.client_token[user], getIP(), web.client_token[user])) -} - -// Gets the external ip address for the server -func getIP() string { - if external_ip != "" { - return external_ip - } else { - if response, err := http.Get("http://myexternalip.com/raw"); err == nil { - defer response.Body.Close() - if response.StatusCode == 200 { - if body, err := ioutil.ReadAll(response.Body); err == nil { - external_ip = strings.TrimSpace(string(body)) - } - } - } - return external_ip - } -} - -// Generates a pseudorandom string of characters -func randSeq(n int) string { - var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - b := make([]rune, n) - for i := range b { - b[i] = letters[rand.Intn(len(letters))] - } - return string(b) -} From 500bf8696ac8c0cf8e910cb1453665ea9c67a8e3 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 18:05:53 +0100 Subject: [PATCH 243/297] Removed web interface as it is unfinshed --- main.go | 7 ------- 1 file changed, 7 deletions(-) diff --git a/main.go b/main.go index b918974..69bd62f 100644 --- a/main.go +++ b/main.go @@ -174,8 +174,6 @@ var dj = mumbledj{ cache: NewSongCache(), } -var web *WebServer - // main primarily performs startup tasks. Grabs and parses commandline // args, sets up the gumble client and its listeners, and then connects to the server. func main() { @@ -251,10 +249,5 @@ func main() { Verbose("Testing is enabled") Test(password, address, port, strings.Split(accesstokens, " ")) } - - if isNil(web) { - Verbose("WEB IS NIL") - } - <-dj.keepAlive } From c0e1d502e22c3a5ce4ebee4a177b972a9b95cd79 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 18:10:16 +0100 Subject: [PATCH 244/297] Removed remaining references to web interface --- README.md | 1 - strings.go | 5 ----- 2 files changed, 6 deletions(-) diff --git a/README.md b/README.md index a54d434..cbadd15 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,6 @@ Command | Description | Arguments | Admin | Example **help** | Displays this list of commands in Mumble chat. | None | No | `!help` **volume** | Either outputs the current volume or changes the current volume. If desired volume is not provided, the current volume will be displayed in chat. Otherwise, the volume for the bot will be changed to desired volume if it is within the allowed volume range. | None OR desired volume | No | `!volume 0.5`, `!volume` **move** | Moves MumbleDJ into channel if it exists. | Channel | Yes | `!move Music` -**web** | Displays a unique url for the user to control mumbledj from a web browser | None | No | `!web` **reload** | Reloads `mumbledj.gcfg` to retrieve updated configuration settings. | None | Yes | `!reload` **reset** | Stops all audio and resets the song queue. | None | Yes | `!reset` **numsongs** | Outputs the number of songs in the queue in chat. Individual songs and songs within playlists are both counted. | None | No | `!numsongs` diff --git a/strings.go b/strings.go index 9d5524f..8e3d626 100644 --- a/strings.go +++ b/strings.go @@ -169,9 +169,4 @@ const CURRENT_SONG_HTML = ` // playlist is playing. const CURRENT_SONG_PLAYLIST_HTML = ` The song currently playing is "%s", added %s from the playlist "%s". -` -// URL of the server for connecting via a web address -const WEB_ADDRESS = ` - Control mumbledj from a web browser: http://%s:9563/%s -` From 984159d6272e5f2a267b0a22c34e34307c429146 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 18:11:48 +0100 Subject: [PATCH 245/297] Removed remaining references to web interface --- strings.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strings.go b/strings.go index 8e3d626..be2c4f7 100644 --- a/strings.go +++ b/strings.go @@ -169,4 +169,4 @@ const CURRENT_SONG_HTML = ` // playlist is playing. const CURRENT_SONG_PLAYLIST_HTML = ` The song currently playing is "%s", added %s from the playlist "%s". - +` \ No newline at end of file From cf666ad364907c2a7229e10ae26ddad93f4ad7a0 Mon Sep 17 00:00:00 2001 From: Michael Oultram Date: Sat, 15 Aug 2015 18:55:46 +0100 Subject: [PATCH 246/297] Update README.md --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index cbadd15..5bc7ea8 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ MumbleDJ [![Circle CI](https://circleci.com/gh/MichaelOultram/mumbledj/tree/mast * [Commands](#commands) * [Installation](#installation) * [YouTube API Keys](#youtube-api-keys) + * [Soundcloud API Keys](#soundcloud-api-keys) * [Setup Guide](#setup-guide) * [Update Guide](#update-guide) * [Troubleshooting](#troubleshooting) @@ -87,6 +88,19 @@ Effective April 20th, 2015, all requests to YouTube's API must use v3 of their A **8)** Close your current terminal window and open another one up. You should be able to use MumbleDJ now! +###SOUNDCLOUD API KEYS +A soundcloud API key is required for soundcloud integration. If no soundcloud api key is found, then the service will be disabled (youtube links will still work however). + +**1)** Login/signup for a soundcloud account on [https://soundcloud.com](https://soundcloud.com) + +**2)** Now to get the API key create a new app here: [http://soundcloud.com/you/apps/new](http://soundcloud.com/you/apps/new) + +**3)** Copy the Client ID (not the Client Secret) + +**4)** Open up `~/.bashrc` with your favorite text editor (or `~/.zshrc` if you use `zsh`). Add the following line to the bottom: `export SOUNDCLOUD_API_KEY=""`. Replace \ with your API key. + +**5)** Close your current terminal window and open another one up. You should be able to use soundcloud on MumbleDJ now! + ###SETUP GUIDE **1)** Install and correctly configure [`Go`](https://golang.org/) (1.4 or higher). Specifically, make sure to follow [this guide](https://golang.org/doc/code.html) and set the `GOPATH` environment variable properly. From 14ae00973dc16a72253505d8836f71b16db87024 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 19:17:26 +0100 Subject: [PATCH 247/297] Enables/Disables services based on whether API key exists --- main.go | 25 ++++++++++++++++++------- service.go | 10 +++++++++- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/main.go b/main.go index 69bd62f..0340d2a 100644 --- a/main.go +++ b/main.go @@ -133,28 +133,39 @@ func (dj *mumbledj) SendPrivateMessage(user *gumble.User, message string) { } } -// PerformStartupChecks checks the MumbleDJ installation to ensure proper usage. -func PerformStartupChecks() { +// CheckAPIKeys enables the services with API keys in the environment varaibles +func CheckAPIKeys() { + // Checks YouTube API key if os.Getenv("YOUTUBE_API_KEY") == "" { - fmt.Printf("You do not have a YouTube API key defined in your environment variables.\n" + + fmt.Printf("The youtube service has been disabled as you do not have a YouTube API key defined in your environment variables.\n" + "Please see the following link for info on how to fix this: https://github.com/matthieugrieger/mumbledj#youtube-api-keys\n") - os.Exit(1) + } else { + AddService(YouTube{}) + } + + // Checks Soundcloud API key + if os.Getenv("SOUNDCLOUD_API_KEY") == "" { + fmt.Printf("The soundcloud service has been disabled as you do not have a Soundcloud API key defined in your environment variables.\n" + + "Please see the following link for info on how to fix this: https://github.com/matthieugrieger/mumbledj#soundcloud-api-keys\n") + } else { + AddService(SoundCloud{}) } } -// Prints out messages only if verbose flag is true +// Verbose prints out messages only if verbose flag is true func Verbose(msg string) { if dj.verbose { fmt.Printf(msg + "\n") } } -// Checks to see if an object is nil +// isNil checks to see if an object is nil func isNil(a interface{}) bool { defer func() { recover() }() return a == nil || reflect.ValueOf(a).IsNil() } +// RegexpFromURL loops through an array of patterns to see if it matches the url func RegexpFromURL(url string, patterns []string) *regexp.Regexp { for _, pattern := range patterns { if re, err := regexp.Compile(pattern); err == nil { @@ -178,7 +189,7 @@ var dj = mumbledj{ // args, sets up the gumble client and its listeners, and then connects to the server. func main() { - PerformStartupChecks() + CheckAPIKeys() if currentUser, err := user.Current(); err == nil { dj.homeDir = currentUser.HomeDir diff --git a/service.go b/service.go index 15a5947..78ae1bc 100644 --- a/service.go +++ b/service.go @@ -52,7 +52,15 @@ type Playlist interface { Title() string } -var services = []Service{YouTube{}, SoundCloud{}} +var services []Service + +func AddService(service Service) { + if services == nil { + service = Service{service} + } else { + service = append(service, services) + } +} func findServiceAndAdd(user *gumble.User, url string) error { var urlService Service From 098c12dfda32450519b3b4fe2d83d8a80b93e444 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 19:30:15 +0100 Subject: [PATCH 248/297] Enable/Disable services based on API key existence --- main.go | 4 ++-- service.go | 8 -------- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/main.go b/main.go index 0340d2a..9b0f445 100644 --- a/main.go +++ b/main.go @@ -140,7 +140,7 @@ func CheckAPIKeys() { fmt.Printf("The youtube service has been disabled as you do not have a YouTube API key defined in your environment variables.\n" + "Please see the following link for info on how to fix this: https://github.com/matthieugrieger/mumbledj#youtube-api-keys\n") } else { - AddService(YouTube{}) + services = append(services, YouTube{}) } // Checks Soundcloud API key @@ -148,7 +148,7 @@ func CheckAPIKeys() { fmt.Printf("The soundcloud service has been disabled as you do not have a Soundcloud API key defined in your environment variables.\n" + "Please see the following link for info on how to fix this: https://github.com/matthieugrieger/mumbledj#soundcloud-api-keys\n") } else { - AddService(SoundCloud{}) + services = append(services, SoundCloud{}) } } diff --git a/service.go b/service.go index 78ae1bc..8af34f6 100644 --- a/service.go +++ b/service.go @@ -54,14 +54,6 @@ type Playlist interface { var services []Service -func AddService(service Service) { - if services == nil { - service = Service{service} - } else { - service = append(service, services) - } -} - func findServiceAndAdd(user *gumble.User, url string) error { var urlService Service From 41587d8e2340a0e6bff86989afdc0185ac55d0d4 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 19:40:21 +0100 Subject: [PATCH 249/297] Removed unneeded test command Testing is instead specified as a command line argument --- commands.go | 7 ------- 1 file changed, 7 deletions(-) diff --git a/commands.go b/commands.go index 5c52bb0..ee449e2 100644 --- a/commands.go +++ b/commands.go @@ -152,13 +152,6 @@ func parseCommand(user *gumble.User, username, command string) { } else { dj.SendPrivateMessage(user, NO_PERMISSION_MSG) } - // Test command (WORKAROUND) - case "test": - if dj.HasPermission(username, dj.conf.Permissions.AdminKill) { - test.testYoutubeSong() - } else { - dj.SendPrivateMessage(user, NO_PERMISSION_MSG) - } default: dj.SendPrivateMessage(user, COMMAND_DOESNT_EXIST_MSG) } From c538af8a14a6383baf34c858300ef74d315bedb4 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 19:56:00 +0100 Subject: [PATCH 250/297] Updated youtube_dl song and playlist type names --- service.go | 6 ++--- service_soundcloud.go | 4 +-- service_youtube.go | 4 +-- youtube_dl.go | 59 ++++++++++++++++++++++--------------------- 4 files changed, 37 insertions(+), 36 deletions(-) diff --git a/service.go b/service.go index 8af34f6..caaf680 100644 --- a/service.go +++ b/service.go @@ -14,11 +14,11 @@ import ( "github.com/layeh/gumble/gumble" ) -// Service interface. Each service should implement these functions +// Service interface. Each service will implement these functions type Service interface { ServiceName() string - URLRegex(string) bool // Can service deal with URL - NewRequest(*gumble.User, string) (string, error) // Create song/playlist and add to the queue + URLRegex(string) bool + NewRequest(*gumble.User, string) (string, error) } // Song interface. Each service will implement these diff --git a/service_soundcloud.go b/service_soundcloud.go index 4e47e8d..250ca26 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -50,7 +50,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { // Create playlist title, _ := apiResponse.String("title") permalink, _ := apiResponse.String("permalink_url") - playlist := &YouTubeDLPlaylist{ + playlist := &YouTubePlaylist{ id: permalink, title: title, } @@ -109,7 +109,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play return "", err } - song := &YouTubeDLSong{ + song := &YouTubeSong{ id: strconv.Itoa(id), title: title, url: url, diff --git a/service_youtube.go b/service_youtube.go index b437d71..2592061 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -161,7 +161,7 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis } if dj.conf.General.MaxSongDuration == 0 || totalSeconds <= dj.conf.General.MaxSongDuration { - song := &YouTubeDLSong{ + song := &YouTubeSong{ submitter: user, title: title, id: id, @@ -193,7 +193,7 @@ func (yt YouTube) NewPlaylist(user *gumble.User, id string) (Playlist, error) { } title, _ := apiResponse.String("items", "0", "snippet", "title") - playlist := &YouTubeDLPlaylist{ + playlist := &YouTubePlaylist{ id: id, title: title, } diff --git a/youtube_dl.go b/youtube_dl.go index c1685ee..0721506 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -11,8 +11,8 @@ import ( "github.com/layeh/gumble/gumble_ffmpeg" ) -// Extends a Song -type YouTubeDLSong struct { +// YouTubeSong implements the Song interface +type YouTubeSong struct { id string title string thumbnail string @@ -26,18 +26,19 @@ type YouTubeDLSong struct { dontSkip bool } -type YouTubeDLPlaylist struct { +// YouTubePlaylist implements the Playlist interface +type YouTubePlaylist struct { id string title string } -// ------------- -// YouTubeDLSong -// ------------- +// ------------ +// YOUTUBE SONG +// ------------ // Download downloads the song via youtube-dl if it does not already exist on disk. // All downloaded songs are stored in ~/.mumbledj/songs and should be automatically cleaned. -func (dl *YouTubeDLSong) Download() error { +func (dl *YouTubeSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { @@ -64,7 +65,7 @@ func (dl *YouTubeDLSong) Download() error { // Play plays the song. Once the song is playing, a notification is displayed in a text message that features the song // thumbnail, URL, title, duration, and submitter. -func (dl *YouTubeDLSong) Play() { +func (dl *YouTubeSong) Play() { if dl.offset != 0 { offsetDuration, _ := time.ParseDuration(fmt.Sprintf("%ds", dl.offset)) dj.audioStream.Offset = offsetDuration @@ -89,7 +90,7 @@ func (dl *YouTubeDLSong) Play() { } // Delete deletes the song from ~/.mumbledj/songs if the cache is disabled. -func (dl *YouTubeDLSong) Delete() error { +func (dl *YouTubeSong) Delete() error { if dj.conf.Cache.Enabled == false { filePath := fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()) if _, err := os.Stat(filePath); err == nil { @@ -105,7 +106,7 @@ func (dl *YouTubeDLSong) Delete() error { // AddSkip adds a skip to the skippers slice. If the user is already in the slice, AddSkip // returns an error and does not add a duplicate skip. -func (dl *YouTubeDLSong) AddSkip(username string) error { +func (dl *YouTubeSong) AddSkip(username string) error { for _, user := range dl.skippers { if username == user { return errors.New("This user has already skipped the current song.") @@ -117,7 +118,7 @@ func (dl *YouTubeDLSong) AddSkip(username string) error { // RemoveSkip removes a skip from the skippers slice. If username is not in slice, an error is // returned. -func (dl *YouTubeDLSong) RemoveSkip(username string) error { +func (dl *YouTubeSong) RemoveSkip(username string) error { for i, user := range dl.skippers { if username == user { dl.skippers = append(dl.skippers[:i], dl.skippers[i+1:]...) @@ -130,7 +131,7 @@ func (dl *YouTubeDLSong) RemoveSkip(username string) error { // SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's // channel and the number of usernames in the skippers slice. If the value is greater than or equal // to the skip ratio defined in the config, the function returns true, and returns false otherwise. -func (dl *YouTubeDLSong) SkipReached(channelUsers int) bool { +func (dl *YouTubeSong) SkipReached(channelUsers int) bool { if float32(len(dl.skippers))/float32(channelUsers) >= dj.conf.General.SkipRatio { return true } @@ -138,47 +139,47 @@ func (dl *YouTubeDLSong) SkipReached(channelUsers int) bool { } // Submitter returns the name of the submitter of the Song. -func (dl *YouTubeDLSong) Submitter() string { +func (dl *YouTubeSong) Submitter() string { return dl.submitter.Name } // Title returns the title of the Song. -func (dl *YouTubeDLSong) Title() string { +func (dl *YouTubeSong) Title() string { return dl.title } // ID returns the id of the Song. -func (dl *YouTubeDLSong) ID() string { +func (dl *YouTubeSong) ID() string { return dl.id } // Filename returns the filename of the Song. -func (dl *YouTubeDLSong) Filename() string { +func (dl *YouTubeSong) Filename() string { return dl.id + dl.format } // Duration returns the duration of the Song. -func (dl *YouTubeDLSong) Duration() string { +func (dl *YouTubeSong) Duration() string { return dl.duration } // Thumbnail returns the thumbnail URL for the Song. -func (dl *YouTubeDLSong) Thumbnail() string { +func (dl *YouTubeSong) Thumbnail() string { return dl.thumbnail } // Playlist returns the playlist type for the Song (may be nil). -func (dl *YouTubeDLSong) Playlist() Playlist { +func (dl *YouTubeSong) Playlist() Playlist { return dl.playlist } // DontSkip returns the DontSkip boolean value for the Song. -func (dl *YouTubeDLSong) DontSkip() bool { +func (dl *YouTubeSong) DontSkip() bool { return dl.dontSkip } // SetDontSkip sets the DontSkip boolean value for the Song. -func (dl *YouTubeDLSong) SetDontSkip(value bool) { +func (dl *YouTubeSong) SetDontSkip(value bool) { dl.dontSkip = value } @@ -187,7 +188,7 @@ func (dl *YouTubeDLSong) SetDontSkip(value bool) { // ---------------- // AddSkip adds a skip to the playlist's skippers slice. -func (p *YouTubeDLPlaylist) AddSkip(username string) error { +func (p *YouTubePlaylist) AddSkip(username string) error { for _, user := range dj.playlistSkips[p.ID()] { if username == user { return errors.New("This user has already skipped the current song.") @@ -199,7 +200,7 @@ func (p *YouTubeDLPlaylist) AddSkip(username string) error { // RemoveSkip removes a skip from the playlist's skippers slice. If username is not in the slice // an error is returned. -func (p *YouTubeDLPlaylist) RemoveSkip(username string) error { +func (p *YouTubePlaylist) RemoveSkip(username string) error { for i, user := range dj.playlistSkips[p.ID()] { if username == user { dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()][:i], dj.playlistSkips[p.ID()][i+1:]...) @@ -210,26 +211,26 @@ func (p *YouTubeDLPlaylist) RemoveSkip(username string) error { } // DeleteSkippers removes the skippers entry in dj.playlistSkips. -func (p *YouTubeDLPlaylist) DeleteSkippers() { +func (p *YouTubePlaylist) DeleteSkippers() { delete(dj.playlistSkips, p.ID()) } // SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's // channel and the number of usernames in the skippers slice. If the value is greater than or equal // to the skip ratio defined in the config, the function returns true, and returns false otherwise. -func (p *YouTubeDLPlaylist) SkipReached(channelUsers int) bool { +func (p *YouTubePlaylist) SkipReached(channelUsers int) bool { if float32(len(dj.playlistSkips[p.ID()]))/float32(channelUsers) >= dj.conf.General.PlaylistSkipRatio { return true } return false } -// ID returns the id of the YouTubeDLPlaylist. -func (p *YouTubeDLPlaylist) ID() string { +// ID returns the id of the YouTubePlaylist. +func (p *YouTubePlaylist) ID() string { return p.id } -// Title returns the title of the YouTubeDLPlaylist. -func (p *YouTubeDLPlaylist) Title() string { +// Title returns the title of the YouTubePlaylist. +func (p *YouTubePlaylist) Title() string { return p.title } From 5fed70ca662130676bbca4d8496a1d83a639508c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 15 Aug 2015 22:22:59 +0100 Subject: [PATCH 251/297] Cleanup comments --- commands.go | 2 +- main.go | 33 +++++++++--------- service.go | 17 +++++++-- service_soundcloud.go | 80 +++++++++++++++---------------------------- service_youtube.go | 18 +++------- 5 files changed, 65 insertions(+), 85 deletions(-) diff --git a/commands.go b/commands.go index ee449e2..5d3d0de 100644 --- a/commands.go +++ b/commands.go @@ -164,7 +164,7 @@ func add(user *gumble.User, url string) error { dj.SendPrivateMessage(user, NO_ARGUMENT_MSG) return errors.New("NO_ARGUMENT") } else { - err := findServiceAndAdd(user, url) + err := FindServiceAndAdd(user, url) if err != nil { dj.SendPrivateMessage(user, err.Error()) } diff --git a/main.go b/main.go index 9b0f445..1bd6df7 100644 --- a/main.go +++ b/main.go @@ -135,21 +135,34 @@ func (dj *mumbledj) SendPrivateMessage(user *gumble.User, message string) { // CheckAPIKeys enables the services with API keys in the environment varaibles func CheckAPIKeys() { + anyDisabled := false + // Checks YouTube API key if os.Getenv("YOUTUBE_API_KEY") == "" { - fmt.Printf("The youtube service has been disabled as you do not have a YouTube API key defined in your environment variables.\n" + - "Please see the following link for info on how to fix this: https://github.com/matthieugrieger/mumbledj#youtube-api-keys\n") + anyDisabled = true + fmt.Printf("The youtube service has been disabled as you do not have a YouTube API key defined in your environment variables.\n") } else { services = append(services, YouTube{}) } // Checks Soundcloud API key if os.Getenv("SOUNDCLOUD_API_KEY") == "" { - fmt.Printf("The soundcloud service has been disabled as you do not have a Soundcloud API key defined in your environment variables.\n" + - "Please see the following link for info on how to fix this: https://github.com/matthieugrieger/mumbledj#soundcloud-api-keys\n") + anyDisabled = true + fmt.Printf("The soundcloud service has been disabled as you do not have a Soundcloud API key defined in your environment variables.\n") } else { services = append(services, SoundCloud{}) } + + // Checks to see if any service was disabled + if anyDisabled { + fmt.Printf("Please see the following link for info on how to enable services: https://github.com/matthieugrieger/mumbledj\n") + } + + // Exits application if no services are enabled + if services == nil { + fmt.Printf("No services are enabled, and thus closing\n") + os.Exit(1) + } } // Verbose prints out messages only if verbose flag is true @@ -165,18 +178,6 @@ func isNil(a interface{}) bool { return a == nil || reflect.ValueOf(a).IsNil() } -// RegexpFromURL loops through an array of patterns to see if it matches the url -func RegexpFromURL(url string, patterns []string) *regexp.Regexp { - for _, pattern := range patterns { - if re, err := regexp.Compile(pattern); err == nil { - if re.MatchString(url) { - return re - } - } - } - return nil -} - // dj variable declaration. This is done outside of main() to allow global use. var dj = mumbledj{ keepAlive: make(chan bool), diff --git a/service.go b/service.go index caaf680..624314f 100644 --- a/service.go +++ b/service.go @@ -16,7 +16,6 @@ import ( // Service interface. Each service will implement these functions type Service interface { - ServiceName() string URLRegex(string) bool NewRequest(*gumble.User, string) (string, error) } @@ -54,7 +53,7 @@ type Playlist interface { var services []Service -func findServiceAndAdd(user *gumble.User, url string) error { +func FindServiceAndAdd(user *gumble.User, url string) error { var urlService Service // Checks all services to see if any can take the URL @@ -65,7 +64,7 @@ func findServiceAndAdd(user *gumble.User, url string) error { } if urlService == nil { - Verbose("Invalid_URL") + Verbose("INVALID_URL") return errors.New("INVALID_URL") } else { oldLength := dj.queue.Len() @@ -91,3 +90,15 @@ func findServiceAndAdd(user *gumble.User, url string) error { return err } } + +// RegexpFromURL loops through an array of patterns to see if it matches the url +func RegexpFromURL(url string, patterns []string) *regexp.Regexp { + for _, pattern := range patterns { + if re, err := regexp.Compile(pattern); err == nil { + if re.MatchString(url) { + return re + } + } + } + return nil +} diff --git a/service_soundcloud.go b/service_soundcloud.go index 250ca26..a1c2b2a 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -11,7 +11,7 @@ import ( ) // Regular expressions for soundcloud urls -var soundcloudSongPattern = `https?:\/\/(www\.)?soundcloud\.com\/([\w-]+)\/([\w-]+)` +var soundcloudSongPattern = `https?:\/\/(www\.)?soundcloud\.com\/([\w-]+)\/([\w-]+)(#t=\n\n?(:\n\n)*)?` var soundcloudPlaylistPattern = `https?:\/\/(www\.)?soundcloud\.com\/([\w-]+)\/sets\/([\w-]+)` // SoundCloud implements the Service interface @@ -21,17 +21,12 @@ type SoundCloud struct{} // SOUNDCLOUD SERVICE // ------------------ -// Name of the service -func (sc SoundCloud) ServiceName() string { - return "SoundCloud" -} - -// Checks to see if service will accept URL +// URLRegex checks to see if service will accept URL func (sc SoundCloud) URLRegex(url string) bool { return RegexpFromURL(url, []string{soundcloudSongPattern, soundcloudPlaylistPattern}) != nil } -// Creates the requested song/playlist and adds to the queue +// NewRequest creates the requested song/playlist and adds to the queue func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { var apiResponse *jsonq.JsonQuery var err error @@ -74,53 +69,34 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { } } -// Creates a track and adds to the queue -func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, playlist Playlist) (string, error) { - title, err := trackData.String("title") - if err != nil { - return "", err - } - - id, err := trackData.Int("id") - if err != nil { - return "", err - } - - duration, err := trackData.Int("duration") - if err != nil { - return "", err - } +// NewSong creates a track and adds to the queue +func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, playlist Playlist) (Song, error) { + title, _ := trackData.String("title") + id, _ := trackData.Int("id") + duration, _ := trackData.Int("duration") + url, _ := trackData.String("permalink_url") thumbnail, err := trackData.String("artwork_url") if err != nil { // Song has no artwork, using profile avatar instead - userObj, err := trackData.Object("user") - if err != nil { - return "", err - } - - thumbnail, err = jsonq.NewQuery(userObj).String("avatar_url") - if err != nil { - return "", err + userObj, _ := trackData.Object("user") + thumbnail, _ = jsonq.NewQuery(userObj).String("avatar_url") + } + + if dj.conf.General.MaxSongDuration == 0 || (duration/1000) <= dj.conf.General.MaxSongDuration { + song := &YouTubeSong{ + id: strconv.Itoa(id), + title: title, + url: url, + thumbnail: thumbnail, + submitter: user, + duration: strconv.Itoa(duration), + format: "mp3", + playlist: playlist, + skippers: make([]string, 0), + dontSkip: false, } + dj.queue.AddSong(song) + return song, nil } - - url, err := trackData.String("permalink_url") - if err != nil { - return "", err - } - - song := &YouTubeSong{ - id: strconv.Itoa(id), - title: title, - url: url, - thumbnail: thumbnail, - submitter: user, - duration: strconv.Itoa(duration), - format: "mp3", - playlist: playlist, - skippers: make([]string, 0), - dontSkip: false, - } - dj.queue.AddSong(song) - return title, nil + return nil, errors.New(VIDEO_TOO_LONG_MSG) } diff --git a/service_youtube.go b/service_youtube.go index 2592061..6457e20 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -25,11 +25,9 @@ import ( // Regular expressions for youtube urls var youtubePlaylistPattern = `https?:\/\/www\.youtube\.com\/playlist\?list=([\w-]+)` var youtubeVideoPatterns = []string{ - `https?:\/\/www\.youtube\.com\/watch\?v=([\w-]+)(\&t=\d*m?\d*s?)?`, - `https?:\/\/youtube\.com\/watch\?v=([\w-]+)(\&t=\d*m?\d*s?)?`, + `https?:\/\/(www\.)?youtube\.com\/watch\?v=([\w-]+)(\&t=\d*m?\d*s?)?`, + `https?:\/\/(www\.)?youtube\.com\/v\/([\w-]+)(\?t=\d*m?\d*s?)?`, `https?:\/\/youtu.be\/([\w-]+)(\?t=\d*m?\d*s?)?`, - `https?:\/\/youtube.com\/v\/([\w-]+)(\?t=\d*m?\d*s?)?`, - `https?:\/\/www.youtube.com\/v\/([\w-]+)(\?t=\d*m?\d*s?)?`, } // ------ @@ -43,17 +41,12 @@ type YouTube struct{} // YOUTUBE SERVICE // --------------- -// Name of the service -func (yt YouTube) ServiceName() string { - return "Youtube" -} - -// Checks to see if service will accept URL +// URLRegex checks to see if service will accept URL func (yt YouTube) URLRegex(url string) bool { return RegexpFromURL(url, append(youtubeVideoPatterns, []string{youtubePlaylistPattern}...)) != nil } -// Creates the requested song/playlist and adds to the queue +// NewRequest creates the requested song/playlist and adds to the queue func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { var shortURL, startOffset = "", "" if re, err := regexp.Compile(youtubePlaylistPattern); err == nil { @@ -85,8 +78,7 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { } } -// NewSong gathers the metadata for a song extracted from a YouTube video, and returns -// the song. +// NewSong gathers the metadata for a song extracted from a YouTube video, and returns the song. func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlist) (Song, error) { var apiResponse *jsonq.JsonQuery var err error From 29eec2d242d140c0f4ff28e647fbae0ba0961cc8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 01:10:35 +0100 Subject: [PATCH 252/297] Removed the verbose command --- README.md | 1 - main.go | 13 +------------ service.go | 3 +-- service_soundcloud.go | 4 ---- service_youtube.go | 2 -- youtube_dl.go | 5 +---- 6 files changed, 3 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 5bc7ea8..3cd40cd 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,6 @@ All commandline parameters are optional. Below are descriptions of all the avail * `-key`: Path to user PEM key. Defaults to no key. * `-insecure`: If included, the bot will not check the certs for the server. Try using this commandline flag if you are having connection issues. * `-accesstokens`: List of access tokens for the bot separated by spaces. Defaults to no access tokens. -* `-verbose`: Prints out song status into the console. ## FEATURES * Plays audio from both YouTube videos and YouTube playlists! diff --git a/main.go b/main.go index 1bd6df7..0de2dc4 100644 --- a/main.go +++ b/main.go @@ -37,7 +37,6 @@ type mumbledj struct { homeDir string playlistSkips map[string][]string cache *SongCache - verbose bool } // OnConnect event. First moves MumbleDJ into the default channel specified @@ -165,13 +164,6 @@ func CheckAPIKeys() { } } -// Verbose prints out messages only if verbose flag is true -func Verbose(msg string) { - if dj.verbose { - fmt.Printf(msg + "\n") - } -} - // isNil checks to see if an object is nil func isNil(a interface{}) bool { defer func() { recover() }() @@ -203,7 +195,7 @@ func main() { } var address, port, username, password, channel, pemCert, pemKey, accesstokens string - var insecure, verbose, testcode bool + var insecure, testcode bool flag.StringVar(&address, "server", "localhost", "address for Mumble server") flag.StringVar(&port, "port", "64738", "port for Mumble server") @@ -214,7 +206,6 @@ func main() { flag.StringVar(&pemKey, "key", "", "path to user PEM key for MumbleDJ") flag.StringVar(&accesstokens, "accesstokens", "", "list of access tokens for channel auth") flag.BoolVar(&insecure, "insecure", false, "skip certificate checking") - flag.BoolVar(&verbose, "verbose", false, "[debug] prints out debug messages to the console") flag.BoolVar(&testcode, "test", false, "[debug] tests the features of mumbledj") flag.Parse() @@ -242,7 +233,6 @@ func main() { } dj.defaultChannel = strings.Split(channel, "/") - dj.verbose = verbose dj.client.Attach(gumbleutil.Listener{ Connect: dj.OnConnect, @@ -258,7 +248,6 @@ func main() { } if testcode { - Verbose("Testing is enabled") Test(password, address, port, strings.Split(accesstokens, " ")) } <-dj.keepAlive diff --git a/service.go b/service.go index 624314f..c6ec6e1 100644 --- a/service.go +++ b/service.go @@ -64,8 +64,7 @@ func FindServiceAndAdd(user *gumble.User, url string) error { } if urlService == nil { - Verbose("INVALID_URL") - return errors.New("INVALID_URL") + return errors.New(INVALID_URL_MSG) } else { oldLength := dj.queue.Len() var title string diff --git a/service_soundcloud.go b/service_soundcloud.go index a1c2b2a..a204010 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -39,9 +39,6 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { if err == nil { // PLAYLIST if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { - // Check duration of playlist - //duration, _ := apiResponse.Int("duration") - // Create playlist title, _ := apiResponse.String("title") permalink, _ := apiResponse.String("permalink_url") @@ -57,7 +54,6 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { if err == nil { return playlist.Title(), nil } else { - Verbose("soundcloud.NewRequest: " + err.Error()) return "", err } } else { diff --git a/service_youtube.go b/service_youtube.go index 6457e20..cc5a536 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -69,7 +69,6 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { if !isNil(song) { return song.Title(), nil } else { - Verbose("youtube.NewRequest: " + err.Error()) return "", err } } @@ -167,7 +166,6 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis dontSkip: false, } dj.queue.AddSong(song) - Verbose(song.Submitter() + " added track " + song.Title()) return song, nil } diff --git a/youtube_dl.go b/youtube_dl.go index 0721506..64afb97 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -54,9 +54,7 @@ func (dl *YouTubeSong) Download() error { for s := range cmd.Args { args += cmd.Args[s] + " " } - Verbose(args) - Verbose(string(output)) - Verbose("youtube-dl: " + err.Error()) + fmt.Printf(args + "\n" + string(output) + "\n" + "youtube-dl: " + err.Error() + "\n") return errors.New("Song download failed.") } } @@ -80,7 +78,6 @@ func (dl *YouTubeSong) Play() { message = fmt.Sprintf(message+`
`, dl.playlist.Title()) } dj.client.Self.Channel.Send(message+`
%s (%s)
Added by %s
From playlist "%s"
From playlist "%s"
`, false) - Verbose("Now playing " + dl.title) go func() { dj.audioStream.Wait() From 46d7217fa1ce44942ac3039f563789f814bd55cc Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 01:15:39 +0100 Subject: [PATCH 253/297] Removed unneeded get function in SongQueue --- songqueue.go | 8 -------- 1 file changed, 8 deletions(-) diff --git a/songqueue.go b/songqueue.go index d00f771..f1bdc1c 100644 --- a/songqueue.go +++ b/songqueue.go @@ -77,14 +77,6 @@ func (q *SongQueue) Traverse(visit func(i int, s Song)) { } } -// Gets the song at a specific point in the queue -func (q *SongQueue) Get(i int) (Song, error) { - if q.Len() > i+1 { - return q.queue[i], nil - } - return nil, errors.New("Out of Bounds") -} - // OnSongFinished event. Deletes Song that just finished playing, then queues the next Song (if exists). func (q *SongQueue) OnSongFinished() { resetOffset, _ := time.ParseDuration(fmt.Sprintf("%ds", 0)) From a5fe8960f2a203a8823ad1dc57a052eae5cbbe7c Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 01:18:46 +0100 Subject: [PATCH 254/297] Fixing build errors --- main.go | 1 - service.go | 1 + service_soundcloud.go | 4 ++-- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 0de2dc4..3682ac7 100644 --- a/main.go +++ b/main.go @@ -14,7 +14,6 @@ import ( "os" "os/user" "reflect" - "regexp" "strings" "time" diff --git a/service.go b/service.go index c6ec6e1..a8e400c 100644 --- a/service.go +++ b/service.go @@ -10,6 +10,7 @@ package main import ( "errors" "fmt" + "regexp" "github.com/layeh/gumble/gumble" ) diff --git a/service_soundcloud.go b/service_soundcloud.go index a204010..1917e3d 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -66,7 +66,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { } // NewSong creates a track and adds to the queue -func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, playlist Playlist) (Song, error) { +func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, playlist Playlist) (string, error) { title, _ := trackData.String("title") id, _ := trackData.Int("id") duration, _ := trackData.Int("duration") @@ -94,5 +94,5 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play dj.queue.AddSong(song) return song, nil } - return nil, errors.New(VIDEO_TOO_LONG_MSG) + return "", errors.New(VIDEO_TOO_LONG_MSG) } From 7a12696df3801da4e5043f3468f5b4974cfdb4b3 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 01:19:51 +0100 Subject: [PATCH 255/297] Fixing build errors --- service_soundcloud.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 1917e3d..f332002 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -92,7 +92,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play dontSkip: false, } dj.queue.AddSong(song) - return song, nil + return song.Title(), nil } return "", errors.New(VIDEO_TOO_LONG_MSG) } From 62c26c23e89df4712c3682021a84a8ee7f7aa6d2 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 01:21:14 +0100 Subject: [PATCH 256/297] Removed verbose tag from circle.yml --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index aeeb361..0d99b58 100644 --- a/circle.yml +++ b/circle.yml @@ -23,5 +23,5 @@ dependencies: test: override: - - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -verbose=true -test=true: + - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -test=true: timeout: 180 \ No newline at end of file From 95ad3cf09bb0ac7b85878a3c73ce8bd4b9a24526 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 01:28:22 +0100 Subject: [PATCH 257/297] Reverted youtube patterns --- service_youtube.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/service_youtube.go b/service_youtube.go index cc5a536..06c9543 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -25,9 +25,11 @@ import ( // Regular expressions for youtube urls var youtubePlaylistPattern = `https?:\/\/www\.youtube\.com\/playlist\?list=([\w-]+)` var youtubeVideoPatterns = []string{ - `https?:\/\/(www\.)?youtube\.com\/watch\?v=([\w-]+)(\&t=\d*m?\d*s?)?`, - `https?:\/\/(www\.)?youtube\.com\/v\/([\w-]+)(\?t=\d*m?\d*s?)?`, + `https?:\/\/www\.youtube\.com\/watch\?v=([\w-]+)(\&t=\d*m?\d*s?)?`, + `https?:\/\/youtube\.com\/watch\?v=([\w-]+)(\&t=\d*m?\d*s?)?`, `https?:\/\/youtu.be\/([\w-]+)(\?t=\d*m?\d*s?)?`, + `https?:\/\/youtube.com\/v\/([\w-]+)(\?t=\d*m?\d*s?)?`, + `https?:\/\/www.youtube.com\/v\/([\w-]+)(\?t=\d*m?\d*s?)?`, } // ------ From c45b7c94358ff76010a9716e38a0323a3692dcdc Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 02:04:36 +0100 Subject: [PATCH 258/297] Soundcloud links with a time will be offset --- service_soundcloud.go | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index f332002..476e15c 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -5,6 +5,8 @@ import ( "fmt" "os" "strconv" + "strings" + "time" "github.com/jmoiron/jsonq" "github.com/layeh/gumble/gumble" @@ -61,15 +63,22 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { } } else { // SONG - return sc.NewSong(user, apiResponse, nil) + // Calculating offset + offset := 0 + timesplit := strings.Split(url, "#t=") + if timesplit.size == 2 { + offset = time.Duration(timesplit[1]).Seconds() + } + + return sc.NewSong(user, apiResponse, offset, nil) } } // NewSong creates a track and adds to the queue -func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, playlist Playlist) (string, error) { +func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offset int, playlist Playlist) (string, error) { title, _ := trackData.String("title") id, _ := trackData.Int("id") - duration, _ := trackData.Int("duration") + durationMS, _ := trackData.Int("duration") url, _ := trackData.String("permalink_url") thumbnail, err := trackData.String("artwork_url") if err != nil { @@ -78,14 +87,19 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, play thumbnail, _ = jsonq.NewQuery(userObj).String("avatar_url") } - if dj.conf.General.MaxSongDuration == 0 || (duration/1000) <= dj.conf.General.MaxSongDuration { + // Check song is not longer than the MaxSongDuration + if dj.conf.General.MaxSongDuration == 0 || (durationMS/1000) <= dj.conf.General.MaxSongDuration { + duration, err = time.ParseDuration(strconv.Itoa(durationMS) + "ms") + duration = strings.NewReplacer("h", ":", "m", ":", "s", ":").Replace(duration.String()) + song := &YouTubeSong{ id: strconv.Itoa(id), title: title, url: url, thumbnail: thumbnail, submitter: user, - duration: strconv.Itoa(duration), + duration: duration, + offset: offset, format: "mp3", playlist: playlist, skippers: make([]string, 0), From 79305a408df6c0eda4f5eedbb9ad94f83f50784b Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 02:10:17 +0100 Subject: [PATCH 259/297] Soundcloud links with a time will be offset --- service_soundcloud.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 476e15c..cf5a76b 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -51,7 +51,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { // Add all tracks for _, t := range tracks { - sc.NewSong(user, jsonq.NewQuery(t), playlist) + sc.NewSong(user, jsonq.NewQuery(t), 0, playlist) } if err == nil { return playlist.Title(), nil @@ -66,8 +66,8 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { // Calculating offset offset := 0 timesplit := strings.Split(url, "#t=") - if timesplit.size == 2 { - offset = time.Duration(timesplit[1]).Seconds() + if timesplit.Length == 2 { + offset = time.ParseDuration(timesplit[1]).Seconds() } return sc.NewSong(user, apiResponse, offset, nil) @@ -89,7 +89,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offs // Check song is not longer than the MaxSongDuration if dj.conf.General.MaxSongDuration == 0 || (durationMS/1000) <= dj.conf.General.MaxSongDuration { - duration, err = time.ParseDuration(strconv.Itoa(durationMS) + "ms") + duration, _ := time.ParseDuration(strconv.Itoa(durationMS) + "ms") duration = strings.NewReplacer("h", ":", "m", ":", "s", ":").Replace(duration.String()) song := &YouTubeSong{ From 3c4513ae32e483487959a00dfad805aabea88698 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 02:14:08 +0100 Subject: [PATCH 260/297] Soundcloud links with a time will be offset --- service_soundcloud.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index cf5a76b..48ebbb1 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -66,8 +66,9 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { // Calculating offset offset := 0 timesplit := strings.Split(url, "#t=") - if timesplit.Length == 2 { - offset = time.ParseDuration(timesplit[1]).Seconds() + if timesplit.Size == 2 { + duration, _ := time.ParseDuration(timesplit[1]) + offset = duration.Seconds() } return sc.NewSong(user, apiResponse, offset, nil) @@ -89,8 +90,8 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offs // Check song is not longer than the MaxSongDuration if dj.conf.General.MaxSongDuration == 0 || (durationMS/1000) <= dj.conf.General.MaxSongDuration { - duration, _ := time.ParseDuration(strconv.Itoa(durationMS) + "ms") - duration = strings.NewReplacer("h", ":", "m", ":", "s", ":").Replace(duration.String()) + timeDuration, _ := time.ParseDuration(strconv.Itoa(durationMS) + "ms") + duration = strings.NewReplacer("h", ":", "m", ":", "s", ":").Replace(timeDuration.String()) song := &YouTubeSong{ id: strconv.Itoa(id), From 565d25b5880e93c2857ab33760c60b07a4c97aae Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 02:19:26 +0100 Subject: [PATCH 261/297] Soundcloud links with a time will be offset --- service_soundcloud.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 48ebbb1..af3f077 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -66,9 +66,9 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { // Calculating offset offset := 0 timesplit := strings.Split(url, "#t=") - if timesplit.Size == 2 { + if len(timesplit) == 2 { duration, _ := time.ParseDuration(timesplit[1]) - offset = duration.Seconds() + offset = int(duration.Seconds()) } return sc.NewSong(user, apiResponse, offset, nil) @@ -91,7 +91,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offs // Check song is not longer than the MaxSongDuration if dj.conf.General.MaxSongDuration == 0 || (durationMS/1000) <= dj.conf.General.MaxSongDuration { timeDuration, _ := time.ParseDuration(strconv.Itoa(durationMS) + "ms") - duration = strings.NewReplacer("h", ":", "m", ":", "s", ":").Replace(timeDuration.String()) + duration := strings.NewReplacer("h", ":", "m", ":", "s", ":").Replace(timeDuration.String()) song := &YouTubeSong{ id: strconv.Itoa(id), From d4c3de34e737123179996da350f51052c186df5f Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 14:33:19 +0100 Subject: [PATCH 262/297] Fixing offset for soundcloud --- service_soundcloud.go | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index af3f077..39ed3ed 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -32,7 +32,8 @@ func (sc SoundCloud) URLRegex(url string) bool { func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { var apiResponse *jsonq.JsonQuery var err error - url = fmt.Sprintf("http://api.soundcloud.com/resolve?url=%s&client_id=%s", url, os.Getenv("SOUNDCLOUD_API_KEY")) + timesplit := strings.Split(url, "#t=") + url = fmt.Sprintf("http://api.soundcloud.com/resolve?url=%s&client_id=%s", timesplit[0], os.Getenv("SOUNDCLOUD_API_KEY")) if apiResponse, err = PerformGetRequest(url); err != nil { return "", errors.New(INVALID_API_KEY) } @@ -53,24 +54,21 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { for _, t := range tracks { sc.NewSong(user, jsonq.NewQuery(t), 0, playlist) } - if err == nil { - return playlist.Title(), nil - } else { - return "", err - } - } else { - return "", errors.New("NO_PLAYLIST_PERMISSION") + return playlist.Title(), nil } + return "", errors.New(NO_PLAYLIST_PERMISSION_MSG) } else { // SONG - // Calculating offset offset := 0 - timesplit := strings.Split(url, "#t=") if len(timesplit) == 2 { - duration, _ := time.ParseDuration(timesplit[1]) - offset = int(duration.Seconds()) + timesplit = strings.Split(timesplit[1], ":") + multiplier := 1 + for i := len(timesplit) - 1; i >= 0; i-- { + offset += strconv.Itoa(timesplit[i]) * multiplier + mutiplier *= 60 + } + fmt.Printf("Offset: " + offset) // DEBUG } - return sc.NewSong(user, apiResponse, offset, nil) } } @@ -91,7 +89,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offs // Check song is not longer than the MaxSongDuration if dj.conf.General.MaxSongDuration == 0 || (durationMS/1000) <= dj.conf.General.MaxSongDuration { timeDuration, _ := time.ParseDuration(strconv.Itoa(durationMS) + "ms") - duration := strings.NewReplacer("h", ":", "m", ":", "s", ":").Replace(timeDuration.String()) + duration := timeDuration.String() song := &YouTubeSong{ id: strconv.Itoa(id), From 0760455962e109752068dfa2de4a50e7d08ec2a2 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 14:37:49 +0100 Subject: [PATCH 263/297] Fixing build errors --- service_soundcloud.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 39ed3ed..5897a1c 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -64,10 +64,10 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { timesplit = strings.Split(timesplit[1], ":") multiplier := 1 for i := len(timesplit) - 1; i >= 0; i-- { - offset += strconv.Itoa(timesplit[i]) * multiplier + offset += strconv.Atoa(timesplit[i]) * multiplier mutiplier *= 60 } - fmt.Printf("Offset: " + offset) // DEBUG + fmt.Printf("Offset: " + strconv.Itoa(offset)) // DEBUG } return sc.NewSong(user, apiResponse, offset, nil) } From 92c8230ae80cad17ee4814f188d952ff251d19e9 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 19:10:49 +0100 Subject: [PATCH 264/297] Fixing build issues --- service_soundcloud.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 5897a1c..afe52f9 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -64,8 +64,8 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { timesplit = strings.Split(timesplit[1], ":") multiplier := 1 for i := len(timesplit) - 1; i >= 0; i-- { - offset += strconv.Atoa(timesplit[i]) * multiplier - mutiplier *= 60 + offset += strconv.Atoi(timesplit[i]) * multiplier + multiplier *= 60 } fmt.Printf("Offset: " + strconv.Itoa(offset)) // DEBUG } From 55e2b7168f680d9fb73b45f760c6fe1fe683b6a1 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sun, 16 Aug 2015 19:12:39 +0100 Subject: [PATCH 265/297] Fixing build issues --- service_soundcloud.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index afe52f9..2b4714d 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -64,7 +64,8 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { timesplit = strings.Split(timesplit[1], ":") multiplier := 1 for i := len(timesplit) - 1; i >= 0; i-- { - offset += strconv.Atoi(timesplit[i]) * multiplier + time, _ := strconv.Atoi(timesplit[i]) + offset += time * multiplier multiplier *= 60 } fmt.Printf("Offset: " + strconv.Itoa(offset)) // DEBUG From 41f12e9feb25482a8361f2b4cbc6b53601be7b49 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Thu, 20 Aug 2015 22:28:44 +0100 Subject: [PATCH 266/297] Updated soundcloud duration formatting --- Goopfile.lock | 8 -------- service_soundcloud.go | 5 ++--- 2 files changed, 2 insertions(+), 11 deletions(-) delete mode 100644 Goopfile.lock diff --git a/Goopfile.lock b/Goopfile.lock deleted file mode 100644 index 887e548..0000000 --- a/Goopfile.lock +++ /dev/null @@ -1,8 +0,0 @@ -code.google.com/p/gcfg #c2d3050044d0 -github.com/golang/protobuf #0f7a9caded1fb3c9cc5a9b4bcf2ff633cc8ae644 -github.com/jmoiron/jsonq #7c27c8eb9f6831555a4209f6a7d579159e766a3c -github.com/layeh/gopus #2f86fa22bc209cc0ccbc6418dfbad9199e3dbc78 -github.com/layeh/gumble/gumble #8b9989d9c4090874546c45ceaa6ff21e95705bc4 -github.com/layeh/gumble/gumble_ffmpeg #c9fcce8fc4b71c7c53a5d3d9d48a1e001ad19a19 -github.com/layeh/gumble/gumbleutil #abf58b0ea8b2661897f81cf69c2a6a3e37152d74 -github.com/timshannon/go-openal #f4fbb66b2922de93753ac8069ff62d20a56a7450 diff --git a/service_soundcloud.go b/service_soundcloud.go index 2b4714d..45ce9bb 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -68,7 +68,6 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { offset += time * multiplier multiplier *= 60 } - fmt.Printf("Offset: " + strconv.Itoa(offset)) // DEBUG } return sc.NewSong(user, apiResponse, offset, nil) } @@ -89,8 +88,8 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offs // Check song is not longer than the MaxSongDuration if dj.conf.General.MaxSongDuration == 0 || (durationMS/1000) <= dj.conf.General.MaxSongDuration { - timeDuration, _ := time.ParseDuration(strconv.Itoa(durationMS) + "ms") - duration := timeDuration.String() + timeDuration, _ := time.ParseDuration(strconv.Itoa(durationMS/1000) + "s") + duration := strings.NewReplacer("h", ":", "m", ":", "s", "").Replace(timeDuration.String()) song := &YouTubeSong{ id: strconv.Itoa(id), From 4672e843fe86980f2c9297af69b1b0b05d0719a6 Mon Sep 17 00:00:00 2001 From: Michael Oultram Date: Wed, 26 Aug 2015 18:45:08 +0100 Subject: [PATCH 267/297] Update README.md --- README.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 3cd40cd..4fddf94 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ MumbleDJ [![Circle CI](https://circleci.com/gh/MichaelOultram/mumbledj/tree/master.svg?style=svg)](https://circleci.com/gh/MichaelOultram/mumbledj/tree/master) ======== -**A Mumble bot that plays music fetched from YouTube videos.** +**A Mumble bot that plays music fetched from YouTube videos and Soundcloud tracks.** * [Usage](#usage) * [Features](#features) @@ -31,7 +31,8 @@ All commandline parameters are optional. Below are descriptions of all the avail * `-accesstokens`: List of access tokens for the bot separated by spaces. Defaults to no access tokens. ## FEATURES -* Plays audio from both YouTube videos and YouTube playlists! +* Plays audio from YouTube and Soundcloud! +* Supports playlists and individual videos/tracks. * Displays thumbnail, title, duration, submitter, and playlist title (if exists) when a new song is played. * Incredible customization options. Nearly everything is able to be tweaked in `~/.mumbledj/mumbledj.gcfg`. * A large array of [commands](#commands) that perform a wide variety of functions. @@ -43,7 +44,7 @@ These are all of the chat commands currently supported by MumbleDJ. All command Command | Description | Arguments | Admin | Example --------|-------------|-----------|-------|-------- -**add** | Adds a YouTube video's audio to the song queue. If no songs are currently in the queue, the audio will begin playing immediately. YouTube playlists may also be added using this command. Please note, however, that if a YouTube playlist contains over 25 videos only the first 25 videos will be placed in the song queue. | youtube_video_url OR youtube_playlist_url | No | `!add https://www.youtube.com/watch?v=5xfEr2Oxdys` +**add** | Adds a YouTube video's audio to the song queue. If no songs are currently in the queue, the audio will begin playing immediately. YouTube playlists may also be added using this command. Please note, however, that if a YouTube playlist contains over 25 videos only the first 25 videos will be placed in the song queue. | youtube_video_url OR youtube_playlist_url OR soundcloud_track_url OR soundcloud_playlist_url | No | `!add https://www.youtube.com/watch?v=5xfEr2Oxdys` **skip**| Submits a vote to skip the current song. Once the skip ratio target (specified in `mumbledj.gcfg`) is met, the song will be skipped and the next will start playing. Each user may only submit one skip per song. | None | No | `!skip` **skipplaylist** | Submits a vote to skip the current playlist. Once the skip ratio target (specified in mumbledj.gcfg) is met, the playlist will be skipped and the next song/playlist will start playing. Each user may only submit one skip per playlist. | None | No | `!skipplaylist` **forceskip** | An admin command that forces a song skip. | None | Yes | `!forceskip` @@ -61,9 +62,6 @@ Command | Description | Arguments | Admin | Example **cachesize** | Outputs the total file size of the cache in MB. | None | Yes | `!cachesize` **kill** | Safely cleans the bot environment and disconnects from the server. Please use this command to stop the bot instead of force closing, as the kill command deletes any remaining songs in the `~/.mumbledj/songs` directory. | None | Yes | `!kill` - - - ## INSTALLATION ###YOUTUBE API KEYS From 12374d9c17e7ae7e278e605ec5feaf9566e078da Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Wed, 26 Aug 2015 19:06:20 +0100 Subject: [PATCH 268/297] [no ci] Minimizing unneeded changes --- .gitattributes | 1 - config.gcfg | 2 +- strings.go | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) delete mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 73ec672..0000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -README.md merge=ours \ No newline at end of file diff --git a/config.gcfg b/config.gcfg index c55e52c..db67c05 100644 --- a/config.gcfg +++ b/config.gcfg @@ -140,7 +140,7 @@ AdminsEnabled = true # SYNTAX: In order to specify multiple admins, repeat the Admins="username" # line of code. Each line has one username, and an unlimited amount of usernames may # be entered in this matter. -Admins = "BottleOToast" +Admins = "Matt" # Make add an admin command? # DEFAULT VALUE: false diff --git a/strings.go b/strings.go index be2c4f7..d48e7a7 100644 --- a/strings.go +++ b/strings.go @@ -169,4 +169,4 @@ const CURRENT_SONG_HTML = ` // playlist is playing. const CURRENT_SONG_PLAYLIST_HTML = ` The song currently playing is "%s", added %s from the playlist "%s". -` \ No newline at end of file +` From 79472a1791c7b9c447fd64c3d1f34ff0a63895d5 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 25 Sep 2015 17:25:52 +0100 Subject: [PATCH 269/297] Removed all test code --- Makefile | 2 +- README.md | 4 +- circle.yml | 27 ------------- install-dependencies.sh | 37 ------------------ main.go | 8 +--- service_soundcloud.go | 7 ++++ test.go | 85 ----------------------------------------- youtube_dl.go | 7 ++++ 8 files changed, 19 insertions(+), 158 deletions(-) delete mode 100644 circle.yml delete mode 100644 install-dependencies.sh delete mode 100644 test.go diff --git a/Makefile b/Makefile index 97d8a23..4bf8c1e 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ all: mumbledj mumbledj: main.go commands.go parseconfig.go strings.go service.go youtube_dl.go service_youtube.go service_soundcloud.go songqueue.go cache.go - if [ ! -f $(GOPATH)/bin/goop ]; then go get github.com/nitrous-io/goop; fi; + go get github.com/nitrous-io/goop; fi; rm -rf Goopfile.lock goop install goop go build diff --git a/README.md b/README.md index 4fddf94..0af6bb0 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ These are all of the chat commands currently supported by MumbleDJ. All command Command | Description | Arguments | Admin | Example --------|-------------|-----------|-------|-------- -**add** | Adds a YouTube video's audio to the song queue. If no songs are currently in the queue, the audio will begin playing immediately. YouTube playlists may also be added using this command. Please note, however, that if a YouTube playlist contains over 25 videos only the first 25 videos will be placed in the song queue. | youtube_video_url OR youtube_playlist_url OR soundcloud_track_url OR soundcloud_playlist_url | No | `!add https://www.youtube.com/watch?v=5xfEr2Oxdys` +**add** | Adds audio from a url to the song queue. If no songs are currently in the queue, the audio will begin playing immediately. Playlists may also be added using this command. Please note, however, that if a YouTube playlist contains over 25 videos only the first 25 videos will be placed in the song queue. | youtube_video_url OR youtube_playlist_url OR soundcloud_track_url OR soundcloud_playlist_url | No | `!add https://www.youtube.com/watch?v=5xfEr2Oxdys` **skip**| Submits a vote to skip the current song. Once the skip ratio target (specified in `mumbledj.gcfg`) is met, the song will be skipped and the next will start playing. Each user may only submit one skip per song. | None | No | `!skip` **skipplaylist** | Submits a vote to skip the current playlist. Once the skip ratio target (specified in mumbledj.gcfg) is met, the playlist will be skipped and the next song/playlist will start playing. Each user may only submit one skip per playlist. | None | No | `!skipplaylist` **forceskip** | An admin command that forces a song skip. | None | Yes | `!forceskip` @@ -83,7 +83,7 @@ Effective April 20th, 2015, all requests to YouTube's API must use v3 of their A **7)** Open up `~/.bashrc` with your favorite text editor (or `~/.zshrc` if you use `zsh`). Add the following line to the bottom: `export YOUTUBE_API_KEY=""`. Replace \ with your API key. -**8)** Close your current terminal window and open another one up. You should be able to use MumbleDJ now! +**8)** Close your current terminal window and open another one up. You should be able to use Youtube on MumbleDJ now! ###SOUNDCLOUD API KEYS A soundcloud API key is required for soundcloud integration. If no soundcloud api key is found, then the service will be disabled (youtube links will still work however). diff --git a/circle.yml b/circle.yml deleted file mode 100644 index 0d99b58..0000000 --- a/circle.yml +++ /dev/null @@ -1,27 +0,0 @@ -machine: - environment: - PATH: $HOME/bin/:$PATH - LD_RUN_PATH: $LD_RUN_PATH:$HOME/opus/lib - LD_LIBRARY_PATH: $LD_LIBRARY_PATH:$HOME/opus/lib - PKG_CONFIG_PATH: $PKG_CONFIG_PATH:$HOME/opus/lib/pkgconfig - -dependencies: - pre: - - bash install-dependencies.sh - - override: - - make - - make install - - cache_directories: - - "~/opus" - - "~/bin" - - "~/mumbledj/.vendor" - - "/home/ubuntu/.go_workspace/bin" - - "/home/ubuntu/.go_workspace/pkg" - - "/home/ubuntu/.go_workspace/src/github.com/nitrous-io" - -test: - override: - - mumbledj -server=$MUMBLE_IP -port=$MUMBLE_PORT -username=circleci -password=$MUMBLE_PASSWORD -test=true: - timeout: 180 \ No newline at end of file diff --git a/install-dependencies.sh b/install-dependencies.sh deleted file mode 100644 index cb03750..0000000 --- a/install-dependencies.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/sh -set -e - -# removing old ffmpeg -sudo rm -rf /usr/bin/ffmpeg -sudo rm -rf /usr/bin/X11/ffmpeg -sudo rm -rf /usr/share/man/man1/ffmpeg.1.gz - -# check to see if ffmpeg is installed -if [ ! -f "$HOME/bin/ffmpeg" ]; then - echo 'Installing ffmpeg' - wget http://johnvansickle.com/ffmpeg/releases/ffmpeg-release-64bit-static.tar.xz -O /tmp/ffmpeg.tar.xz - tar -xvf /tmp/ffmpeg.tar.xz --strip 1 --no-anchored ffmpeg ffprobe - chmod a+rx ffmpeg ffprobe - mv ff* ~/bin -else - echo 'Using cached version of ffmpeg.'; -fi - -# check to see if youtube-dl is installed -if [ ! -f "$HOME/bin/youtube-dl" ]; then - echo 'Installing youtube-dl' - curl https://yt-dl.org/latest/youtube-dl -o ~/bin/youtube-dl - chmod a+rx ~/bin/youtube-dl -else - echo 'Using cached version of youtube-dl.'; -fi - -# check to see if opus is installed -if [ ! -d "$HOME/opus/lib" ]; then - echo 'Installing opus' - wget http://downloads.xiph.org/releases/opus/opus-1.0.3.tar.gz - tar xzvf opus-1.0.3.tar.gz - cd opus-1.0.3 && ./configure --prefix=$HOME/opus && make && make install -else - echo 'Using cached version of opus.'; -fi \ No newline at end of file diff --git a/main.go b/main.go index 3682ac7..86c45c0 100644 --- a/main.go +++ b/main.go @@ -153,7 +153,7 @@ func CheckAPIKeys() { // Checks to see if any service was disabled if anyDisabled { - fmt.Printf("Please see the following link for info on how to enable services: https://github.com/matthieugrieger/mumbledj\n") + fmt.Printf("Please see the following link for info on how to enable missing services: https://github.com/matthieugrieger/mumbledj\n") } // Exits application if no services are enabled @@ -194,7 +194,7 @@ func main() { } var address, port, username, password, channel, pemCert, pemKey, accesstokens string - var insecure, testcode bool + var insecure bool flag.StringVar(&address, "server", "localhost", "address for Mumble server") flag.StringVar(&port, "port", "64738", "port for Mumble server") @@ -205,7 +205,6 @@ func main() { flag.StringVar(&pemKey, "key", "", "path to user PEM key for MumbleDJ") flag.StringVar(&accesstokens, "accesstokens", "", "list of access tokens for channel auth") flag.BoolVar(&insecure, "insecure", false, "skip certificate checking") - flag.BoolVar(&testcode, "test", false, "[debug] tests the features of mumbledj") flag.Parse() dj.config = gumble.Config{ @@ -246,8 +245,5 @@ func main() { os.Exit(1) } - if testcode { - Test(password, address, port, strings.Split(accesstokens, " ")) - } <-dj.keepAlive } diff --git a/service_soundcloud.go b/service_soundcloud.go index 45ce9bb..055a946 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -1,3 +1,10 @@ +/* + * MumbleDJ + * By Matthieu Grieger + * service_soundcloud.go + * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) + */ + package main import ( diff --git a/test.go b/test.go deleted file mode 100644 index 4edbe03..0000000 --- a/test.go +++ /dev/null @@ -1,85 +0,0 @@ -package main - -import ( - "fmt" - "github.com/layeh/gumble/gumble" - "os" - "time" -) - -type TestSettings struct { - password string - ip string - port string - accesstokens []string -} - -var test TestSettings - -func Test(password, ip, port string, accesstokens []string) { - test = TestSettings{ - password: password, - ip: ip, - port: port, - accesstokens: accesstokens, - } - test.testYoutubeSong() -} - -func (t TestSettings) createClient(uname string) *gumble.Client { - config := gumble.Config{ - Username: uname, - Password: t.password, - Address: t.ip + ":" + t.port, - Tokens: t.accesstokens, - } - config.TLSConfig.InsecureSkipVerify = true - client := gumble.NewClient(&config) - return client -} - -func (t TestSettings) testYoutubeSong() { - dummyClient := t.createClient("dummy") - if err := dummyClient.Connect(); err != nil { - panic(err) - } - - dj.client.Request(gumble.RequestUserList) - time.Sleep(time.Second * 5) - dummyUser := dj.client.Users.Find("dummy") - if dummyUser == nil { - fmt.Printf("User does not exist, printing users\n") - for _, user := range dj.client.Users { - fmt.Printf(user.Name + "\n") - } - fmt.Printf("End of user list\n") - os.Exit(1) - } - - // Don't judge, I used the (autogenerated) Top Tracks for United Kingdom playlist - songs := map[string]string{ - "http://www.youtube.com/watch?v=QcIy9NiNbmo": "Taylor Swift - Bad Blood ft. Kendrick Lamar", - "https://www.youtube.com/watch?v=vjW8wmF5VWc": "Silentó - Watch Me (Whip/Nae Nae) (Official)", - "http://youtu.be/nsDwItoNlLc": "Tinie Tempah ft. Jess Glynne - Not Letting Go (Official Video)", - "https://youtu.be/hXTAn4ELEwM": "Years & Years - Shine", - "http://youtube.com/watch?v=RgKAFK5djSk": "Wiz Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack", - "https://youtube.com/watch?v=qWWSM3wCiKY": "Calvin Harris & Disciples - How Deep Is Your Love (Audio)", - "http://www.youtube.com/v/yzTuBuRdAyA": "The Weeknd - The Hills", - "https://www.youtube.com/v/cNw8A5pwbVI": "Pia Mia - Do It Again ft. Chris Brown, Tyga", - } - - for url, title := range songs { - err := add(dummyUser, url) - if err != nil { - fmt.Printf("For: %s; Expected: %s; Got: %s\n", url, title, err.Error()) - } else if dj.queue.CurrentSong().Title() != title { - fmt.Printf("For: %s; Expected: %s; Got: %s\n", url, title, dj.queue.CurrentSong().Title()) - } - - time.Sleep(time.Second * 10) - skip(dummyUser, false, false) - } - - os.Exit(0) - dummyClient.Disconnect() -} diff --git a/youtube_dl.go b/youtube_dl.go index 64afb97..630e861 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -1,3 +1,10 @@ +/* + * MumbleDJ + * By Matthieu Grieger + * youtube_dl.go + * Copyright (c) 2014, 2015 Matthieu Grieger (MIT License) + */ + package main import ( From 58bfc9ce23d286d584143b34bc5a46775ff9b1a7 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 25 Sep 2015 17:33:13 +0100 Subject: [PATCH 270/297] Cleaning up comments --- README.md | 5 ++++- service.go | 2 ++ service_youtube.go | 8 -------- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 0af6bb0..bcab76a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -MumbleDJ [![Circle CI](https://circleci.com/gh/MichaelOultram/mumbledj/tree/master.svg?style=svg)](https://circleci.com/gh/MichaelOultram/mumbledj/tree/master) +MumbleDJ ======== **A Mumble bot that plays music fetched from YouTube videos and Soundcloud tracks.** @@ -62,6 +62,9 @@ Command | Description | Arguments | Admin | Example **cachesize** | Outputs the total file size of the cache in MB. | None | Yes | `!cachesize` **kill** | Safely cleans the bot environment and disconnects from the server. Please use this command to stop the bot instead of force closing, as the kill command deletes any remaining songs in the `~/.mumbledj/songs` directory. | None | Yes | `!kill` + + + ## INSTALLATION ###YOUTUBE API KEYS diff --git a/service.go b/service.go index a8e400c..097c412 100644 --- a/service.go +++ b/service.go @@ -54,6 +54,8 @@ type Playlist interface { var services []Service +// FindServiceAndAdd tries the given url with each service +// and adds the song/playlist with the correct service func FindServiceAndAdd(user *gumble.User, url string) error { var urlService Service diff --git a/service_youtube.go b/service_youtube.go index 06c9543..7a05e36 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -32,17 +32,9 @@ var youtubeVideoPatterns = []string{ `https?:\/\/www.youtube.com\/v\/([\w-]+)(\?t=\d*m?\d*s?)?`, } -// ------ -// TYPES -// ------ - // YouTube implements the Service interface type YouTube struct{} -// --------------- -// YOUTUBE SERVICE -// --------------- - // URLRegex checks to see if service will accept URL func (yt YouTube) URLRegex(url string) bool { return RegexpFromURL(url, append(youtubeVideoPatterns, []string{youtubePlaylistPattern}...)) != nil From 8b07d526eb5c238a67c927168b82fb3fa7921b08 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 25 Sep 2015 17:43:22 +0100 Subject: [PATCH 271/297] Removed FI from Make file --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 4bf8c1e..af8cc7e 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ all: mumbledj mumbledj: main.go commands.go parseconfig.go strings.go service.go youtube_dl.go service_youtube.go service_soundcloud.go songqueue.go cache.go - go get github.com/nitrous-io/goop; fi; + go get github.com/nitrous-io/goop rm -rf Goopfile.lock goop install goop go build From 4f14cfdd0f5f47debbd9d3de04f8c0de0ea5fd94 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 25 Sep 2015 17:48:04 +0100 Subject: [PATCH 272/297] Added dot for output filename --- youtube_dl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/youtube_dl.go b/youtube_dl.go index 630e861..0a359e9 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -159,7 +159,7 @@ func (dl *YouTubeSong) ID() string { // Filename returns the filename of the Song. func (dl *YouTubeSong) Filename() string { - return dl.id + dl.format + return dl.id + "." + dl.format } // Duration returns the duration of the Song. From 179594e4454fa9f3951d466d96cece37f5a2ce80 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Fri, 25 Sep 2015 17:52:53 +0100 Subject: [PATCH 273/297] Made youtube-dl verbose --- youtube_dl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/youtube_dl.go b/youtube_dl.go index 0a359e9..efd9963 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -49,7 +49,7 @@ func (dl *YouTubeSong) Download() error { // Checks to see if song is already downloaded if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename())); os.IsNotExist(err) { - cmd := exec.Command("youtube-dl", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format", dl.format, "--prefer-ffmpeg", dl.url) + cmd := exec.Command("youtube-dl", "--verbose", "--no-mtime", "--output", fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, dl.Filename()), "--format", dl.format, "--prefer-ffmpeg", dl.url) output, err := cmd.CombinedOutput() if err == nil { if dj.conf.Cache.Enabled { From 2880d78db1043b3a27700ea57261848694b2f54b Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 14:52:39 +0100 Subject: [PATCH 274/297] Song conditions are now checked in Service --- service.go | 71 ++++++++++++----- service_soundcloud.go | 88 ++++++++++++--------- service_youtube.go | 176 +++++++++++++++--------------------------- strings.go | 22 +++--- youtube_dl.go | 29 +++++++ 5 files changed, 203 insertions(+), 183 deletions(-) diff --git a/service.go b/service.go index 097c412..62b6449 100644 --- a/service.go +++ b/service.go @@ -11,14 +11,18 @@ import ( "errors" "fmt" "regexp" + "strconv" + "time" "github.com/layeh/gumble/gumble" ) // Service interface. Each service will implement these functions type Service interface { + ServiceName() string + TrackName() string URLRegex(string) bool - NewRequest(*gumble.User, string) (string, error) + NewRequest(*gumble.User, string) ([]Song, error) } // Song interface. Each service will implement these @@ -54,7 +58,7 @@ type Playlist interface { var services []Service -// FindServiceAndAdd tries the given url with each service +// FindServiceAndAdd tries the given url with each service // and adds the song/playlist with the correct service func FindServiceAndAdd(user *gumble.User, url string) error { var urlService Service @@ -69,27 +73,54 @@ func FindServiceAndAdd(user *gumble.User, url string) error { if urlService == nil { return errors.New(INVALID_URL_MSG) } else { - oldLength := dj.queue.Len() var title string - var err error + var songsAdded = 0 + var err errors - if title, err = urlService.NewRequest(user, url); err == nil { - dj.client.Self.Channel.Send(fmt.Sprintf(SONG_ADDED_HTML, user.Name, title), false) - - // Starts playing the new song if nothing else is playing - if oldLength == 0 && dj.queue.Len() != 0 && !dj.audioStream.IsPlaying() { - if err := dj.queue.CurrentSong().Download(); err == nil { - dj.queue.CurrentSong().Play() - } else { - dj.queue.CurrentSong().Delete() - dj.queue.OnSongFinished() - return errors.New("FAILED_TO_DOWNLOAD") - } - } - } else { - dj.SendPrivateMessage(user, err.Error()) + // Get service to create songs + if songArray, err = urlService.NewRequest(user, url); err != nil { + return err + } + + // Check Playlist Permission + if len(songArray) > 1 && !dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { + return errors.New(NO_PLAYLIST_PERMISSION_MSG) + } + + // Loop through all songs and add to the queue + oldLength := dj.queue.Len() + for song := range songArray { + time, _ := time.ParseDuration(song.Duration()) + if dj.conf.General.MaxSongDuration == 0 || int(time.Seconds()) <= dj.conf.General.MaxSongDuration { + if !isNil(song.Playlist()) { + title = song.Playlist().Title() + } else { + title = song.Title() + } + + dj.queue.AddSong(song) + songsAdded++ + } + } + + if songsAdded == 0 { + return errors.New(TRACK_TOO_LONG_MSG) + } else if songsAdded == 1 { + dj.client.Self.Channel.Send(fmt.Sprintf(SONG_ADDED_HTML, user.Name, title), false) + } else { + dj.client.Self.Channel.Send(fmt.Sprintf(PLAYLIST_ADDED_HTML, user.Name, title), false) + } + + // Starts playing the new song if nothing else is playing + if oldLength == 0 && dj.queue.Len() != 0 && !dj.audioStream.IsPlaying() { + if err := dj.queue.CurrentSong().Download(); err == nil { + dj.queue.CurrentSong().Play() + } else { + dj.queue.CurrentSong().Delete() + dj.queue.OnSongFinished() + return errors.New(AUDIO_FAIL_MSG) + } } - return err } } diff --git a/service_soundcloud.go b/service_soundcloud.go index 055a946..b8722dc 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -30,14 +30,25 @@ type SoundCloud struct{} // SOUNDCLOUD SERVICE // ------------------ +// ServiceName is the human readable version of the service name +func (sc SoundCloud) ServiceName() string { + return "Soundcloud" +} + +// TrackName is the human readable version of the service name +func (sc SoundCloud) TrackName() { + return "Song" +} + // URLRegex checks to see if service will accept URL func (sc SoundCloud) URLRegex(url string) bool { return RegexpFromURL(url, []string{soundcloudSongPattern, soundcloudPlaylistPattern}) != nil } // NewRequest creates the requested song/playlist and adds to the queue -func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { +func (sc SoundCloud) NewRequest(user *gumble.User, url string) ([]Song, error) { var apiResponse *jsonq.JsonQuery + var songArray []Song var err error timesplit := strings.Split(url, "#t=") url = fmt.Sprintf("http://api.soundcloud.com/resolve?url=%s&client_id=%s", timesplit[0], os.Getenv("SOUNDCLOUD_API_KEY")) @@ -48,24 +59,24 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { tracks, err := apiResponse.ArrayOfObjects("tracks") if err == nil { // PLAYLIST - if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { - // Create playlist - title, _ := apiResponse.String("title") - permalink, _ := apiResponse.String("permalink_url") - playlist := &YouTubePlaylist{ - id: permalink, - title: title, - } - - // Add all tracks - for _, t := range tracks { - sc.NewSong(user, jsonq.NewQuery(t), 0, playlist) - } - return playlist.Title(), nil + // Create playlist + title, _ := apiResponse.String("title") + permalink, _ := apiResponse.String("permalink_url") + playlist := &YouTubePlaylist{ + id: permalink, + title: title, } - return "", errors.New(NO_PLAYLIST_PERMISSION_MSG) + + // Add all tracks + for _, t := range tracks { + if song, err = sc.NewSong(user, jsonq.NewQuery(t), 0, playlist); err == nil { + songArray = append(songArray, song) + } + } + return songArray, nil } else { // SONG + // Calculate offset offset := 0 if len(timesplit) == 2 { timesplit = strings.Split(timesplit[1], ":") @@ -76,12 +87,17 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) (string, error) { multiplier *= 60 } } - return sc.NewSong(user, apiResponse, offset, nil) + + // Add the track + if song, err = sc.NewSong(user, apiResponse, offset, nil); err != nil { + return nil, err + } + return append(songArray, song), err } } // NewSong creates a track and adds to the queue -func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offset int, playlist Playlist) (string, error) { +func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offset int, playlist Playlist) (Song, error) { title, _ := trackData.String("title") id, _ := trackData.Int("id") durationMS, _ := trackData.Int("duration") @@ -93,26 +109,22 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offs thumbnail, _ = jsonq.NewQuery(userObj).String("avatar_url") } - // Check song is not longer than the MaxSongDuration - if dj.conf.General.MaxSongDuration == 0 || (durationMS/1000) <= dj.conf.General.MaxSongDuration { - timeDuration, _ := time.ParseDuration(strconv.Itoa(durationMS/1000) + "s") - duration := strings.NewReplacer("h", ":", "m", ":", "s", "").Replace(timeDuration.String()) + timeDuration, _ := time.ParseDuration(strconv.Itoa(durationMS/1000) + "s") + duration := timeDuration.String() //Lazy way to display time - song := &YouTubeSong{ - id: strconv.Itoa(id), - title: title, - url: url, - thumbnail: thumbnail, - submitter: user, - duration: duration, - offset: offset, - format: "mp3", - playlist: playlist, - skippers: make([]string, 0), - dontSkip: false, - } - dj.queue.AddSong(song) - return song.Title(), nil + song := &YouTubeSong{ + id: strconv.Itoa(id), + title: title, + url: url, + thumbnail: thumbnail, + submitter: user, + duration: duration, + offset: offset, + format: "mp3", + playlist: playlist, + skippers: make([]string, 0), + dontSkip: false, + service: sc, } - return "", errors.New(VIDEO_TOO_LONG_MSG) + return song, nil } diff --git a/service_youtube.go b/service_youtube.go index 7a05e36..73df91d 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -17,6 +17,7 @@ import ( "regexp" "strconv" "strings" + "time" "github.com/jmoiron/jsonq" "github.com/layeh/gumble/gumble" @@ -35,23 +36,30 @@ var youtubeVideoPatterns = []string{ // YouTube implements the Service interface type YouTube struct{} +// ServiceName is the human readable version of the service name +func (yt YouTube) ServiceName() string { + return "YouTube" +} + +// TrackName is the human readable version of the service name +func (yt YouTube) TrackName() string { + return "Video" +} + // URLRegex checks to see if service will accept URL func (yt YouTube) URLRegex(url string) bool { return RegexpFromURL(url, append(youtubeVideoPatterns, []string{youtubePlaylistPattern}...)) != nil } // NewRequest creates the requested song/playlist and adds to the queue -func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { +func (yt YouTube) NewRequest(user *gumble.User, url string) ([]Song, error) { + var songArray []Song var shortURL, startOffset = "", "" if re, err := regexp.Compile(youtubePlaylistPattern); err == nil { if re.MatchString(url) { - if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) { - shortURL = re.FindStringSubmatch(url)[1] - playlist, err := yt.NewPlaylist(user, shortURL) - return playlist.Title(), err - } else { - return "", errors.New("NO_PLAYLIST_PERMISSION") - } + shortURL = re.FindStringSubmatch(url)[1] + playlist, err := yt.NewPlaylist(user, shortURL) + return playlist.Title(), err } else { re = RegexpFromURL(url, youtubeVideoPatterns) matches := re.FindAllStringSubmatch(url, -1) @@ -60,10 +68,11 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { startOffset = matches[0][2] } song, err := yt.NewSong(user, shortURL, startOffset, nil) - if !isNil(song) { - return song.Title(), nil + if isNil(song) { + songArray = append(songArray, song) + return songArray, nil } else { - return "", err + return nil, err } } } else { @@ -73,97 +82,64 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) { // NewSong gathers the metadata for a song extracted from a YouTube video, and returns the song. func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlist) (Song, error) { - var apiResponse *jsonq.JsonQuery - var err error - url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s", - id, os.Getenv("YOUTUBE_API_KEY")) - if apiResponse, err = PerformGetRequest(url); err != nil { - return nil, errors.New(INVALID_API_KEY) - } + url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s", id, os.Getenv("YOUTUBE_API_KEY")) + if apiResponse, err := PerformGetRequest(url); err == nil { + title, _ := apiResponse.String("items", "0", "snippet", "title") + thumbnail, _ := apiResponse.String("items", "0", "snippet", "thumbnails", "high", "url") + duration, _ := apiResponse.String("items", "0", "contentDetails", "duration") - var offsetDays, offsetHours, offsetMinutes, offsetSeconds int64 - if offset != "" { - offsetExp := regexp.MustCompile(`t\=(?P\d+d)?(?P\d+h)?(?P\d+m)?(?P\d+s)?`) - offsetMatch := offsetExp.FindStringSubmatch(offset) - offsetResult := make(map[string]string) - for i, name := range offsetExp.SubexpNames() { - if i < len(offsetMatch) { - offsetResult[name] = offsetMatch[i] - } - } - - if offsetResult["days"] != "" { - offsetDays, _ = strconv.ParseInt(strings.TrimSuffix(offsetResult["days"], "d"), 10, 32) - } - if offsetResult["hours"] != "" { - offsetHours, _ = strconv.ParseInt(strings.TrimSuffix(offsetResult["hours"], "h"), 10, 32) - } - if offsetResult["minutes"] != "" { - offsetMinutes, _ = strconv.ParseInt(strings.TrimSuffix(offsetResult["minutes"], "m"), 10, 32) - } - if offsetResult["seconds"] != "" { - offsetSeconds, _ = strconv.ParseInt(strings.TrimSuffix(offsetResult["seconds"], "s"), 10, 32) - } - } - - title, _ := apiResponse.String("items", "0", "snippet", "title") - thumbnail, _ := apiResponse.String("items", "0", "snippet", "thumbnails", "high", "url") - duration, _ := apiResponse.String("items", "0", "contentDetails", "duration") - - var days, hours, minutes, seconds int64 - timestampExp := regexp.MustCompile(`P(?P\d+D)?T(?P\d+H)?(?P\d+M)?(?P\d+S)?`) - timestampMatch := timestampExp.FindStringSubmatch(duration) - timestampResult := make(map[string]string) - for i, name := range timestampExp.SubexpNames() { - if i < len(timestampMatch) { - timestampResult[name] = timestampMatch[i] - } - } - - if timestampResult["days"] != "" { - days, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["days"], "D"), 10, 32) - } - if timestampResult["hours"] != "" { - hours, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["hours"], "H"), 10, 32) - } - if timestampResult["minutes"] != "" { - minutes, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["minutes"], "M"), 10, 32) - } - if timestampResult["seconds"] != "" { - seconds, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["seconds"], "S"), 10, 32) - } - - totalSeconds := int((days * 86400) + (hours * 3600) + (minutes * 60) + seconds) - var durationString string - if hours != 0 { - if days != 0 { - durationString = fmt.Sprintf("%d:%02d:%02d:%02d", days, hours, minutes, seconds) - } else { - durationString = fmt.Sprintf("%d:%02d:%02d", hours, minutes, seconds) - } - } else { - durationString = fmt.Sprintf("%d:%02d", minutes, seconds) - } - - if dj.conf.General.MaxSongDuration == 0 || totalSeconds <= dj.conf.General.MaxSongDuration { song := &YouTubeSong{ submitter: user, title: title, id: id, url: "https://youtu.be/" + id, - offset: int((offsetDays * 86400) + (offsetHours * 3600) + (offsetMinutes * 60) + offsetSeconds), - duration: durationString, + offset: yt.parseTime(offset).Seconds(), + duration: yt.parseTime(duration).Seconds(), thumbnail: thumbnail, format: "m4a", skippers: make([]string, 0), playlist: playlist, dontSkip: false, + service: yt, } dj.queue.AddSong(song) return song, nil } - return nil, errors.New(VIDEO_TOO_LONG_MSG) + return nil, errors.New(fmt.Sprintf(INVALID_API_KEY, yt.ServiceName())) +} + +// parseTime converts from the string youtube returns to a time.Duration +func (yt YouTube) parseTime(duration string) time.Duration { + var days, hours, minutes, seconds, totalSeconds int64 + if duration != "" { + timestampExp := regexp.MustCompile(`P(?P\d+D)?T(?P\d+H)?(?P\d+M)?(?P\d+S)?`) + timestampMatch := timestampExp.FindStringSubmatch(duration) + timestampResult := make(map[string]string) + for i, name := range timestampExp.SubexpNames() { + if i < len(timestampMatch) { + timestampResult[name] = timestampMatch[i] + } + } + + if timestampResult["days"] != "" { + days, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["days"], "D"), 10, 32) + } + if timestampResult["hours"] != "" { + hours, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["hours"], "H"), 10, 32) + } + if timestampResult["minutes"] != "" { + minutes, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["minutes"], "M"), 10, 32) + } + if timestampResult["seconds"] != "" { + seconds, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["seconds"], "S"), 10, 32) + } + + totalSeconds = int((days * 86400) + (hours * 3600) + (minutes * 60) + seconds) + } else { + totalSeconds = 0 + } + return time.ParseDuration(totalSeconds + "s") } // NewPlaylist gathers the metadata for a YouTube playlist and returns it. @@ -200,31 +176,3 @@ func (yt YouTube) NewPlaylist(user *gumble.User, id string) (Playlist, error) { } return playlist, nil } - -// PerformGetRequest does all the grunt work for a YouTube HTTPS GET request. -func PerformGetRequest(url string) (*jsonq.JsonQuery, error) { - jsonString := "" - - if response, err := http.Get(url); err == nil { - defer response.Body.Close() - if response.StatusCode == 200 { - if body, err := ioutil.ReadAll(response.Body); err == nil { - jsonString = string(body) - } - } else { - if response.StatusCode == 403 { - return nil, errors.New("Invalid API key supplied.") - } - return nil, errors.New("Invalid ID supplied.") - } - } else { - return nil, errors.New("An error occurred while receiving HTTP GET response.") - } - - jsonData := map[string]interface{}{} - decoder := json.NewDecoder(strings.NewReader(jsonString)) - decoder.Decode(&jsonData) - jq := jsonq.NewQuery(jsonData) - - return jq, nil -} diff --git a/strings.go b/strings.go index d48e7a7..54b55f5 100644 --- a/strings.go +++ b/strings.go @@ -7,8 +7,8 @@ package main -// Message shown to users when the bot has an invalid YouTube API key. -const INVALID_API_KEY = "MumbleDJ does not have a valid YouTube API key." +// Message shown to users when the bot has an invalid API key. +const INVALID_API_KEY = "MumbleDJ does not have a valid %s API key." // Message shown to users when they do not have permission to execute a command. const NO_PERMISSION_MSG = "You do not have permission to execute that command." @@ -26,7 +26,7 @@ const CHANNEL_DOES_NOT_EXIST_MSG = "The channel you specified does not exist." const INVALID_URL_MSG = "The URL you submitted does not match the required format." // Message shown to users when they attempt to add a video that's too long -const VIDEO_TOO_LONG_MSG = "The video you submitted exceeds the duration allowed by the server." +const TRACK_TOO_LONG_MSG = "The %s you submitted exceeds the duration allowed by the server." // Message shown to users when they attempt to perform an action on a song when // no song is playing. @@ -54,10 +54,10 @@ const ADMIN_SONG_SKIP_MSG = "An admin has decided to skip the current song." const ADMIN_PLAYLIST_SKIP_MSG = "An admin has decided to skip the current playlist." // Message shown to users when the audio for a video could not be downloaded. -const AUDIO_FAIL_MSG = "The audio download for this video failed. YouTube has likely not generated the audio files for this video yet. Skipping to the next song!" +const AUDIO_FAIL_MSG = "The audio download for this video failed. %s has likely not generated the audio files for this %s yet. Skipping to the next song!" -// Message shown to users when they supply a YouTube URL that does not contain a valid ID. -const INVALID_YOUTUBE_ID_MSG = "The YouTube URL you supplied did not contain a valid YouTube ID." +// Message shown to users when they supply an URL that does not contain a valid ID. +const INVALID_ID_MSG = "The %s URL you supplied did not contain a valid ID." // Message shown to user when they successfully update the bot's comment. const COMMENT_UPDATED_MSG = "The comment for the bot has successfully been updated." @@ -78,7 +78,7 @@ const SONG_ADDED_HTML = ` // Message shown to channel when a playlist is added to the queue by a user. const PLAYLIST_ADDED_HTML = ` - %s has added the playlist "%s" to the queue. + %s has added the %s "%s" to the queue. ` // Message shown to channel when a song has been skipped. @@ -95,7 +95,7 @@ const PLAYLIST_SKIPPED_HTML = ` const HELP_HTML = `
User Commands:

!help - Displays this help.

-

!add - Adds songs to queue.

+

!add - Adds songs/playlists to queue.

!volume - Either tells you the current volume or sets it to a new volume.

!skip - Casts a vote to skip the current song

!skipplaylist - Casts a vote to skip over the current playlist.

@@ -132,12 +132,12 @@ const SUBMITTER_SKIP_HTML = ` // Message shown to users when another user votes to skip the current playlist. const PLAYLIST_SKIP_ADDED_HTML = ` - %s has voted to skip the current playlist. + %s has voted to skip the current %s. ` // Message shown to users when the submitter of a song decides to skip their song. const PLAYLIST_SUBMITTER_SKIP_HTML = ` - The current playlist has been skipped by %s, the submitter. + The current %s has been skipped by %s, the submitter. ` // Message shown to users when they successfully change the volume. @@ -168,5 +168,5 @@ const CURRENT_SONG_HTML = ` // Message shown to users when the currentsong command is issued when a song from a // playlist is playing. const CURRENT_SONG_PLAYLIST_HTML = ` - The song currently playing is "%s", added %s from the playlist "%s". + The %s currently playing is "%s", added %s from the %s "%s". ` diff --git a/youtube_dl.go b/youtube_dl.go index efd9963..479b43e 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -31,6 +31,7 @@ type YouTubeSong struct { playlist Playlist skippers []string dontSkip bool + service Service } // YouTubePlaylist implements the Playlist interface @@ -238,3 +239,31 @@ func (p *YouTubePlaylist) ID() string { func (p *YouTubePlaylist) Title() string { return p.title } + +// PerformGetRequest does all the grunt work for HTTPS GET request. +func PerformGetRequest(url string) (*jsonq.JsonQuery, error) { + jsonString := "" + + if response, err := http.Get(url); err == nil { + defer response.Body.Close() + if response.StatusCode == 200 { + if body, err := ioutil.ReadAll(response.Body); err == nil { + jsonString = string(body) + } + } else { + if response.StatusCode == 403 { + return nil, errors.New("Invalid API key supplied.") + } + return nil, errors.New("Invalid ID supplied.") + } + } else { + return nil, errors.New("An error occurred while receiving HTTP GET response.") + } + + jsonData := map[string]interface{}{} + decoder := json.NewDecoder(strings.NewReader(jsonString)) + decoder.Decode(&jsonData) + jq := jsonq.NewQuery(jsonData) + + return jq, nil +} From b49dd882287fe4de14cb665d6880a6aad77b6cd8 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 14:57:29 +0100 Subject: [PATCH 275/297] Fixing build errors --- service.go | 8 +++++--- service_youtube.go | 3 --- youtube_dl.go | 3 +++ 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/service.go b/service.go index 62b6449..d7525a8 100644 --- a/service.go +++ b/service.go @@ -11,7 +11,6 @@ import ( "errors" "fmt" "regexp" - "strconv" "time" "github.com/layeh/gumble/gumble" @@ -75,10 +74,10 @@ func FindServiceAndAdd(user *gumble.User, url string) error { } else { var title string var songsAdded = 0 - var err errors + var err error // Get service to create songs - if songArray, err = urlService.NewRequest(user, url); err != nil { + if songArray, err := urlService.NewRequest(user, url); err != nil { return err } @@ -90,6 +89,7 @@ func FindServiceAndAdd(user *gumble.User, url string) error { // Loop through all songs and add to the queue oldLength := dj.queue.Len() for song := range songArray { + // Check song is not too long time, _ := time.ParseDuration(song.Duration()) if dj.conf.General.MaxSongDuration == 0 || int(time.Seconds()) <= dj.conf.General.MaxSongDuration { if !isNil(song.Playlist()) { @@ -98,11 +98,13 @@ func FindServiceAndAdd(user *gumble.User, url string) error { title = song.Title() } + // Add song to queue dj.queue.AddSong(song) songsAdded++ } } + // Alert channel of added song/playlist if songsAdded == 0 { return errors.New(TRACK_TOO_LONG_MSG) } else if songsAdded == 1 { diff --git a/service_youtube.go b/service_youtube.go index 73df91d..71622c0 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -8,11 +8,8 @@ package main import ( - "encoding/json" "errors" "fmt" - "io/ioutil" - "net/http" "os" "regexp" "strconv" diff --git a/youtube_dl.go b/youtube_dl.go index 479b43e..983874a 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -8,8 +8,11 @@ package main import ( + "encoding/json" "errors" "fmt" + "io/ioutil" + "net/http" "os" "os/exec" "time" From 1a8c1ce4d0d4110c4bb8d4317a84972b81581505 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 15:01:09 +0100 Subject: [PATCH 276/297] Fixing build errors --- service.go | 3 ++- service_soundcloud.go | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/service.go b/service.go index d7525a8..347d79d 100644 --- a/service.go +++ b/service.go @@ -74,7 +74,7 @@ func FindServiceAndAdd(user *gumble.User, url string) error { } else { var title string var songsAdded = 0 - var err error + var songArray []Song // Get service to create songs if songArray, err := urlService.NewRequest(user, url); err != nil { @@ -123,6 +123,7 @@ func FindServiceAndAdd(user *gumble.User, url string) error { return errors.New(AUDIO_FAIL_MSG) } } + return nil } } diff --git a/service_soundcloud.go b/service_soundcloud.go index b8722dc..aaac378 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -36,7 +36,7 @@ func (sc SoundCloud) ServiceName() string { } // TrackName is the human readable version of the service name -func (sc SoundCloud) TrackName() { +func (sc SoundCloud) TrackName() string { return "Song" } @@ -53,7 +53,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) ([]Song, error) { timesplit := strings.Split(url, "#t=") url = fmt.Sprintf("http://api.soundcloud.com/resolve?url=%s&client_id=%s", timesplit[0], os.Getenv("SOUNDCLOUD_API_KEY")) if apiResponse, err = PerformGetRequest(url); err != nil { - return "", errors.New(INVALID_API_KEY) + return nil, errors.New(INVALID_API_KEY) } tracks, err := apiResponse.ArrayOfObjects("tracks") @@ -69,7 +69,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) ([]Song, error) { // Add all tracks for _, t := range tracks { - if song, err = sc.NewSong(user, jsonq.NewQuery(t), 0, playlist); err == nil { + if song, err := sc.NewSong(user, jsonq.NewQuery(t), 0, playlist); err == nil { songArray = append(songArray, song) } } @@ -89,7 +89,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) ([]Song, error) { } // Add the track - if song, err = sc.NewSong(user, apiResponse, offset, nil); err != nil { + if song, err := sc.NewSong(user, apiResponse, offset, nil); err != nil { return nil, err } return append(songArray, song), err From 02b9778cc272d8aeba35fbe0b744e53ba3815461 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 15:09:07 +0100 Subject: [PATCH 277/297] Fixing build errors --- service.go | 3 ++- service_soundcloud.go | 11 ++++------- service_youtube.go | 15 +++++++++------ youtube_dl.go | 6 ++++-- 4 files changed, 19 insertions(+), 16 deletions(-) diff --git a/service.go b/service.go index 347d79d..32a36c1 100644 --- a/service.go +++ b/service.go @@ -75,9 +75,10 @@ func FindServiceAndAdd(user *gumble.User, url string) error { var title string var songsAdded = 0 var songArray []Song + var err error // Get service to create songs - if songArray, err := urlService.NewRequest(user, url); err != nil { + if songArray, err = urlService.NewRequest(user, url); err != nil { return err } diff --git a/service_soundcloud.go b/service_soundcloud.go index aaac378..2ed1570 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -89,10 +89,10 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) ([]Song, error) { } // Add the track - if song, err := sc.NewSong(user, apiResponse, offset, nil); err != nil { - return nil, err + if song, err := sc.NewSong(user, apiResponse, offset, nil); err == nil { + return append(songArray, song), err } - return append(songArray, song), err + return nil, err } } @@ -109,16 +109,13 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offs thumbnail, _ = jsonq.NewQuery(userObj).String("avatar_url") } - timeDuration, _ := time.ParseDuration(strconv.Itoa(durationMS/1000) + "s") - duration := timeDuration.String() //Lazy way to display time - song := &YouTubeSong{ id: strconv.Itoa(id), title: title, url: url, thumbnail: thumbnail, submitter: user, - duration: duration, + duration: durationMS / 1000, offset: offset, format: "mp3", playlist: playlist, diff --git a/service_youtube.go b/service_youtube.go index 71622c0..e354d9d 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -73,7 +73,7 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) ([]Song, error) { } } } else { - return "", err + return nil, err } } @@ -90,8 +90,8 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis title: title, id: id, url: "https://youtu.be/" + id, - offset: yt.parseTime(offset).Seconds(), - duration: yt.parseTime(duration).Seconds(), + offset: int(yt.parseTime(offset).Seconds()), + duration: int(yt.parseTime(duration).Seconds()), thumbnail: thumbnail, format: "m4a", skippers: make([]string, 0), @@ -140,8 +140,9 @@ func (yt YouTube) parseTime(duration string) time.Duration { } // NewPlaylist gathers the metadata for a YouTube playlist and returns it. -func (yt YouTube) NewPlaylist(user *gumble.User, id string) (Playlist, error) { +func (yt YouTube) NewPlaylist(user *gumble.User, id string) ([]Song, error) { var apiResponse *jsonq.JsonQuery + var songArray []Song var err error // Retrieve title of playlist url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=%s&key=%s", id, os.Getenv("YOUTUBE_API_KEY")) @@ -169,7 +170,9 @@ func (yt YouTube) NewPlaylist(user *gumble.User, id string) (Playlist, error) { for i := 0; i < numVideos; i++ { index := strconv.Itoa(i) videoID, _ := apiResponse.String("items", index, "snippet", "resourceId", "videoId") - yt.NewSong(user, videoID, "", playlist) + if song, err := yt.NewSong(user, videoID, "", playlist); err == nil { + songArray = append(songArray, song) + } } - return playlist, nil + return songArray, nil } diff --git a/youtube_dl.go b/youtube_dl.go index 983874a..64d60b1 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -15,6 +15,7 @@ import ( "net/http" "os" "os/exec" + "strconv" "time" "github.com/layeh/gumble/gumble" @@ -27,7 +28,7 @@ type YouTubeSong struct { title string thumbnail string submitter *gumble.User - duration string + duration int url string offset int format string @@ -168,7 +169,8 @@ func (dl *YouTubeSong) Filename() string { // Duration returns the duration of the Song. func (dl *YouTubeSong) Duration() string { - return dl.duration + timeDuration, _ := time.ParseDuration(stvconv.Iota(dl.duration) + "s") + return timeDuration.String() } // Thumbnail returns the thumbnail URL for the Song. From 9d78f9fdc015af44fdc27a4454a516a19fb056ed Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 15:14:09 +0100 Subject: [PATCH 278/297] Fixing build errors --- service.go | 10 +++++----- youtube_dl.go | 12 ++++++------ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/service.go b/service.go index 32a36c1..480634d 100644 --- a/service.go +++ b/service.go @@ -89,14 +89,14 @@ func FindServiceAndAdd(user *gumble.User, url string) error { // Loop through all songs and add to the queue oldLength := dj.queue.Len() - for song := range songArray { + for songToAdd := range songArray { // Check song is not too long - time, _ := time.ParseDuration(song.Duration()) + time, _ := time.ParseDuration(songToAdd.Duration) if dj.conf.General.MaxSongDuration == 0 || int(time.Seconds()) <= dj.conf.General.MaxSongDuration { - if !isNil(song.Playlist()) { - title = song.Playlist().Title() + if !isNil(songToAdd.Playlist()) { + title = songToAdd.Playlist().Title() } else { - title = song.Title() + title = songToAdd.Title() } // Add song to queue diff --git a/youtube_dl.go b/youtube_dl.go index 64d60b1..b2ae282 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -28,7 +28,7 @@ type YouTubeSong struct { title string thumbnail string submitter *gumble.User - duration int + Duration int url string offset int format string @@ -74,7 +74,7 @@ func (dl *YouTubeSong) Download() error { } // Play plays the song. Once the song is playing, a notification is displayed in a text message that features the song -// thumbnail, URL, title, duration, and submitter. +// thumbnail, URL, title, Duration, and submitter. func (dl *YouTubeSong) Play() { if dl.offset != 0 { offsetDuration, _ := time.ParseDuration(fmt.Sprintf("%ds", dl.offset)) @@ -85,7 +85,7 @@ func (dl *YouTubeSong) Play() { panic(err) } else { message := `` - message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.duration, dl.submitter.Name) + message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.Duration, dl.submitter.Name) if !isNil(dl.playlist) { message = fmt.Sprintf(message+``, dl.playlist.Title()) } @@ -167,9 +167,9 @@ func (dl *YouTubeSong) Filename() string { return dl.id + "." + dl.format } -// Duration returns the duration of the Song. -func (dl *YouTubeSong) Duration() string { - timeDuration, _ := time.ParseDuration(stvconv.Iota(dl.duration) + "s") +// Duration returns the Duration of the Song. +func (dl *YouTubeSong) DurationString() string { + timeDuration, _ := time.ParseDuration(stvconv.Iota(dl.Duration) + "s") return timeDuration.String() } From dc5741cf86bd6d698d44eacb3fe339127172ff52 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 15:16:22 +0100 Subject: [PATCH 279/297] Fixing build issues --- service.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/service.go b/service.go index 480634d..9272a95 100644 --- a/service.go +++ b/service.go @@ -89,14 +89,14 @@ func FindServiceAndAdd(user *gumble.User, url string) error { // Loop through all songs and add to the queue oldLength := dj.queue.Len() - for songToAdd := range songArray { + for _, song := range songArray { // Check song is not too long - time, _ := time.ParseDuration(songToAdd.Duration) + time, _ := time.ParseDuration(song.Duration) if dj.conf.General.MaxSongDuration == 0 || int(time.Seconds()) <= dj.conf.General.MaxSongDuration { - if !isNil(songToAdd.Playlist()) { - title = songToAdd.Playlist().Title() + if !isNil(song.Playlist()) { + title = song.Playlist().Title() } else { - title = songToAdd.Title() + title = song.Title() } // Add song to queue From df35d03ebee50a1068c70370b358575640f48053 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 15:57:17 +0100 Subject: [PATCH 280/297] Fixing build errors --- service.go | 2 +- service_soundcloud.go | 3 +-- service_youtube.go | 6 +++--- youtube_dl.go | 2 +- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/service.go b/service.go index 9272a95..17a2e77 100644 --- a/service.go +++ b/service.go @@ -37,7 +37,7 @@ type Song interface { Title() string ID() string Filename() string - Duration() string + DurationString() string Thumbnail() string Playlist() Playlist DontSkip() bool diff --git a/service_soundcloud.go b/service_soundcloud.go index 2ed1570..54fa26f 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -13,7 +13,6 @@ import ( "os" "strconv" "strings" - "time" "github.com/jmoiron/jsonq" "github.com/layeh/gumble/gumble" @@ -115,7 +114,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offs url: url, thumbnail: thumbnail, submitter: user, - duration: durationMS / 1000, + Duration: durationMS / 1000, offset: offset, format: "mp3", playlist: playlist, diff --git a/service_youtube.go b/service_youtube.go index e354d9d..6447f05 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -91,7 +91,7 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis id: id, url: "https://youtu.be/" + id, offset: int(yt.parseTime(offset).Seconds()), - duration: int(yt.parseTime(duration).Seconds()), + Duration: int(yt.parseTime(duration).Seconds()), thumbnail: thumbnail, format: "m4a", skippers: make([]string, 0), @@ -132,11 +132,11 @@ func (yt YouTube) parseTime(duration string) time.Duration { seconds, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["seconds"], "S"), 10, 32) } - totalSeconds = int((days * 86400) + (hours * 3600) + (minutes * 60) + seconds) + totalSeconds = int64((days * 86400) + (hours * 3600) + (minutes * 60) + seconds) } else { totalSeconds = 0 } - return time.ParseDuration(totalSeconds + "s") + return time.ParseDuration(strconv.Itoa(totalSeconds) + "s") } // NewPlaylist gathers the metadata for a YouTube playlist and returns it. diff --git a/youtube_dl.go b/youtube_dl.go index b2ae282..c0b9b89 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -15,9 +15,9 @@ import ( "net/http" "os" "os/exec" - "strconv" "time" + "github.com/jmoiron/jsonq" "github.com/layeh/gumble/gumble" "github.com/layeh/gumble/gumble_ffmpeg" ) From a7f1055ab57ad1b089d8f3f54e066943cf678127 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 16:04:39 +0100 Subject: [PATCH 281/297] Fixing build issues --- service.go | 3 ++- service_youtube.go | 6 +++--- youtube_dl.go | 17 ++++++++++++----- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/service.go b/service.go index 17a2e77..a24e8ad 100644 --- a/service.go +++ b/service.go @@ -37,6 +37,7 @@ type Song interface { Title() string ID() string Filename() string + DurationInt() int DurationString() string Thumbnail() string Playlist() Playlist @@ -91,7 +92,7 @@ func FindServiceAndAdd(user *gumble.User, url string) error { oldLength := dj.queue.Len() for _, song := range songArray { // Check song is not too long - time, _ := time.ParseDuration(song.Duration) + time, _ := time.ParseDuration(song.DurationInt()) if dj.conf.General.MaxSongDuration == 0 || int(time.Seconds()) <= dj.conf.General.MaxSongDuration { if !isNil(song.Playlist()) { title = song.Playlist().Title() diff --git a/service_youtube.go b/service_youtube.go index 6447f05..991cf9c 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -55,8 +55,7 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) ([]Song, error) { if re, err := regexp.Compile(youtubePlaylistPattern); err == nil { if re.MatchString(url) { shortURL = re.FindStringSubmatch(url)[1] - playlist, err := yt.NewPlaylist(user, shortURL) - return playlist.Title(), err + return yt.NewPlaylist(user, shortURL) } else { re = RegexpFromURL(url, youtubeVideoPatterns) matches := re.FindAllStringSubmatch(url, -1) @@ -136,7 +135,8 @@ func (yt YouTube) parseTime(duration string) time.Duration { } else { totalSeconds = 0 } - return time.ParseDuration(strconv.Itoa(totalSeconds) + "s") + output, _ := time.ParseDuration(strconv.Itoa(int(totalSeconds)) + "s") + return output } // NewPlaylist gathers the metadata for a YouTube playlist and returns it. diff --git a/youtube_dl.go b/youtube_dl.go index c0b9b89..2b1e352 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -15,6 +15,8 @@ import ( "net/http" "os" "os/exec" + "strconv" + "strings" "time" "github.com/jmoiron/jsonq" @@ -28,7 +30,7 @@ type YouTubeSong struct { title string thumbnail string submitter *gumble.User - Duration int + duration int url string offset int format string @@ -74,7 +76,7 @@ func (dl *YouTubeSong) Download() error { } // Play plays the song. Once the song is playing, a notification is displayed in a text message that features the song -// thumbnail, URL, title, Duration, and submitter. +// thumbnail, URL, title, duration, and submitter. func (dl *YouTubeSong) Play() { if dl.offset != 0 { offsetDuration, _ := time.ParseDuration(fmt.Sprintf("%ds", dl.offset)) @@ -85,7 +87,7 @@ func (dl *YouTubeSong) Play() { panic(err) } else { message := `
%s (%s)
Added by %s
From playlist "%s"
` - message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.Duration, dl.submitter.Name) + message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.duration, dl.submitter.Name) if !isNil(dl.playlist) { message = fmt.Sprintf(message+``, dl.playlist.Title()) } @@ -167,9 +169,14 @@ func (dl *YouTubeSong) Filename() string { return dl.id + "." + dl.format } -// Duration returns the Duration of the Song. +// DurationInt returns number of seconds for the Song. +func (dl *YouTubeSong) DurationInt() string { + return duration +} + +// DurationString returns the pretty version of duration for the Song. func (dl *YouTubeSong) DurationString() string { - timeDuration, _ := time.ParseDuration(stvconv.Iota(dl.Duration) + "s") + timeDuration, _ := time.ParseDuration(strconv.Iota(dl.duration) + "s") return timeDuration.String() } From cd03a947ed4952f31cfcecaac3938e02ae7dd902 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 16:06:48 +0100 Subject: [PATCH 282/297] Fixing build errors --- service_soundcloud.go | 2 +- service_youtube.go | 2 +- youtube_dl.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 54fa26f..3491d99 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -114,7 +114,7 @@ func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offs url: url, thumbnail: thumbnail, submitter: user, - Duration: durationMS / 1000, + duration: durationMS / 1000, offset: offset, format: "mp3", playlist: playlist, diff --git a/service_youtube.go b/service_youtube.go index 991cf9c..453044c 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -90,7 +90,7 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis id: id, url: "https://youtu.be/" + id, offset: int(yt.parseTime(offset).Seconds()), - Duration: int(yt.parseTime(duration).Seconds()), + duration: int(yt.parseTime(duration).Seconds()), thumbnail: thumbnail, format: "m4a", skippers: make([]string, 0), diff --git a/youtube_dl.go b/youtube_dl.go index 2b1e352..fcd6dba 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -176,7 +176,7 @@ func (dl *YouTubeSong) DurationInt() string { // DurationString returns the pretty version of duration for the Song. func (dl *YouTubeSong) DurationString() string { - timeDuration, _ := time.ParseDuration(strconv.Iota(dl.duration) + "s") + timeDuration, _ := time.ParseDuration(strconv.Itoa(dl.duration) + "s") return timeDuration.String() } From 508065f6080a2ad127a483c2b96167c3d7368e8a Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 16:15:41 +0100 Subject: [PATCH 283/297] Making Duration of type time.Duration --- main.go | 1 - service.go | 6 ++---- youtube_dl.go | 11 +++-------- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/main.go b/main.go index 86c45c0..bda7499 100644 --- a/main.go +++ b/main.go @@ -170,7 +170,6 @@ func isNil(a interface{}) bool { } // dj variable declaration. This is done outside of main() to allow global use. -var dj = mumbledj{ keepAlive: make(chan bool), queue: NewSongQueue(), playlistSkips: make(map[string][]string), diff --git a/service.go b/service.go index a24e8ad..8f4a23d 100644 --- a/service.go +++ b/service.go @@ -37,8 +37,7 @@ type Song interface { Title() string ID() string Filename() string - DurationInt() int - DurationString() string + Duration() time.Duration Thumbnail() string Playlist() Playlist DontSkip() bool @@ -92,8 +91,7 @@ func FindServiceAndAdd(user *gumble.User, url string) error { oldLength := dj.queue.Len() for _, song := range songArray { // Check song is not too long - time, _ := time.ParseDuration(song.DurationInt()) - if dj.conf.General.MaxSongDuration == 0 || int(time.Seconds()) <= dj.conf.General.MaxSongDuration { + if dj.conf.General.MaxSongDuration == 0 || song.Duration().Seconds()) <= dj.conf.General.MaxSongDuration { if !isNil(song.Playlist()) { title = song.Playlist().Title() } else { diff --git a/youtube_dl.go b/youtube_dl.go index fcd6dba..acecf24 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -169,15 +169,10 @@ func (dl *YouTubeSong) Filename() string { return dl.id + "." + dl.format } -// DurationInt returns number of seconds for the Song. -func (dl *YouTubeSong) DurationInt() string { - return duration -} - -// DurationString returns the pretty version of duration for the Song. -func (dl *YouTubeSong) DurationString() string { +// Duration returns duration for the Song. +func (dl *YouTubeSong) Duration() time.Duration { timeDuration, _ := time.ParseDuration(strconv.Itoa(dl.duration) + "s") - return timeDuration.String() + return timeDuration } // Thumbnail returns the thumbnail URL for the Song. From 0cbd0fda45e7ab68ad44b8b1f575a202c44b9574 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 16:19:06 +0100 Subject: [PATCH 284/297] Fixed accidental deletion --- main.go | 1 + 1 file changed, 1 insertion(+) diff --git a/main.go b/main.go index bda7499..86c45c0 100644 --- a/main.go +++ b/main.go @@ -170,6 +170,7 @@ func isNil(a interface{}) bool { } // dj variable declaration. This is done outside of main() to allow global use. +var dj = mumbledj{ keepAlive: make(chan bool), queue: NewSongQueue(), playlistSkips: make(map[string][]string), From b8a10924f8ed070eafe14a60ecc070884bb41ef1 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 16:20:16 +0100 Subject: [PATCH 285/297] Removed unneeded bracket --- service.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service.go b/service.go index 8f4a23d..baf2758 100644 --- a/service.go +++ b/service.go @@ -91,7 +91,7 @@ func FindServiceAndAdd(user *gumble.User, url string) error { oldLength := dj.queue.Len() for _, song := range songArray { // Check song is not too long - if dj.conf.General.MaxSongDuration == 0 || song.Duration().Seconds()) <= dj.conf.General.MaxSongDuration { + if dj.conf.General.MaxSongDuration == 0 || song.Duration().Seconds() <= dj.conf.General.MaxSongDuration { if !isNil(song.Playlist()) { title = song.Playlist().Title() } else { From b829c794e623783cf402a3ceb3988175547d9eed Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 16:22:22 +0100 Subject: [PATCH 286/297] Convert the duration seconds from float64 to int --- service.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service.go b/service.go index baf2758..55dc7ba 100644 --- a/service.go +++ b/service.go @@ -91,7 +91,7 @@ func FindServiceAndAdd(user *gumble.User, url string) error { oldLength := dj.queue.Len() for _, song := range songArray { // Check song is not too long - if dj.conf.General.MaxSongDuration == 0 || song.Duration().Seconds() <= dj.conf.General.MaxSongDuration { + if dj.conf.General.MaxSongDuration == 0 || int(song.Duration().Seconds()) <= dj.conf.General.MaxSongDuration { if !isNil(song.Playlist()) { title = song.Playlist().Title() } else { From a7be06533cfba674595d3caa47c28195860731b4 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 16:26:59 +0100 Subject: [PATCH 287/297] Stopped adding youtube tracks twice --- service_youtube.go | 1 - 1 file changed, 1 deletion(-) diff --git a/service_youtube.go b/service_youtube.go index 453044c..9883a74 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -98,7 +98,6 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis dontSkip: false, service: yt, } - dj.queue.AddSong(song) return song, nil } From e05ce579d997a8b51f90f2c8450a1dfcd34ca802 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 16:50:19 +0100 Subject: [PATCH 288/297] Debugging why a single video can not be added --- service.go | 2 ++ strings.go | 2 +- youtube_dl.go | 4 ++-- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/service.go b/service.go index 55dc7ba..4e9401e 100644 --- a/service.go +++ b/service.go @@ -90,6 +90,7 @@ func FindServiceAndAdd(user *gumble.User, url string) error { // Loop through all songs and add to the queue oldLength := dj.queue.Len() for _, song := range songArray { + fmt.Printf("Song loop, title: %s, duration: %d", song.Title(), int(song.Duration().Seconds())) // Check song is not too long if dj.conf.General.MaxSongDuration == 0 || int(song.Duration().Seconds()) <= dj.conf.General.MaxSongDuration { if !isNil(song.Playlist()) { @@ -103,6 +104,7 @@ func FindServiceAndAdd(user *gumble.User, url string) error { songsAdded++ } } + fmt.Printf("Songs added: %d", songsAdded) // Alert channel of added song/playlist if songsAdded == 0 { diff --git a/strings.go b/strings.go index 54b55f5..ec69cf5 100644 --- a/strings.go +++ b/strings.go @@ -78,7 +78,7 @@ const SONG_ADDED_HTML = ` // Message shown to channel when a playlist is added to the queue by a user. const PLAYLIST_ADDED_HTML = ` - %s has added the %s "%s" to the queue. + %s has added the playlist "%s" to the queue. ` // Message shown to channel when a song has been skipped. diff --git a/youtube_dl.go b/youtube_dl.go index acecf24..d7110bd 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -87,9 +87,9 @@ func (dl *YouTubeSong) Play() { panic(err) } else { message := `
%s (%s)
Added by %s
From playlist "%s"
` - message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.duration, dl.submitter.Name) + message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.duration.String(), dl.submitter.Name) if !isNil(dl.playlist) { - message = fmt.Sprintf(message+``, dl.playlist.Title()) + message = fmt.Sprintf(message+``, dl.Playlist().Title()) } dj.client.Self.Channel.Send(message+`
%s (%s)
Added by %s
From playlist "%s"
From playlist "%s"
`, false) From 1aebcfce77b3a3b85a7cd843c2cbd79cf5101c00 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 16:51:44 +0100 Subject: [PATCH 289/297] Fixing build issue --- youtube_dl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/youtube_dl.go b/youtube_dl.go index d7110bd..9217529 100644 --- a/youtube_dl.go +++ b/youtube_dl.go @@ -87,7 +87,7 @@ func (dl *YouTubeSong) Play() { panic(err) } else { message := `` - message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.duration.String(), dl.submitter.Name) + message = fmt.Sprintf(message, dl.thumbnail, dl.url, dl.title, dl.Duration().String(), dl.submitter.Name) if !isNil(dl.playlist) { message = fmt.Sprintf(message+``, dl.Playlist().Title()) } From 91a8dcb2bdc26097fb215e9681be2ccabad23a27 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 16:56:50 +0100 Subject: [PATCH 290/297] Fixed issue where a single youtube video could not be added --- service.go | 4 +--- service_youtube.go | 5 ++--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/service.go b/service.go index 4e9401e..1e855b5 100644 --- a/service.go +++ b/service.go @@ -90,7 +90,6 @@ func FindServiceAndAdd(user *gumble.User, url string) error { // Loop through all songs and add to the queue oldLength := dj.queue.Len() for _, song := range songArray { - fmt.Printf("Song loop, title: %s, duration: %d", song.Title(), int(song.Duration().Seconds())) // Check song is not too long if dj.conf.General.MaxSongDuration == 0 || int(song.Duration().Seconds()) <= dj.conf.General.MaxSongDuration { if !isNil(song.Playlist()) { @@ -104,11 +103,10 @@ func FindServiceAndAdd(user *gumble.User, url string) error { songsAdded++ } } - fmt.Printf("Songs added: %d", songsAdded) // Alert channel of added song/playlist if songsAdded == 0 { - return errors.New(TRACK_TOO_LONG_MSG) + return errors.New(fmt.Sprintf(TRACK_TOO_LONG_MSG, urlService.ServiceName())) } else if songsAdded == 1 { dj.client.Self.Channel.Send(fmt.Sprintf(SONG_ADDED_HTML, user.Name, title), false) } else { diff --git a/service_youtube.go b/service_youtube.go index 9883a74..1ef3b7b 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -64,9 +64,8 @@ func (yt YouTube) NewRequest(user *gumble.User, url string) ([]Song, error) { startOffset = matches[0][2] } song, err := yt.NewSong(user, shortURL, startOffset, nil) - if isNil(song) { - songArray = append(songArray, song) - return songArray, nil + if !isNil(song) { + return append(songArray, song), nil } else { return nil, err } From a6101472366f78dc566ff33ee02a1d9036047e04 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 17:11:13 +0100 Subject: [PATCH 291/297] Updated strings to make the word playlist static --- service_soundcloud.go | 2 +- strings.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/service_soundcloud.go b/service_soundcloud.go index 3491d99..d49498b 100644 --- a/service_soundcloud.go +++ b/service_soundcloud.go @@ -52,7 +52,7 @@ func (sc SoundCloud) NewRequest(user *gumble.User, url string) ([]Song, error) { timesplit := strings.Split(url, "#t=") url = fmt.Sprintf("http://api.soundcloud.com/resolve?url=%s&client_id=%s", timesplit[0], os.Getenv("SOUNDCLOUD_API_KEY")) if apiResponse, err = PerformGetRequest(url); err != nil { - return nil, errors.New(INVALID_API_KEY) + return nil, errors.New(fmt.Sprintf(INVALID_API_KEY, sc.ServiceName())) } tracks, err := apiResponse.ArrayOfObjects("tracks") diff --git a/strings.go b/strings.go index ec69cf5..76b7541 100644 --- a/strings.go +++ b/strings.go @@ -132,12 +132,12 @@ const SUBMITTER_SKIP_HTML = ` // Message shown to users when another user votes to skip the current playlist. const PLAYLIST_SKIP_ADDED_HTML = ` - %s has voted to skip the current %s. + %s has voted to skip the current playlist. ` // Message shown to users when the submitter of a song decides to skip their song. const PLAYLIST_SUBMITTER_SKIP_HTML = ` - The current %s has been skipped by %s, the submitter. + The current playlist has been skipped by %s, the submitter. ` // Message shown to users when they successfully change the volume. From d2d75f093def1e72dee8e0a1653ce3c5986ec7aa Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 17:30:55 +0100 Subject: [PATCH 292/297] Fixing offset for youtube videos --- service_youtube.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_youtube.go b/service_youtube.go index 1ef3b7b..a2c5b0c 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -108,7 +108,7 @@ func (yt YouTube) parseTime(duration string) time.Duration { var days, hours, minutes, seconds, totalSeconds int64 if duration != "" { timestampExp := regexp.MustCompile(`P(?P\d+D)?T(?P\d+H)?(?P\d+M)?(?P\d+S)?`) - timestampMatch := timestampExp.FindStringSubmatch(duration) + timestampMatch := timestampExp.FindStringSubmatch(strings.ToUpper(duration)) timestampResult := make(map[string]string) for i, name := range timestampExp.SubexpNames() { if i < len(timestampMatch) { From ac775479575914961d76ba02f398edac80c62768 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 17:37:19 +0100 Subject: [PATCH 293/297] Fixed youtube offset for reals this time --- service_youtube.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/service_youtube.go b/service_youtube.go index a2c5b0c..1568d8b 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -88,8 +88,8 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis title: title, id: id, url: "https://youtu.be/" + id, - offset: int(yt.parseTime(offset).Seconds()), - duration: int(yt.parseTime(duration).Seconds()), + offset: int(yt.parseTime(offset, `t\=(?P\d+d)?(?P\d+h)?(?P\d+m)?(?P\d+s)?`).Seconds()), + duration: int(yt.parseTime(duration, `P(?P\d+D)?T(?P\d+H)?(?P\d+M)?(?P\d+S)?`).Seconds()), thumbnail: thumbnail, format: "m4a", skippers: make([]string, 0), @@ -104,10 +104,10 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis } // parseTime converts from the string youtube returns to a time.Duration -func (yt YouTube) parseTime(duration string) time.Duration { +func (yt YouTube) parseTime(duration, regex string) time.Duration { var days, hours, minutes, seconds, totalSeconds int64 if duration != "" { - timestampExp := regexp.MustCompile(`P(?P\d+D)?T(?P\d+H)?(?P\d+M)?(?P\d+S)?`) + timestampExp := regexp.MustCompile(regex) timestampMatch := timestampExp.FindStringSubmatch(strings.ToUpper(duration)) timestampResult := make(map[string]string) for i, name := range timestampExp.SubexpNames() { From 061370df0b7ab920dc7d86a57dc480f8e292c20d Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 17:44:33 +0100 Subject: [PATCH 294/297] Fixed youtube offset --- service_youtube.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service_youtube.go b/service_youtube.go index 1568d8b..04c0eed 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -88,7 +88,7 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis title: title, id: id, url: "https://youtu.be/" + id, - offset: int(yt.parseTime(offset, `t\=(?P\d+d)?(?P\d+h)?(?P\d+m)?(?P\d+s)?`).Seconds()), + offset: int(yt.parseTime(offset, `t\=(?P\d+D)?(?P\d+H)?(?P\d+M)?(?P\d+S)?`).Seconds()), duration: int(yt.parseTime(duration, `P(?P\d+D)?T(?P\d+H)?(?P\d+M)?(?P\d+S)?`).Seconds()), thumbnail: thumbnail, format: "m4a", From eaf10a39f1897bd33b8449f7f10617a3a36b9a82 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 17:47:13 +0100 Subject: [PATCH 295/297] Added debug statement to work out why youtube videos won't offset --- service_youtube.go | 1 + 1 file changed, 1 insertion(+) diff --git a/service_youtube.go b/service_youtube.go index 04c0eed..e2fc76c 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -105,6 +105,7 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis // parseTime converts from the string youtube returns to a time.Duration func (yt YouTube) parseTime(duration, regex string) time.Duration { + fmt.Printf("parseTime(%s)", duration) var days, hours, minutes, seconds, totalSeconds int64 if duration != "" { timestampExp := regexp.MustCompile(regex) From 995e93d627acfc995668c9b186450cfd4e36da65 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 17:51:34 +0100 Subject: [PATCH 296/297] youtube offset --- service_youtube.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service_youtube.go b/service_youtube.go index e2fc76c..cd61648 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -88,7 +88,7 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis title: title, id: id, url: "https://youtu.be/" + id, - offset: int(yt.parseTime(offset, `t\=(?P\d+D)?(?P\d+H)?(?P\d+M)?(?P\d+S)?`).Seconds()), + offset: int(yt.parseTime(offset, `\?T\=(?P\d+D)?(?P\d+H)?(?P\d+M)?(?P\d+S)?`).Seconds()), duration: int(yt.parseTime(duration, `P(?P\d+D)?T(?P\d+H)?(?P\d+M)?(?P\d+S)?`).Seconds()), thumbnail: thumbnail, format: "m4a", @@ -105,7 +105,7 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis // parseTime converts from the string youtube returns to a time.Duration func (yt YouTube) parseTime(duration, regex string) time.Duration { - fmt.Printf("parseTime(%s)", duration) + fmt.Printf("parseTime(%s)", strings.ToUpper(duration)) var days, hours, minutes, seconds, totalSeconds int64 if duration != "" { timestampExp := regexp.MustCompile(regex) From 5c61238a2d9b9d3db20a05979ecee57741c50871 Mon Sep 17 00:00:00 2001 From: MichaelOultram Date: Sat, 26 Sep 2015 17:52:41 +0100 Subject: [PATCH 297/297] Removed debug message --- service_youtube.go | 1 - 1 file changed, 1 deletion(-) diff --git a/service_youtube.go b/service_youtube.go index cd61648..74da95f 100644 --- a/service_youtube.go +++ b/service_youtube.go @@ -105,7 +105,6 @@ func (yt YouTube) NewSong(user *gumble.User, id, offset string, playlist Playlis // parseTime converts from the string youtube returns to a time.Duration func (yt YouTube) parseTime(duration, regex string) time.Duration { - fmt.Printf("parseTime(%s)", strings.ToUpper(duration)) var days, hours, minutes, seconds, totalSeconds int64 if duration != "" { timestampExp := regexp.MustCompile(regex)
%s (%s)
Added by %s
From playlist "%s"