mirror of
https://github.com/sosedoff/pgweb.git
synced 2024-12-14 19:21:46 +03:00
commit
b3307b5557
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,4 +1,4 @@
|
||||
.DS_Store
|
||||
pgweb
|
||||
bin
|
||||
bindata.go
|
||||
|
||||
|
29
Godeps/Godeps.json
generated
Normal file
29
Godeps/Godeps.json
generated
Normal file
@ -0,0 +1,29 @@
|
||||
{
|
||||
"ImportPath": "pgweb",
|
||||
"GoVersion": "go1.3.3",
|
||||
"Deps": [
|
||||
{
|
||||
"ImportPath": "github.com/gin-gonic/gin",
|
||||
"Comment": "v0.4-8-g3b079bb",
|
||||
"Rev": "3b079bb6f79ae501e73a5401c41b589f6616b61e"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/jessevdk/go-flags",
|
||||
"Comment": "v1-265-g1c87b97",
|
||||
"Rev": "1c87b9727cd7c200be13a5d8280d7ea514469235"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/jmoiron/sqlx",
|
||||
"Comment": "sqlx-v1.0-49-g79215a1",
|
||||
"Rev": "79215a1536dd456d2a5afa112479b4f67fbe9f21"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/julienschmidt/httprouter",
|
||||
"Rev": "46807412fe50aaceb73bb57061c2230fd26a1640"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/lib/pq",
|
||||
"Rev": "7175accbed18058468c07811f76440d6e8d7cf19"
|
||||
}
|
||||
]
|
||||
}
|
5
Godeps/Readme
generated
Normal file
5
Godeps/Readme
generated
Normal file
@ -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.
|
2
Godeps/_workspace/.gitignore
generated
vendored
Normal file
2
Godeps/_workspace/.gitignore
generated
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
/pkg
|
||||
/bin
|
2
Godeps/_workspace/src/github.com/gin-gonic/gin/.gitignore
generated
vendored
Normal file
2
Godeps/_workspace/src/github.com/gin-gonic/gin/.gitignore
generated
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
Godeps/*
|
||||
!Godeps/Godeps.json
|
5
Godeps/_workspace/src/github.com/gin-gonic/gin/.travis.yml
generated
vendored
Normal file
5
Godeps/_workspace/src/github.com/gin-gonic/gin/.travis.yml
generated
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.3
|
||||
- tip
|
108
Godeps/_workspace/src/github.com/gin-gonic/gin/AUTHORS.md
generated
vendored
Normal file
108
Godeps/_workspace/src/github.com/gin-gonic/gin/AUTHORS.md
generated
vendored
Normal file
@ -0,0 +1,108 @@
|
||||
List of all the awesome people working to make Gin the best Web Framework in Go!
|
||||
|
||||
|
||||
|
||||
##gin 0.x series authors
|
||||
|
||||
**Lead Developer:** Manu Martinez-Almeida (@manucorporat)
|
||||
**Staff:**
|
||||
Javier Provecho (@javierprovecho)
|
||||
|
||||
People and companies, who have contributed, in alphabetical order.
|
||||
|
||||
**@adammck (Adam Mckaig)**
|
||||
- Add MIT license
|
||||
|
||||
|
||||
**@AlexanderChen1989 (Alexander)**
|
||||
- Typos in README
|
||||
|
||||
|
||||
**@alexandernyquist (Alexander Nyquist)**
|
||||
- Using template.Must to fix multiple return issue
|
||||
- ★ Added support for OPTIONS verb
|
||||
- ★ Setting response headers before calling WriteHeader
|
||||
- Improved documentation for model binding
|
||||
- ★ Added Content.Redirect()
|
||||
- ★ Added tons of Unit tests
|
||||
|
||||
|
||||
**@austinheap (Austin Heap)**
|
||||
- Added travis CI integration
|
||||
|
||||
|
||||
**@bluele (Jun Kimura)**
|
||||
- Fixes code examples in README
|
||||
|
||||
|
||||
**@chad-russell**
|
||||
- ★ Support for serializing gin.H into XML
|
||||
|
||||
|
||||
**@dickeyxxx (Jeff Dickey)**
|
||||
- Typos in README
|
||||
|
||||
|
||||
**@fmd (Fareed Dudhia)**
|
||||
- Fix typo. SetHTTPTemplate -> SetHTMLTemplate
|
||||
|
||||
|
||||
**@jasonrhansen**
|
||||
- Fix spelling and grammar errors in documentation
|
||||
|
||||
|
||||
**@julienschmidt (Julien Schmidt)**
|
||||
- gofmt the code examples
|
||||
|
||||
|
||||
**@kyledinh (Kyle Dinh)**
|
||||
- Adds RunTLS()
|
||||
|
||||
|
||||
**@LinusU (Linus Unnebäck)**
|
||||
- Small fixes in README
|
||||
|
||||
|
||||
**@lucas-clemente (Lucas Clemente)**
|
||||
- ★ work around path.Join removing trailing slashes from routes
|
||||
|
||||
|
||||
**@mdigger (Dmitry Sedykh)**
|
||||
- Fixes Form binding when content-type is x-www-form-urlencoded
|
||||
- No repeat call c.Writer.Status() in gin.Logger
|
||||
- Fixes Content-Type for json render
|
||||
|
||||
|
||||
**@mopemope (Yutaka Matsubara)**
|
||||
- ★ Adds Godep support (Dependencies Manager)
|
||||
- Fix variadic parameter in the flexible render API
|
||||
- Fix Corrupted plain render
|
||||
|
||||
|
||||
**@msemenistyi (Mykyta Semenistyi)**
|
||||
- update Readme.md. Add code to String method
|
||||
|
||||
|
||||
**@msoedov (Sasha Myasoedov)**
|
||||
- ★ Adds tons of unit tests.
|
||||
|
||||
|
||||
**@ngerakines (Nick Gerakines)**
|
||||
- ★ Improves API, c.GET() doesn't panic
|
||||
- Adds MustGet() method
|
||||
|
||||
|
||||
**@r8k (Rajiv Kilaparti)**
|
||||
- Fix Port usage in README.
|
||||
|
||||
|
||||
**@silasb (Silas Baronda)**
|
||||
- Fixing quotes in README
|
||||
|
||||
|
||||
**@SkuliOskarsson (Skuli Oskarsson)**
|
||||
- Fixes some texts in README II
|
||||
|
||||
|
||||
**@yuyabee**
|
||||
- Fixed README
|
54
Godeps/_workspace/src/github.com/gin-gonic/gin/CHANGELOG.md
generated
vendored
Normal file
54
Godeps/_workspace/src/github.com/gin-gonic/gin/CHANGELOG.md
generated
vendored
Normal file
@ -0,0 +1,54 @@
|
||||
#Changelog
|
||||
|
||||
###Gin 0.4 (Aug 21, 2014)
|
||||
|
||||
- [NEW] Development mode
|
||||
- [NEW] Unit tests
|
||||
- [NEW] Add Content.Redirect()
|
||||
- [FIX] Deferring WriteHeader()
|
||||
- [FIX] Improved documentation for model binding
|
||||
|
||||
|
||||
###Gin 0.3 (Jul 18, 2014)
|
||||
|
||||
- [PERFORMANCE] Normal log and error log are printed in the same call.
|
||||
- [PERFORMANCE] Improve performance of NoRouter()
|
||||
- [PERFORMANCE] Improve context's memory locality, reduce CPU cache faults.
|
||||
- [NEW] Flexible rendering API
|
||||
- [NEW] Add Context.File()
|
||||
- [NEW] Add shorcut RunTLS() for http.ListenAndServeTLS
|
||||
- [FIX] Rename NotFound404() to NoRoute()
|
||||
- [FIX] Errors in context are purged
|
||||
- [FIX] Adds HEAD method in Static file serving
|
||||
- [FIX] Refactors Static() file serving
|
||||
- [FIX] Using keyed initialization to fix app-engine integration
|
||||
- [FIX] Can't unmarshal JSON array, #63
|
||||
- [FIX] Renaming Context.Req to Context.Request
|
||||
- [FIX] Check application/x-www-form-urlencoded when parsing form
|
||||
|
||||
|
||||
###Gin 0.2b (Jul 08, 2014)
|
||||
- [PERFORMANCE] Using sync.Pool to allocatio/gc overhead
|
||||
- [NEW] Travis CI integration
|
||||
- [NEW] Completely new logger
|
||||
- [NEW] New API for serving static files. gin.Static()
|
||||
- [NEW] gin.H() can be serialized into XML
|
||||
- [NEW] Typed errors. Errors can be typed. Internet/external/custom.
|
||||
- [NEW] Support for Godebs
|
||||
- [NEW] Travis/Godocs badges in README
|
||||
- [NEW] New Bind() and BindWith() methods for parsing request body.
|
||||
- [NEW] Add Content.Copy()
|
||||
- [NEW] Add context.LastError()
|
||||
- [NEW] Add shorcut for OPTIONS HTTP method
|
||||
- [FIX] Tons of README fixes
|
||||
- [FIX] Header is written before body
|
||||
- [FIX] BasicAuth() and changes API a little bit
|
||||
- [FIX] Recovery() middleware only prints panics
|
||||
- [FIX] Context.Get() does not panic anymore. Use MustGet() instead.
|
||||
- [FIX] Multiple http.WriteHeader() in NotFound handlers
|
||||
- [FIX] Engine.Run() panics if http server can't be setted up
|
||||
- [FIX] Crash when route path doesn't start with '/'
|
||||
- [FIX] Do not update header when status code is negative
|
||||
- [FIX] Setting response headers before calling WriteHeader in context.String()
|
||||
- [FIX] Add MIT license
|
||||
- [FIX] Changes behaviour of ErrorLogger() and Logger()
|
10
Godeps/_workspace/src/github.com/gin-gonic/gin/Godeps/Godeps.json
generated
vendored
Normal file
10
Godeps/_workspace/src/github.com/gin-gonic/gin/Godeps/Godeps.json
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"ImportPath": "github.com/gin-gonic/gin",
|
||||
"GoVersion": "go1.3",
|
||||
"Deps": [
|
||||
{
|
||||
"ImportPath": "github.com/julienschmidt/httprouter",
|
||||
"Rev": "7deadb6844d2c6ff1dfb812eaa439b87cdaedf20"
|
||||
}
|
||||
]
|
||||
}
|
21
Godeps/_workspace/src/github.com/gin-gonic/gin/LICENSE
generated
vendored
Normal file
21
Godeps/_workspace/src/github.com/gin-gonic/gin/LICENSE
generated
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Manuel Martínez-Almeida
|
||||
|
||||
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.
|
472
Godeps/_workspace/src/github.com/gin-gonic/gin/README.md
generated
vendored
Normal file
472
Godeps/_workspace/src/github.com/gin-gonic/gin/README.md
generated
vendored
Normal file
@ -0,0 +1,472 @@
|
||||
#Gin Web Framework
|
||||
|
||||
[![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin)
|
||||
[![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin)
|
||||
|
||||
Gin is a web framework written in Golang. It features a martini-like API with much better performance, up to 40 times faster. If you need performance and good productivity, you will love Gin.
|
||||
![Gin console logger](http://gin-gonic.github.io/gin/other/console.png)
|
||||
|
||||
##Gin is new, will it be supported?
|
||||
|
||||
Yes, Gin is an internal project of [my](https://github.com/manucorporat) upcoming startup. We developed it and we are going to continue using and improve it.
|
||||
|
||||
|
||||
##Roadmap for v1.0
|
||||
- [x] Performance improments, reduce allocation and garbage collection overhead
|
||||
- [x] Fix bugs
|
||||
- [ ] Stable API
|
||||
- [ ] Ask our designer for a cool logo
|
||||
- [ ] Add tons of unit tests
|
||||
- [ ] Add internal benchmarks suite
|
||||
- [x] Improve logging system
|
||||
- [x] Improve JSON/XML validation using bindings
|
||||
- [x] Improve XML support
|
||||
- [x] Flexible rendering system
|
||||
- [ ] More powerful validation API
|
||||
- [ ] Improve documentation
|
||||
- [ ] Add more cool middlewares, for example redis caching (this also helps developers to understand the framework).
|
||||
- [x] Continuous integration
|
||||
|
||||
|
||||
|
||||
## Start using it
|
||||
Obviously, you need to have Git and Go! already installed to run Gin.
|
||||
Run this in your terminal
|
||||
|
||||
```
|
||||
go get github.com/gin-gonic/gin
|
||||
```
|
||||
Then import it in your Go! code:
|
||||
|
||||
```
|
||||
import "github.com/gin-gonic/gin"
|
||||
```
|
||||
|
||||
|
||||
##Community
|
||||
If you'd like to help out with the project, there's a mailing list and IRC channel where Gin discussions normally happen.
|
||||
|
||||
* IRC
|
||||
* [irc.freenode.net #getgin](irc://irc.freenode.net:6667/getgin)
|
||||
* [Webchat](http://webchat.freenode.net?randomnick=1&channels=%23getgin)
|
||||
* Mailing List
|
||||
* Subscribe: [getgin@librelist.org](mailto:getgin@librelist.org)
|
||||
* [Archives](http://librelist.com/browser/getgin/)
|
||||
|
||||
|
||||
##API Examples
|
||||
|
||||
#### Create most basic PING/PONG HTTP endpoint
|
||||
```go
|
||||
package main
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
r.GET("/ping", func(c *gin.Context) {
|
||||
c.String(200, "pong")
|
||||
})
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
#### Using GET, POST, PUT, PATCH, DELETE and OPTIONS
|
||||
|
||||
```go
|
||||
func main() {
|
||||
// Creates a gin router + logger and recovery (crash-free) middlewares
|
||||
r := gin.Default()
|
||||
|
||||
r.GET("/someGet", getting)
|
||||
r.POST("/somePost", posting)
|
||||
r.PUT("/somePut", putting)
|
||||
r.DELETE("/someDelete", deleting)
|
||||
r.PATCH("/somePatch", patching)
|
||||
r.HEAD("/someHead", head)
|
||||
r.OPTIONS("/someOptions", options)
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
#### Parameters in path
|
||||
|
||||
```go
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// This handler will match /user/john but will not match neither /user/ or /user
|
||||
r.GET("/user/:name", func(c *gin.Context) {
|
||||
name := c.Params.ByName("name")
|
||||
message := "Hello "+name
|
||||
c.String(200, message)
|
||||
})
|
||||
|
||||
// However, this one will match /user/john and also /user/john/send
|
||||
r.GET("/user/:name/*action", func(c *gin.Context) {
|
||||
name := c.Params.ByName("name")
|
||||
action := c.Params.ByName("action")
|
||||
message := name + " is " + action
|
||||
c.String(200, message)
|
||||
})
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### Grouping routes
|
||||
```go
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// Simple group: v1
|
||||
v1 := r.Group("/v1")
|
||||
{
|
||||
v1.POST("/login", loginEndpoint)
|
||||
v1.POST("/submit", submitEndpoint)
|
||||
v1.POST("/read", readEndpoint)
|
||||
}
|
||||
|
||||
// Simple group: v2
|
||||
v2 := r.Group("/v2")
|
||||
{
|
||||
v2.POST("/login", loginEndpoint)
|
||||
v2.POST("/submit", submitEndpoint)
|
||||
v2.POST("/read", readEndpoint)
|
||||
}
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### Blank Gin without middlewares by default
|
||||
|
||||
Use
|
||||
|
||||
```go
|
||||
r := gin.New()
|
||||
```
|
||||
instead of
|
||||
|
||||
```go
|
||||
r := gin.Default()
|
||||
```
|
||||
|
||||
|
||||
#### Using middlewares
|
||||
```go
|
||||
func main() {
|
||||
// Creates a router without any middleware by default
|
||||
r := gin.New()
|
||||
|
||||
// Global middlewares
|
||||
r.Use(gin.Logger())
|
||||
r.Use(gin.Recovery())
|
||||
|
||||
// Per route middlewares, you can add as many as you desire.
|
||||
r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
|
||||
|
||||
// Authorization group
|
||||
// authorized := r.Group("/", AuthRequired())
|
||||
// exactly the same than:
|
||||
authorized := r.Group("/")
|
||||
// per group middlewares! in this case we use the custom created
|
||||
// AuthRequired() middleware just in the "authorized" group.
|
||||
authorized.Use(AuthRequired())
|
||||
{
|
||||
authorized.POST("/login", loginEndpoint)
|
||||
authorized.POST("/submit", submitEndpoint)
|
||||
authorized.POST("/read", readEndpoint)
|
||||
|
||||
// nested group
|
||||
testing := authorized.Group("testing")
|
||||
testing.GET("/analytics", analyticsEndpoint)
|
||||
}
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
#### Model binding and validation
|
||||
|
||||
To bind a request body into a type, use model binding. We currently support binding of JSON, XML and standard form values (foo=bar&boo=baz).
|
||||
|
||||
Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set `json:"fieldname"`.
|
||||
|
||||
When using the Bind-method, Gin tries to infer the binder depending on the Content-Type header. If you are sure what you are binding, you can use BindWith.
|
||||
|
||||
You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, the current request will fail with an error.
|
||||
|
||||
```go
|
||||
// Binding from JSON
|
||||
type LoginJSON struct {
|
||||
User string `json:"user" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
// Binding from form values
|
||||
type LoginForm struct {
|
||||
User string `form:"user" binding:"required"`
|
||||
Password string `form:"password" binding:"required"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// Example for binding JSON ({"user": "manu", "password": "123"})
|
||||
r.POST("/login", func(c *gin.Context) {
|
||||
var json LoginJSON
|
||||
|
||||
c.Bind(&json) // This will infer what binder to use depending on the content-type header.
|
||||
if json.User == "manu" && json.Password == "123" {
|
||||
c.JSON(200, gin.H{"status": "you are logged in"})
|
||||
} else {
|
||||
c.JSON(401, gin.H{"status": "unauthorized"})
|
||||
}
|
||||
})
|
||||
|
||||
// Example for binding a HTLM form (user=manu&password=123)
|
||||
r.POST("/login", func(c *gin.Context) {
|
||||
var form LoginForm
|
||||
|
||||
c.BindWith(&form, binding.Form) // You can also specify which binder to use. We support binding.Form, binding.JSON and binding.XML.
|
||||
if form.User == "manu" && form.Password == "123" {
|
||||
c.JSON(200, gin.H{"status": "you are logged in"})
|
||||
} else {
|
||||
c.JSON(401, gin.H{"status": "unauthorized"})
|
||||
}
|
||||
})
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
#### XML and JSON rendering
|
||||
|
||||
```go
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// gin.H is a shortcup for map[string]interface{}
|
||||
r.GET("/someJSON", func(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"message": "hey", "status": 200})
|
||||
})
|
||||
|
||||
r.GET("/moreJSON", func(c *gin.Context) {
|
||||
// You also can use a struct
|
||||
var msg struct {
|
||||
Name string `json:"user"`
|
||||
Message string
|
||||
Number int
|
||||
}
|
||||
msg.Name = "Lena"
|
||||
msg.Message = "hey"
|
||||
msg.Number = 123
|
||||
// Note that msg.Name becomes "user" in the JSON
|
||||
// Will output : {"user": "Lena", "Message": "hey", "Number": 123}
|
||||
c.JSON(200, msg)
|
||||
})
|
||||
|
||||
r.GET("/someXML", func(c *gin.Context) {
|
||||
c.XML(200, gin.H{"message": "hey", "status": 200})
|
||||
})
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
####HTML rendering
|
||||
|
||||
Using LoadHTMLTemplates()
|
||||
|
||||
```go
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
r.LoadHTMLTemplates("templates/*")
|
||||
r.GET("/index", func(c *gin.Context) {
|
||||
obj := gin.H{"title": "Main website"}
|
||||
c.HTML(200, "index.tmpl", obj)
|
||||
})
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
You can also use your own html template render
|
||||
|
||||
```go
|
||||
import "html/template"
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
html := template.Must(template.ParseFiles("file1", "file2"))
|
||||
r.HTMLTemplates = html
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
#### Redirects
|
||||
|
||||
Issuing a HTTP redirect is easy:
|
||||
|
||||
```go
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
c.Redirect(301, "http://www.google.com/")
|
||||
})
|
||||
```
|
||||
Both internal and external locations are supported.
|
||||
|
||||
|
||||
#### Custom Middlewares
|
||||
|
||||
```go
|
||||
func Logger() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
t := time.Now()
|
||||
|
||||
// Set example variable
|
||||
c.Set("example", "12345")
|
||||
|
||||
// before request
|
||||
|
||||
c.Next()
|
||||
|
||||
// after request
|
||||
latency := time.Since(t)
|
||||
log.Print(latency)
|
||||
|
||||
// access the status we are sending
|
||||
status := c.Writer.Status()
|
||||
log.Println(status)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
r := gin.New()
|
||||
r.Use(Logger())
|
||||
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
example := c.MustGet("example").(string)
|
||||
|
||||
// it would print: "12345"
|
||||
log.Println(example)
|
||||
})
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
#### Using BasicAuth() middleware
|
||||
```go
|
||||
// similate some private data
|
||||
var secrets = gin.H{
|
||||
"foo": gin.H{"email": "foo@bar.com", "phone": "123433"},
|
||||
"austin": gin.H{"email": "austin@example.com", "phone": "666"},
|
||||
"lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},
|
||||
}
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// Group using gin.BasicAuth() middleware
|
||||
// gin.Accounts is a shortcut for map[string]string
|
||||
authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
|
||||
"foo": "bar",
|
||||
"austin": "1234",
|
||||
"lena": "hello2",
|
||||
"manu": "4321",
|
||||
}))
|
||||
|
||||
// /admin/secrets endpoint
|
||||
// hit "localhost:8080/admin/secrets
|
||||
authorized.GET("/secrets", func(c *gin.Context) {
|
||||
// get user, it was setted by the BasicAuth middleware
|
||||
user := c.Get(gin.AuthUserKey).(string)
|
||||
if secret, ok := secrets[user]; ok {
|
||||
c.JSON(200, gin.H{"user": user, "secret": secret})
|
||||
} else {
|
||||
c.JSON(200, gin.H{"user": user, "secret": "NO SECRET :("})
|
||||
}
|
||||
})
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### Goroutines inside a middleware
|
||||
When starting inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy.
|
||||
|
||||
```go
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
r.GET("/long_async", func(c *gin.Context) {
|
||||
// create copy to be used inside the goroutine
|
||||
c_cp := c.Copy()
|
||||
go func() {
|
||||
// simulate a long task with time.Sleep(). 5 seconds
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// note than you are using the copied context "c_cp", IMPORTANT
|
||||
log.Println("Done! in path " + c_cp.Request.URL.Path)
|
||||
}()
|
||||
})
|
||||
|
||||
|
||||
r.GET("/long_sync", func(c *gin.Context) {
|
||||
// simulate a long task with time.Sleep(). 5 seconds
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// since we are NOT using a goroutine, we do not have to copy the context
|
||||
log.Println("Done! in path " + c.Request.URL.Path)
|
||||
})
|
||||
|
||||
// Listen and server on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
#### Custom HTTP configuration
|
||||
|
||||
Use `http.ListenAndServe()` directly, like this:
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
http.ListenAndServe(":8080", router)
|
||||
}
|
||||
```
|
||||
or
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
|
||||
s := &http.Server{
|
||||
Addr: ":8080",
|
||||
Handler: router,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20,
|
||||
}
|
||||
s.ListenAndServe()
|
||||
}
|
||||
```
|
92
Godeps/_workspace/src/github.com/gin-gonic/gin/auth.go
generated
vendored
Normal file
92
Godeps/_workspace/src/github.com/gin-gonic/gin/auth.go
generated
vendored
Normal file
@ -0,0 +1,92 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"sort"
|
||||
)
|
||||
|
||||
const (
|
||||
AuthUserKey = "user"
|
||||
)
|
||||
|
||||
type (
|
||||
BasicAuthPair struct {
|
||||
Code string
|
||||
User string
|
||||
}
|
||||
Accounts map[string]string
|
||||
Pairs []BasicAuthPair
|
||||
)
|
||||
|
||||
func (a Pairs) Len() int { return len(a) }
|
||||
func (a Pairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
func (a Pairs) Less(i, j int) bool { return a[i].Code < a[j].Code }
|
||||
|
||||
func processCredentials(accounts Accounts) (Pairs, error) {
|
||||
if len(accounts) == 0 {
|
||||
return nil, errors.New("Empty list of authorized credentials.")
|
||||
}
|
||||
pairs := make(Pairs, 0, len(accounts))
|
||||
for user, password := range accounts {
|
||||
if len(user) == 0 || len(password) == 0 {
|
||||
return nil, errors.New("User or password is empty")
|
||||
}
|
||||
base := user + ":" + password
|
||||
code := "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
|
||||
pairs = append(pairs, BasicAuthPair{code, user})
|
||||
}
|
||||
// We have to sort the credentials in order to use bsearch later.
|
||||
sort.Sort(pairs)
|
||||
return pairs, nil
|
||||
}
|
||||
|
||||
func secureCompare(given, actual string) bool {
|
||||
if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
|
||||
return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
|
||||
} else {
|
||||
/* Securely compare actual to itself to keep constant time, but always return false */
|
||||
return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
|
||||
}
|
||||
}
|
||||
|
||||
func searchCredential(pairs Pairs, auth string) string {
|
||||
if len(auth) == 0 {
|
||||
return ""
|
||||
}
|
||||
// Search user in the slice of allowed credentials
|
||||
r := sort.Search(len(pairs), func(i int) bool { return pairs[i].Code >= auth })
|
||||
if r < len(pairs) && secureCompare(pairs[r].Code, auth) {
|
||||
return pairs[r].User
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where
|
||||
// the key is the user name and the value is the password.
|
||||
func BasicAuth(accounts Accounts) HandlerFunc {
|
||||
|
||||
pairs, err := processCredentials(accounts)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return func(c *Context) {
|
||||
// Search user in the slice of allowed credentials
|
||||
user := searchCredential(pairs, c.Request.Header.Get("Authorization"))
|
||||
if len(user) == 0 {
|
||||
// Credentials doesn't match, we return 401 Unauthorized and abort request.
|
||||
c.Writer.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
|
||||
c.Fail(401, errors.New("Unauthorized"))
|
||||
} else {
|
||||
// user is allowed, set UserId to key "user" in this context, the userId can be read later using
|
||||
// c.Get(gin.AuthUserKey)
|
||||
c.Set(AuthUserKey, user)
|
||||
}
|
||||
}
|
||||
}
|
61
Godeps/_workspace/src/github.com/gin-gonic/gin/auth_test.go
generated
vendored
Normal file
61
Godeps/_workspace/src/github.com/gin-gonic/gin/auth_test.go
generated
vendored
Normal file
@ -0,0 +1,61 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBasicAuthSucceed(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", "/login", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r := New()
|
||||
accounts := Accounts{"admin": "password"}
|
||||
r.Use(BasicAuth(accounts))
|
||||
|
||||
r.GET("/login", func(c *Context) {
|
||||
c.String(200, "autorized")
|
||||
})
|
||||
|
||||
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("Response code should be Ok, was: %s", w.Code)
|
||||
}
|
||||
bodyAsString := w.Body.String()
|
||||
|
||||
if bodyAsString != "autorized" {
|
||||
t.Errorf("Response body should be `autorized`, was %s", bodyAsString)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicAuth401(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", "/login", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r := New()
|
||||
accounts := Accounts{"foo": "bar"}
|
||||
r.Use(BasicAuth(accounts))
|
||||
|
||||
r.GET("/login", func(c *Context) {
|
||||
c.String(200, "autorized")
|
||||
})
|
||||
|
||||
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 401 {
|
||||
t.Errorf("Response code should be Not autorized, was: %s", w.Code)
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" {
|
||||
t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
209
Godeps/_workspace/src/github.com/gin-gonic/gin/binding/binding.go
generated
vendored
Normal file
209
Godeps/_workspace/src/github.com/gin-gonic/gin/binding/binding.go
generated
vendored
Normal file
@ -0,0 +1,209 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package binding
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type (
|
||||
Binding interface {
|
||||
Bind(*http.Request, interface{}) error
|
||||
}
|
||||
|
||||
// JSON binding
|
||||
jsonBinding struct{}
|
||||
|
||||
// XML binding
|
||||
xmlBinding struct{}
|
||||
|
||||
// // form binding
|
||||
formBinding struct{}
|
||||
)
|
||||
|
||||
var (
|
||||
JSON = jsonBinding{}
|
||||
XML = xmlBinding{}
|
||||
Form = formBinding{} // todo
|
||||
)
|
||||
|
||||
func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error {
|
||||
decoder := json.NewDecoder(req.Body)
|
||||
if err := decoder.Decode(obj); err == nil {
|
||||
return Validate(obj)
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (_ xmlBinding) Bind(req *http.Request, obj interface{}) error {
|
||||
decoder := xml.NewDecoder(req.Body)
|
||||
if err := decoder.Decode(obj); err == nil {
|
||||
return Validate(obj)
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (_ formBinding) Bind(req *http.Request, obj interface{}) error {
|
||||
if err := req.ParseForm(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := mapForm(obj, req.Form); err != nil {
|
||||
return err
|
||||
}
|
||||
return Validate(obj)
|
||||
}
|
||||
|
||||
func mapForm(ptr interface{}, form map[string][]string) error {
|
||||
typ := reflect.TypeOf(ptr).Elem()
|
||||
formStruct := reflect.ValueOf(ptr).Elem()
|
||||
for i := 0; i < typ.NumField(); i++ {
|
||||
typeField := typ.Field(i)
|
||||
if inputFieldName := typeField.Tag.Get("form"); inputFieldName != "" {
|
||||
structField := formStruct.Field(i)
|
||||
if !structField.CanSet() {
|
||||
continue
|
||||
}
|
||||
|
||||
inputValue, exists := form[inputFieldName]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
numElems := len(inputValue)
|
||||
if structField.Kind() == reflect.Slice && numElems > 0 {
|
||||
sliceOf := structField.Type().Elem().Kind()
|
||||
slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
|
||||
for i := 0; i < numElems; i++ {
|
||||
if err := setWithProperType(sliceOf, inputValue[i], slice.Index(i)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
formStruct.Elem().Field(i).Set(slice)
|
||||
} else {
|
||||
if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error {
|
||||
switch valueKind {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
if val == "" {
|
||||
val = "0"
|
||||
}
|
||||
intVal, err := strconv.Atoi(val)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
structField.SetInt(int64(intVal))
|
||||
}
|
||||
case reflect.Bool:
|
||||
if val == "" {
|
||||
val = "false"
|
||||
}
|
||||
boolVal, err := strconv.ParseBool(val)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
structField.SetBool(boolVal)
|
||||
}
|
||||
case reflect.Float32:
|
||||
if val == "" {
|
||||
val = "0.0"
|
||||
}
|
||||
floatVal, err := strconv.ParseFloat(val, 32)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
structField.SetFloat(floatVal)
|
||||
}
|
||||
case reflect.Float64:
|
||||
if val == "" {
|
||||
val = "0.0"
|
||||
}
|
||||
floatVal, err := strconv.ParseFloat(val, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
structField.SetFloat(floatVal)
|
||||
}
|
||||
case reflect.String:
|
||||
structField.SetString(val)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Don't pass in pointers to bind to. Can lead to bugs. See:
|
||||
// https://github.com/codegangsta/martini-contrib/issues/40
|
||||
// https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659
|
||||
func ensureNotPointer(obj interface{}) {
|
||||
if reflect.TypeOf(obj).Kind() == reflect.Ptr {
|
||||
panic("Pointers are not accepted as binding models")
|
||||
}
|
||||
}
|
||||
|
||||
func Validate(obj interface{}) error {
|
||||
typ := reflect.TypeOf(obj)
|
||||
val := reflect.ValueOf(obj)
|
||||
|
||||
if typ.Kind() == reflect.Ptr {
|
||||
typ = typ.Elem()
|
||||
val = val.Elem()
|
||||
}
|
||||
|
||||
switch typ.Kind() {
|
||||
case reflect.Struct:
|
||||
for i := 0; i < typ.NumField(); i++ {
|
||||
field := typ.Field(i)
|
||||
|
||||
// Allow ignored fields in the struct
|
||||
if field.Tag.Get("form") == "-" {
|
||||
continue
|
||||
}
|
||||
|
||||
fieldValue := val.Field(i).Interface()
|
||||
zero := reflect.Zero(field.Type).Interface()
|
||||
|
||||
if strings.Index(field.Tag.Get("binding"), "required") > -1 {
|
||||
fieldType := field.Type.Kind()
|
||||
if fieldType == reflect.Struct {
|
||||
err := Validate(fieldValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if reflect.DeepEqual(zero, fieldValue) {
|
||||
return errors.New("Required " + field.Name)
|
||||
} else if fieldType == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct {
|
||||
err := Validate(fieldValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case reflect.Slice:
|
||||
for i := 0; i < val.Len(); i++ {
|
||||
fieldValue := val.Index(i).Interface()
|
||||
err := Validate(fieldValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
277
Godeps/_workspace/src/github.com/gin-gonic/gin/context.go
generated
vendored
Normal file
277
Godeps/_workspace/src/github.com/gin-gonic/gin/context.go
generated
vendored
Normal file
@ -0,0 +1,277 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/gin-gonic/gin/render"
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const (
|
||||
ErrorTypeInternal = 1 << iota
|
||||
ErrorTypeExternal = 1 << iota
|
||||
ErrorTypeAll = 0xffffffff
|
||||
)
|
||||
|
||||
// Used internally to collect errors that occurred during an http request.
|
||||
type errorMsg struct {
|
||||
Err string `json:"error"`
|
||||
Type uint32 `json:"-"`
|
||||
Meta interface{} `json:"meta"`
|
||||
}
|
||||
|
||||
type errorMsgs []errorMsg
|
||||
|
||||
func (a errorMsgs) ByType(typ uint32) errorMsgs {
|
||||
if len(a) == 0 {
|
||||
return a
|
||||
}
|
||||
result := make(errorMsgs, 0, len(a))
|
||||
for _, msg := range a {
|
||||
if msg.Type&typ > 0 {
|
||||
result = append(result, msg)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (a errorMsgs) String() string {
|
||||
if len(a) == 0 {
|
||||
return ""
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
for i, msg := range a {
|
||||
text := fmt.Sprintf("Error #%02d: %s \n Meta: %v\n", (i + 1), msg.Err, msg.Meta)
|
||||
buffer.WriteString(text)
|
||||
}
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
// Context is the most important part of gin. It allows us to pass variables between middleware,
|
||||
// manage the flow, validate the JSON of a request and render a JSON response for example.
|
||||
type Context struct {
|
||||
writermem responseWriter
|
||||
Request *http.Request
|
||||
Writer ResponseWriter
|
||||
Keys map[string]interface{}
|
||||
Errors errorMsgs
|
||||
Params httprouter.Params
|
||||
Engine *Engine
|
||||
handlers []HandlerFunc
|
||||
index int8
|
||||
}
|
||||
|
||||
/************************************/
|
||||
/********** ROUTES GROUPING *********/
|
||||
/************************************/
|
||||
|
||||
func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {
|
||||
c := engine.cache.Get().(*Context)
|
||||
c.writermem.reset(w)
|
||||
c.Request = req
|
||||
c.Params = params
|
||||
c.handlers = handlers
|
||||
c.Keys = nil
|
||||
c.index = -1
|
||||
c.Errors = c.Errors[0:0]
|
||||
return c
|
||||
}
|
||||
|
||||
/************************************/
|
||||
/****** FLOW AND ERROR MANAGEMENT****/
|
||||
/************************************/
|
||||
|
||||
func (c *Context) Copy() *Context {
|
||||
var cp Context = *c
|
||||
cp.index = AbortIndex
|
||||
cp.handlers = nil
|
||||
return &cp
|
||||
}
|
||||
|
||||
// Next should be used only in the middlewares.
|
||||
// It executes the pending handlers in the chain inside the calling handler.
|
||||
// See example in github.
|
||||
func (c *Context) Next() {
|
||||
c.index++
|
||||
s := int8(len(c.handlers))
|
||||
for ; c.index < s; c.index++ {
|
||||
c.handlers[c.index](c)
|
||||
}
|
||||
}
|
||||
|
||||
// Forces the system to do not continue calling the pending handlers.
|
||||
// For example, the first handler checks if the request is authorized. If it's not, context.Abort(401) should be called.
|
||||
// The rest of pending handlers would never be called for that request.
|
||||
func (c *Context) Abort(code int) {
|
||||
if code >= 0 {
|
||||
c.Writer.WriteHeader(code)
|
||||
}
|
||||
c.index = AbortIndex
|
||||
}
|
||||
|
||||
// Fail is the same as Abort plus an error message.
|
||||
// Calling `context.Fail(500, err)` is equivalent to:
|
||||
// ```
|
||||
// context.Error("Operation aborted", err)
|
||||
// context.Abort(500)
|
||||
// ```
|
||||
func (c *Context) Fail(code int, err error) {
|
||||
c.Error(err, "Operation aborted")
|
||||
c.Abort(code)
|
||||
}
|
||||
|
||||
func (c *Context) ErrorTyped(err error, typ uint32, meta interface{}) {
|
||||
c.Errors = append(c.Errors, errorMsg{
|
||||
Err: err.Error(),
|
||||
Type: typ,
|
||||
Meta: meta,
|
||||
})
|
||||
}
|
||||
|
||||
// Attaches an error to the current context. The error is pushed to a list of errors.
|
||||
// It's a good idea to call Error for each error that occurred during the resolution of a request.
|
||||
// A middleware can be used to collect all the errors and push them to a database together, print a log, or append it in the HTTP response.
|
||||
func (c *Context) Error(err error, meta interface{}) {
|
||||
c.ErrorTyped(err, ErrorTypeExternal, meta)
|
||||
}
|
||||
|
||||
func (c *Context) LastError() error {
|
||||
s := len(c.Errors)
|
||||
if s > 0 {
|
||||
return errors.New(c.Errors[s-1].Err)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/************************************/
|
||||
/******** METADATA MANAGEMENT********/
|
||||
/************************************/
|
||||
|
||||
// Sets a new pair key/value just for the specified context.
|
||||
// It also lazy initializes the hashmap.
|
||||
func (c *Context) Set(key string, item interface{}) {
|
||||
if c.Keys == nil {
|
||||
c.Keys = make(map[string]interface{})
|
||||
}
|
||||
c.Keys[key] = item
|
||||
}
|
||||
|
||||
// Get returns the value for the given key or an error if the key does not exist.
|
||||
func (c *Context) Get(key string) (interface{}, error) {
|
||||
if c.Keys != nil {
|
||||
item, ok := c.Keys[key]
|
||||
if ok {
|
||||
return item, nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("Key does not exist.")
|
||||
}
|
||||
|
||||
// MustGet returns the value for the given key or panics if the value doesn't exist.
|
||||
func (c *Context) MustGet(key string) interface{} {
|
||||
value, err := c.Get(key)
|
||||
if err != nil || value == nil {
|
||||
log.Panicf("Key %s doesn't exist", key)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/************************************/
|
||||
/******** ENCOGING MANAGEMENT********/
|
||||
/************************************/
|
||||
|
||||
// This function checks the Content-Type to select a binding engine automatically,
|
||||
// Depending the "Content-Type" header different bindings are used:
|
||||
// "application/json" --> JSON binding
|
||||
// "application/xml" --> XML binding
|
||||
// else --> returns an error
|
||||
// if Parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. It decodes the json payload into the struct specified as a pointer.Like ParseBody() but this method also writes a 400 error if the json is not valid.
|
||||
func (c *Context) Bind(obj interface{}) bool {
|
||||
var b binding.Binding
|
||||
ctype := filterFlags(c.Request.Header.Get("Content-Type"))
|
||||
switch {
|
||||
case c.Request.Method == "GET" || ctype == MIMEPOSTForm:
|
||||
b = binding.Form
|
||||
case ctype == MIMEJSON:
|
||||
b = binding.JSON
|
||||
case ctype == MIMEXML || ctype == MIMEXML2:
|
||||
b = binding.XML
|
||||
default:
|
||||
c.Fail(400, errors.New("unknown content-type: "+ctype))
|
||||
return false
|
||||
}
|
||||
return c.BindWith(obj, b)
|
||||
}
|
||||
|
||||
func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
|
||||
if err := b.Bind(c.Request, obj); err != nil {
|
||||
c.Fail(400, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
|
||||
if err := render.Render(c.Writer, code, obj...); err != nil {
|
||||
c.ErrorTyped(err, ErrorTypeInternal, obj)
|
||||
c.Abort(500)
|
||||
}
|
||||
}
|
||||
|
||||
// Serializes the given struct as JSON into the response body in a fast and efficient way.
|
||||
// It also sets the Content-Type as "application/json".
|
||||
func (c *Context) JSON(code int, obj interface{}) {
|
||||
c.Render(code, render.JSON, obj)
|
||||
}
|
||||
|
||||
// Serializes the given struct as XML into the response body in a fast and efficient way.
|
||||
// It also sets the Content-Type as "application/xml".
|
||||
func (c *Context) XML(code int, obj interface{}) {
|
||||
c.Render(code, render.XML, obj)
|
||||
}
|
||||
|
||||
// Renders the HTTP template specified by its file name.
|
||||
// It also updates the HTTP code and sets the Content-Type as "text/html".
|
||||
// See http://golang.org/doc/articles/wiki/
|
||||
func (c *Context) HTML(code int, name string, obj interface{}) {
|
||||
c.Render(code, c.Engine.HTMLRender, name, obj)
|
||||
}
|
||||
|
||||
// Writes the given string into the response body and sets the Content-Type to "text/plain".
|
||||
func (c *Context) String(code int, format string, values ...interface{}) {
|
||||
c.Render(code, render.Plain, format, values)
|
||||
}
|
||||
|
||||
// Returns a HTTP redirect to the specific location.
|
||||
func (c *Context) Redirect(code int, location string) {
|
||||
if code >= 300 && code <= 308 {
|
||||
c.Render(code, render.Redirect, location)
|
||||
} else {
|
||||
panic(fmt.Sprintf("Cannot send a redirect with status code %d", code))
|
||||
}
|
||||
}
|
||||
|
||||
// Writes some data into the body stream and updates the HTTP code.
|
||||
func (c *Context) Data(code int, contentType string, data []byte) {
|
||||
if len(contentType) > 0 {
|
||||
c.Writer.Header().Set("Content-Type", contentType)
|
||||
}
|
||||
if code >= 0 {
|
||||
c.Writer.WriteHeader(code)
|
||||
}
|
||||
c.Writer.Write(data)
|
||||
}
|
||||
|
||||
// Writes the specified file into the body stream
|
||||
func (c *Context) File(filepath string) {
|
||||
http.ServeFile(c.Writer, c.Request, filepath)
|
||||
}
|
442
Godeps/_workspace/src/github.com/gin-gonic/gin/context_test.go
generated
vendored
Normal file
442
Godeps/_workspace/src/github.com/gin-gonic/gin/context_test.go
generated
vendored
Normal file
@ -0,0 +1,442 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestContextParamsGet tests that a parameter can be parsed from the URL.
|
||||
func TestContextParamsByName(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", "/test/alexandernyquist", nil)
|
||||
w := httptest.NewRecorder()
|
||||
name := ""
|
||||
|
||||
r := New()
|
||||
r.GET("/test/:name", func(c *Context) {
|
||||
name = c.Params.ByName("name")
|
||||
})
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if name != "alexandernyquist" {
|
||||
t.Errorf("Url parameter was not correctly parsed. Should be alexandernyquist, was %s.", name)
|
||||
}
|
||||
}
|
||||
|
||||
// TestContextSetGet tests that a parameter is set correctly on the
|
||||
// current context and can be retrieved using Get.
|
||||
func TestContextSetGet(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r := New()
|
||||
r.GET("/test", func(c *Context) {
|
||||
// Key should be lazily created
|
||||
if c.Keys != nil {
|
||||
t.Error("Keys should be nil")
|
||||
}
|
||||
|
||||
// Set
|
||||
c.Set("foo", "bar")
|
||||
|
||||
v, err := c.Get("foo")
|
||||
if err != nil {
|
||||
t.Errorf("Error on exist key")
|
||||
}
|
||||
if v != "bar" {
|
||||
t.Errorf("Value should be bar, was %s", v)
|
||||
}
|
||||
})
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
}
|
||||
|
||||
// TestContextJSON tests that the response is serialized as JSON
|
||||
// and Content-Type is set to application/json
|
||||
func TestContextJSON(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r := New()
|
||||
r.GET("/test", func(c *Context) {
|
||||
c.JSON(200, H{"foo": "bar"})
|
||||
})
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Body.String() != "{\"foo\":\"bar\"}\n" {
|
||||
t.Errorf("Response should be {\"foo\":\"bar\"}, was: %s", w.Body.String())
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("Content-Type") != "application/json" {
|
||||
t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestContextHTML tests that the response executes the templates
|
||||
// and responds with Content-Type set to text/html
|
||||
func TestContextHTML(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r := New()
|
||||
templ, _ := template.New("t").Parse(`Hello {{.Name}}`)
|
||||
r.SetHTMLTemplate(templ)
|
||||
|
||||
type TestData struct{ Name string }
|
||||
|
||||
r.GET("/test", func(c *Context) {
|
||||
c.HTML(200, "t", TestData{"alexandernyquist"})
|
||||
})
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Body.String() != "Hello alexandernyquist" {
|
||||
t.Errorf("Response should be Hello alexandernyquist, was: %s", w.Body.String())
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("Content-Type") != "text/html" {
|
||||
t.Errorf("Content-Type should be text/html, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestContextString tests that the response is returned
|
||||
// with Content-Type set to text/plain
|
||||
func TestContextString(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r := New()
|
||||
r.GET("/test", func(c *Context) {
|
||||
c.String(200, "test")
|
||||
})
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Body.String() != "test" {
|
||||
t.Errorf("Response should be test, was: %s", w.Body.String())
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("Content-Type") != "text/plain" {
|
||||
t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestContextXML tests that the response is serialized as XML
|
||||
// and Content-Type is set to application/xml
|
||||
func TestContextXML(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r := New()
|
||||
r.GET("/test", func(c *Context) {
|
||||
c.XML(200, H{"foo": "bar"})
|
||||
})
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Body.String() != "<map><foo>bar</foo></map>" {
|
||||
t.Errorf("Response should be <map><foo>bar</foo></map>, was: %s", w.Body.String())
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("Content-Type") != "application/xml" {
|
||||
t.Errorf("Content-Type should be application/xml, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestContextData tests that the response can be written from `bytesting`
|
||||
// with specified MIME type
|
||||
func TestContextData(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", "/test/csv", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r := New()
|
||||
r.GET("/test/csv", func(c *Context) {
|
||||
c.Data(200, "text/csv", []byte(`foo,bar`))
|
||||
})
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Body.String() != "foo,bar" {
|
||||
t.Errorf("Response should be foo&bar, was: %s", w.Body.String())
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("Content-Type") != "text/csv" {
|
||||
t.Errorf("Content-Type should be text/csv, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextFile(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", "/test/file", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r := New()
|
||||
r.GET("/test/file", func(c *Context) {
|
||||
c.File("./gin.go")
|
||||
})
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
bodyAsString := w.Body.String()
|
||||
|
||||
if len(bodyAsString) == 0 {
|
||||
t.Errorf("Got empty body instead of file data")
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {
|
||||
t.Errorf("Content-Type should be text/plain; charset=utf-8, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandlerFunc - ensure that custom middleware works properly
|
||||
func TestHandlerFunc(t *testing.T) {
|
||||
|
||||
req, _ := http.NewRequest("GET", "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r := New()
|
||||
var stepsPassed int = 0
|
||||
|
||||
r.Use(func(context *Context) {
|
||||
stepsPassed += 1
|
||||
context.Next()
|
||||
stepsPassed += 1
|
||||
})
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 404 {
|
||||
t.Errorf("Response code should be Not found, was: %s", w.Code)
|
||||
}
|
||||
|
||||
if stepsPassed != 2 {
|
||||
t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers
|
||||
func TestBadAbortHandlersChain(t *testing.T) {
|
||||
// SETUP
|
||||
var stepsPassed int = 0
|
||||
r := New()
|
||||
r.Use(func(c *Context) {
|
||||
stepsPassed += 1
|
||||
c.Next()
|
||||
stepsPassed += 1
|
||||
// after check and abort
|
||||
c.Abort(409)
|
||||
})
|
||||
r.Use(func(c *Context) {
|
||||
stepsPassed += 1
|
||||
c.Next()
|
||||
stepsPassed += 1
|
||||
c.Abort(403)
|
||||
})
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, "GET", "/")
|
||||
|
||||
// TEST
|
||||
if w.Code != 409 {
|
||||
t.Errorf("Response code should be Forbiden, was: %d", w.Code)
|
||||
}
|
||||
if stepsPassed != 4 {
|
||||
t.Errorf("Falied to switch context in handler function: %d", stepsPassed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order
|
||||
func TestAbortHandlersChain(t *testing.T) {
|
||||
// SETUP
|
||||
var stepsPassed int = 0
|
||||
r := New()
|
||||
r.Use(func(context *Context) {
|
||||
stepsPassed += 1
|
||||
context.Abort(409)
|
||||
})
|
||||
r.Use(func(context *Context) {
|
||||
stepsPassed += 1
|
||||
context.Next()
|
||||
stepsPassed += 1
|
||||
})
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, "GET", "/")
|
||||
|
||||
// TEST
|
||||
if w.Code != 409 {
|
||||
t.Errorf("Response code should be Conflict, was: %d", w.Code)
|
||||
}
|
||||
if stepsPassed != 1 {
|
||||
t.Errorf("Falied to switch context in handler function: %d", stepsPassed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as
|
||||
// as well as Abort
|
||||
func TestFailHandlersChain(t *testing.T) {
|
||||
// SETUP
|
||||
var stepsPassed int = 0
|
||||
r := New()
|
||||
r.Use(func(context *Context) {
|
||||
stepsPassed += 1
|
||||
context.Fail(500, errors.New("foo"))
|
||||
})
|
||||
r.Use(func(context *Context) {
|
||||
stepsPassed += 1
|
||||
context.Next()
|
||||
stepsPassed += 1
|
||||
})
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, "GET", "/")
|
||||
|
||||
// TEST
|
||||
if w.Code != 500 {
|
||||
t.Errorf("Response code should be Server error, was: %d", w.Code)
|
||||
}
|
||||
if stepsPassed != 1 {
|
||||
t.Errorf("Falied to switch context in handler function: %d", stepsPassed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingJSON(t *testing.T) {
|
||||
|
||||
body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))
|
||||
|
||||
r := New()
|
||||
r.POST("/binding/json", func(c *Context) {
|
||||
var body struct {
|
||||
Foo string `json:"foo"`
|
||||
}
|
||||
if c.Bind(&body) {
|
||||
c.JSON(200, H{"parsed": body.Foo})
|
||||
}
|
||||
})
|
||||
|
||||
req, _ := http.NewRequest("POST", "/binding/json", body)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("Response code should be Ok, was: %s", w.Code)
|
||||
}
|
||||
|
||||
if w.Body.String() != "{\"parsed\":\"bar\"}\n" {
|
||||
t.Errorf("Response should be {\"parsed\":\"bar\"}, was: %s", w.Body.String())
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("Content-Type") != "application/json" {
|
||||
t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingJSONEncoding(t *testing.T) {
|
||||
|
||||
body := bytes.NewBuffer([]byte("{\"foo\":\"嘉\"}"))
|
||||
|
||||
r := New()
|
||||
r.POST("/binding/json", func(c *Context) {
|
||||
var body struct {
|
||||
Foo string `json:"foo"`
|
||||
}
|
||||
if c.Bind(&body) {
|
||||
c.JSON(200, H{"parsed": body.Foo})
|
||||
}
|
||||
})
|
||||
|
||||
req, _ := http.NewRequest("POST", "/binding/json", body)
|
||||
req.Header.Set("Content-Type", "application/json; charset=utf-8")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("Response code should be Ok, was: %s", w.Code)
|
||||
}
|
||||
|
||||
if w.Body.String() != "{\"parsed\":\"嘉\"}\n" {
|
||||
t.Errorf("Response should be {\"parsed\":\"嘉\"}, was: %s", w.Body.String())
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("Content-Type") != "application/json" {
|
||||
t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingJSONNoContentType(t *testing.T) {
|
||||
|
||||
body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))
|
||||
|
||||
r := New()
|
||||
r.POST("/binding/json", func(c *Context) {
|
||||
var body struct {
|
||||
Foo string `json:"foo"`
|
||||
}
|
||||
if c.Bind(&body) {
|
||||
c.JSON(200, H{"parsed": body.Foo})
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
req, _ := http.NewRequest("POST", "/binding/json", body)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 400 {
|
||||
t.Errorf("Response code should be Bad request, was: %s", w.Code)
|
||||
}
|
||||
|
||||
if w.Body.String() == "{\"parsed\":\"bar\"}\n" {
|
||||
t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String())
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("Content-Type") == "application/json" {
|
||||
t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingJSONMalformed(t *testing.T) {
|
||||
|
||||
body := bytes.NewBuffer([]byte("\"foo\":\"bar\"\n"))
|
||||
|
||||
r := New()
|
||||
r.POST("/binding/json", func(c *Context) {
|
||||
var body struct {
|
||||
Foo string `json:"foo"`
|
||||
}
|
||||
if c.Bind(&body) {
|
||||
c.JSON(200, H{"parsed": body.Foo})
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
req, _ := http.NewRequest("POST", "/binding/json", body)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 400 {
|
||||
t.Errorf("Response code should be Bad request, was: %s", w.Code)
|
||||
}
|
||||
if w.Body.String() == "{\"parsed\":\"bar\"}\n" {
|
||||
t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String())
|
||||
}
|
||||
|
||||
if w.HeaderMap.Get("Content-Type") == "application/json" {
|
||||
t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
47
Godeps/_workspace/src/github.com/gin-gonic/gin/deprecated.go
generated
vendored
Normal file
47
Godeps/_workspace/src/github.com/gin-gonic/gin/deprecated.go
generated
vendored
Normal file
@ -0,0 +1,47 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// DEPRECATED, use Bind() instead.
|
||||
// Like ParseBody() but this method also writes a 400 error if the json is not valid.
|
||||
func (c *Context) EnsureBody(item interface{}) bool {
|
||||
return c.Bind(item)
|
||||
}
|
||||
|
||||
// DEPRECATED use bindings directly
|
||||
// Parses the body content as a JSON input. It decodes the json payload into the struct specified as a pointer.
|
||||
func (c *Context) ParseBody(item interface{}) error {
|
||||
return binding.JSON.Bind(c.Request, item)
|
||||
}
|
||||
|
||||
// DEPRECATED use gin.Static() instead
|
||||
// ServeFiles serves files from the given file system root.
|
||||
// The path must end with "/*filepath", files are then served from the local
|
||||
// path /defined/root/dir/*filepath.
|
||||
// For example if root is "/etc" and *filepath is "passwd", the local file
|
||||
// "/etc/passwd" would be served.
|
||||
// Internally a http.FileServer is used, therefore http.NotFound is used instead
|
||||
// of the Router's NotFound handler.
|
||||
// To use the operating system's file system implementation,
|
||||
// use http.Dir:
|
||||
// router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
|
||||
func (engine *Engine) ServeFiles(path string, root http.FileSystem) {
|
||||
engine.router.ServeFiles(path, root)
|
||||
}
|
||||
|
||||
// DEPRECATED use gin.LoadHTMLGlob() or gin.LoadHTMLFiles() instead
|
||||
func (engine *Engine) LoadHTMLTemplates(pattern string) {
|
||||
engine.LoadHTMLGlob(pattern)
|
||||
}
|
||||
|
||||
// DEPRECATED. Use NotFound() instead
|
||||
func (engine *Engine) NotFound404(handlers ...HandlerFunc) {
|
||||
engine.NoRoute(handlers...)
|
||||
}
|
7
Godeps/_workspace/src/github.com/gin-gonic/gin/examples/app-engine/README.md
generated
vendored
Normal file
7
Godeps/_workspace/src/github.com/gin-gonic/gin/examples/app-engine/README.md
generated
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
# Guide to run Gin under App Engine LOCAL Development Server
|
||||
|
||||
1. Download, install and setup Go in your computer. (That includes setting your `$GOPATH`.)
|
||||
2. Download SDK for your platform from here: `https://developers.google.com/appengine/downloads?hl=es#Google_App_Engine_SDK_for_Go`
|
||||
3. Download Gin source code using: `$ go get github.com/gin-gonic/gin`
|
||||
4. Navigate to examples folder: `$ cd $GOPATH/src/github.com/gin-gonic/gin/examples/`
|
||||
5. Run it: `$ goapp serve app-engine/`
|
8
Godeps/_workspace/src/github.com/gin-gonic/gin/examples/app-engine/app.yaml
generated
vendored
Normal file
8
Godeps/_workspace/src/github.com/gin-gonic/gin/examples/app-engine/app.yaml
generated
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
application: hello
|
||||
version: 1
|
||||
runtime: go
|
||||
api_version: go1
|
||||
|
||||
handlers:
|
||||
- url: /.*
|
||||
script: _go_app
|
23
Godeps/_workspace/src/github.com/gin-gonic/gin/examples/app-engine/hello.go
generated
vendored
Normal file
23
Godeps/_workspace/src/github.com/gin-gonic/gin/examples/app-engine/hello.go
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
package hello
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// This function's name is a must. App Engine uses it to drive the requests properly.
|
||||
func init() {
|
||||
// Starts a new Gin instance with no middle-ware
|
||||
r := gin.New()
|
||||
|
||||
// Define your handlers
|
||||
r.GET("/", func(c *gin.Context){
|
||||
c.String(200, "Hello World!")
|
||||
})
|
||||
r.GET("/ping", func(c *gin.Context){
|
||||
c.String(200, "pong")
|
||||
})
|
||||
|
||||
// Handle all requests using net/http
|
||||
http.Handle("/", r)
|
||||
}
|
56
Godeps/_workspace/src/github.com/gin-gonic/gin/examples/example_basic.go
generated
vendored
Normal file
56
Godeps/_workspace/src/github.com/gin-gonic/gin/examples/example_basic.go
generated
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var DB = make(map[string]string)
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// Ping test
|
||||
r.GET("/ping", func(c *gin.Context) {
|
||||
c.String(200, "pong")
|
||||
})
|
||||
|
||||
// Get user value
|
||||
r.GET("/user/:name", func(c *gin.Context) {
|
||||
user := c.Params.ByName("name")
|
||||
value, ok := DB[user]
|
||||
if ok {
|
||||
c.JSON(200, gin.H{"user": user, "value": value})
|
||||
} else {
|
||||
c.JSON(200, gin.H{"user": user, "status": "no value"})
|
||||
}
|
||||
})
|
||||
|
||||
// Authorized group (uses gin.BasicAuth() middleware)
|
||||
// Same than:
|
||||
// authorized := r.Group("/")
|
||||
// authorized.Use(gin.BasicAuth(gin.Credentials{
|
||||
// "foo": "bar",
|
||||
// "manu": "123",
|
||||
//}))
|
||||
authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
|
||||
"foo": "bar", // user:foo password:bar
|
||||
"manu": "123", // user:manu password:123
|
||||
}))
|
||||
|
||||
authorized.POST("admin", func(c *gin.Context) {
|
||||
user := c.MustGet(gin.AuthUserKey).(string)
|
||||
|
||||
// Parse JSON
|
||||
var json struct {
|
||||
Value string `json:"value" binding:"required"`
|
||||
}
|
||||
|
||||
if c.Bind(&json) {
|
||||
DB[user] = json.Value
|
||||
c.JSON(200, gin.H{"status": "ok"})
|
||||
}
|
||||
})
|
||||
|
||||
// Listen and Server in 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
262
Godeps/_workspace/src/github.com/gin-gonic/gin/gin.go
generated
vendored
Normal file
262
Godeps/_workspace/src/github.com/gin-gonic/gin/gin.go
generated
vendored
Normal file
@ -0,0 +1,262 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin/render"
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"html/template"
|
||||
"math"
|
||||
"net/http"
|
||||
"path"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
AbortIndex = math.MaxInt8 / 2
|
||||
MIMEJSON = "application/json"
|
||||
MIMEHTML = "text/html"
|
||||
MIMEXML = "application/xml"
|
||||
MIMEXML2 = "text/xml"
|
||||
MIMEPlain = "text/plain"
|
||||
MIMEPOSTForm = "application/x-www-form-urlencoded"
|
||||
)
|
||||
|
||||
type (
|
||||
HandlerFunc func(*Context)
|
||||
|
||||
// Used internally to configure router, a RouterGroup is associated with a prefix
|
||||
// and an array of handlers (middlewares)
|
||||
RouterGroup struct {
|
||||
Handlers []HandlerFunc
|
||||
prefix string
|
||||
parent *RouterGroup
|
||||
engine *Engine
|
||||
}
|
||||
|
||||
// Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.
|
||||
Engine struct {
|
||||
*RouterGroup
|
||||
HTMLRender render.Render
|
||||
cache sync.Pool
|
||||
finalNoRoute []HandlerFunc
|
||||
noRoute []HandlerFunc
|
||||
router *httprouter.Router
|
||||
}
|
||||
)
|
||||
|
||||
func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {
|
||||
c := engine.createContext(w, req, nil, engine.finalNoRoute)
|
||||
// set 404 by default, useful for logging
|
||||
c.Writer.WriteHeader(404)
|
||||
c.Next()
|
||||
if !c.Writer.Written() {
|
||||
if c.Writer.Status() == 404 {
|
||||
c.Data(-1, MIMEPlain, []byte("404 page not found"))
|
||||
} else {
|
||||
c.Writer.WriteHeaderNow()
|
||||
}
|
||||
}
|
||||
engine.cache.Put(c)
|
||||
}
|
||||
|
||||
// Returns a new blank Engine instance without any middleware attached.
|
||||
// The most basic configuration
|
||||
func New() *Engine {
|
||||
engine := &Engine{}
|
||||
engine.RouterGroup = &RouterGroup{nil, "/", nil, engine}
|
||||
engine.router = httprouter.New()
|
||||
engine.router.NotFound = engine.handle404
|
||||
engine.cache.New = func() interface{} {
|
||||
c := &Context{Engine: engine}
|
||||
c.Writer = &c.writermem
|
||||
return c
|
||||
}
|
||||
return engine
|
||||
}
|
||||
|
||||
// Returns a Engine instance with the Logger and Recovery already attached.
|
||||
func Default() *Engine {
|
||||
engine := New()
|
||||
engine.Use(Recovery(), Logger())
|
||||
return engine
|
||||
}
|
||||
|
||||
func (engine *Engine) LoadHTMLGlob(pattern string) {
|
||||
if gin_mode == debugCode {
|
||||
engine.HTMLRender = render.HTMLDebug
|
||||
} else {
|
||||
templ := template.Must(template.ParseGlob(pattern))
|
||||
engine.SetHTMLTemplate(templ)
|
||||
}
|
||||
}
|
||||
|
||||
func (engine *Engine) LoadHTMLFiles(files ...string) {
|
||||
if gin_mode == debugCode {
|
||||
engine.HTMLRender = render.HTMLDebug
|
||||
} else {
|
||||
templ := template.Must(template.ParseFiles(files...))
|
||||
engine.SetHTMLTemplate(templ)
|
||||
}
|
||||
}
|
||||
|
||||
func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
|
||||
engine.HTMLRender = render.HTMLRender{
|
||||
Template: templ,
|
||||
}
|
||||
}
|
||||
|
||||
// Adds handlers for NoRoute. It return a 404 code by default.
|
||||
func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
|
||||
engine.noRoute = handlers
|
||||
engine.finalNoRoute = engine.combineHandlers(engine.noRoute)
|
||||
}
|
||||
|
||||
func (engine *Engine) Use(middlewares ...HandlerFunc) {
|
||||
engine.RouterGroup.Use(middlewares...)
|
||||
engine.finalNoRoute = engine.combineHandlers(engine.noRoute)
|
||||
}
|
||||
|
||||
// ServeHTTP makes the router implement the http.Handler interface.
|
||||
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
engine.router.ServeHTTP(w, req)
|
||||
}
|
||||
|
||||
func (engine *Engine) Run(addr string) {
|
||||
if gin_mode == debugCode {
|
||||
fmt.Println("[GIN-debug] Listening and serving HTTP on " + addr)
|
||||
}
|
||||
if err := http.ListenAndServe(addr, engine); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (engine *Engine) RunTLS(addr string, cert string, key string) {
|
||||
if gin_mode == debugCode {
|
||||
fmt.Println("[GIN-debug] Listening and serving HTTPS on " + addr)
|
||||
}
|
||||
if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
/************************************/
|
||||
/********** ROUTES GROUPING *********/
|
||||
/************************************/
|
||||
|
||||
// Adds middlewares to the group, see example code in github.
|
||||
func (group *RouterGroup) Use(middlewares ...HandlerFunc) {
|
||||
group.Handlers = append(group.Handlers, middlewares...)
|
||||
}
|
||||
|
||||
// Creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
|
||||
// For example, all the routes that use a common middlware for authorization could be grouped.
|
||||
func (group *RouterGroup) Group(component string, handlers ...HandlerFunc) *RouterGroup {
|
||||
prefix := group.pathFor(component)
|
||||
|
||||
return &RouterGroup{
|
||||
Handlers: group.combineHandlers(handlers),
|
||||
parent: group,
|
||||
prefix: prefix,
|
||||
engine: group.engine,
|
||||
}
|
||||
}
|
||||
|
||||
func (group *RouterGroup) pathFor(p string) string {
|
||||
joined := path.Join(group.prefix, p)
|
||||
// Append a '/' if the last component had one, but only if it's not there already
|
||||
if len(p) > 0 && p[len(p)-1] == '/' && joined[len(joined)-1] != '/' {
|
||||
return joined + "/"
|
||||
}
|
||||
return joined
|
||||
}
|
||||
|
||||
// Handle registers a new request handle and middlewares with the given path and method.
|
||||
// The last handler should be the real handler, the other ones should be middlewares that can and should be shared among different routes.
|
||||
// See the example code in github.
|
||||
//
|
||||
// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
|
||||
// functions can be used.
|
||||
//
|
||||
// This function is intended for bulk loading and to allow the usage of less
|
||||
// frequently used, non-standardized or custom methods (e.g. for internal
|
||||
// communication with a proxy).
|
||||
func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {
|
||||
p = group.pathFor(p)
|
||||
handlers = group.combineHandlers(handlers)
|
||||
if gin_mode == debugCode {
|
||||
nuHandlers := len(handlers)
|
||||
name := funcName(handlers[nuHandlers-1])
|
||||
fmt.Printf("[GIN-debug] %-5s %-25s --> %s (%d handlers)\n", method, p, name, nuHandlers)
|
||||
}
|
||||
group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
|
||||
c := group.engine.createContext(w, req, params, handlers)
|
||||
c.Next()
|
||||
c.Writer.WriteHeaderNow()
|
||||
group.engine.cache.Put(c)
|
||||
})
|
||||
}
|
||||
|
||||
// POST is a shortcut for router.Handle("POST", path, handle)
|
||||
func (group *RouterGroup) POST(path string, handlers ...HandlerFunc) {
|
||||
group.Handle("POST", path, handlers)
|
||||
}
|
||||
|
||||
// GET is a shortcut for router.Handle("GET", path, handle)
|
||||
func (group *RouterGroup) GET(path string, handlers ...HandlerFunc) {
|
||||
group.Handle("GET", path, handlers)
|
||||
}
|
||||
|
||||
// DELETE is a shortcut for router.Handle("DELETE", path, handle)
|
||||
func (group *RouterGroup) DELETE(path string, handlers ...HandlerFunc) {
|
||||
group.Handle("DELETE", path, handlers)
|
||||
}
|
||||
|
||||
// PATCH is a shortcut for router.Handle("PATCH", path, handle)
|
||||
func (group *RouterGroup) PATCH(path string, handlers ...HandlerFunc) {
|
||||
group.Handle("PATCH", path, handlers)
|
||||
}
|
||||
|
||||
// PUT is a shortcut for router.Handle("PUT", path, handle)
|
||||
func (group *RouterGroup) PUT(path string, handlers ...HandlerFunc) {
|
||||
group.Handle("PUT", path, handlers)
|
||||
}
|
||||
|
||||
// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
|
||||
func (group *RouterGroup) OPTIONS(path string, handlers ...HandlerFunc) {
|
||||
group.Handle("OPTIONS", path, handlers)
|
||||
}
|
||||
|
||||
// HEAD is a shortcut for router.Handle("HEAD", path, handle)
|
||||
func (group *RouterGroup) HEAD(path string, handlers ...HandlerFunc) {
|
||||
group.Handle("HEAD", path, handlers)
|
||||
}
|
||||
|
||||
// Static serves files from the given file system root.
|
||||
// Internally a http.FileServer is used, therefore http.NotFound is used instead
|
||||
// of the Router's NotFound handler.
|
||||
// To use the operating system's file system implementation,
|
||||
// use :
|
||||
// router.Static("/static", "/var/www")
|
||||
func (group *RouterGroup) Static(p, root string) {
|
||||
prefix := group.pathFor(p)
|
||||
p = path.Join(p, "/*filepath")
|
||||
fileServer := http.StripPrefix(prefix, http.FileServer(http.Dir(root)))
|
||||
group.GET(p, func(c *Context) {
|
||||
fileServer.ServeHTTP(c.Writer, c.Request)
|
||||
})
|
||||
group.HEAD(p, func(c *Context) {
|
||||
fileServer.ServeHTTP(c.Writer, c.Request)
|
||||
})
|
||||
}
|
||||
|
||||
func (group *RouterGroup) combineHandlers(handlers []HandlerFunc) []HandlerFunc {
|
||||
s := len(group.Handlers) + len(handlers)
|
||||
h := make([]HandlerFunc, 0, s)
|
||||
h = append(h, group.Handlers...)
|
||||
h = append(h, handlers...)
|
||||
return h
|
||||
}
|
207
Godeps/_workspace/src/github.com/gin-gonic/gin/gin_test.go
generated
vendored
Normal file
207
Godeps/_workspace/src/github.com/gin-gonic/gin/gin_test.go
generated
vendored
Normal file
@ -0,0 +1,207 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func init() {
|
||||
SetMode(TestMode)
|
||||
}
|
||||
|
||||
func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
|
||||
req, _ := http.NewRequest(method, path, nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// TestSingleRouteOK tests that POST route is correctly invoked.
|
||||
func testRouteOK(method string, t *testing.T) {
|
||||
// SETUP
|
||||
passed := false
|
||||
r := New()
|
||||
r.Handle(method, "/test", []HandlerFunc{func(c *Context) {
|
||||
passed = true
|
||||
}})
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, method, "/test")
|
||||
|
||||
// TEST
|
||||
if passed == false {
|
||||
t.Errorf(method + " route handler was not invoked.")
|
||||
}
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
|
||||
}
|
||||
}
|
||||
func TestRouterGroupRouteOK(t *testing.T) {
|
||||
testRouteOK("POST", t)
|
||||
testRouteOK("DELETE", t)
|
||||
testRouteOK("PATCH", t)
|
||||
testRouteOK("PUT", t)
|
||||
testRouteOK("OPTIONS", t)
|
||||
testRouteOK("HEAD", t)
|
||||
}
|
||||
|
||||
// TestSingleRouteOK tests that POST route is correctly invoked.
|
||||
func testRouteNotOK(method string, t *testing.T) {
|
||||
// SETUP
|
||||
passed := false
|
||||
r := New()
|
||||
r.Handle(method, "/test_2", []HandlerFunc{func(c *Context) {
|
||||
passed = true
|
||||
}})
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, method, "/test")
|
||||
|
||||
// TEST
|
||||
if passed == true {
|
||||
t.Errorf(method + " route handler was invoked, when it should not")
|
||||
}
|
||||
if w.Code != http.StatusNotFound {
|
||||
// If this fails, it's because httprouter needs to be updated to at least f78f58a0db
|
||||
t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestSingleRouteOK tests that POST route is correctly invoked.
|
||||
func TestRouteNotOK(t *testing.T) {
|
||||
testRouteNotOK("POST", t)
|
||||
testRouteNotOK("DELETE", t)
|
||||
testRouteNotOK("PATCH", t)
|
||||
testRouteNotOK("PUT", t)
|
||||
testRouteNotOK("OPTIONS", t)
|
||||
testRouteNotOK("HEAD", t)
|
||||
}
|
||||
|
||||
// TestSingleRouteOK tests that POST route is correctly invoked.
|
||||
func testRouteNotOK2(method string, t *testing.T) {
|
||||
// SETUP
|
||||
passed := false
|
||||
r := New()
|
||||
var methodRoute string
|
||||
if method == "POST" {
|
||||
methodRoute = "GET"
|
||||
} else {
|
||||
methodRoute = "POST"
|
||||
}
|
||||
r.Handle(methodRoute, "/test", []HandlerFunc{func(c *Context) {
|
||||
passed = true
|
||||
}})
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, method, "/test")
|
||||
|
||||
// TEST
|
||||
if passed == true {
|
||||
t.Errorf(method + " route handler was invoked, when it should not")
|
||||
}
|
||||
if w.Code != http.StatusNotFound {
|
||||
// If this fails, it's because httprouter needs to be updated to at least f78f58a0db
|
||||
t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestSingleRouteOK tests that POST route is correctly invoked.
|
||||
func TestRouteNotOK2(t *testing.T) {
|
||||
testRouteNotOK2("POST", t)
|
||||
testRouteNotOK2("DELETE", t)
|
||||
testRouteNotOK2("PATCH", t)
|
||||
testRouteNotOK2("PUT", t)
|
||||
testRouteNotOK2("OPTIONS", t)
|
||||
testRouteNotOK2("HEAD", t)
|
||||
}
|
||||
|
||||
// TestHandleStaticFile - ensure the static file handles properly
|
||||
func TestHandleStaticFile(t *testing.T) {
|
||||
// SETUP file
|
||||
testRoot, _ := os.Getwd()
|
||||
f, err := ioutil.TempFile(testRoot, "")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
filePath := path.Join("/", path.Base(f.Name()))
|
||||
f.WriteString("Gin Web Framework")
|
||||
f.Close()
|
||||
|
||||
// SETUP gin
|
||||
r := New()
|
||||
r.Static("./", testRoot)
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, "GET", filePath)
|
||||
|
||||
// TEST
|
||||
if w.Code != 200 {
|
||||
t.Errorf("Response code should be Ok, was: %s", w.Code)
|
||||
}
|
||||
if w.Body.String() != "Gin Web Framework" {
|
||||
t.Errorf("Response should be test, was: %s", w.Body.String())
|
||||
}
|
||||
if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {
|
||||
t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleStaticDir - ensure the root/sub dir handles properly
|
||||
func TestHandleStaticDir(t *testing.T) {
|
||||
// SETUP
|
||||
r := New()
|
||||
r.Static("/", "./")
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, "GET", "/")
|
||||
|
||||
// TEST
|
||||
bodyAsString := w.Body.String()
|
||||
if w.Code != 200 {
|
||||
t.Errorf("Response code should be Ok, was: %s", w.Code)
|
||||
}
|
||||
if len(bodyAsString) == 0 {
|
||||
t.Errorf("Got empty body instead of file tree")
|
||||
}
|
||||
if !strings.Contains(bodyAsString, "gin.go") {
|
||||
t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)
|
||||
}
|
||||
if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {
|
||||
t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleHeadToDir - ensure the root/sub dir handles properly
|
||||
func TestHandleHeadToDir(t *testing.T) {
|
||||
// SETUP
|
||||
r := New()
|
||||
r.Static("/", "./")
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, "HEAD", "/")
|
||||
|
||||
// TEST
|
||||
bodyAsString := w.Body.String()
|
||||
if w.Code != 200 {
|
||||
t.Errorf("Response code should be Ok, was: %s", w.Code)
|
||||
}
|
||||
if len(bodyAsString) == 0 {
|
||||
t.Errorf("Got empty body instead of file tree")
|
||||
}
|
||||
if !strings.Contains(bodyAsString, "gin.go") {
|
||||
t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)
|
||||
}
|
||||
if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {
|
||||
t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
}
|
82
Godeps/_workspace/src/github.com/gin-gonic/gin/logger.go
generated
vendored
Normal file
82
Godeps/_workspace/src/github.com/gin-gonic/gin/logger.go
generated
vendored
Normal file
@ -0,0 +1,82 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ErrorLogger() HandlerFunc {
|
||||
return ErrorLoggerT(ErrorTypeAll)
|
||||
}
|
||||
|
||||
func ErrorLoggerT(typ uint32) HandlerFunc {
|
||||
return func(c *Context) {
|
||||
c.Next()
|
||||
|
||||
errs := c.Errors.ByType(typ)
|
||||
if len(errs) > 0 {
|
||||
// -1 status code = do not change current one
|
||||
c.JSON(-1, c.Errors)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
|
||||
white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
|
||||
yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
|
||||
red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
|
||||
reset = string([]byte{27, 91, 48, 109})
|
||||
)
|
||||
|
||||
func Logger() HandlerFunc {
|
||||
stdlogger := log.New(os.Stdout, "", 0)
|
||||
//errlogger := log.New(os.Stderr, "", 0)
|
||||
|
||||
return func(c *Context) {
|
||||
// Start timer
|
||||
start := time.Now()
|
||||
|
||||
// Process request
|
||||
c.Next()
|
||||
|
||||
// save the IP of the requester
|
||||
requester := c.Request.Header.Get("X-Real-IP")
|
||||
// if the requester-header is empty, check the forwarded-header
|
||||
if len(requester) == 0 {
|
||||
requester = c.Request.Header.Get("X-Forwarded-For")
|
||||
}
|
||||
// if the requester is still empty, use the hard-coded address from the socket
|
||||
if len(requester) == 0 {
|
||||
requester = c.Request.RemoteAddr
|
||||
}
|
||||
|
||||
var color string
|
||||
code := c.Writer.Status()
|
||||
switch {
|
||||
case code >= 200 && code <= 299:
|
||||
color = green
|
||||
case code >= 300 && code <= 399:
|
||||
color = white
|
||||
case code >= 400 && code <= 499:
|
||||
color = yellow
|
||||
default:
|
||||
color = red
|
||||
}
|
||||
end := time.Now()
|
||||
latency := end.Sub(start)
|
||||
stdlogger.Printf("[GIN] %v |%s %3d %s| %12v | %s %4s %s\n%s",
|
||||
end.Format("2006/01/02 - 15:04:05"),
|
||||
color, code, reset,
|
||||
latency,
|
||||
requester,
|
||||
c.Request.Method, c.Request.URL.Path,
|
||||
c.Errors.String(),
|
||||
)
|
||||
}
|
||||
}
|
46
Godeps/_workspace/src/github.com/gin-gonic/gin/mode.go
generated
vendored
Normal file
46
Godeps/_workspace/src/github.com/gin-gonic/gin/mode.go
generated
vendored
Normal file
@ -0,0 +1,46 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"os"
|
||||
)
|
||||
|
||||
const GIN_MODE = "GIN_MODE"
|
||||
|
||||
const (
|
||||
DebugMode string = "debug"
|
||||
ReleaseMode string = "release"
|
||||
TestMode string = "test"
|
||||
)
|
||||
const (
|
||||
debugCode = iota
|
||||
releaseCode = iota
|
||||
testCode = iota
|
||||
)
|
||||
|
||||
var gin_mode int = debugCode
|
||||
|
||||
func SetMode(value string) {
|
||||
switch value {
|
||||
case DebugMode:
|
||||
gin_mode = debugCode
|
||||
case ReleaseMode:
|
||||
gin_mode = releaseCode
|
||||
case TestMode:
|
||||
gin_mode = testCode
|
||||
default:
|
||||
panic("gin mode unknown, the allowed modes are: " + DebugMode + " and " + ReleaseMode)
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
value := os.Getenv(GIN_MODE)
|
||||
if len(value) == 0 {
|
||||
SetMode(DebugMode)
|
||||
} else {
|
||||
SetMode(value)
|
||||
}
|
||||
}
|
98
Godeps/_workspace/src/github.com/gin-gonic/gin/recovery.go
generated
vendored
Normal file
98
Godeps/_workspace/src/github.com/gin-gonic/gin/recovery.go
generated
vendored
Normal file
@ -0,0 +1,98 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
var (
|
||||
dunno = []byte("???")
|
||||
centerDot = []byte("·")
|
||||
dot = []byte(".")
|
||||
slash = []byte("/")
|
||||
)
|
||||
|
||||
// stack returns a nicely formated stack frame, skipping skip frames
|
||||
func stack(skip int) []byte {
|
||||
buf := new(bytes.Buffer) // the returned data
|
||||
// As we loop, we open files and read them. These variables record the currently
|
||||
// loaded file.
|
||||
var lines [][]byte
|
||||
var lastFile string
|
||||
for i := skip; ; i++ { // Skip the expected number of frames
|
||||
pc, file, line, ok := runtime.Caller(i)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
// Print this much at least. If we can't find the source, it won't show.
|
||||
fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
|
||||
if file != lastFile {
|
||||
data, err := ioutil.ReadFile(file)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
lines = bytes.Split(data, []byte{'\n'})
|
||||
lastFile = file
|
||||
}
|
||||
fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// source returns a space-trimmed slice of the n'th line.
|
||||
func source(lines [][]byte, n int) []byte {
|
||||
n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
|
||||
if n < 0 || n >= len(lines) {
|
||||
return dunno
|
||||
}
|
||||
return bytes.TrimSpace(lines[n])
|
||||
}
|
||||
|
||||
// function returns, if possible, the name of the function containing the PC.
|
||||
func function(pc uintptr) []byte {
|
||||
fn := runtime.FuncForPC(pc)
|
||||
if fn == nil {
|
||||
return dunno
|
||||
}
|
||||
name := []byte(fn.Name())
|
||||
// The name includes the path name to the package, which is unnecessary
|
||||
// since the file name is already included. Plus, it has center dots.
|
||||
// That is, we see
|
||||
// runtime/debug.*T·ptrmethod
|
||||
// and want
|
||||
// *T.ptrmethod
|
||||
// Also the package path might contains dot (e.g. code.google.com/...),
|
||||
// so first eliminate the path prefix
|
||||
if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {
|
||||
name = name[lastslash+1:]
|
||||
}
|
||||
if period := bytes.Index(name, dot); period >= 0 {
|
||||
name = name[period+1:]
|
||||
}
|
||||
name = bytes.Replace(name, centerDot, dot, -1)
|
||||
return name
|
||||
}
|
||||
|
||||
// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
|
||||
// While Martini is in development mode, Recovery will also output the panic as HTML.
|
||||
func Recovery() HandlerFunc {
|
||||
return func(c *Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
stack := stack(3)
|
||||
log.Printf("PANIC: %s\n%s", err, stack)
|
||||
c.Writer.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
}()
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
56
Godeps/_workspace/src/github.com/gin-gonic/gin/recovery_test.go
generated
vendored
Normal file
56
Godeps/_workspace/src/github.com/gin-gonic/gin/recovery_test.go
generated
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestPanicInHandler assert that panic has been recovered.
|
||||
func TestPanicInHandler(t *testing.T) {
|
||||
// SETUP
|
||||
log.SetOutput(bytes.NewBuffer(nil)) // Disable panic logs for testing
|
||||
r := New()
|
||||
r.Use(Recovery())
|
||||
r.GET("/recovery", func(_ *Context) {
|
||||
panic("Oupps, Houston, we have a problem")
|
||||
})
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, "GET", "/recovery")
|
||||
|
||||
// restore logging
|
||||
log.SetOutput(os.Stderr)
|
||||
|
||||
if w.Code != 500 {
|
||||
t.Errorf("Response code should be Internal Server Error, was: %s", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.
|
||||
func TestPanicWithAbort(t *testing.T) {
|
||||
// SETUP
|
||||
log.SetOutput(bytes.NewBuffer(nil))
|
||||
r := New()
|
||||
r.Use(Recovery())
|
||||
r.GET("/recovery", func(c *Context) {
|
||||
c.Abort(400)
|
||||
panic("Oupps, Houston, we have a problem")
|
||||
})
|
||||
|
||||
// RUN
|
||||
w := PerformRequest(r, "GET", "/recovery")
|
||||
|
||||
// restore logging
|
||||
log.SetOutput(os.Stderr)
|
||||
|
||||
// TEST
|
||||
if w.Code != 500 {
|
||||
t.Errorf("Response code should be Bad request, was: %s", w.Code)
|
||||
}
|
||||
}
|
101
Godeps/_workspace/src/github.com/gin-gonic/gin/render/render.go
generated
vendored
Normal file
101
Godeps/_workspace/src/github.com/gin-gonic/gin/render/render.go
generated
vendored
Normal file
@ -0,0 +1,101 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package render
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type (
|
||||
Render interface {
|
||||
Render(http.ResponseWriter, int, ...interface{}) error
|
||||
}
|
||||
|
||||
// JSON binding
|
||||
jsonRender struct{}
|
||||
|
||||
// XML binding
|
||||
xmlRender struct{}
|
||||
|
||||
// Plain text
|
||||
plainRender struct{}
|
||||
|
||||
// Redirects
|
||||
redirectRender struct{}
|
||||
|
||||
// Redirects
|
||||
htmlDebugRender struct{}
|
||||
|
||||
// form binding
|
||||
HTMLRender struct {
|
||||
Template *template.Template
|
||||
}
|
||||
)
|
||||
|
||||
var (
|
||||
JSON = jsonRender{}
|
||||
XML = xmlRender{}
|
||||
Plain = plainRender{}
|
||||
Redirect = redirectRender{}
|
||||
HTMLDebug = htmlDebugRender{}
|
||||
)
|
||||
|
||||
func writeHeader(w http.ResponseWriter, code int, contentType string) {
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (_ jsonRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
|
||||
writeHeader(w, code, "application/json")
|
||||
encoder := json.NewEncoder(w)
|
||||
return encoder.Encode(data[0])
|
||||
}
|
||||
|
||||
func (_ redirectRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
|
||||
w.Header().Set("Location", data[0].(string))
|
||||
w.WriteHeader(code)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_ xmlRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
|
||||
writeHeader(w, code, "application/xml")
|
||||
encoder := xml.NewEncoder(w)
|
||||
return encoder.Encode(data[0])
|
||||
}
|
||||
|
||||
func (_ plainRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
|
||||
writeHeader(w, code, "text/plain")
|
||||
format := data[0].(string)
|
||||
args := data[1].([]interface{})
|
||||
var err error
|
||||
if len(args) > 0 {
|
||||
_, err = w.Write([]byte(fmt.Sprintf(format, args...)))
|
||||
} else {
|
||||
_, err = w.Write([]byte(format))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (_ htmlDebugRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
|
||||
writeHeader(w, code, "text/html")
|
||||
file := data[0].(string)
|
||||
obj := data[1]
|
||||
t, err := template.ParseFiles(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return t.ExecuteTemplate(w, file, obj)
|
||||
}
|
||||
|
||||
func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
|
||||
writeHeader(w, code, "text/html")
|
||||
file := data[0].(string)
|
||||
obj := data[1]
|
||||
return html.Template.ExecuteTemplate(w, file, obj)
|
||||
}
|
89
Godeps/_workspace/src/github.com/gin-gonic/gin/response_writer.go
generated
vendored
Normal file
89
Godeps/_workspace/src/github.com/gin-gonic/gin/response_writer.go
generated
vendored
Normal file
@ -0,0 +1,89 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type (
|
||||
ResponseWriter interface {
|
||||
http.ResponseWriter
|
||||
http.Hijacker
|
||||
http.Flusher
|
||||
http.CloseNotifier
|
||||
|
||||
Status() int
|
||||
Written() bool
|
||||
WriteHeaderNow()
|
||||
}
|
||||
|
||||
responseWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
written bool
|
||||
}
|
||||
)
|
||||
|
||||
func (w *responseWriter) reset(writer http.ResponseWriter) {
|
||||
w.ResponseWriter = writer
|
||||
w.status = 200
|
||||
w.written = false
|
||||
}
|
||||
|
||||
func (w *responseWriter) WriteHeader(code int) {
|
||||
if code > 0 {
|
||||
w.status = code
|
||||
if w.written {
|
||||
log.Println("[GIN] WARNING. Headers were already written!")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *responseWriter) WriteHeaderNow() {
|
||||
if !w.written {
|
||||
w.written = true
|
||||
w.ResponseWriter.WriteHeader(w.status)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *responseWriter) Write(data []byte) (n int, err error) {
|
||||
w.WriteHeaderNow()
|
||||
return w.ResponseWriter.Write(data)
|
||||
}
|
||||
|
||||
func (w *responseWriter) Status() int {
|
||||
return w.status
|
||||
}
|
||||
|
||||
func (w *responseWriter) Written() bool {
|
||||
return w.written
|
||||
}
|
||||
|
||||
// Implements the http.Hijacker interface
|
||||
func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
hijacker, ok := w.ResponseWriter.(http.Hijacker)
|
||||
if !ok {
|
||||
return nil, nil, errors.New("the ResponseWriter doesn't support the Hijacker interface")
|
||||
}
|
||||
return hijacker.Hijack()
|
||||
}
|
||||
|
||||
// Implements the http.CloseNotify interface
|
||||
func (w *responseWriter) CloseNotify() <-chan bool {
|
||||
return w.ResponseWriter.(http.CloseNotifier).CloseNotify()
|
||||
}
|
||||
|
||||
// Implements the http.Flush interface
|
||||
func (w *responseWriter) Flush() {
|
||||
flusher, ok := w.ResponseWriter.(http.Flusher)
|
||||
if ok {
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
50
Godeps/_workspace/src/github.com/gin-gonic/gin/utils.go
generated
vendored
Normal file
50
Godeps/_workspace/src/github.com/gin-gonic/gin/utils.go
generated
vendored
Normal file
@ -0,0 +1,50 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"reflect"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
type H map[string]interface{}
|
||||
|
||||
// Allows type H to be used with xml.Marshal
|
||||
func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
||||
start.Name = xml.Name{
|
||||
Space: "",
|
||||
Local: "map",
|
||||
}
|
||||
if err := e.EncodeToken(start); err != nil {
|
||||
return err
|
||||
}
|
||||
for key, value := range h {
|
||||
elem := xml.StartElement{
|
||||
Name: xml.Name{Space: "", Local: key},
|
||||
Attr: []xml.Attr{},
|
||||
}
|
||||
if err := e.EncodeElement(value, elem); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := e.EncodeToken(xml.EndElement{Name: start.Name}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func filterFlags(content string) string {
|
||||
for i, a := range content {
|
||||
if a == ' ' || a == ';' {
|
||||
return content[:i]
|
||||
}
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
func funcName(f interface{}) string {
|
||||
return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
|
||||
}
|
35
Godeps/_workspace/src/github.com/jessevdk/go-flags/.travis.yml
generated
vendored
Normal file
35
Godeps/_workspace/src/github.com/jessevdk/go-flags/.travis.yml
generated
vendored
Normal file
@ -0,0 +1,35 @@
|
||||
language: go
|
||||
|
||||
install:
|
||||
# go-flags
|
||||
- go get -d -v ./...
|
||||
- go build -v ./...
|
||||
|
||||
# linting
|
||||
- go get code.google.com/p/go.tools/cmd/vet
|
||||
- go get github.com/golang/lint
|
||||
- go install github.com/golang/lint/golint
|
||||
|
||||
# code coverage
|
||||
- go get code.google.com/p/go.tools/cmd/cover
|
||||
- go get github.com/onsi/ginkgo/ginkgo
|
||||
- go get github.com/modocache/gover
|
||||
- if [ "$TRAVIS_SECURE_ENV_VARS" = "true" ]; then go get github.com/mattn/goveralls; fi
|
||||
|
||||
script:
|
||||
# go-flags
|
||||
- $(exit $(gofmt -l . | wc -l))
|
||||
- go test -v ./...
|
||||
|
||||
# linting
|
||||
- go tool vet -all=true -v=true . || true
|
||||
- $(go env GOPATH | awk 'BEGIN{FS=":"} {print $1}')/bin/golint ./...
|
||||
|
||||
# code coverage
|
||||
- $(go env GOPATH | awk 'BEGIN{FS=":"} {print $1}')/bin/ginkgo -r -cover
|
||||
- $(go env GOPATH | awk 'BEGIN{FS=":"} {print $1}')/bin/gover
|
||||
- if [ "$TRAVIS_SECURE_ENV_VARS" = "true" ]; then $(go env GOPATH | awk 'BEGIN{FS=":"} {print $1}')/bin/goveralls -coverprofile=gover.coverprofile -service=travis-ci -repotoken $COVERALLS_TOKEN; fi
|
||||
|
||||
env:
|
||||
# coveralls.io
|
||||
secure: "RCYbiB4P0RjQRIoUx/vG/AjP3mmYCbzOmr86DCww1Z88yNcy3hYr3Cq8rpPtYU5v0g7wTpu4adaKIcqRE9xknYGbqj3YWZiCoBP1/n4Z+9sHW3Dsd9D/GRGeHUus0laJUGARjWoCTvoEtOgTdGQDoX7mH+pUUY0FBltNYUdOiiU="
|
26
Godeps/_workspace/src/github.com/jessevdk/go-flags/LICENSE
generated
vendored
Normal file
26
Godeps/_workspace/src/github.com/jessevdk/go-flags/LICENSE
generated
vendored
Normal file
@ -0,0 +1,26 @@
|
||||
Copyright (c) 2012 Jesse van den Kieboom. 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.
|
131
Godeps/_workspace/src/github.com/jessevdk/go-flags/README.md
generated
vendored
Normal file
131
Godeps/_workspace/src/github.com/jessevdk/go-flags/README.md
generated
vendored
Normal file
@ -0,0 +1,131 @@
|
||||
go-flags: a go library for parsing command line arguments
|
||||
=========================================================
|
||||
|
||||
[![GoDoc](https://godoc.org/github.com/jessevdk/go-flags?status.png)](https://godoc.org/github.com/jessevdk/go-flags) [![Build Status](https://travis-ci.org/jessevdk/go-flags.svg?branch=master)](https://travis-ci.org/jessevdk/go-flags) [![Coverage Status](https://img.shields.io/coveralls/jessevdk/go-flags.svg)](https://coveralls.io/r/jessevdk/go-flags?branch=master)
|
||||
|
||||
This library provides similar functionality to the builtin flag library of
|
||||
go, but provides much more functionality and nicer formatting. From the
|
||||
documentation:
|
||||
|
||||
Package flags provides an extensive command line option parser.
|
||||
The flags package is similar in functionality to the go builtin flag package
|
||||
but provides more options and uses reflection to provide a convenient and
|
||||
succinct way of specifying command line options.
|
||||
|
||||
Supported features:
|
||||
* Options with short names (-v)
|
||||
* Options with long names (--verbose)
|
||||
* Options with and without arguments (bool v.s. other type)
|
||||
* Options with optional arguments and default values
|
||||
* Multiple option groups each containing a set of options
|
||||
* Generate and print well-formatted help message
|
||||
* Passing remaining command line arguments after -- (optional)
|
||||
* Ignoring unknown command line options (optional)
|
||||
* Supports -I/usr/include -I=/usr/include -I /usr/include option argument specification
|
||||
* Supports multiple short options -aux
|
||||
* Supports all primitive go types (string, int{8..64}, uint{8..64}, float)
|
||||
* Supports same option multiple times (can store in slice or last option counts)
|
||||
* Supports maps
|
||||
* Supports function callbacks
|
||||
* Supports namespaces for (nested) option groups
|
||||
|
||||
The flags package uses structs, reflection and struct field tags
|
||||
to allow users to specify command line options. This results in very simple
|
||||
and concise specification of your application options. For example:
|
||||
|
||||
type Options struct {
|
||||
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
|
||||
}
|
||||
|
||||
This specifies one option with a short name -v and a long name --verbose.
|
||||
When either -v or --verbose is found on the command line, a 'true' value
|
||||
will be appended to the Verbose field. e.g. when specifying -vvv, the
|
||||
resulting value of Verbose will be {[true, true, true]}.
|
||||
|
||||
Example:
|
||||
--------
|
||||
var opts struct {
|
||||
// Slice of bool will append 'true' each time the option
|
||||
// is encountered (can be set multiple times, like -vvv)
|
||||
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
|
||||
|
||||
// Example of automatic marshalling to desired type (uint)
|
||||
Offset uint `long:"offset" description:"Offset"`
|
||||
|
||||
// Example of a callback, called each time the option is found.
|
||||
Call func(string) `short:"c" description:"Call phone number"`
|
||||
|
||||
// Example of a required flag
|
||||
Name string `short:"n" long:"name" description:"A name" required:"true"`
|
||||
|
||||
// Example of a value name
|
||||
File string `short:"f" long:"file" description:"A file" value-name:"FILE"`
|
||||
|
||||
// Example of a pointer
|
||||
Ptr *int `short:"p" description:"A pointer to an integer"`
|
||||
|
||||
// Example of a slice of strings
|
||||
StringSlice []string `short:"s" description:"A slice of strings"`
|
||||
|
||||
// Example of a slice of pointers
|
||||
PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"`
|
||||
|
||||
// Example of a map
|
||||
IntMap map[string]int `long:"intmap" description:"A map from string to int"`
|
||||
}
|
||||
|
||||
// Callback which will invoke callto:<argument> to call a number.
|
||||
// Note that this works just on OS X (and probably only with
|
||||
// Skype) but it shows the idea.
|
||||
opts.Call = func(num string) {
|
||||
cmd := exec.Command("open", "callto:"+num)
|
||||
cmd.Start()
|
||||
cmd.Process.Release()
|
||||
}
|
||||
|
||||
// Make some fake arguments to parse.
|
||||
args := []string{
|
||||
"-vv",
|
||||
"--offset=5",
|
||||
"-n", "Me",
|
||||
"-p", "3",
|
||||
"-s", "hello",
|
||||
"-s", "world",
|
||||
"--ptrslice", "hello",
|
||||
"--ptrslice", "world",
|
||||
"--intmap", "a:1",
|
||||
"--intmap", "b:5",
|
||||
"arg1",
|
||||
"arg2",
|
||||
"arg3",
|
||||
}
|
||||
|
||||
// Parse flags from `args'. Note that here we use flags.ParseArgs for
|
||||
// the sake of making a working example. Normally, you would simply use
|
||||
// flags.Parse(&opts) which uses os.Args
|
||||
args, err := flags.ParseArgs(&opts, args)
|
||||
|
||||
if err != nil {
|
||||
panic(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Printf("Verbosity: %v\n", opts.Verbose)
|
||||
fmt.Printf("Offset: %d\n", opts.Offset)
|
||||
fmt.Printf("Name: %s\n", opts.Name)
|
||||
fmt.Printf("Ptr: %d\n", *opts.Ptr)
|
||||
fmt.Printf("StringSlice: %v\n", opts.StringSlice)
|
||||
fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1])
|
||||
fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"])
|
||||
fmt.Printf("Remaining args: %s\n", strings.Join(args, " "))
|
||||
|
||||
// Output: Verbosity: [true true]
|
||||
// Offset: 5
|
||||
// Name: Me
|
||||
// Ptr: 3
|
||||
// StringSlice: [hello world]
|
||||
// PtrSlice: [hello world]
|
||||
// IntMap: [a:1 b:5]
|
||||
// Remaining args: arg1 arg2 arg3
|
||||
|
||||
More information can be found in the godocs: <http://godoc.org/github.com/jessevdk/go-flags>
|
21
Godeps/_workspace/src/github.com/jessevdk/go-flags/arg.go
generated
vendored
Normal file
21
Godeps/_workspace/src/github.com/jessevdk/go-flags/arg.go
generated
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// Arg represents a positional argument on the command line.
|
||||
type Arg struct {
|
||||
// The name of the positional argument (used in the help)
|
||||
Name string
|
||||
|
||||
// A description of the positional argument (used in the help)
|
||||
Description string
|
||||
|
||||
value reflect.Value
|
||||
tag multiTag
|
||||
}
|
||||
|
||||
func (a *Arg) isRemaining() bool {
|
||||
return a.value.Type().Kind() == reflect.Slice
|
||||
}
|
53
Godeps/_workspace/src/github.com/jessevdk/go-flags/arg_test.go
generated
vendored
Normal file
53
Godeps/_workspace/src/github.com/jessevdk/go-flags/arg_test.go
generated
vendored
Normal file
@ -0,0 +1,53 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPositional(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Positional struct {
|
||||
Command int
|
||||
Filename string
|
||||
Rest []string
|
||||
} `positional-args:"yes" required:"yes"`
|
||||
}{}
|
||||
|
||||
p := NewParser(&opts, Default)
|
||||
ret, err := p.ParseArgs([]string{"10", "arg_test.go", "a", "b"})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if opts.Positional.Command != 10 {
|
||||
t.Fatalf("Expected opts.Positional.Command to be 10, but got %v", opts.Positional.Command)
|
||||
}
|
||||
|
||||
if opts.Positional.Filename != "arg_test.go" {
|
||||
t.Fatalf("Expected opts.Positional.Filename to be \"arg_test.go\", but got %v", opts.Positional.Filename)
|
||||
}
|
||||
|
||||
assertStringArray(t, opts.Positional.Rest, []string{"a", "b"})
|
||||
assertStringArray(t, ret, []string{})
|
||||
}
|
||||
|
||||
func TestPositionalRequired(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Positional struct {
|
||||
Command int
|
||||
Filename string
|
||||
Rest []string
|
||||
} `positional-args:"yes" required:"yes"`
|
||||
}{}
|
||||
|
||||
p := NewParser(&opts, None)
|
||||
_, err := p.ParseArgs([]string{"10"})
|
||||
|
||||
assertError(t, err, ErrRequired, "the required argument `Filename` was not provided")
|
||||
}
|
177
Godeps/_workspace/src/github.com/jessevdk/go-flags/assert_test.go
generated
vendored
Normal file
177
Godeps/_workspace/src/github.com/jessevdk/go-flags/assert_test.go
generated
vendored
Normal file
@ -0,0 +1,177 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func assertCallerInfo() (string, int) {
|
||||
ptr := make([]uintptr, 15)
|
||||
n := runtime.Callers(1, ptr)
|
||||
|
||||
if n == 0 {
|
||||
return "", 0
|
||||
}
|
||||
|
||||
mef := runtime.FuncForPC(ptr[0])
|
||||
mefile, meline := mef.FileLine(ptr[0])
|
||||
|
||||
for i := 2; i < n; i++ {
|
||||
f := runtime.FuncForPC(ptr[i])
|
||||
file, line := f.FileLine(ptr[i])
|
||||
|
||||
if file != mefile {
|
||||
return file, line
|
||||
}
|
||||
}
|
||||
|
||||
return mefile, meline
|
||||
}
|
||||
|
||||
func assertErrorf(t *testing.T, format string, args ...interface{}) {
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
|
||||
file, line := assertCallerInfo()
|
||||
|
||||
t.Errorf("%s:%d: %s", path.Base(file), line, msg)
|
||||
}
|
||||
|
||||
func assertFatalf(t *testing.T, format string, args ...interface{}) {
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
|
||||
file, line := assertCallerInfo()
|
||||
|
||||
t.Fatalf("%s:%d: %s", path.Base(file), line, msg)
|
||||
}
|
||||
|
||||
func assertString(t *testing.T, a string, b string) {
|
||||
if a != b {
|
||||
assertErrorf(t, "Expected %#v, but got %#v", b, a)
|
||||
}
|
||||
}
|
||||
|
||||
func assertStringArray(t *testing.T, a []string, b []string) {
|
||||
if len(a) != len(b) {
|
||||
assertErrorf(t, "Expected %#v, but got %#v", b, a)
|
||||
return
|
||||
}
|
||||
|
||||
for i, v := range a {
|
||||
if b[i] != v {
|
||||
assertErrorf(t, "Expected %#v, but got %#v", b, a)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertBoolArray(t *testing.T, a []bool, b []bool) {
|
||||
if len(a) != len(b) {
|
||||
assertErrorf(t, "Expected %#v, but got %#v", b, a)
|
||||
return
|
||||
}
|
||||
|
||||
for i, v := range a {
|
||||
if b[i] != v {
|
||||
assertErrorf(t, "Expected %#v, but got %#v", b, a)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertParserSuccess(t *testing.T, data interface{}, args ...string) (*Parser, []string) {
|
||||
parser := NewParser(data, Default&^PrintErrors)
|
||||
ret, err := parser.ParseArgs(args)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected parse error: %s", err)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return parser, ret
|
||||
}
|
||||
|
||||
func assertParseSuccess(t *testing.T, data interface{}, args ...string) []string {
|
||||
_, ret := assertParserSuccess(t, data, args...)
|
||||
return ret
|
||||
}
|
||||
|
||||
func assertError(t *testing.T, err error, typ ErrorType, msg string) {
|
||||
if err == nil {
|
||||
assertFatalf(t, "Expected error: %s", msg)
|
||||
return
|
||||
}
|
||||
|
||||
if e, ok := err.(*Error); !ok {
|
||||
assertFatalf(t, "Expected Error type, but got %#v", err)
|
||||
} else {
|
||||
if e.Type != typ {
|
||||
assertErrorf(t, "Expected error type {%s}, but got {%s}", typ, e.Type)
|
||||
}
|
||||
|
||||
if e.Message != msg {
|
||||
assertErrorf(t, "Expected error message %#v, but got %#v", msg, e.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertParseFail(t *testing.T, typ ErrorType, msg string, data interface{}, args ...string) []string {
|
||||
parser := NewParser(data, Default&^PrintErrors)
|
||||
ret, err := parser.ParseArgs(args)
|
||||
|
||||
assertError(t, err, typ, msg)
|
||||
return ret
|
||||
}
|
||||
|
||||
func diff(a, b string) (string, error) {
|
||||
atmp, err := ioutil.TempFile("", "help-diff")
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
btmp, err := ioutil.TempFile("", "help-diff")
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if _, err := io.WriteString(atmp, a); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if _, err := io.WriteString(btmp, b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
ret, err := exec.Command("diff", "-u", "-d", "--label", "got", atmp.Name(), "--label", "expected", btmp.Name()).Output()
|
||||
|
||||
os.Remove(atmp.Name())
|
||||
os.Remove(btmp.Name())
|
||||
|
||||
if err.Error() == "exit status 1" {
|
||||
return string(ret), nil
|
||||
}
|
||||
|
||||
return string(ret), err
|
||||
}
|
||||
|
||||
func assertDiff(t *testing.T, actual, expected, msg string) {
|
||||
if actual == expected {
|
||||
return
|
||||
}
|
||||
|
||||
ret, err := diff(actual, expected)
|
||||
|
||||
if err != nil {
|
||||
assertErrorf(t, "Unexpected diff error: %s", err)
|
||||
assertErrorf(t, "Unexpected %s, expected:\n\n%s\n\nbut got\n\n%s", msg, expected, actual)
|
||||
} else {
|
||||
assertErrorf(t, "Unexpected %s:\n\n%s", msg, ret)
|
||||
}
|
||||
}
|
16
Godeps/_workspace/src/github.com/jessevdk/go-flags/check_crosscompile.sh
generated
vendored
Normal file
16
Godeps/_workspace/src/github.com/jessevdk/go-flags/check_crosscompile.sh
generated
vendored
Normal file
@ -0,0 +1,16 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
echo '# linux arm7'
|
||||
GOARM=7 GOARCH=arm GOOS=linux go build
|
||||
echo '# linux arm5'
|
||||
GOARM=5 GOARCH=arm GOOS=linux go build
|
||||
echo '# windows 386'
|
||||
GOARCH=386 GOOS=windows go build
|
||||
echo '# windows amd64'
|
||||
GOARCH=amd64 GOOS=windows go build
|
||||
echo '# darwin'
|
||||
GOARCH=amd64 GOOS=darwin go build
|
||||
echo '# freebsd'
|
||||
GOARCH=amd64 GOOS=freebsd go build
|
59
Godeps/_workspace/src/github.com/jessevdk/go-flags/closest.go
generated
vendored
Normal file
59
Godeps/_workspace/src/github.com/jessevdk/go-flags/closest.go
generated
vendored
Normal file
@ -0,0 +1,59 @@
|
||||
package flags
|
||||
|
||||
func levenshtein(s string, t string) int {
|
||||
if len(s) == 0 {
|
||||
return len(t)
|
||||
}
|
||||
|
||||
if len(t) == 0 {
|
||||
return len(s)
|
||||
}
|
||||
|
||||
dists := make([][]int, len(s)+1)
|
||||
for i := range dists {
|
||||
dists[i] = make([]int, len(t)+1)
|
||||
dists[i][0] = i
|
||||
}
|
||||
|
||||
for j := range t {
|
||||
dists[0][j] = j
|
||||
}
|
||||
|
||||
for i, sc := range s {
|
||||
for j, tc := range t {
|
||||
if sc == tc {
|
||||
dists[i+1][j+1] = dists[i][j]
|
||||
} else {
|
||||
dists[i+1][j+1] = dists[i][j] + 1
|
||||
if dists[i+1][j] < dists[i+1][j+1] {
|
||||
dists[i+1][j+1] = dists[i+1][j] + 1
|
||||
}
|
||||
if dists[i][j+1] < dists[i+1][j+1] {
|
||||
dists[i+1][j+1] = dists[i][j+1] + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dists[len(s)][len(t)]
|
||||
}
|
||||
|
||||
func closestChoice(cmd string, choices []string) (string, int) {
|
||||
if len(choices) == 0 {
|
||||
return "", 0
|
||||
}
|
||||
|
||||
mincmd := -1
|
||||
mindist := -1
|
||||
|
||||
for i, c := range choices {
|
||||
l := levenshtein(cmd, c)
|
||||
|
||||
if mincmd < 0 || l < mindist {
|
||||
mindist = l
|
||||
mincmd = i
|
||||
}
|
||||
}
|
||||
|
||||
return choices[mincmd], mindist
|
||||
}
|
106
Godeps/_workspace/src/github.com/jessevdk/go-flags/command.go
generated
vendored
Normal file
106
Godeps/_workspace/src/github.com/jessevdk/go-flags/command.go
generated
vendored
Normal file
@ -0,0 +1,106 @@
|
||||
package flags
|
||||
|
||||
// Command represents an application command. Commands can be added to the
|
||||
// parser (which itself is a command) and are selected/executed when its name
|
||||
// is specified on the command line. The Command type embeds a Group and
|
||||
// therefore also carries a set of command specific options.
|
||||
type Command struct {
|
||||
// Embedded, see Group for more information
|
||||
*Group
|
||||
|
||||
// The name by which the command can be invoked
|
||||
Name string
|
||||
|
||||
// The active sub command (set by parsing) or nil
|
||||
Active *Command
|
||||
|
||||
// Whether subcommands are optional
|
||||
SubcommandsOptional bool
|
||||
|
||||
// Aliases for the command
|
||||
Aliases []string
|
||||
|
||||
// Whether positional arguments are required
|
||||
ArgsRequired bool
|
||||
|
||||
commands []*Command
|
||||
hasBuiltinHelpGroup bool
|
||||
args []*Arg
|
||||
}
|
||||
|
||||
// Commander is an interface which can be implemented by any command added in
|
||||
// the options. When implemented, the Execute method will be called for the last
|
||||
// specified (sub)command providing the remaining command line arguments.
|
||||
type Commander interface {
|
||||
// Execute will be called for the last active (sub)command. The
|
||||
// args argument contains the remaining command line arguments. The
|
||||
// error that Execute returns will be eventually passed out of the
|
||||
// Parse method of the Parser.
|
||||
Execute(args []string) error
|
||||
}
|
||||
|
||||
// Usage is an interface which can be implemented to show a custom usage string
|
||||
// in the help message shown for a command.
|
||||
type Usage interface {
|
||||
// Usage is called for commands to allow customized printing of command
|
||||
// usage in the generated help message.
|
||||
Usage() string
|
||||
}
|
||||
|
||||
// AddCommand adds a new command to the parser with the given name and data. The
|
||||
// data needs to be a pointer to a struct from which the fields indicate which
|
||||
// options are in the command. The provided data can implement the Command and
|
||||
// Usage interfaces.
|
||||
func (c *Command) AddCommand(command string, shortDescription string, longDescription string, data interface{}) (*Command, error) {
|
||||
cmd := newCommand(command, shortDescription, longDescription, data)
|
||||
|
||||
cmd.parent = c
|
||||
|
||||
if err := cmd.scan(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.commands = append(c.commands, cmd)
|
||||
return cmd, nil
|
||||
}
|
||||
|
||||
// AddGroup adds a new group to the command with the given name and data. The
|
||||
// data needs to be a pointer to a struct from which the fields indicate which
|
||||
// options are in the group.
|
||||
func (c *Command) AddGroup(shortDescription string, longDescription string, data interface{}) (*Group, error) {
|
||||
group := newGroup(shortDescription, longDescription, data)
|
||||
|
||||
group.parent = c
|
||||
|
||||
if err := group.scanType(c.scanSubcommandHandler(group)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.groups = append(c.groups, group)
|
||||
return group, nil
|
||||
}
|
||||
|
||||
// Commands returns a list of subcommands of this command.
|
||||
func (c *Command) Commands() []*Command {
|
||||
return c.commands
|
||||
}
|
||||
|
||||
// Find locates the subcommand with the given name and returns it. If no such
|
||||
// command can be found Find will return nil.
|
||||
func (c *Command) Find(name string) *Command {
|
||||
for _, cc := range c.commands {
|
||||
if cc.match(name) {
|
||||
return cc
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Args returns a list of positional arguments associated with this command.
|
||||
func (c *Command) Args() []*Arg {
|
||||
ret := make([]*Arg, len(c.args))
|
||||
copy(ret, c.args)
|
||||
|
||||
return ret
|
||||
}
|
250
Godeps/_workspace/src/github.com/jessevdk/go-flags/command_private.go
generated
vendored
Normal file
250
Godeps/_workspace/src/github.com/jessevdk/go-flags/command_private.go
generated
vendored
Normal file
@ -0,0 +1,250 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type lookup struct {
|
||||
shortNames map[string]*Option
|
||||
longNames map[string]*Option
|
||||
|
||||
commands map[string]*Command
|
||||
}
|
||||
|
||||
func newCommand(name string, shortDescription string, longDescription string, data interface{}) *Command {
|
||||
return &Command{
|
||||
Group: newGroup(shortDescription, longDescription, data),
|
||||
Name: name,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) scanSubcommandHandler(parentg *Group) scanHandler {
|
||||
f := func(realval reflect.Value, sfield *reflect.StructField) (bool, error) {
|
||||
mtag := newMultiTag(string(sfield.Tag))
|
||||
|
||||
if err := mtag.Parse(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
|
||||
positional := mtag.Get("positional-args")
|
||||
|
||||
if len(positional) != 0 {
|
||||
stype := realval.Type()
|
||||
|
||||
for i := 0; i < stype.NumField(); i++ {
|
||||
field := stype.Field(i)
|
||||
|
||||
m := newMultiTag((string(field.Tag)))
|
||||
|
||||
if err := m.Parse(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
|
||||
name := m.Get("name")
|
||||
|
||||
if len(name) == 0 {
|
||||
name = field.Name
|
||||
}
|
||||
|
||||
arg := &Arg{
|
||||
Name: name,
|
||||
Description: m.Get("description"),
|
||||
|
||||
value: realval.Field(i),
|
||||
tag: m,
|
||||
}
|
||||
|
||||
c.args = append(c.args, arg)
|
||||
|
||||
if len(mtag.Get("required")) != 0 {
|
||||
c.ArgsRequired = true
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
subcommand := mtag.Get("command")
|
||||
|
||||
if len(subcommand) != 0 {
|
||||
ptrval := reflect.NewAt(realval.Type(), unsafe.Pointer(realval.UnsafeAddr()))
|
||||
|
||||
shortDescription := mtag.Get("description")
|
||||
longDescription := mtag.Get("long-description")
|
||||
subcommandsOptional := mtag.Get("subcommands-optional")
|
||||
aliases := mtag.GetMany("alias")
|
||||
|
||||
subc, err := c.AddCommand(subcommand, shortDescription, longDescription, ptrval.Interface())
|
||||
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
|
||||
if len(subcommandsOptional) > 0 {
|
||||
subc.SubcommandsOptional = true
|
||||
}
|
||||
|
||||
if len(aliases) > 0 {
|
||||
subc.Aliases = aliases
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return parentg.scanSubGroupHandler(realval, sfield)
|
||||
}
|
||||
|
||||
return f
|
||||
}
|
||||
|
||||
func (c *Command) scan() error {
|
||||
return c.scanType(c.scanSubcommandHandler(c.Group))
|
||||
}
|
||||
|
||||
func (c *Command) eachCommand(f func(*Command), recurse bool) {
|
||||
f(c)
|
||||
|
||||
for _, cc := range c.commands {
|
||||
if recurse {
|
||||
cc.eachCommand(f, true)
|
||||
} else {
|
||||
f(cc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) eachActiveGroup(f func(cc *Command, g *Group)) {
|
||||
c.eachGroup(func(g *Group) {
|
||||
f(c, g)
|
||||
})
|
||||
|
||||
if c.Active != nil {
|
||||
c.Active.eachActiveGroup(f)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) addHelpGroups(showHelp func() error) {
|
||||
if !c.hasBuiltinHelpGroup {
|
||||
c.addHelpGroup(showHelp)
|
||||
c.hasBuiltinHelpGroup = true
|
||||
}
|
||||
|
||||
for _, cc := range c.commands {
|
||||
cc.addHelpGroups(showHelp)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) makeLookup() lookup {
|
||||
ret := lookup{
|
||||
shortNames: make(map[string]*Option),
|
||||
longNames: make(map[string]*Option),
|
||||
commands: make(map[string]*Command),
|
||||
}
|
||||
|
||||
c.eachGroup(func(g *Group) {
|
||||
for _, option := range g.options {
|
||||
if option.ShortName != 0 {
|
||||
ret.shortNames[string(option.ShortName)] = option
|
||||
}
|
||||
|
||||
if len(option.LongName) > 0 {
|
||||
ret.longNames[option.LongNameWithNamespace()] = option
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for _, subcommand := range c.commands {
|
||||
ret.commands[subcommand.Name] = subcommand
|
||||
|
||||
for _, a := range subcommand.Aliases {
|
||||
ret.commands[a] = subcommand
|
||||
}
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (c *Command) groupByName(name string) *Group {
|
||||
if grp := c.Group.groupByName(name); grp != nil {
|
||||
return grp
|
||||
}
|
||||
|
||||
for _, subc := range c.commands {
|
||||
prefix := subc.Name + "."
|
||||
|
||||
if strings.HasPrefix(name, prefix) {
|
||||
if grp := subc.groupByName(name[len(prefix):]); grp != nil {
|
||||
return grp
|
||||
}
|
||||
} else if name == subc.Name {
|
||||
return subc.Group
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type commandList []*Command
|
||||
|
||||
func (c commandList) Less(i, j int) bool {
|
||||
return c[i].Name < c[j].Name
|
||||
}
|
||||
|
||||
func (c commandList) Len() int {
|
||||
return len(c)
|
||||
}
|
||||
|
||||
func (c commandList) Swap(i, j int) {
|
||||
c[i], c[j] = c[j], c[i]
|
||||
}
|
||||
|
||||
func (c *Command) sortedCommands() []*Command {
|
||||
ret := make(commandList, len(c.commands))
|
||||
copy(ret, c.commands)
|
||||
|
||||
sort.Sort(ret)
|
||||
return []*Command(ret)
|
||||
}
|
||||
|
||||
func (c *Command) match(name string) bool {
|
||||
if c.Name == name {
|
||||
return true
|
||||
}
|
||||
|
||||
for _, v := range c.Aliases {
|
||||
if v == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *Command) hasCliOptions() bool {
|
||||
ret := false
|
||||
|
||||
c.eachGroup(func(g *Group) {
|
||||
if g.isBuiltinHelp {
|
||||
return
|
||||
}
|
||||
|
||||
for _, opt := range g.options {
|
||||
if opt.canCli() {
|
||||
ret = true
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (c *Command) fillParseState(s *parseState) {
|
||||
s.positional = make([]*Arg, len(c.args))
|
||||
copy(s.positional, c.args)
|
||||
|
||||
s.lookup = c.makeLookup()
|
||||
s.command = c
|
||||
}
|
354
Godeps/_workspace/src/github.com/jessevdk/go-flags/command_test.go
generated
vendored
Normal file
354
Godeps/_workspace/src/github.com/jessevdk/go-flags/command_test.go
generated
vendored
Normal file
@ -0,0 +1,354 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCommandInline(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Command struct {
|
||||
G bool `short:"g"`
|
||||
} `command:"cmd"`
|
||||
}{}
|
||||
|
||||
p, ret := assertParserSuccess(t, &opts, "-v", "cmd", "-g")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if p.Active == nil {
|
||||
t.Errorf("Expected active command")
|
||||
}
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
|
||||
if !opts.Command.G {
|
||||
t.Errorf("Expected Command.G to be true")
|
||||
}
|
||||
|
||||
if p.Command.Find("cmd") != p.Active {
|
||||
t.Errorf("Expected to find command `cmd' to be active")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandInlineMulti(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
C1 struct {
|
||||
} `command:"c1"`
|
||||
|
||||
C2 struct {
|
||||
G bool `short:"g"`
|
||||
} `command:"c2"`
|
||||
}{}
|
||||
|
||||
p, ret := assertParserSuccess(t, &opts, "-v", "c2", "-g")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if p.Active == nil {
|
||||
t.Errorf("Expected active command")
|
||||
}
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
|
||||
if !opts.C2.G {
|
||||
t.Errorf("Expected C2.G to be true")
|
||||
}
|
||||
|
||||
if p.Command.Find("c1") == nil {
|
||||
t.Errorf("Expected to find command `c1'")
|
||||
}
|
||||
|
||||
if c2 := p.Command.Find("c2"); c2 == nil {
|
||||
t.Errorf("Expected to find command `c2'")
|
||||
} else if c2 != p.Active {
|
||||
t.Errorf("Expected to find command `c2' to be active")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandFlagOrder1(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Command struct {
|
||||
G bool `short:"g"`
|
||||
} `command:"cmd"`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrUnknownFlag, "unknown flag `g'", &opts, "-v", "-g", "cmd")
|
||||
}
|
||||
|
||||
func TestCommandFlagOrder2(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Command struct {
|
||||
G bool `short:"g"`
|
||||
} `command:"cmd"`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrUnknownFlag, "unknown flag `v'", &opts, "cmd", "-v", "-g")
|
||||
}
|
||||
|
||||
func TestCommandEstimate(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Cmd1 struct {
|
||||
} `command:"remove"`
|
||||
|
||||
Cmd2 struct {
|
||||
} `command:"add"`
|
||||
}{}
|
||||
|
||||
p := NewParser(&opts, None)
|
||||
_, err := p.ParseArgs([]string{})
|
||||
|
||||
assertError(t, err, ErrCommandRequired, "Please specify one command of: add or remove")
|
||||
}
|
||||
|
||||
func TestCommandEstimate2(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Cmd1 struct {
|
||||
} `command:"remove"`
|
||||
|
||||
Cmd2 struct {
|
||||
} `command:"add"`
|
||||
}{}
|
||||
|
||||
p := NewParser(&opts, None)
|
||||
_, err := p.ParseArgs([]string{"rmive"})
|
||||
|
||||
assertError(t, err, ErrUnknownCommand, "Unknown command `rmive', did you mean `remove'?")
|
||||
}
|
||||
|
||||
type testCommand struct {
|
||||
G bool `short:"g"`
|
||||
Executed bool
|
||||
EArgs []string
|
||||
}
|
||||
|
||||
func (c *testCommand) Execute(args []string) error {
|
||||
c.Executed = true
|
||||
c.EArgs = args
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestCommandExecute(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Command testCommand `command:"cmd"`
|
||||
}{}
|
||||
|
||||
assertParseSuccess(t, &opts, "-v", "cmd", "-g", "a", "b")
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
|
||||
if !opts.Command.Executed {
|
||||
t.Errorf("Did not execute command")
|
||||
}
|
||||
|
||||
if !opts.Command.G {
|
||||
t.Errorf("Expected Command.C to be true")
|
||||
}
|
||||
|
||||
assertStringArray(t, opts.Command.EArgs, []string{"a", "b"})
|
||||
}
|
||||
|
||||
func TestCommandClosest(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Cmd1 struct {
|
||||
} `command:"remove"`
|
||||
|
||||
Cmd2 struct {
|
||||
} `command:"add"`
|
||||
}{}
|
||||
|
||||
args := assertParseFail(t, ErrUnknownCommand, "Unknown command `addd', did you mean `add'?", &opts, "-v", "addd")
|
||||
|
||||
assertStringArray(t, args, []string{"addd"})
|
||||
}
|
||||
|
||||
func TestCommandAdd(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
}{}
|
||||
|
||||
var cmd = struct {
|
||||
G bool `short:"g"`
|
||||
}{}
|
||||
|
||||
p := NewParser(&opts, Default)
|
||||
c, err := p.AddCommand("cmd", "", "", &cmd)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
ret, err := p.ParseArgs([]string{"-v", "cmd", "-g", "rest"})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
assertStringArray(t, ret, []string{"rest"})
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
|
||||
if !cmd.G {
|
||||
t.Errorf("Expected Command.G to be true")
|
||||
}
|
||||
|
||||
if p.Command.Find("cmd") != c {
|
||||
t.Errorf("Expected to find command `cmd'")
|
||||
}
|
||||
|
||||
if p.Commands()[0] != c {
|
||||
t.Errorf("Expected command %#v, but got %#v", c, p.Commands()[0])
|
||||
}
|
||||
|
||||
if c.Options()[0].ShortName != 'g' {
|
||||
t.Errorf("Expected short name `g' but got %v", c.Options()[0].ShortName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandNestedInline(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Command struct {
|
||||
G bool `short:"g"`
|
||||
|
||||
Nested struct {
|
||||
N string `long:"n"`
|
||||
} `command:"nested"`
|
||||
} `command:"cmd"`
|
||||
}{}
|
||||
|
||||
p, ret := assertParserSuccess(t, &opts, "-v", "cmd", "-g", "nested", "--n", "n", "rest")
|
||||
|
||||
assertStringArray(t, ret, []string{"rest"})
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
|
||||
if !opts.Command.G {
|
||||
t.Errorf("Expected Command.G to be true")
|
||||
}
|
||||
|
||||
assertString(t, opts.Command.Nested.N, "n")
|
||||
|
||||
if c := p.Command.Find("cmd"); c == nil {
|
||||
t.Errorf("Expected to find command `cmd'")
|
||||
} else {
|
||||
if c != p.Active {
|
||||
t.Errorf("Expected `cmd' to be the active parser command")
|
||||
}
|
||||
|
||||
if nested := c.Find("nested"); nested == nil {
|
||||
t.Errorf("Expected to find command `nested'")
|
||||
} else if nested != c.Active {
|
||||
t.Errorf("Expected to find command `nested' to be the active `cmd' command")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequiredOnCommand(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v" required:"true"`
|
||||
|
||||
Command struct {
|
||||
G bool `short:"g"`
|
||||
} `command:"cmd"`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrRequired, fmt.Sprintf("the required flag `%cv' was not specified", defaultShortOptDelimiter), &opts, "cmd")
|
||||
}
|
||||
|
||||
func TestRequiredAllOnCommand(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v" required:"true"`
|
||||
Missing bool `long:"missing" required:"true"`
|
||||
|
||||
Command struct {
|
||||
G bool `short:"g"`
|
||||
} `command:"cmd"`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrRequired, fmt.Sprintf("the required flags `%smissing' and `%cv' were not specified", defaultLongOptDelimiter, defaultShortOptDelimiter), &opts, "cmd")
|
||||
}
|
||||
|
||||
func TestDefaultOnCommand(t *testing.T) {
|
||||
var opts = struct {
|
||||
Command struct {
|
||||
G bool `short:"g" default:"true"`
|
||||
} `command:"cmd"`
|
||||
}{}
|
||||
|
||||
assertParseSuccess(t, &opts, "cmd")
|
||||
|
||||
if !opts.Command.G {
|
||||
t.Errorf("Expected G to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubcommandsOptional(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Cmd1 struct {
|
||||
} `command:"remove"`
|
||||
|
||||
Cmd2 struct {
|
||||
} `command:"add"`
|
||||
}{}
|
||||
|
||||
p := NewParser(&opts, None)
|
||||
p.SubcommandsOptional = true
|
||||
|
||||
_, err := p.ParseArgs([]string{"-v"})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandAlias(t *testing.T) {
|
||||
var opts = struct {
|
||||
Command struct {
|
||||
G bool `short:"g" default:"true"`
|
||||
} `command:"cmd" alias:"cm"`
|
||||
}{}
|
||||
|
||||
assertParseSuccess(t, &opts, "cm")
|
||||
|
||||
if !opts.Command.G {
|
||||
t.Errorf("Expected G to be true")
|
||||
}
|
||||
}
|
304
Godeps/_workspace/src/github.com/jessevdk/go-flags/completion.go
generated
vendored
Normal file
304
Godeps/_workspace/src/github.com/jessevdk/go-flags/completion.go
generated
vendored
Normal file
@ -0,0 +1,304 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Completion is a type containing information of a completion.
|
||||
type Completion struct {
|
||||
// The completed item
|
||||
Item string
|
||||
|
||||
// A description of the completed item (optional)
|
||||
Description string
|
||||
}
|
||||
|
||||
type completions []Completion
|
||||
|
||||
func (c completions) Len() int {
|
||||
return len(c)
|
||||
}
|
||||
|
||||
func (c completions) Less(i, j int) bool {
|
||||
return c[i].Item < c[j].Item
|
||||
}
|
||||
|
||||
func (c completions) Swap(i, j int) {
|
||||
c[i], c[j] = c[j], c[i]
|
||||
}
|
||||
|
||||
// Completer is an interface which can be implemented by types
|
||||
// to provide custom command line argument completion.
|
||||
type Completer interface {
|
||||
// Complete receives a prefix representing a (partial) value
|
||||
// for its type and should provide a list of possible valid
|
||||
// completions.
|
||||
Complete(match string) []Completion
|
||||
}
|
||||
|
||||
type completion struct {
|
||||
parser *Parser
|
||||
|
||||
ShowDescriptions bool
|
||||
}
|
||||
|
||||
// Filename is a string alias which provides filename completion.
|
||||
type Filename string
|
||||
|
||||
func completionsWithoutDescriptions(items []string) []Completion {
|
||||
ret := make([]Completion, len(items))
|
||||
|
||||
for i, v := range items {
|
||||
ret[i].Item = v
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
// Complete returns a list of existing files with the given
|
||||
// prefix.
|
||||
func (f *Filename) Complete(match string) []Completion {
|
||||
ret, _ := filepath.Glob(match + "*")
|
||||
return completionsWithoutDescriptions(ret)
|
||||
}
|
||||
|
||||
func (c *completion) skipPositional(s *parseState, n int) {
|
||||
if n >= len(s.positional) {
|
||||
s.positional = nil
|
||||
} else {
|
||||
s.positional = s.positional[n:]
|
||||
}
|
||||
}
|
||||
|
||||
func (c *completion) completeOptionNames(names map[string]*Option, prefix string, match string) []Completion {
|
||||
n := make([]Completion, 0, len(names))
|
||||
|
||||
for k, opt := range names {
|
||||
if strings.HasPrefix(k, match) {
|
||||
n = append(n, Completion{
|
||||
Item: prefix + k,
|
||||
Description: opt.Description,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return n
|
||||
}
|
||||
|
||||
func (c *completion) completeLongNames(s *parseState, prefix string, match string) []Completion {
|
||||
return c.completeOptionNames(s.lookup.longNames, prefix, match)
|
||||
}
|
||||
|
||||
func (c *completion) completeShortNames(s *parseState, prefix string, match string) []Completion {
|
||||
if len(match) != 0 {
|
||||
return []Completion{
|
||||
Completion{
|
||||
Item: prefix + match,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return c.completeOptionNames(s.lookup.shortNames, prefix, match)
|
||||
}
|
||||
|
||||
func (c *completion) completeCommands(s *parseState, match string) []Completion {
|
||||
n := make([]Completion, 0, len(s.command.commands))
|
||||
|
||||
for _, cmd := range s.command.commands {
|
||||
if cmd.data != c && strings.HasPrefix(cmd.Name, match) {
|
||||
n = append(n, Completion{
|
||||
Item: cmd.Name,
|
||||
Description: cmd.ShortDescription,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return n
|
||||
}
|
||||
|
||||
func (c *completion) completeValue(value reflect.Value, prefix string, match string) []Completion {
|
||||
i := value.Interface()
|
||||
|
||||
var ret []Completion
|
||||
|
||||
if cmp, ok := i.(Completer); ok {
|
||||
ret = cmp.Complete(match)
|
||||
} else if value.CanAddr() {
|
||||
if cmp, ok = value.Addr().Interface().(Completer); ok {
|
||||
ret = cmp.Complete(match)
|
||||
}
|
||||
}
|
||||
|
||||
for i, v := range ret {
|
||||
ret[i].Item = prefix + v.Item
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (c *completion) completeArg(arg *Arg, prefix string, match string) []Completion {
|
||||
if arg.isRemaining() {
|
||||
// For remaining positional args (that are parsed into a slice), complete
|
||||
// based on the element type.
|
||||
return c.completeValue(reflect.New(arg.value.Type().Elem()), prefix, match)
|
||||
}
|
||||
|
||||
return c.completeValue(arg.value, prefix, match)
|
||||
}
|
||||
|
||||
func (c *completion) complete(args []string) []Completion {
|
||||
if len(args) == 0 {
|
||||
args = []string{""}
|
||||
}
|
||||
|
||||
s := &parseState{
|
||||
args: args,
|
||||
}
|
||||
|
||||
c.parser.fillParseState(s)
|
||||
|
||||
var opt *Option
|
||||
|
||||
for len(s.args) > 1 {
|
||||
arg := s.pop()
|
||||
|
||||
if (c.parser.Options&PassDoubleDash) != None && arg == "--" {
|
||||
opt = nil
|
||||
c.skipPositional(s, len(s.args)-1)
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
if argumentIsOption(arg) {
|
||||
prefix, optname, islong := stripOptionPrefix(arg)
|
||||
optname, _, argument := splitOption(prefix, optname, islong)
|
||||
|
||||
if argument == nil {
|
||||
var o *Option
|
||||
canarg := true
|
||||
|
||||
if islong {
|
||||
o = s.lookup.longNames[optname]
|
||||
} else {
|
||||
for i, r := range optname {
|
||||
sname := string(r)
|
||||
o = s.lookup.shortNames[sname]
|
||||
|
||||
if o == nil {
|
||||
break
|
||||
}
|
||||
|
||||
if i == 0 && o.canArgument() && len(optname) != len(sname) {
|
||||
canarg = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if o == nil && (c.parser.Options&PassAfterNonOption) != None {
|
||||
opt = nil
|
||||
c.skipPositional(s, len(s.args)-1)
|
||||
|
||||
break
|
||||
} else if o != nil && o.canArgument() && !o.OptionalArgument && canarg {
|
||||
if len(s.args) > 1 {
|
||||
s.pop()
|
||||
} else {
|
||||
opt = o
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if len(s.positional) > 0 {
|
||||
if !s.positional[0].isRemaining() {
|
||||
// Don't advance beyond a remaining positional arg (because
|
||||
// it consumes all subsequent args).
|
||||
s.positional = s.positional[1:]
|
||||
}
|
||||
} else if cmd, ok := s.lookup.commands[arg]; ok {
|
||||
cmd.fillParseState(s)
|
||||
}
|
||||
|
||||
opt = nil
|
||||
}
|
||||
}
|
||||
|
||||
lastarg := s.args[len(s.args)-1]
|
||||
var ret []Completion
|
||||
|
||||
if opt != nil {
|
||||
// Completion for the argument of 'opt'
|
||||
ret = c.completeValue(opt.value, "", lastarg)
|
||||
} else if argumentIsOption(lastarg) {
|
||||
// Complete the option
|
||||
prefix, optname, islong := stripOptionPrefix(lastarg)
|
||||
optname, split, argument := splitOption(prefix, optname, islong)
|
||||
|
||||
if argument == nil && !islong {
|
||||
rname, n := utf8.DecodeRuneInString(optname)
|
||||
sname := string(rname)
|
||||
|
||||
if opt := s.lookup.shortNames[sname]; opt != nil && opt.canArgument() {
|
||||
ret = c.completeValue(opt.value, prefix+sname, optname[n:])
|
||||
} else {
|
||||
ret = c.completeShortNames(s, prefix, optname)
|
||||
}
|
||||
} else if argument != nil {
|
||||
if islong {
|
||||
opt = s.lookup.longNames[optname]
|
||||
} else {
|
||||
opt = s.lookup.shortNames[optname]
|
||||
}
|
||||
|
||||
if opt != nil {
|
||||
ret = c.completeValue(opt.value, prefix+optname+split, *argument)
|
||||
}
|
||||
} else if islong {
|
||||
ret = c.completeLongNames(s, prefix, optname)
|
||||
} else {
|
||||
ret = c.completeShortNames(s, prefix, optname)
|
||||
}
|
||||
} else if len(s.positional) > 0 {
|
||||
// Complete for positional argument
|
||||
ret = c.completeArg(s.positional[0], "", lastarg)
|
||||
} else if len(s.command.commands) > 0 {
|
||||
// Complete for command
|
||||
ret = c.completeCommands(s, lastarg)
|
||||
}
|
||||
|
||||
sort.Sort(completions(ret))
|
||||
return ret
|
||||
}
|
||||
|
||||
func (c *completion) execute(args []string) {
|
||||
ret := c.complete(args)
|
||||
|
||||
if c.ShowDescriptions && len(ret) > 1 {
|
||||
maxl := 0
|
||||
|
||||
for _, v := range ret {
|
||||
if len(v.Item) > maxl {
|
||||
maxl = len(v.Item)
|
||||
}
|
||||
}
|
||||
|
||||
for _, v := range ret {
|
||||
fmt.Printf("%s", v.Item)
|
||||
|
||||
if len(v.Description) > 0 {
|
||||
fmt.Printf("%s # %s", strings.Repeat(" ", maxl-len(v.Item)), v.Description)
|
||||
}
|
||||
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
} else {
|
||||
for _, v := range ret {
|
||||
fmt.Println(v.Item)
|
||||
}
|
||||
}
|
||||
}
|
289
Godeps/_workspace/src/github.com/jessevdk/go-flags/completion_test.go
generated
vendored
Normal file
289
Godeps/_workspace/src/github.com/jessevdk/go-flags/completion_test.go
generated
vendored
Normal file
@ -0,0 +1,289 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type TestComplete struct {
|
||||
}
|
||||
|
||||
func (t *TestComplete) Complete(match string) []Completion {
|
||||
options := []string{
|
||||
"hello world",
|
||||
"hello universe",
|
||||
"hello multiverse",
|
||||
}
|
||||
|
||||
ret := make([]Completion, 0, len(options))
|
||||
|
||||
for _, o := range options {
|
||||
if strings.HasPrefix(o, match) {
|
||||
ret = append(ret, Completion{
|
||||
Item: o,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
var completionTestOptions struct {
|
||||
Verbose bool `short:"v" long:"verbose" description:"Verbose messages"`
|
||||
Debug bool `short:"d" long:"debug" description:"Enable debug"`
|
||||
Version bool `long:"version" description:"Show version"`
|
||||
Required bool `long:"required" required:"true" description:"This is required"`
|
||||
|
||||
AddCommand struct {
|
||||
Positional struct {
|
||||
Filename Filename
|
||||
} `positional-args:"yes"`
|
||||
} `command:"add" description:"add an item"`
|
||||
|
||||
AddMultiCommand struct {
|
||||
Positional struct {
|
||||
Filename []Filename
|
||||
} `positional-args:"yes"`
|
||||
} `command:"add-multi" description:"add multiple items"`
|
||||
|
||||
RemoveCommand struct {
|
||||
Other bool `short:"o"`
|
||||
File Filename `short:"f" long:"filename"`
|
||||
} `command:"rm" description:"remove an item"`
|
||||
|
||||
RenameCommand struct {
|
||||
Completed TestComplete `short:"c" long:"completed"`
|
||||
} `command:"rename" description:"rename an item"`
|
||||
}
|
||||
|
||||
type completionTest struct {
|
||||
Args []string
|
||||
Completed []string
|
||||
ShowDescriptions bool
|
||||
}
|
||||
|
||||
var completionTests []completionTest
|
||||
|
||||
func init() {
|
||||
_, sourcefile, _, _ := runtime.Caller(0)
|
||||
completionTestSourcedir := filepath.Join(filepath.SplitList(path.Dir(sourcefile))...)
|
||||
|
||||
completionTestFilename := []string{filepath.Join(completionTestSourcedir, "completion.go"), filepath.Join(completionTestSourcedir, "completion_test.go")}
|
||||
|
||||
completionTests = []completionTest{
|
||||
{
|
||||
// Short names
|
||||
[]string{"-"},
|
||||
[]string{"-d", "-v"},
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Short names concatenated
|
||||
[]string{"-dv"},
|
||||
[]string{"-dv"},
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Long names
|
||||
[]string{"--"},
|
||||
[]string{"--debug", "--required", "--verbose", "--version"},
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Long names with descriptions
|
||||
[]string{"--"},
|
||||
[]string{
|
||||
"--debug # Enable debug",
|
||||
"--required # This is required",
|
||||
"--verbose # Verbose messages",
|
||||
"--version # Show version",
|
||||
},
|
||||
true,
|
||||
},
|
||||
|
||||
{
|
||||
// Long names partial
|
||||
[]string{"--ver"},
|
||||
[]string{"--verbose", "--version"},
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Commands
|
||||
[]string{""},
|
||||
[]string{"add", "add-multi", "rename", "rm"},
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Commands with descriptions
|
||||
[]string{""},
|
||||
[]string{
|
||||
"add # add an item",
|
||||
"add-multi # add multiple items",
|
||||
"rename # rename an item",
|
||||
"rm # remove an item",
|
||||
},
|
||||
true,
|
||||
},
|
||||
|
||||
{
|
||||
// Commands partial
|
||||
[]string{"r"},
|
||||
[]string{"rename", "rm"},
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Positional filename
|
||||
[]string{"add", filepath.Join(completionTestSourcedir, "completion")},
|
||||
completionTestFilename,
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Multiple positional filename (1 arg)
|
||||
[]string{"add-multi", filepath.Join(completionTestSourcedir, "completion")},
|
||||
completionTestFilename,
|
||||
false,
|
||||
},
|
||||
{
|
||||
// Multiple positional filename (2 args)
|
||||
[]string{"add-multi", filepath.Join(completionTestSourcedir, "completion.go"), filepath.Join(completionTestSourcedir, "completion")},
|
||||
completionTestFilename,
|
||||
false,
|
||||
},
|
||||
{
|
||||
// Multiple positional filename (3 args)
|
||||
[]string{"add-multi", filepath.Join(completionTestSourcedir, "completion.go"), filepath.Join(completionTestSourcedir, "completion.go"), filepath.Join(completionTestSourcedir, "completion")},
|
||||
completionTestFilename,
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Flag filename
|
||||
[]string{"rm", "-f", path.Join(completionTestSourcedir, "completion")},
|
||||
completionTestFilename,
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Flag short concat last filename
|
||||
[]string{"rm", "-of", path.Join(completionTestSourcedir, "completion")},
|
||||
completionTestFilename,
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Flag concat filename
|
||||
[]string{"rm", "-f" + path.Join(completionTestSourcedir, "completion")},
|
||||
[]string{"-f" + completionTestFilename[0], "-f" + completionTestFilename[1]},
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Flag equal concat filename
|
||||
[]string{"rm", "-f=" + path.Join(completionTestSourcedir, "completion")},
|
||||
[]string{"-f=" + completionTestFilename[0], "-f=" + completionTestFilename[1]},
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Flag concat long filename
|
||||
[]string{"rm", "--filename=" + path.Join(completionTestSourcedir, "completion")},
|
||||
[]string{"--filename=" + completionTestFilename[0], "--filename=" + completionTestFilename[1]},
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Flag long filename
|
||||
[]string{"rm", "--filename", path.Join(completionTestSourcedir, "completion")},
|
||||
completionTestFilename,
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
// Custom completed
|
||||
[]string{"rename", "-c", "hello un"},
|
||||
[]string{"hello universe"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletion(t *testing.T) {
|
||||
p := NewParser(&completionTestOptions, Default)
|
||||
c := &completion{parser: p}
|
||||
|
||||
for _, test := range completionTests {
|
||||
if test.ShowDescriptions {
|
||||
continue
|
||||
}
|
||||
|
||||
ret := c.complete(test.Args)
|
||||
items := make([]string, len(ret))
|
||||
|
||||
for i, v := range ret {
|
||||
items[i] = v.Item
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(items, test.Completed) {
|
||||
t.Errorf("Args: %#v, %#v\n Expected: %#v\n Got: %#v", test.Args, test.ShowDescriptions, test.Completed, items)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParserCompletion(t *testing.T) {
|
||||
for _, test := range completionTests {
|
||||
if test.ShowDescriptions {
|
||||
os.Setenv("GO_FLAGS_COMPLETION", "verbose")
|
||||
} else {
|
||||
os.Setenv("GO_FLAGS_COMPLETION", "1")
|
||||
}
|
||||
|
||||
tmp := os.Stdout
|
||||
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stdout = w
|
||||
|
||||
out := make(chan string)
|
||||
|
||||
go func() {
|
||||
var buf bytes.Buffer
|
||||
|
||||
io.Copy(&buf, r)
|
||||
|
||||
out <- buf.String()
|
||||
}()
|
||||
|
||||
p := NewParser(&completionTestOptions, None)
|
||||
|
||||
_, err := p.ParseArgs(test.Args)
|
||||
|
||||
w.Close()
|
||||
|
||||
os.Stdout = tmp
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %s", err)
|
||||
}
|
||||
|
||||
got := strings.Split(strings.Trim(<-out, "\n"), "\n")
|
||||
|
||||
if !reflect.DeepEqual(got, test.Completed) {
|
||||
t.Errorf("Expected: %#v\nGot: %#v", test.Completed, got)
|
||||
}
|
||||
}
|
||||
|
||||
os.Setenv("GO_FLAGS_COMPLETION", "")
|
||||
}
|
357
Godeps/_workspace/src/github.com/jessevdk/go-flags/convert.go
generated
vendored
Normal file
357
Godeps/_workspace/src/github.com/jessevdk/go-flags/convert.go
generated
vendored
Normal file
@ -0,0 +1,357 @@
|
||||
// Copyright 2012 Jesse van den Kieboom. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Marshaler is the interface implemented by types that can marshal themselves
|
||||
// to a string representation of the flag.
|
||||
type Marshaler interface {
|
||||
// MarshalFlag marshals a flag value to its string representation.
|
||||
MarshalFlag() (string, error)
|
||||
}
|
||||
|
||||
// Unmarshaler is the interface implemented by types that can unmarshal a flag
|
||||
// argument to themselves. The provided value is directly passed from the
|
||||
// command line.
|
||||
type Unmarshaler interface {
|
||||
// UnmarshalFlag unmarshals a string value representation to the flag
|
||||
// value (which therefore needs to be a pointer receiver).
|
||||
UnmarshalFlag(value string) error
|
||||
}
|
||||
|
||||
func getBase(options multiTag, base int) (int, error) {
|
||||
sbase := options.Get("base")
|
||||
|
||||
var err error
|
||||
var ivbase int64
|
||||
|
||||
if sbase != "" {
|
||||
ivbase, err = strconv.ParseInt(sbase, 10, 32)
|
||||
base = int(ivbase)
|
||||
}
|
||||
|
||||
return base, err
|
||||
}
|
||||
|
||||
func convertMarshal(val reflect.Value) (bool, string, error) {
|
||||
// Check first for the Marshaler interface
|
||||
if val.Type().NumMethod() > 0 && val.CanInterface() {
|
||||
if marshaler, ok := val.Interface().(Marshaler); ok {
|
||||
ret, err := marshaler.MarshalFlag()
|
||||
return true, ret, err
|
||||
}
|
||||
}
|
||||
|
||||
return false, "", nil
|
||||
}
|
||||
|
||||
func convertToString(val reflect.Value, options multiTag) (string, error) {
|
||||
if ok, ret, err := convertMarshal(val); ok {
|
||||
return ret, err
|
||||
}
|
||||
|
||||
tp := val.Type()
|
||||
|
||||
// Support for time.Duration
|
||||
if tp == reflect.TypeOf((*time.Duration)(nil)).Elem() {
|
||||
stringer := val.Interface().(fmt.Stringer)
|
||||
return stringer.String(), nil
|
||||
}
|
||||
|
||||
switch tp.Kind() {
|
||||
case reflect.String:
|
||||
return val.String(), nil
|
||||
case reflect.Bool:
|
||||
if val.Bool() {
|
||||
return "true", nil
|
||||
}
|
||||
|
||||
return "false", nil
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
base, err := getBase(options, 10)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return strconv.FormatInt(val.Int(), base), nil
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
base, err := getBase(options, 10)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return strconv.FormatUint(val.Uint(), base), nil
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return strconv.FormatFloat(val.Float(), 'g', -1, tp.Bits()), nil
|
||||
case reflect.Slice:
|
||||
if val.Len() == 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
ret := "["
|
||||
|
||||
for i := 0; i < val.Len(); i++ {
|
||||
if i != 0 {
|
||||
ret += ", "
|
||||
}
|
||||
|
||||
item, err := convertToString(val.Index(i), options)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
ret += item
|
||||
}
|
||||
|
||||
return ret + "]", nil
|
||||
case reflect.Map:
|
||||
ret := "{"
|
||||
|
||||
for i, key := range val.MapKeys() {
|
||||
if i != 0 {
|
||||
ret += ", "
|
||||
}
|
||||
|
||||
keyitem, err := convertToString(key, options)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
item, err := convertToString(val.MapIndex(key), options)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
ret += keyitem + ":" + item
|
||||
}
|
||||
|
||||
return ret + "}", nil
|
||||
case reflect.Ptr:
|
||||
return convertToString(reflect.Indirect(val), options)
|
||||
case reflect.Interface:
|
||||
if !val.IsNil() {
|
||||
return convertToString(val.Elem(), options)
|
||||
}
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func convertUnmarshal(val string, retval reflect.Value) (bool, error) {
|
||||
if retval.Type().NumMethod() > 0 && retval.CanInterface() {
|
||||
if unmarshaler, ok := retval.Interface().(Unmarshaler); ok {
|
||||
return true, unmarshaler.UnmarshalFlag(val)
|
||||
}
|
||||
}
|
||||
|
||||
if retval.Type().Kind() != reflect.Ptr && retval.CanAddr() {
|
||||
return convertUnmarshal(val, retval.Addr())
|
||||
}
|
||||
|
||||
if retval.Type().Kind() == reflect.Interface && !retval.IsNil() {
|
||||
return convertUnmarshal(val, retval.Elem())
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func convert(val string, retval reflect.Value, options multiTag) error {
|
||||
if ok, err := convertUnmarshal(val, retval); ok {
|
||||
return err
|
||||
}
|
||||
|
||||
tp := retval.Type()
|
||||
|
||||
// Support for time.Duration
|
||||
if tp == reflect.TypeOf((*time.Duration)(nil)).Elem() {
|
||||
parsed, err := time.ParseDuration(val)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
retval.SetInt(int64(parsed))
|
||||
return nil
|
||||
}
|
||||
|
||||
switch tp.Kind() {
|
||||
case reflect.String:
|
||||
retval.SetString(val)
|
||||
case reflect.Bool:
|
||||
if val == "" {
|
||||
retval.SetBool(true)
|
||||
} else {
|
||||
b, err := strconv.ParseBool(val)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
retval.SetBool(b)
|
||||
}
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
base, err := getBase(options, 10)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
parsed, err := strconv.ParseInt(val, base, tp.Bits())
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
retval.SetInt(parsed)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
base, err := getBase(options, 10)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
parsed, err := strconv.ParseUint(val, base, tp.Bits())
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
retval.SetUint(parsed)
|
||||
case reflect.Float32, reflect.Float64:
|
||||
parsed, err := strconv.ParseFloat(val, tp.Bits())
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
retval.SetFloat(parsed)
|
||||
case reflect.Slice:
|
||||
elemtp := tp.Elem()
|
||||
|
||||
elemvalptr := reflect.New(elemtp)
|
||||
elemval := reflect.Indirect(elemvalptr)
|
||||
|
||||
if err := convert(val, elemval, options); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
retval.Set(reflect.Append(retval, elemval))
|
||||
case reflect.Map:
|
||||
parts := strings.SplitN(val, ":", 2)
|
||||
|
||||
key := parts[0]
|
||||
var value string
|
||||
|
||||
if len(parts) == 2 {
|
||||
value = parts[1]
|
||||
}
|
||||
|
||||
keytp := tp.Key()
|
||||
keyval := reflect.New(keytp)
|
||||
|
||||
if err := convert(key, keyval, options); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
valuetp := tp.Elem()
|
||||
valueval := reflect.New(valuetp)
|
||||
|
||||
if err := convert(value, valueval, options); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if retval.IsNil() {
|
||||
retval.Set(reflect.MakeMap(tp))
|
||||
}
|
||||
|
||||
retval.SetMapIndex(reflect.Indirect(keyval), reflect.Indirect(valueval))
|
||||
case reflect.Ptr:
|
||||
if retval.IsNil() {
|
||||
retval.Set(reflect.New(retval.Type().Elem()))
|
||||
}
|
||||
|
||||
return convert(val, reflect.Indirect(retval), options)
|
||||
case reflect.Interface:
|
||||
if !retval.IsNil() {
|
||||
return convert(val, retval.Elem(), options)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isPrint(s string) bool {
|
||||
for _, c := range s {
|
||||
if !strconv.IsPrint(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func quoteIfNeeded(s string) string {
|
||||
if !isPrint(s) {
|
||||
return strconv.Quote(s)
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func unquoteIfPossible(s string) (string, error) {
|
||||
if len(s) == 0 || s[0] != '"' {
|
||||
return s, nil
|
||||
}
|
||||
|
||||
return strconv.Unquote(s)
|
||||
}
|
||||
|
||||
func wrapText(s string, l int, prefix string) string {
|
||||
// Basic text wrapping of s at spaces to fit in l
|
||||
var ret string
|
||||
|
||||
s = strings.TrimSpace(s)
|
||||
|
||||
for len(s) > l {
|
||||
// Try to split on space
|
||||
suffix := ""
|
||||
|
||||
pos := strings.LastIndex(s[:l], " ")
|
||||
|
||||
if pos < 0 {
|
||||
pos = l - 1
|
||||
suffix = "-\n"
|
||||
}
|
||||
|
||||
if len(ret) != 0 {
|
||||
ret += "\n" + prefix
|
||||
}
|
||||
|
||||
ret += strings.TrimSpace(s[:pos]) + suffix
|
||||
s = strings.TrimSpace(s[pos:])
|
||||
}
|
||||
|
||||
if len(s) > 0 {
|
||||
if len(ret) != 0 {
|
||||
ret += "\n" + prefix
|
||||
}
|
||||
|
||||
return ret + s
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
175
Godeps/_workspace/src/github.com/jessevdk/go-flags/convert_test.go
generated
vendored
Normal file
175
Godeps/_workspace/src/github.com/jessevdk/go-flags/convert_test.go
generated
vendored
Normal file
@ -0,0 +1,175 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func expectConvert(t *testing.T, o *Option, expected string) {
|
||||
s, err := convertToString(o.value, o.tag)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
assertString(t, s, expected)
|
||||
}
|
||||
|
||||
func TestConvertToString(t *testing.T) {
|
||||
d, _ := time.ParseDuration("1h2m4s")
|
||||
|
||||
var opts = struct {
|
||||
String string `long:"string"`
|
||||
|
||||
Int int `long:"int"`
|
||||
Int8 int8 `long:"int8"`
|
||||
Int16 int16 `long:"int16"`
|
||||
Int32 int32 `long:"int32"`
|
||||
Int64 int64 `long:"int64"`
|
||||
|
||||
Uint uint `long:"uint"`
|
||||
Uint8 uint8 `long:"uint8"`
|
||||
Uint16 uint16 `long:"uint16"`
|
||||
Uint32 uint32 `long:"uint32"`
|
||||
Uint64 uint64 `long:"uint64"`
|
||||
|
||||
Float32 float32 `long:"float32"`
|
||||
Float64 float64 `long:"float64"`
|
||||
|
||||
Duration time.Duration `long:"duration"`
|
||||
|
||||
Bool bool `long:"bool"`
|
||||
|
||||
IntSlice []int `long:"int-slice"`
|
||||
IntFloatMap map[int]float64 `long:"int-float-map"`
|
||||
|
||||
PtrBool *bool `long:"ptr-bool"`
|
||||
Interface interface{} `long:"interface"`
|
||||
|
||||
Int32Base int32 `long:"int32-base" base:"16"`
|
||||
Uint32Base uint32 `long:"uint32-base" base:"16"`
|
||||
}{
|
||||
"string",
|
||||
|
||||
-2,
|
||||
-1,
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
|
||||
1.2,
|
||||
-3.4,
|
||||
|
||||
d,
|
||||
true,
|
||||
|
||||
[]int{-3, 4, -2},
|
||||
map[int]float64{-2: 4.5},
|
||||
|
||||
new(bool),
|
||||
float32(5.2),
|
||||
|
||||
-5823,
|
||||
4232,
|
||||
}
|
||||
|
||||
p := NewNamedParser("test", Default)
|
||||
grp, _ := p.AddGroup("test group", "", &opts)
|
||||
|
||||
expects := []string{
|
||||
"string",
|
||||
"-2",
|
||||
"-1",
|
||||
"0",
|
||||
"1",
|
||||
"2",
|
||||
|
||||
"1",
|
||||
"2",
|
||||
"3",
|
||||
"4",
|
||||
"5",
|
||||
|
||||
"1.2",
|
||||
"-3.4",
|
||||
|
||||
"1h2m4s",
|
||||
"true",
|
||||
|
||||
"[-3, 4, -2]",
|
||||
"{-2:4.5}",
|
||||
|
||||
"false",
|
||||
"5.2",
|
||||
|
||||
"-16bf",
|
||||
"1088",
|
||||
}
|
||||
|
||||
for i, v := range grp.Options() {
|
||||
expectConvert(t, v, expects[i])
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertToStringInvalidIntBase(t *testing.T) {
|
||||
var opts = struct {
|
||||
Int int `long:"int" base:"no"`
|
||||
}{
|
||||
2,
|
||||
}
|
||||
|
||||
p := NewNamedParser("test", Default)
|
||||
grp, _ := p.AddGroup("test group", "", &opts)
|
||||
o := grp.Options()[0]
|
||||
|
||||
_, err := convertToString(o.value, o.tag)
|
||||
|
||||
if err != nil {
|
||||
err = newErrorf(ErrMarshal, "%v", err)
|
||||
}
|
||||
|
||||
assertError(t, err, ErrMarshal, "strconv.ParseInt: parsing \"no\": invalid syntax")
|
||||
}
|
||||
|
||||
func TestConvertToStringInvalidUintBase(t *testing.T) {
|
||||
var opts = struct {
|
||||
Uint uint `long:"uint" base:"no"`
|
||||
}{
|
||||
2,
|
||||
}
|
||||
|
||||
p := NewNamedParser("test", Default)
|
||||
grp, _ := p.AddGroup("test group", "", &opts)
|
||||
o := grp.Options()[0]
|
||||
|
||||
_, err := convertToString(o.value, o.tag)
|
||||
|
||||
if err != nil {
|
||||
err = newErrorf(ErrMarshal, "%v", err)
|
||||
}
|
||||
|
||||
assertError(t, err, ErrMarshal, "strconv.ParseInt: parsing \"no\": invalid syntax")
|
||||
}
|
||||
|
||||
func TestWrapText(t *testing.T) {
|
||||
s := "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
|
||||
|
||||
got := wrapText(s, 60, " ")
|
||||
expected := `Lorem ipsum dolor sit amet, consectetur adipisicing elit,
|
||||
sed do eiusmod tempor incididunt ut labore et dolore magna
|
||||
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
|
||||
ullamco laboris nisi ut aliquip ex ea commodo consequat.
|
||||
Duis aute irure dolor in reprehenderit in voluptate velit
|
||||
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
|
||||
occaecat cupidatat non proident, sunt in culpa qui officia
|
||||
deserunt mollit anim id est laborum.`
|
||||
|
||||
assertDiff(t, got, expected, "wrapped text")
|
||||
}
|
123
Godeps/_workspace/src/github.com/jessevdk/go-flags/error.go
generated
vendored
Normal file
123
Godeps/_workspace/src/github.com/jessevdk/go-flags/error.go
generated
vendored
Normal file
@ -0,0 +1,123 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ErrorType represents the type of error.
|
||||
type ErrorType uint
|
||||
|
||||
const (
|
||||
// ErrUnknown indicates a generic error.
|
||||
ErrUnknown ErrorType = iota
|
||||
|
||||
// ErrExpectedArgument indicates that an argument was expected.
|
||||
ErrExpectedArgument
|
||||
|
||||
// ErrUnknownFlag indicates an unknown flag.
|
||||
ErrUnknownFlag
|
||||
|
||||
// ErrUnknownGroup indicates an unknown group.
|
||||
ErrUnknownGroup
|
||||
|
||||
// ErrMarshal indicates a marshalling error while converting values.
|
||||
ErrMarshal
|
||||
|
||||
// ErrHelp indicates that the built-in help was shown (the error
|
||||
// contains the help message).
|
||||
ErrHelp
|
||||
|
||||
// ErrNoArgumentForBool indicates that an argument was given for a
|
||||
// boolean flag (which don't not take any arguments).
|
||||
ErrNoArgumentForBool
|
||||
|
||||
// ErrRequired indicates that a required flag was not provided.
|
||||
ErrRequired
|
||||
|
||||
// ErrShortNameTooLong indicates that a short flag name was specified,
|
||||
// longer than one character.
|
||||
ErrShortNameTooLong
|
||||
|
||||
// ErrDuplicatedFlag indicates that a short or long flag has been
|
||||
// defined more than once
|
||||
ErrDuplicatedFlag
|
||||
|
||||
// ErrTag indicates an error while parsing flag tags.
|
||||
ErrTag
|
||||
|
||||
// ErrCommandRequired indicates that a command was required but not
|
||||
// specified
|
||||
ErrCommandRequired
|
||||
|
||||
// ErrUnknownCommand indicates that an unknown command was specified.
|
||||
ErrUnknownCommand
|
||||
)
|
||||
|
||||
func (e ErrorType) String() string {
|
||||
switch e {
|
||||
case ErrUnknown:
|
||||
return "unknown"
|
||||
case ErrExpectedArgument:
|
||||
return "expected argument"
|
||||
case ErrUnknownFlag:
|
||||
return "unknown flag"
|
||||
case ErrUnknownGroup:
|
||||
return "unknown group"
|
||||
case ErrMarshal:
|
||||
return "marshal"
|
||||
case ErrHelp:
|
||||
return "help"
|
||||
case ErrNoArgumentForBool:
|
||||
return "no argument for bool"
|
||||
case ErrRequired:
|
||||
return "required"
|
||||
case ErrShortNameTooLong:
|
||||
return "short name too long"
|
||||
case ErrDuplicatedFlag:
|
||||
return "duplicated flag"
|
||||
case ErrTag:
|
||||
return "tag"
|
||||
case ErrCommandRequired:
|
||||
return "command required"
|
||||
case ErrUnknownCommand:
|
||||
return "unknown command"
|
||||
}
|
||||
|
||||
return "unrecognized error type"
|
||||
}
|
||||
|
||||
// Error represents a parser error. The error returned from Parse is of this
|
||||
// type. The error contains both a Type and Message.
|
||||
type Error struct {
|
||||
// The type of error
|
||||
Type ErrorType
|
||||
|
||||
// The error message
|
||||
Message string
|
||||
}
|
||||
|
||||
// Error returns the error's message
|
||||
func (e *Error) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func newError(tp ErrorType, message string) *Error {
|
||||
return &Error{
|
||||
Type: tp,
|
||||
Message: message,
|
||||
}
|
||||
}
|
||||
|
||||
func newErrorf(tp ErrorType, format string, args ...interface{}) *Error {
|
||||
return newError(tp, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
func wrapError(err error) *Error {
|
||||
ret, ok := err.(*Error)
|
||||
|
||||
if !ok {
|
||||
return newError(ErrUnknown, err.Error())
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
110
Godeps/_workspace/src/github.com/jessevdk/go-flags/example_test.go
generated
vendored
Normal file
110
Godeps/_workspace/src/github.com/jessevdk/go-flags/example_test.go
generated
vendored
Normal file
@ -0,0 +1,110 @@
|
||||
// Example of use of the flags package.
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func Example() {
|
||||
var opts struct {
|
||||
// Slice of bool will append 'true' each time the option
|
||||
// is encountered (can be set multiple times, like -vvv)
|
||||
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
|
||||
|
||||
// Example of automatic marshalling to desired type (uint)
|
||||
Offset uint `long:"offset" description:"Offset"`
|
||||
|
||||
// Example of a callback, called each time the option is found.
|
||||
Call func(string) `short:"c" description:"Call phone number"`
|
||||
|
||||
// Example of a required flag
|
||||
Name string `short:"n" long:"name" description:"A name" required:"true"`
|
||||
|
||||
// Example of a value name
|
||||
File string `short:"f" long:"file" description:"A file" value-name:"FILE"`
|
||||
|
||||
// Example of a pointer
|
||||
Ptr *int `short:"p" description:"A pointer to an integer"`
|
||||
|
||||
// Example of a slice of strings
|
||||
StringSlice []string `short:"s" description:"A slice of strings"`
|
||||
|
||||
// Example of a slice of pointers
|
||||
PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"`
|
||||
|
||||
// Example of a map
|
||||
IntMap map[string]int `long:"intmap" description:"A map from string to int"`
|
||||
|
||||
// Example of a filename (useful for completion)
|
||||
Filename Filename `long:"filename" description:"A filename"`
|
||||
|
||||
// Example of positional arguments
|
||||
Args struct {
|
||||
Id string
|
||||
Num int
|
||||
Rest []string
|
||||
} `positional-args:"yes" required:"yes"`
|
||||
}
|
||||
|
||||
// Callback which will invoke callto:<argument> to call a number.
|
||||
// Note that this works just on OS X (and probably only with
|
||||
// Skype) but it shows the idea.
|
||||
opts.Call = func(num string) {
|
||||
cmd := exec.Command("open", "callto:"+num)
|
||||
cmd.Start()
|
||||
cmd.Process.Release()
|
||||
}
|
||||
|
||||
// Make some fake arguments to parse.
|
||||
args := []string{
|
||||
"-vv",
|
||||
"--offset=5",
|
||||
"-n", "Me",
|
||||
"-p", "3",
|
||||
"-s", "hello",
|
||||
"-s", "world",
|
||||
"--ptrslice", "hello",
|
||||
"--ptrslice", "world",
|
||||
"--intmap", "a:1",
|
||||
"--intmap", "b:5",
|
||||
"--filename", "hello.go",
|
||||
"id",
|
||||
"10",
|
||||
"remaining1",
|
||||
"remaining2",
|
||||
}
|
||||
|
||||
// Parse flags from `args'. Note that here we use flags.ParseArgs for
|
||||
// the sake of making a working example. Normally, you would simply use
|
||||
// flags.Parse(&opts) which uses os.Args
|
||||
_, err := ParseArgs(&opts, args)
|
||||
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Printf("Verbosity: %v\n", opts.Verbose)
|
||||
fmt.Printf("Offset: %d\n", opts.Offset)
|
||||
fmt.Printf("Name: %s\n", opts.Name)
|
||||
fmt.Printf("Ptr: %d\n", *opts.Ptr)
|
||||
fmt.Printf("StringSlice: %v\n", opts.StringSlice)
|
||||
fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1])
|
||||
fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"])
|
||||
fmt.Printf("Filename: %v\n", opts.Filename)
|
||||
fmt.Printf("Args.Id: %s\n", opts.Args.Id)
|
||||
fmt.Printf("Args.Num: %d\n", opts.Args.Num)
|
||||
fmt.Printf("Args.Rest: %v\n", opts.Args.Rest)
|
||||
|
||||
// Output: Verbosity: [true true]
|
||||
// Offset: 5
|
||||
// Name: Me
|
||||
// Ptr: 3
|
||||
// StringSlice: [hello world]
|
||||
// PtrSlice: [hello world]
|
||||
// IntMap: [a:1 b:5]
|
||||
// Filename: hello.go
|
||||
// Args.Id: id
|
||||
// Args.Num: 10
|
||||
// Args.Rest: [remaining1 remaining2]
|
||||
}
|
23
Godeps/_workspace/src/github.com/jessevdk/go-flags/examples/add.go
generated
vendored
Normal file
23
Godeps/_workspace/src/github.com/jessevdk/go-flags/examples/add.go
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type AddCommand struct {
|
||||
All bool `short:"a" long:"all" description:"Add all files"`
|
||||
}
|
||||
|
||||
var addCommand AddCommand
|
||||
|
||||
func (x *AddCommand) Execute(args []string) error {
|
||||
fmt.Printf("Adding (all=%v): %#v\n", x.All, args)
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
parser.AddCommand("add",
|
||||
"Add a file",
|
||||
"The add command adds a file to the repository. Use -a to add all files.",
|
||||
&addCommand)
|
||||
}
|
9
Godeps/_workspace/src/github.com/jessevdk/go-flags/examples/bash-completion
generated
vendored
Normal file
9
Godeps/_workspace/src/github.com/jessevdk/go-flags/examples/bash-completion
generated
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
_examples() {
|
||||
args=("${COMP_WORDS[@]:1:$COMP_CWORD}")
|
||||
|
||||
local IFS=$'\n'
|
||||
COMPREPLY=($(GO_FLAGS_COMPLETION=1 ${COMP_WORDS[0]} "${args[@]}"))
|
||||
return 1
|
||||
}
|
||||
|
||||
complete -F _examples examples
|
75
Godeps/_workspace/src/github.com/jessevdk/go-flags/examples/main.go
generated
vendored
Normal file
75
Godeps/_workspace/src/github.com/jessevdk/go-flags/examples/main.go
generated
vendored
Normal file
@ -0,0 +1,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jessevdk/go-flags"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type EditorOptions struct {
|
||||
Input flags.Filename `short:"i" long:"input" description:"Input file" default:"-"`
|
||||
Output flags.Filename `short:"o" long:"output" description:"Output file" default:"-"`
|
||||
}
|
||||
|
||||
type Point struct {
|
||||
X, Y int
|
||||
}
|
||||
|
||||
func (p *Point) UnmarshalFlag(value string) error {
|
||||
parts := strings.Split(value, ",")
|
||||
|
||||
if len(parts) != 2 {
|
||||
return errors.New("expected two numbers separated by a ,")
|
||||
}
|
||||
|
||||
x, err := strconv.ParseInt(parts[0], 10, 32)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
y, err := strconv.ParseInt(parts[1], 10, 32)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
p.X = int(x)
|
||||
p.Y = int(y)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p Point) MarshalFlag() (string, error) {
|
||||
return fmt.Sprintf("%d,%d", p.X, p.Y), nil
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
// Example of verbosity with level
|
||||
Verbose []bool `short:"v" long:"verbose" description:"Verbose output"`
|
||||
|
||||
// Example of optional value
|
||||
User string `short:"u" long:"user" description:"User name" optional:"yes" optional-value:"pancake"`
|
||||
|
||||
// Example of map with multiple default values
|
||||
Users map[string]string `long:"users" description:"User e-mail map" default:"system:system@example.org" default:"admin:admin@example.org"`
|
||||
|
||||
// Example of option group
|
||||
Editor EditorOptions `group:"Editor Options"`
|
||||
|
||||
// Example of custom type Marshal/Unmarshal
|
||||
Point Point `long:"point" description:"A x,y point" default:"1,2"`
|
||||
}
|
||||
|
||||
var options Options
|
||||
|
||||
var parser = flags.NewParser(&options, flags.Default)
|
||||
|
||||
func main() {
|
||||
if _, err := parser.Parse(); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
23
Godeps/_workspace/src/github.com/jessevdk/go-flags/examples/rm.go
generated
vendored
Normal file
23
Godeps/_workspace/src/github.com/jessevdk/go-flags/examples/rm.go
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type RmCommand struct {
|
||||
Force bool `short:"f" long:"force" description:"Force removal of files"`
|
||||
}
|
||||
|
||||
var rmCommand RmCommand
|
||||
|
||||
func (x *RmCommand) Execute(args []string) error {
|
||||
fmt.Printf("Removing (force=%v): %#v\n", x.Force, args)
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
parser.AddCommand("rm",
|
||||
"Remove a file",
|
||||
"The rm command removes a file to the repository. Use -f to force removal of files.",
|
||||
&rmCommand)
|
||||
}
|
238
Godeps/_workspace/src/github.com/jessevdk/go-flags/flags.go
generated
vendored
Normal file
238
Godeps/_workspace/src/github.com/jessevdk/go-flags/flags.go
generated
vendored
Normal file
@ -0,0 +1,238 @@
|
||||
// Copyright 2012 Jesse van den Kieboom. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package flags provides an extensive command line option parser.
|
||||
The flags package is similar in functionality to the go built-in flag package
|
||||
but provides more options and uses reflection to provide a convenient and
|
||||
succinct way of specifying command line options.
|
||||
|
||||
|
||||
Supported features
|
||||
|
||||
The following features are supported in go-flags:
|
||||
|
||||
Options with short names (-v)
|
||||
Options with long names (--verbose)
|
||||
Options with and without arguments (bool v.s. other type)
|
||||
Options with optional arguments and default values
|
||||
Option default values from ENVIRONMENT_VARIABLES, including slice and map values
|
||||
Multiple option groups each containing a set of options
|
||||
Generate and print well-formatted help message
|
||||
Passing remaining command line arguments after -- (optional)
|
||||
Ignoring unknown command line options (optional)
|
||||
Supports -I/usr/include -I=/usr/include -I /usr/include option argument specification
|
||||
Supports multiple short options -aux
|
||||
Supports all primitive go types (string, int{8..64}, uint{8..64}, float)
|
||||
Supports same option multiple times (can store in slice or last option counts)
|
||||
Supports maps
|
||||
Supports function callbacks
|
||||
Supports namespaces for (nested) option groups
|
||||
|
||||
Additional features specific to Windows:
|
||||
Options with short names (/v)
|
||||
Options with long names (/verbose)
|
||||
Windows-style options with arguments use a colon as the delimiter
|
||||
Modify generated help message with Windows-style / options
|
||||
|
||||
|
||||
Basic usage
|
||||
|
||||
The flags package uses structs, reflection and struct field tags
|
||||
to allow users to specify command line options. This results in very simple
|
||||
and concise specification of your application options. For example:
|
||||
|
||||
type Options struct {
|
||||
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
|
||||
}
|
||||
|
||||
This specifies one option with a short name -v and a long name --verbose.
|
||||
When either -v or --verbose is found on the command line, a 'true' value
|
||||
will be appended to the Verbose field. e.g. when specifying -vvv, the
|
||||
resulting value of Verbose will be {[true, true, true]}.
|
||||
|
||||
Slice options work exactly the same as primitive type options, except that
|
||||
whenever the option is encountered, a value is appended to the slice.
|
||||
|
||||
Map options from string to primitive type are also supported. On the command
|
||||
line, you specify the value for such an option as key:value. For example
|
||||
|
||||
type Options struct {
|
||||
AuthorInfo string[string] `short:"a"`
|
||||
}
|
||||
|
||||
Then, the AuthorInfo map can be filled with something like
|
||||
-a name:Jesse -a "surname:van den Kieboom".
|
||||
|
||||
Finally, for full control over the conversion between command line argument
|
||||
values and options, user defined types can choose to implement the Marshaler
|
||||
and Unmarshaler interfaces.
|
||||
|
||||
|
||||
Available field tags
|
||||
|
||||
The following is a list of tags for struct fields supported by go-flags:
|
||||
|
||||
short: the short name of the option (single character)
|
||||
long: the long name of the option
|
||||
required: whether an option is required to appear on the command
|
||||
line. If a required option is not present, the parser will
|
||||
return ErrRequired (optional)
|
||||
description: the description of the option (optional)
|
||||
long-description: the long description of the option. Currently only
|
||||
displayed in generated man pages (optional)
|
||||
no-flag: if non-empty this field is ignored as an option (optional)
|
||||
|
||||
optional: whether an argument of the option is optional (optional)
|
||||
optional-value: the value of an optional option when the option occurs
|
||||
without an argument. This tag can be specified multiple
|
||||
times in the case of maps or slices (optional)
|
||||
default: the default value of an option. This tag can be specified
|
||||
multiple times in the case of slices or maps (optional)
|
||||
default-mask: when specified, this value will be displayed in the help
|
||||
instead of the actual default value. This is useful
|
||||
mostly for hiding otherwise sensitive information from
|
||||
showing up in the help. If default-mask takes the special
|
||||
value "-", then no default value will be shown at all
|
||||
(optional)
|
||||
env: the default value of the option is overridden from the
|
||||
specified environment variable, if one has been defined.
|
||||
(optional)
|
||||
env-delim: the 'env' default value from environment is split into
|
||||
multiple values with the given delimiter string, use with
|
||||
slices and maps (optional)
|
||||
value-name: the name of the argument value (to be shown in the help,
|
||||
(optional)
|
||||
|
||||
base: a base (radix) used to convert strings to integer values, the
|
||||
default base is 10 (i.e. decimal) (optional)
|
||||
|
||||
ini-name: the explicit ini option name (optional)
|
||||
no-ini: if non-empty this field is ignored as an ini option
|
||||
(optional)
|
||||
|
||||
group: when specified on a struct field, makes the struct
|
||||
field a separate group with the given name (optional)
|
||||
namespace: when specified on a group struct field, the namespace
|
||||
gets prepended to every option's long name and
|
||||
subgroup's namespace of this group, separated by
|
||||
the parser's namespace delimiter (optional)
|
||||
command: when specified on a struct field, makes the struct
|
||||
field a (sub)command with the given name (optional)
|
||||
subcommands-optional: when specified on a command struct field, makes
|
||||
any subcommands of that command optional (optional)
|
||||
alias: when specified on a command struct field, adds the
|
||||
specified name as an alias for the command. Can be
|
||||
be specified multiple times to add more than one
|
||||
alias (optional)
|
||||
positional-args: when specified on a field with a struct type,
|
||||
uses the fields of that struct to parse remaining
|
||||
positional command line arguments into (in order
|
||||
of the fields). If a field has a slice type,
|
||||
then all remaining arguments will be added to it.
|
||||
Positional arguments are optional by default,
|
||||
unless the "required" tag is specified together
|
||||
with the "positional-args" tag (optional)
|
||||
|
||||
Either the `short:` tag or the `long:` must be specified to make the field eligible as an
|
||||
option.
|
||||
|
||||
|
||||
Option groups
|
||||
|
||||
Option groups are a simple way to semantically separate your options. All
|
||||
options in a particular group are shown together in the help under the name
|
||||
of the group. Namespaces can be used to specify option long names more
|
||||
precisely and emphasize the options affiliation to their group.
|
||||
|
||||
There are currently three ways to specify option groups.
|
||||
|
||||
1. Use NewNamedParser specifying the various option groups.
|
||||
2. Use AddGroup to add a group to an existing parser.
|
||||
3. Add a struct field to the top-level options annotated with the
|
||||
group:"group-name" tag.
|
||||
|
||||
|
||||
|
||||
Commands
|
||||
|
||||
The flags package also has basic support for commands. Commands are often
|
||||
used in monolithic applications that support various commands or actions.
|
||||
Take git for example, all of the add, commit, checkout, etc. are called
|
||||
commands. Using commands you can easily separate multiple functions of your
|
||||
application.
|
||||
|
||||
There are currently two ways to specify a command.
|
||||
|
||||
1. Use AddCommand on an existing parser.
|
||||
2. Add a struct field to your options struct annotated with the
|
||||
command:"command-name" tag.
|
||||
|
||||
The most common, idiomatic way to implement commands is to define a global
|
||||
parser instance and implement each command in a separate file. These
|
||||
command files should define a go init function which calls AddCommand on
|
||||
the global parser.
|
||||
|
||||
When parsing ends and there is an active command and that command implements
|
||||
the Commander interface, then its Execute method will be run with the
|
||||
remaining command line arguments.
|
||||
|
||||
Command structs can have options which become valid to parse after the
|
||||
command has been specified on the command line. It is currently not valid
|
||||
to specify options from the parent level of the command after the command
|
||||
name has occurred. Thus, given a top-level option "-v" and a command "add":
|
||||
|
||||
Valid: ./app -v add
|
||||
Invalid: ./app add -v
|
||||
|
||||
|
||||
Completion
|
||||
|
||||
go-flags has builtin support to provide bash completion of flags, commands
|
||||
and argument values. To use completion, the binary which uses go-flags
|
||||
can be invoked in a special environment to list completion of the current
|
||||
command line argument. It should be noted that this `executes` your application,
|
||||
and it is up to the user to make sure there are no negative side effects (for
|
||||
example from init functions).
|
||||
|
||||
Setting the environment variable `GO_FLAGS_COMPLETION=1` enables completion
|
||||
by replacing the argument parsing routine with the completion routine which
|
||||
outputs completions for the passed arguments. The basic invocation to
|
||||
complete a set of arguments is therefore:
|
||||
|
||||
GO_FLAGS_COMPLETION=1 ./completion-example arg1 arg2 arg3
|
||||
|
||||
where `completion-example` is the binary, `arg1` and `arg2` are
|
||||
the current arguments, and `arg3` (the last argument) is the argument
|
||||
to be completed. If the GO_FLAGS_COMPLETION is set to "verbose", then
|
||||
descriptions of possible completion items will also be shown, if there
|
||||
are more than 1 completion items.
|
||||
|
||||
To use this with bash completion, a simple file can be written which
|
||||
calls the binary which supports go-flags completion:
|
||||
|
||||
_completion_example() {
|
||||
# All arguments except the first one
|
||||
args=("${COMP_WORDS[@]:1:$COMP_CWORD}")
|
||||
|
||||
# Only split on newlines
|
||||
local IFS=$'\n'
|
||||
|
||||
# Call completion (note that the first element of COMP_WORDS is
|
||||
# the executable itself)
|
||||
COMPREPLY=($(GO_FLAGS_COMPLETION=1 ${COMP_WORDS[0]} "${args[@]}"))
|
||||
return 0
|
||||
}
|
||||
|
||||
complete -F _completion_example completion-example
|
||||
|
||||
Completion requires the parser option PassDoubleDash and is therefore enforced if the environment variable GO_FLAGS_COMPLETION is set.
|
||||
|
||||
Customized completion for argument values is supported by implementing
|
||||
the flags.Completer interface for the argument value type. An example
|
||||
of a type which does so is the flags.Filename type, an alias of string
|
||||
allowing simple filename completion. A slice or array argument value
|
||||
whose element type implements flags.Completer will also be completed.
|
||||
*/
|
||||
package flags
|
91
Godeps/_workspace/src/github.com/jessevdk/go-flags/group.go
generated
vendored
Normal file
91
Godeps/_workspace/src/github.com/jessevdk/go-flags/group.go
generated
vendored
Normal file
@ -0,0 +1,91 @@
|
||||
// Copyright 2012 Jesse van den Kieboom. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package flags
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrNotPointerToStruct indicates that a provided data container is not
|
||||
// a pointer to a struct. Only pointers to structs are valid data containers
|
||||
// for options.
|
||||
var ErrNotPointerToStruct = errors.New("provided data is not a pointer to struct")
|
||||
|
||||
// Group represents an option group. Option groups can be used to logically
|
||||
// group options together under a description. Groups are only used to provide
|
||||
// more structure to options both for the user (as displayed in the help message)
|
||||
// and for you, since groups can be nested.
|
||||
type Group struct {
|
||||
// A short description of the group. The
|
||||
// short description is primarily used in the built-in generated help
|
||||
// message
|
||||
ShortDescription string
|
||||
|
||||
// A long description of the group. The long
|
||||
// description is primarily used to present information on commands
|
||||
// (Command embeds Group) in the built-in generated help and man pages.
|
||||
LongDescription string
|
||||
|
||||
// The namespace of the group
|
||||
Namespace string
|
||||
|
||||
// The parent of the group or nil if it has no parent
|
||||
parent interface{}
|
||||
|
||||
// All the options in the group
|
||||
options []*Option
|
||||
|
||||
// All the subgroups
|
||||
groups []*Group
|
||||
|
||||
// Whether the group represents the built-in help group
|
||||
isBuiltinHelp bool
|
||||
|
||||
data interface{}
|
||||
}
|
||||
|
||||
// AddGroup adds a new group to the command with the given name and data. The
|
||||
// data needs to be a pointer to a struct from which the fields indicate which
|
||||
// options are in the group.
|
||||
func (g *Group) AddGroup(shortDescription string, longDescription string, data interface{}) (*Group, error) {
|
||||
group := newGroup(shortDescription, longDescription, data)
|
||||
|
||||
group.parent = g
|
||||
|
||||
if err := group.scan(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
g.groups = append(g.groups, group)
|
||||
return group, nil
|
||||
}
|
||||
|
||||
// Groups returns the list of groups embedded in this group.
|
||||
func (g *Group) Groups() []*Group {
|
||||
return g.groups
|
||||
}
|
||||
|
||||
// Options returns the list of options in this group.
|
||||
func (g *Group) Options() []*Option {
|
||||
return g.options
|
||||
}
|
||||
|
||||
// Find locates the subgroup with the given short description and returns it.
|
||||
// If no such group can be found Find will return nil. Note that the description
|
||||
// is matched case insensitively.
|
||||
func (g *Group) Find(shortDescription string) *Group {
|
||||
lshortDescription := strings.ToLower(shortDescription)
|
||||
|
||||
var ret *Group
|
||||
|
||||
g.eachGroup(func(gg *Group) {
|
||||
if gg != g && strings.ToLower(gg.ShortDescription) == lshortDescription {
|
||||
ret = gg
|
||||
}
|
||||
})
|
||||
|
||||
return ret
|
||||
}
|
254
Godeps/_workspace/src/github.com/jessevdk/go-flags/group_private.go
generated
vendored
Normal file
254
Godeps/_workspace/src/github.com/jessevdk/go-flags/group_private.go
generated
vendored
Normal file
@ -0,0 +1,254 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"unicode/utf8"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type scanHandler func(reflect.Value, *reflect.StructField) (bool, error)
|
||||
|
||||
func newGroup(shortDescription string, longDescription string, data interface{}) *Group {
|
||||
return &Group{
|
||||
ShortDescription: shortDescription,
|
||||
LongDescription: longDescription,
|
||||
|
||||
data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Group) optionByName(name string, namematch func(*Option, string) bool) *Option {
|
||||
prio := 0
|
||||
var retopt *Option
|
||||
|
||||
for _, opt := range g.options {
|
||||
if namematch != nil && namematch(opt, name) && prio < 4 {
|
||||
retopt = opt
|
||||
prio = 4
|
||||
}
|
||||
|
||||
if name == opt.field.Name && prio < 3 {
|
||||
retopt = opt
|
||||
prio = 3
|
||||
}
|
||||
|
||||
if name == opt.LongNameWithNamespace() && prio < 2 {
|
||||
retopt = opt
|
||||
prio = 2
|
||||
}
|
||||
|
||||
if opt.ShortName != 0 && name == string(opt.ShortName) && prio < 1 {
|
||||
retopt = opt
|
||||
prio = 1
|
||||
}
|
||||
}
|
||||
|
||||
return retopt
|
||||
}
|
||||
|
||||
func (g *Group) eachGroup(f func(*Group)) {
|
||||
f(g)
|
||||
|
||||
for _, gg := range g.groups {
|
||||
gg.eachGroup(f)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Group) scanStruct(realval reflect.Value, sfield *reflect.StructField, handler scanHandler) error {
|
||||
stype := realval.Type()
|
||||
|
||||
if sfield != nil {
|
||||
if ok, err := handler(realval, sfield); err != nil {
|
||||
return err
|
||||
} else if ok {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < stype.NumField(); i++ {
|
||||
field := stype.Field(i)
|
||||
|
||||
// PkgName is set only for non-exported fields, which we ignore
|
||||
if field.PkgPath != "" {
|
||||
continue
|
||||
}
|
||||
|
||||
mtag := newMultiTag(string(field.Tag))
|
||||
|
||||
if err := mtag.Parse(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Skip fields with the no-flag tag
|
||||
if mtag.Get("no-flag") != "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Dive deep into structs or pointers to structs
|
||||
kind := field.Type.Kind()
|
||||
fld := realval.Field(i)
|
||||
|
||||
if kind == reflect.Struct {
|
||||
if err := g.scanStruct(fld, &field, handler); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if kind == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct {
|
||||
if fld.IsNil() {
|
||||
fld.Set(reflect.New(fld.Type().Elem()))
|
||||
}
|
||||
|
||||
if err := g.scanStruct(reflect.Indirect(fld), &field, handler); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
longname := mtag.Get("long")
|
||||
shortname := mtag.Get("short")
|
||||
|
||||
// Need at least either a short or long name
|
||||
if longname == "" && shortname == "" && mtag.Get("ini-name") == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
short := rune(0)
|
||||
rc := utf8.RuneCountInString(shortname)
|
||||
|
||||
if rc > 1 {
|
||||
return newErrorf(ErrShortNameTooLong,
|
||||
"short names can only be 1 character long, not `%s'",
|
||||
shortname)
|
||||
|
||||
} else if rc == 1 {
|
||||
short, _ = utf8.DecodeRuneInString(shortname)
|
||||
}
|
||||
|
||||
description := mtag.Get("description")
|
||||
def := mtag.GetMany("default")
|
||||
|
||||
optionalValue := mtag.GetMany("optional-value")
|
||||
valueName := mtag.Get("value-name")
|
||||
defaultMask := mtag.Get("default-mask")
|
||||
|
||||
optional := (mtag.Get("optional") != "")
|
||||
required := (mtag.Get("required") != "")
|
||||
|
||||
option := &Option{
|
||||
Description: description,
|
||||
ShortName: short,
|
||||
LongName: longname,
|
||||
Default: def,
|
||||
EnvDefaultKey: mtag.Get("env"),
|
||||
EnvDefaultDelim: mtag.Get("env-delim"),
|
||||
OptionalArgument: optional,
|
||||
OptionalValue: optionalValue,
|
||||
Required: required,
|
||||
ValueName: valueName,
|
||||
DefaultMask: defaultMask,
|
||||
|
||||
group: g,
|
||||
|
||||
field: field,
|
||||
value: realval.Field(i),
|
||||
tag: mtag,
|
||||
}
|
||||
|
||||
g.options = append(g.options, option)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *Group) checkForDuplicateFlags() *Error {
|
||||
shortNames := make(map[rune]*Option)
|
||||
longNames := make(map[string]*Option)
|
||||
|
||||
var duplicateError *Error
|
||||
|
||||
g.eachGroup(func(g *Group) {
|
||||
for _, option := range g.options {
|
||||
if option.LongName != "" {
|
||||
longName := option.LongNameWithNamespace()
|
||||
|
||||
if otherOption, ok := longNames[longName]; ok {
|
||||
duplicateError = newErrorf(ErrDuplicatedFlag, "option `%s' uses the same long name as option `%s'", option, otherOption)
|
||||
return
|
||||
}
|
||||
longNames[longName] = option
|
||||
}
|
||||
if option.ShortName != 0 {
|
||||
if otherOption, ok := shortNames[option.ShortName]; ok {
|
||||
duplicateError = newErrorf(ErrDuplicatedFlag, "option `%s' uses the same short name as option `%s'", option, otherOption)
|
||||
return
|
||||
}
|
||||
shortNames[option.ShortName] = option
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return duplicateError
|
||||
}
|
||||
|
||||
func (g *Group) scanSubGroupHandler(realval reflect.Value, sfield *reflect.StructField) (bool, error) {
|
||||
mtag := newMultiTag(string(sfield.Tag))
|
||||
|
||||
if err := mtag.Parse(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
|
||||
subgroup := mtag.Get("group")
|
||||
|
||||
if len(subgroup) != 0 {
|
||||
ptrval := reflect.NewAt(realval.Type(), unsafe.Pointer(realval.UnsafeAddr()))
|
||||
description := mtag.Get("description")
|
||||
|
||||
group, err := g.AddGroup(subgroup, description, ptrval.Interface())
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
|
||||
group.Namespace = mtag.Get("namespace")
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (g *Group) scanType(handler scanHandler) error {
|
||||
// Get all the public fields in the data struct
|
||||
ptrval := reflect.ValueOf(g.data)
|
||||
|
||||
if ptrval.Type().Kind() != reflect.Ptr {
|
||||
panic(ErrNotPointerToStruct)
|
||||
}
|
||||
|
||||
stype := ptrval.Type().Elem()
|
||||
|
||||
if stype.Kind() != reflect.Struct {
|
||||
panic(ErrNotPointerToStruct)
|
||||
}
|
||||
|
||||
realval := reflect.Indirect(ptrval)
|
||||
|
||||
if err := g.scanStruct(realval, nil, handler); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := g.checkForDuplicateFlags(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *Group) scan() error {
|
||||
return g.scanType(g.scanSubGroupHandler)
|
||||
}
|
||||
|
||||
func (g *Group) groupByName(name string) *Group {
|
||||
if len(name) == 0 {
|
||||
return g
|
||||
}
|
||||
|
||||
return g.Find(name)
|
||||
}
|
187
Godeps/_workspace/src/github.com/jessevdk/go-flags/group_test.go
generated
vendored
Normal file
187
Godeps/_workspace/src/github.com/jessevdk/go-flags/group_test.go
generated
vendored
Normal file
@ -0,0 +1,187 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGroupInline(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Group struct {
|
||||
G bool `short:"g"`
|
||||
} `group:"Grouped Options"`
|
||||
}{}
|
||||
|
||||
p, ret := assertParserSuccess(t, &opts, "-v", "-g")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
|
||||
if !opts.Group.G {
|
||||
t.Errorf("Expected Group.G to be true")
|
||||
}
|
||||
|
||||
if p.Command.Group.Find("Grouped Options") == nil {
|
||||
t.Errorf("Expected to find group `Grouped Options'")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupAdd(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
}{}
|
||||
|
||||
var grp = struct {
|
||||
G bool `short:"g"`
|
||||
}{}
|
||||
|
||||
p := NewParser(&opts, Default)
|
||||
g, err := p.AddGroup("Grouped Options", "", &grp)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
ret, err := p.ParseArgs([]string{"-v", "-g", "rest"})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
assertStringArray(t, ret, []string{"rest"})
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
|
||||
if !grp.G {
|
||||
t.Errorf("Expected Group.G to be true")
|
||||
}
|
||||
|
||||
if p.Command.Group.Find("Grouped Options") != g {
|
||||
t.Errorf("Expected to find group `Grouped Options'")
|
||||
}
|
||||
|
||||
if p.Groups()[1] != g {
|
||||
t.Errorf("Expected group %#v, but got %#v", g, p.Groups()[0])
|
||||
}
|
||||
|
||||
if g.Options()[0].ShortName != 'g' {
|
||||
t.Errorf("Expected short name `g' but got %v", g.Options()[0].ShortName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupNestedInline(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
|
||||
Group struct {
|
||||
G bool `short:"g"`
|
||||
|
||||
Nested struct {
|
||||
N string `long:"n"`
|
||||
} `group:"Nested Options"`
|
||||
} `group:"Grouped Options"`
|
||||
}{}
|
||||
|
||||
p, ret := assertParserSuccess(t, &opts, "-v", "-g", "--n", "n", "rest")
|
||||
|
||||
assertStringArray(t, ret, []string{"rest"})
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
|
||||
if !opts.Group.G {
|
||||
t.Errorf("Expected Group.G to be true")
|
||||
}
|
||||
|
||||
assertString(t, opts.Group.Nested.N, "n")
|
||||
|
||||
if p.Command.Group.Find("Grouped Options") == nil {
|
||||
t.Errorf("Expected to find group `Grouped Options'")
|
||||
}
|
||||
|
||||
if p.Command.Group.Find("Nested Options") == nil {
|
||||
t.Errorf("Expected to find group `Nested Options'")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupNestedInlineNamespace(t *testing.T) {
|
||||
var opts = struct {
|
||||
Opt string `long:"opt"`
|
||||
|
||||
Group struct {
|
||||
Opt string `long:"opt"`
|
||||
Group struct {
|
||||
Opt string `long:"opt"`
|
||||
} `group:"Subsubgroup" namespace:"sap"`
|
||||
} `group:"Subgroup" namespace:"sip"`
|
||||
}{}
|
||||
|
||||
p, ret := assertParserSuccess(t, &opts, "--opt", "a", "--sip.opt", "b", "--sip.sap.opt", "c", "rest")
|
||||
|
||||
assertStringArray(t, ret, []string{"rest"})
|
||||
|
||||
assertString(t, opts.Opt, "a")
|
||||
assertString(t, opts.Group.Opt, "b")
|
||||
assertString(t, opts.Group.Group.Opt, "c")
|
||||
|
||||
for _, name := range []string{"Subgroup", "Subsubgroup"} {
|
||||
if p.Command.Group.Find(name) == nil {
|
||||
t.Errorf("Expected to find group '%s'", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateShortFlags(t *testing.T) {
|
||||
var opts struct {
|
||||
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
|
||||
Variables []string `short:"v" long:"variable" description:"Set a variable value."`
|
||||
}
|
||||
|
||||
args := []string{
|
||||
"--verbose",
|
||||
"-v", "123",
|
||||
"-v", "456",
|
||||
}
|
||||
|
||||
_, err := ParseArgs(&opts, args)
|
||||
|
||||
if err == nil {
|
||||
t.Errorf("Expected an error with type ErrDuplicatedFlag")
|
||||
} else {
|
||||
err2 := err.(*Error)
|
||||
if err2.Type != ErrDuplicatedFlag {
|
||||
t.Errorf("Expected an error with type ErrDuplicatedFlag")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateLongFlags(t *testing.T) {
|
||||
var opts struct {
|
||||
Test1 []bool `short:"a" long:"testing" description:"Test 1"`
|
||||
Test2 []string `short:"b" long:"testing" description:"Test 2."`
|
||||
}
|
||||
|
||||
args := []string{
|
||||
"--testing",
|
||||
}
|
||||
|
||||
_, err := ParseArgs(&opts, args)
|
||||
|
||||
if err == nil {
|
||||
t.Errorf("Expected an error with type ErrDuplicatedFlag")
|
||||
} else {
|
||||
err2 := err.(*Error)
|
||||
if err2.Type != ErrDuplicatedFlag {
|
||||
t.Errorf("Expected an error with type ErrDuplicatedFlag")
|
||||
}
|
||||
}
|
||||
}
|
426
Godeps/_workspace/src/github.com/jessevdk/go-flags/help.go
generated
vendored
Normal file
426
Godeps/_workspace/src/github.com/jessevdk/go-flags/help.go
generated
vendored
Normal file
@ -0,0 +1,426 @@
|
||||
// Copyright 2012 Jesse van den Kieboom. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package flags
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type alignmentInfo struct {
|
||||
maxLongLen int
|
||||
hasShort bool
|
||||
hasValueName bool
|
||||
terminalColumns int
|
||||
indent bool
|
||||
}
|
||||
|
||||
const (
|
||||
paddingBeforeOption = 2
|
||||
distanceBetweenOptionAndDescription = 2
|
||||
)
|
||||
|
||||
func (a *alignmentInfo) descriptionStart() int {
|
||||
ret := a.maxLongLen + distanceBetweenOptionAndDescription
|
||||
|
||||
if a.hasShort {
|
||||
ret += 2
|
||||
}
|
||||
|
||||
if a.maxLongLen > 0 {
|
||||
ret += 4
|
||||
}
|
||||
|
||||
if a.hasValueName {
|
||||
ret += 3
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (a *alignmentInfo) updateLen(name string, indent bool) {
|
||||
l := utf8.RuneCountInString(name)
|
||||
|
||||
if indent {
|
||||
l = l + 4
|
||||
}
|
||||
|
||||
if l > a.maxLongLen {
|
||||
a.maxLongLen = l
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Parser) getAlignmentInfo() alignmentInfo {
|
||||
ret := alignmentInfo{
|
||||
maxLongLen: 0,
|
||||
hasShort: false,
|
||||
hasValueName: false,
|
||||
terminalColumns: getTerminalColumns(),
|
||||
}
|
||||
|
||||
if ret.terminalColumns <= 0 {
|
||||
ret.terminalColumns = 80
|
||||
}
|
||||
|
||||
var prevcmd *Command
|
||||
|
||||
p.eachActiveGroup(func(c *Command, grp *Group) {
|
||||
if c != prevcmd {
|
||||
for _, arg := range c.args {
|
||||
ret.updateLen(arg.Name, c != p.Command)
|
||||
}
|
||||
}
|
||||
|
||||
for _, info := range grp.options {
|
||||
if !info.canCli() {
|
||||
continue
|
||||
}
|
||||
|
||||
if info.ShortName != 0 {
|
||||
ret.hasShort = true
|
||||
}
|
||||
|
||||
if len(info.ValueName) > 0 {
|
||||
ret.hasValueName = true
|
||||
}
|
||||
|
||||
ret.updateLen(info.LongNameWithNamespace()+info.ValueName, c != p.Command)
|
||||
}
|
||||
})
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (p *Parser) writeHelpOption(writer *bufio.Writer, option *Option, info alignmentInfo) {
|
||||
line := &bytes.Buffer{}
|
||||
|
||||
prefix := paddingBeforeOption
|
||||
|
||||
if info.indent {
|
||||
prefix += 4
|
||||
}
|
||||
|
||||
line.WriteString(strings.Repeat(" ", prefix))
|
||||
|
||||
if option.ShortName != 0 {
|
||||
line.WriteRune(defaultShortOptDelimiter)
|
||||
line.WriteRune(option.ShortName)
|
||||
} else if info.hasShort {
|
||||
line.WriteString(" ")
|
||||
}
|
||||
|
||||
descstart := info.descriptionStart() + paddingBeforeOption
|
||||
|
||||
if len(option.LongName) > 0 {
|
||||
if option.ShortName != 0 {
|
||||
line.WriteString(", ")
|
||||
} else if info.hasShort {
|
||||
line.WriteString(" ")
|
||||
}
|
||||
|
||||
line.WriteString(defaultLongOptDelimiter)
|
||||
line.WriteString(option.LongNameWithNamespace())
|
||||
}
|
||||
|
||||
if option.canArgument() {
|
||||
line.WriteRune(defaultNameArgDelimiter)
|
||||
|
||||
if len(option.ValueName) > 0 {
|
||||
line.WriteString(option.ValueName)
|
||||
}
|
||||
}
|
||||
|
||||
written := line.Len()
|
||||
line.WriteTo(writer)
|
||||
|
||||
if option.Description != "" {
|
||||
dw := descstart - written
|
||||
writer.WriteString(strings.Repeat(" ", dw))
|
||||
|
||||
def := ""
|
||||
defs := option.Default
|
||||
|
||||
if len(option.DefaultMask) != 0 {
|
||||
if option.DefaultMask != "-" {
|
||||
def = option.DefaultMask
|
||||
}
|
||||
} else if len(defs) == 0 && option.canArgument() {
|
||||
var showdef bool
|
||||
|
||||
switch option.field.Type.Kind() {
|
||||
case reflect.Func, reflect.Ptr:
|
||||
showdef = !option.value.IsNil()
|
||||
case reflect.Slice, reflect.String, reflect.Array:
|
||||
showdef = option.value.Len() > 0
|
||||
case reflect.Map:
|
||||
showdef = !option.value.IsNil() && option.value.Len() > 0
|
||||
default:
|
||||
zeroval := reflect.Zero(option.field.Type)
|
||||
showdef = !reflect.DeepEqual(zeroval.Interface(), option.value.Interface())
|
||||
}
|
||||
|
||||
if showdef {
|
||||
def, _ = convertToString(option.value, option.tag)
|
||||
}
|
||||
} else if len(defs) != 0 {
|
||||
l := len(defs) - 1
|
||||
|
||||
for i := 0; i < l; i++ {
|
||||
def += quoteIfNeeded(defs[i]) + ", "
|
||||
}
|
||||
|
||||
def += quoteIfNeeded(defs[l])
|
||||
}
|
||||
|
||||
var envDef string
|
||||
if option.EnvDefaultKey != "" {
|
||||
var envPrintable string
|
||||
if runtime.GOOS == "windows" {
|
||||
envPrintable = "%" + option.EnvDefaultKey + "%"
|
||||
} else {
|
||||
envPrintable = "$" + option.EnvDefaultKey
|
||||
}
|
||||
envDef = fmt.Sprintf(" [%s]", envPrintable)
|
||||
}
|
||||
|
||||
var desc string
|
||||
|
||||
if def != "" {
|
||||
desc = fmt.Sprintf("%s (%v)%s", option.Description, def, envDef)
|
||||
} else {
|
||||
desc = option.Description + envDef
|
||||
}
|
||||
|
||||
writer.WriteString(wrapText(desc,
|
||||
info.terminalColumns-descstart,
|
||||
strings.Repeat(" ", descstart)))
|
||||
}
|
||||
|
||||
writer.WriteString("\n")
|
||||
}
|
||||
|
||||
func maxCommandLength(s []*Command) int {
|
||||
if len(s) == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
ret := len(s[0].Name)
|
||||
|
||||
for _, v := range s[1:] {
|
||||
l := len(v.Name)
|
||||
|
||||
if l > ret {
|
||||
ret = l
|
||||
}
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
// WriteHelp writes a help message containing all the possible options and
|
||||
// their descriptions to the provided writer. Note that the HelpFlag parser
|
||||
// option provides a convenient way to add a -h/--help option group to the
|
||||
// command line parser which will automatically show the help messages using
|
||||
// this method.
|
||||
func (p *Parser) WriteHelp(writer io.Writer) {
|
||||
if writer == nil {
|
||||
return
|
||||
}
|
||||
|
||||
wr := bufio.NewWriter(writer)
|
||||
aligninfo := p.getAlignmentInfo()
|
||||
|
||||
cmd := p.Command
|
||||
|
||||
for cmd.Active != nil {
|
||||
cmd = cmd.Active
|
||||
}
|
||||
|
||||
if p.Name != "" {
|
||||
wr.WriteString("Usage:\n")
|
||||
wr.WriteString(" ")
|
||||
|
||||
allcmd := p.Command
|
||||
|
||||
for allcmd != nil {
|
||||
var usage string
|
||||
|
||||
if allcmd == p.Command {
|
||||
if len(p.Usage) != 0 {
|
||||
usage = p.Usage
|
||||
} else if p.Options&HelpFlag != 0 {
|
||||
usage = "[OPTIONS]"
|
||||
}
|
||||
} else if us, ok := allcmd.data.(Usage); ok {
|
||||
usage = us.Usage()
|
||||
} else if allcmd.hasCliOptions() {
|
||||
usage = fmt.Sprintf("[%s-OPTIONS]", allcmd.Name)
|
||||
}
|
||||
|
||||
if len(usage) != 0 {
|
||||
fmt.Fprintf(wr, " %s %s", allcmd.Name, usage)
|
||||
} else {
|
||||
fmt.Fprintf(wr, " %s", allcmd.Name)
|
||||
}
|
||||
|
||||
if len(allcmd.args) > 0 {
|
||||
fmt.Fprintf(wr, " ")
|
||||
}
|
||||
|
||||
for i, arg := range allcmd.args {
|
||||
if i != 0 {
|
||||
fmt.Fprintf(wr, " ")
|
||||
}
|
||||
|
||||
name := arg.Name
|
||||
|
||||
if arg.isRemaining() {
|
||||
name = name + "..."
|
||||
}
|
||||
|
||||
if !allcmd.ArgsRequired {
|
||||
fmt.Fprintf(wr, "[%s]", name)
|
||||
} else {
|
||||
fmt.Fprintf(wr, "%s", name)
|
||||
}
|
||||
}
|
||||
|
||||
if allcmd.Active == nil && len(allcmd.commands) > 0 {
|
||||
var co, cc string
|
||||
|
||||
if allcmd.SubcommandsOptional {
|
||||
co, cc = "[", "]"
|
||||
} else {
|
||||
co, cc = "<", ">"
|
||||
}
|
||||
|
||||
if len(allcmd.commands) > 3 {
|
||||
fmt.Fprintf(wr, " %scommand%s", co, cc)
|
||||
} else {
|
||||
subcommands := allcmd.sortedCommands()
|
||||
names := make([]string, len(subcommands))
|
||||
|
||||
for i, subc := range subcommands {
|
||||
names[i] = subc.Name
|
||||
}
|
||||
|
||||
fmt.Fprintf(wr, " %s%s%s", co, strings.Join(names, " | "), cc)
|
||||
}
|
||||
}
|
||||
|
||||
allcmd = allcmd.Active
|
||||
}
|
||||
|
||||
fmt.Fprintln(wr)
|
||||
|
||||
if len(cmd.LongDescription) != 0 {
|
||||
fmt.Fprintln(wr)
|
||||
|
||||
t := wrapText(cmd.LongDescription,
|
||||
aligninfo.terminalColumns,
|
||||
"")
|
||||
|
||||
fmt.Fprintln(wr, t)
|
||||
}
|
||||
}
|
||||
|
||||
c := p.Command
|
||||
|
||||
for c != nil {
|
||||
printcmd := c != p.Command
|
||||
|
||||
c.eachGroup(func(grp *Group) {
|
||||
first := true
|
||||
|
||||
// Skip built-in help group for all commands except the top-level
|
||||
// parser
|
||||
if grp.isBuiltinHelp && c != p.Command {
|
||||
return
|
||||
}
|
||||
|
||||
for _, info := range grp.options {
|
||||
if !info.canCli() {
|
||||
continue
|
||||
}
|
||||
|
||||
if printcmd {
|
||||
fmt.Fprintf(wr, "\n[%s command options]\n", c.Name)
|
||||
aligninfo.indent = true
|
||||
printcmd = false
|
||||
}
|
||||
|
||||
if first && cmd.Group != grp {
|
||||
fmt.Fprintln(wr)
|
||||
|
||||
if aligninfo.indent {
|
||||
wr.WriteString(" ")
|
||||
}
|
||||
|
||||
fmt.Fprintf(wr, "%s:\n", grp.ShortDescription)
|
||||
first = false
|
||||
}
|
||||
|
||||
p.writeHelpOption(wr, info, aligninfo)
|
||||
}
|
||||
})
|
||||
|
||||
if len(c.args) > 0 {
|
||||
if c == p.Command {
|
||||
fmt.Fprintf(wr, "\nArguments:\n")
|
||||
} else {
|
||||
fmt.Fprintf(wr, "\n[%s command arguments]\n", c.Name)
|
||||
}
|
||||
|
||||
maxlen := aligninfo.descriptionStart()
|
||||
|
||||
for _, arg := range c.args {
|
||||
prefix := strings.Repeat(" ", paddingBeforeOption)
|
||||
fmt.Fprintf(wr, "%s%s", prefix, arg.Name)
|
||||
|
||||
if len(arg.Description) > 0 {
|
||||
align := strings.Repeat(" ", maxlen-len(arg.Name)-1)
|
||||
fmt.Fprintf(wr, ":%s%s", align, arg.Description)
|
||||
}
|
||||
|
||||
fmt.Fprintln(wr)
|
||||
}
|
||||
}
|
||||
|
||||
c = c.Active
|
||||
}
|
||||
|
||||
scommands := cmd.sortedCommands()
|
||||
|
||||
if len(scommands) > 0 {
|
||||
maxnamelen := maxCommandLength(scommands)
|
||||
|
||||
fmt.Fprintln(wr)
|
||||
fmt.Fprintln(wr, "Available commands:")
|
||||
|
||||
for _, c := range scommands {
|
||||
fmt.Fprintf(wr, " %s", c.Name)
|
||||
|
||||
if len(c.ShortDescription) > 0 {
|
||||
pad := strings.Repeat(" ", maxnamelen-len(c.Name))
|
||||
fmt.Fprintf(wr, "%s %s", pad, c.ShortDescription)
|
||||
|
||||
if len(c.Aliases) > 0 {
|
||||
fmt.Fprintf(wr, " (aliases: %s)", strings.Join(c.Aliases, ", "))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fmt.Fprintln(wr)
|
||||
}
|
||||
}
|
||||
|
||||
wr.Flush()
|
||||
}
|
283
Godeps/_workspace/src/github.com/jessevdk/go-flags/help_test.go
generated
vendored
Normal file
283
Godeps/_workspace/src/github.com/jessevdk/go-flags/help_test.go
generated
vendored
Normal file
@ -0,0 +1,283 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type helpOptions struct {
|
||||
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information" ini-name:"verbose"`
|
||||
Call func(string) `short:"c" description:"Call phone number" ini-name:"call"`
|
||||
PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"`
|
||||
EmptyDescription bool `long:"empty-description"`
|
||||
|
||||
Default string `long:"default" default:"Some\nvalue" description:"Test default value"`
|
||||
DefaultArray []string `long:"default-array" default:"Some value" default:"Other\tvalue" description:"Test default array value"`
|
||||
DefaultMap map[string]string `long:"default-map" default:"some:value" default:"another:value" description:"Testdefault map value"`
|
||||
EnvDefault1 string `long:"env-default1" default:"Some value" env:"ENV_DEFAULT" description:"Test env-default1 value"`
|
||||
EnvDefault2 string `long:"env-default2" env:"ENV_DEFAULT" description:"Test env-default2 value"`
|
||||
|
||||
OnlyIni string `ini-name:"only-ini" description:"Option only available in ini"`
|
||||
|
||||
Other struct {
|
||||
StringSlice []string `short:"s" default:"some" default:"value" description:"A slice of strings"`
|
||||
IntMap map[string]int `long:"intmap" default:"a:1" description:"A map from string to int" ini-name:"int-map"`
|
||||
} `group:"Other Options"`
|
||||
|
||||
Group struct {
|
||||
Opt string `long:"opt" description:"This is a subgroup option"`
|
||||
|
||||
Group struct {
|
||||
Opt string `long:"opt" description:"This is a subsubgroup option"`
|
||||
} `group:"Subsubgroup" namespace:"sap"`
|
||||
} `group:"Subgroup" namespace:"sip"`
|
||||
|
||||
Command struct {
|
||||
ExtraVerbose []bool `long:"extra-verbose" description:"Use for extra verbosity"`
|
||||
} `command:"command" alias:"cm" alias:"cmd" description:"A command"`
|
||||
|
||||
Args struct {
|
||||
Filename string `name:"filename" description:"A filename"`
|
||||
Num int `name:"num" description:"A number"`
|
||||
} `positional-args:"yes"`
|
||||
}
|
||||
|
||||
func TestHelp(t *testing.T) {
|
||||
oldEnv := EnvSnapshot()
|
||||
defer oldEnv.Restore()
|
||||
os.Setenv("ENV_DEFAULT", "env-def")
|
||||
|
||||
var opts helpOptions
|
||||
p := NewNamedParser("TestHelp", HelpFlag)
|
||||
p.AddGroup("Application Options", "The application options", &opts)
|
||||
|
||||
_, err := p.ParseArgs([]string{"--help"})
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("Expected help error")
|
||||
}
|
||||
|
||||
if e, ok := err.(*Error); !ok {
|
||||
t.Fatalf("Expected flags.Error, but got %T", err)
|
||||
} else {
|
||||
if e.Type != ErrHelp {
|
||||
t.Errorf("Expected flags.ErrHelp type, but got %s", e.Type)
|
||||
}
|
||||
|
||||
var expected string
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
expected = `Usage:
|
||||
TestHelp [OPTIONS] [filename] [num] <command>
|
||||
|
||||
Application Options:
|
||||
/v, /verbose Show verbose debug information
|
||||
/c: Call phone number
|
||||
/ptrslice: A slice of pointers to string
|
||||
/empty-description
|
||||
/default: Test default value ("Some\nvalue")
|
||||
/default-array: Test default array value (Some value, "Other\tvalue")
|
||||
/default-map: Testdefault map value (some:value, another:value)
|
||||
/env-default1: Test env-default1 value (Some value) [%ENV_DEFAULT%]
|
||||
/env-default2: Test env-default2 value [%ENV_DEFAULT%]
|
||||
|
||||
Other Options:
|
||||
/s: A slice of strings (some, value)
|
||||
/intmap: A map from string to int (a:1)
|
||||
|
||||
Subgroup:
|
||||
/sip.opt: This is a subgroup option
|
||||
|
||||
Subsubgroup:
|
||||
/sip.sap.opt: This is a subsubgroup option
|
||||
|
||||
Help Options:
|
||||
/? Show this help message
|
||||
/h, /help Show this help message
|
||||
|
||||
Arguments:
|
||||
filename: A filename
|
||||
num: A number
|
||||
|
||||
Available commands:
|
||||
command A command (aliases: cm, cmd)
|
||||
`
|
||||
} else {
|
||||
expected = `Usage:
|
||||
TestHelp [OPTIONS] [filename] [num] <command>
|
||||
|
||||
Application Options:
|
||||
-v, --verbose Show verbose debug information
|
||||
-c= Call phone number
|
||||
--ptrslice= A slice of pointers to string
|
||||
--empty-description
|
||||
--default= Test default value ("Some\nvalue")
|
||||
--default-array= Test default array value (Some value, "Other\tvalue")
|
||||
--default-map= Testdefault map value (some:value, another:value)
|
||||
--env-default1= Test env-default1 value (Some value) [$ENV_DEFAULT]
|
||||
--env-default2= Test env-default2 value [$ENV_DEFAULT]
|
||||
|
||||
Other Options:
|
||||
-s= A slice of strings (some, value)
|
||||
--intmap= A map from string to int (a:1)
|
||||
|
||||
Subgroup:
|
||||
--sip.opt= This is a subgroup option
|
||||
|
||||
Subsubgroup:
|
||||
--sip.sap.opt= This is a subsubgroup option
|
||||
|
||||
Help Options:
|
||||
-h, --help Show this help message
|
||||
|
||||
Arguments:
|
||||
filename: A filename
|
||||
num: A number
|
||||
|
||||
Available commands:
|
||||
command A command (aliases: cm, cmd)
|
||||
`
|
||||
}
|
||||
|
||||
assertDiff(t, e.Message, expected, "help message")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMan(t *testing.T) {
|
||||
oldEnv := EnvSnapshot()
|
||||
defer oldEnv.Restore()
|
||||
os.Setenv("ENV_DEFAULT", "env-def")
|
||||
|
||||
var opts helpOptions
|
||||
p := NewNamedParser("TestMan", HelpFlag)
|
||||
p.ShortDescription = "Test manpage generation"
|
||||
p.LongDescription = "This is a somewhat `longer' description of what this does"
|
||||
p.AddGroup("Application Options", "The application options", &opts)
|
||||
|
||||
p.Commands()[0].LongDescription = "Longer `command' description"
|
||||
|
||||
var buf bytes.Buffer
|
||||
p.WriteManPage(&buf)
|
||||
|
||||
got := buf.String()
|
||||
|
||||
tt := time.Now()
|
||||
|
||||
expected := fmt.Sprintf(`.TH TestMan 1 "%s"
|
||||
.SH NAME
|
||||
TestMan \- Test manpage generation
|
||||
.SH SYNOPSIS
|
||||
\fBTestMan\fP [OPTIONS]
|
||||
.SH DESCRIPTION
|
||||
This is a somewhat \fBlonger\fP description of what this does
|
||||
.SH OPTIONS
|
||||
.TP
|
||||
\fB-v, --verbose\fP
|
||||
Show verbose debug information
|
||||
.TP
|
||||
\fB-c\fP
|
||||
Call phone number
|
||||
.TP
|
||||
\fB--ptrslice\fP
|
||||
A slice of pointers to string
|
||||
.TP
|
||||
\fB--empty-description\fP
|
||||
.TP
|
||||
\fB--default\fP
|
||||
Test default value
|
||||
.TP
|
||||
\fB--default-array\fP
|
||||
Test default array value
|
||||
.TP
|
||||
\fB--default-map\fP
|
||||
Testdefault map value
|
||||
.TP
|
||||
\fB--env-default1\fP
|
||||
Test env-default1 value
|
||||
.TP
|
||||
\fB--env-default2\fP
|
||||
Test env-default2 value
|
||||
.TP
|
||||
\fB-s\fP
|
||||
A slice of strings
|
||||
.TP
|
||||
\fB--intmap\fP
|
||||
A map from string to int
|
||||
.TP
|
||||
\fB--sip.opt\fP
|
||||
This is a subgroup option
|
||||
.TP
|
||||
\fB--sip.sap.opt\fP
|
||||
This is a subsubgroup option
|
||||
.SH COMMANDS
|
||||
.SS command
|
||||
A command
|
||||
|
||||
Longer \fBcommand\fP description
|
||||
|
||||
\fBUsage\fP: TestMan [OPTIONS] command [command-OPTIONS]
|
||||
|
||||
|
||||
\fBAliases\fP: cm, cmd
|
||||
|
||||
.TP
|
||||
\fB--extra-verbose\fP
|
||||
Use for extra verbosity
|
||||
`, tt.Format("2 January 2006"))
|
||||
|
||||
assertDiff(t, got, expected, "man page")
|
||||
}
|
||||
|
||||
type helpCommandNoOptions struct {
|
||||
Command struct {
|
||||
} `command:"command" description:"A command"`
|
||||
}
|
||||
|
||||
func TestHelpCommand(t *testing.T) {
|
||||
oldEnv := EnvSnapshot()
|
||||
defer oldEnv.Restore()
|
||||
os.Setenv("ENV_DEFAULT", "env-def")
|
||||
|
||||
var opts helpCommandNoOptions
|
||||
p := NewNamedParser("TestHelpCommand", HelpFlag)
|
||||
p.AddGroup("Application Options", "The application options", &opts)
|
||||
|
||||
_, err := p.ParseArgs([]string{"command", "--help"})
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("Expected help error")
|
||||
}
|
||||
|
||||
if e, ok := err.(*Error); !ok {
|
||||
t.Fatalf("Expected flags.Error, but got %T", err)
|
||||
} else {
|
||||
if e.Type != ErrHelp {
|
||||
t.Errorf("Expected flags.ErrHelp type, but got %s", e.Type)
|
||||
}
|
||||
|
||||
var expected string
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
expected = `Usage:
|
||||
TestHelpCommand [OPTIONS] command
|
||||
|
||||
Help Options:
|
||||
/? Show this help message
|
||||
/h, /help Show this help message
|
||||
`
|
||||
} else {
|
||||
expected = `Usage:
|
||||
TestHelpCommand [OPTIONS] command
|
||||
|
||||
Help Options:
|
||||
-h, --help Show this help message
|
||||
`
|
||||
}
|
||||
|
||||
assertDiff(t, e.Message, expected, "help message")
|
||||
}
|
||||
}
|
140
Godeps/_workspace/src/github.com/jessevdk/go-flags/ini.go
generated
vendored
Normal file
140
Godeps/_workspace/src/github.com/jessevdk/go-flags/ini.go
generated
vendored
Normal file
@ -0,0 +1,140 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// IniError contains location information on where an error occured.
|
||||
type IniError struct {
|
||||
// The error message.
|
||||
Message string
|
||||
|
||||
// The filename of the file in which the error occurred.
|
||||
File string
|
||||
|
||||
// The line number at which the error occurred.
|
||||
LineNumber uint
|
||||
}
|
||||
|
||||
// Error provides a "file:line: message" formatted message of the ini error.
|
||||
func (x *IniError) Error() string {
|
||||
return fmt.Sprintf(
|
||||
"%s:%d: %s",
|
||||
x.File,
|
||||
x.LineNumber,
|
||||
x.Message,
|
||||
)
|
||||
}
|
||||
|
||||
// IniOptions for writing
|
||||
type IniOptions uint
|
||||
|
||||
const (
|
||||
// IniNone indicates no options.
|
||||
IniNone IniOptions = 0
|
||||
|
||||
// IniIncludeDefaults indicates that default values should be written.
|
||||
IniIncludeDefaults = 1 << iota
|
||||
|
||||
// IniCommentDefaults indicates that if IniIncludeDefaults is used
|
||||
// options with default values are written but commented out.
|
||||
IniCommentDefaults
|
||||
|
||||
// IniIncludeComments indicates that comments containing the description
|
||||
// of an option should be written.
|
||||
IniIncludeComments
|
||||
|
||||
// IniDefault provides a default set of options.
|
||||
IniDefault = IniIncludeComments
|
||||
)
|
||||
|
||||
// IniParser is a utility to read and write flags options from and to ini
|
||||
// formatted strings.
|
||||
type IniParser struct {
|
||||
parser *Parser
|
||||
}
|
||||
|
||||
// NewIniParser creates a new ini parser for a given Parser.
|
||||
func NewIniParser(p *Parser) *IniParser {
|
||||
return &IniParser{
|
||||
parser: p,
|
||||
}
|
||||
}
|
||||
|
||||
// IniParse is a convenience function to parse command line options with default
|
||||
// settings from an ini formatted file. The provided data is a pointer to a struct
|
||||
// representing the default option group (named "Application Options"). For
|
||||
// more control, use flags.NewParser.
|
||||
func IniParse(filename string, data interface{}) error {
|
||||
p := NewParser(data, Default)
|
||||
|
||||
return NewIniParser(p).ParseFile(filename)
|
||||
}
|
||||
|
||||
// ParseFile parses flags from an ini formatted file. See Parse for more
|
||||
// information on the ini file format. The returned errors can be of the type
|
||||
// flags.Error or flags.IniError.
|
||||
func (i *IniParser) ParseFile(filename string) error {
|
||||
i.parser.clearIsSet()
|
||||
|
||||
ini, err := readIniFromFile(filename)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return i.parse(ini)
|
||||
}
|
||||
|
||||
// Parse parses flags from an ini format. You can use ParseFile as a
|
||||
// convenience function to parse from a filename instead of a general
|
||||
// io.Reader.
|
||||
//
|
||||
// The format of the ini file is as follows:
|
||||
//
|
||||
// [Option group name]
|
||||
// option = value
|
||||
//
|
||||
// Each section in the ini file represents an option group or command in the
|
||||
// flags parser. The default flags parser option group (i.e. when using
|
||||
// flags.Parse) is named 'Application Options'. The ini option name is matched
|
||||
// in the following order:
|
||||
//
|
||||
// 1. Compared to the ini-name tag on the option struct field (if present)
|
||||
// 2. Compared to the struct field name
|
||||
// 3. Compared to the option long name (if present)
|
||||
// 4. Compared to the option short name (if present)
|
||||
//
|
||||
// Sections for nested groups and commands can be addressed using a dot `.'
|
||||
// namespacing notation (i.e [subcommand.Options]). Group section names are
|
||||
// matched case insensitive.
|
||||
//
|
||||
// The returned errors can be of the type flags.Error or flags.IniError.
|
||||
func (i *IniParser) Parse(reader io.Reader) error {
|
||||
i.parser.clearIsSet()
|
||||
|
||||
ini, err := readIni(reader, "")
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return i.parse(ini)
|
||||
}
|
||||
|
||||
// WriteFile writes the flags as ini format into a file. See WriteIni
|
||||
// for more information. The returned error occurs when the specified file
|
||||
// could not be opened for writing.
|
||||
func (i *IniParser) WriteFile(filename string, options IniOptions) error {
|
||||
return writeIniToFile(i, filename, options)
|
||||
}
|
||||
|
||||
// Write writes the current values of all the flags to an ini format.
|
||||
// See Parse for more information on the ini file format. You typically
|
||||
// call this only after settings have been parsed since the default values of each
|
||||
// option are stored just before parsing the flags (this is only relevant when
|
||||
// IniIncludeDefaults is _not_ set in options).
|
||||
func (i *IniParser) Write(writer io.Writer, options IniOptions) {
|
||||
writeIni(i, writer, options)
|
||||
}
|
452
Godeps/_workspace/src/github.com/jessevdk/go-flags/ini_private.go
generated
vendored
Normal file
452
Godeps/_workspace/src/github.com/jessevdk/go-flags/ini_private.go
generated
vendored
Normal file
@ -0,0 +1,452 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type iniValue struct {
|
||||
Name string
|
||||
Value string
|
||||
Quoted bool
|
||||
LineNumber uint
|
||||
}
|
||||
|
||||
type iniSection []iniValue
|
||||
type ini struct {
|
||||
File string
|
||||
Sections map[string]iniSection
|
||||
}
|
||||
|
||||
func readFullLine(reader *bufio.Reader) (string, error) {
|
||||
var line []byte
|
||||
|
||||
for {
|
||||
l, more, err := reader.ReadLine()
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if line == nil && !more {
|
||||
return string(l), nil
|
||||
}
|
||||
|
||||
line = append(line, l...)
|
||||
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return string(line), nil
|
||||
}
|
||||
|
||||
func optionIniName(option *Option) string {
|
||||
name := option.tag.Get("_read-ini-name")
|
||||
|
||||
if len(name) != 0 {
|
||||
return name
|
||||
}
|
||||
|
||||
name = option.tag.Get("ini-name")
|
||||
|
||||
if len(name) != 0 {
|
||||
return name
|
||||
}
|
||||
|
||||
return option.field.Name
|
||||
}
|
||||
|
||||
func writeGroupIni(cmd *Command, group *Group, namespace string, writer io.Writer, options IniOptions) {
|
||||
var sname string
|
||||
|
||||
if len(namespace) != 0 {
|
||||
sname = namespace
|
||||
}
|
||||
|
||||
if cmd.Group != group && len(group.ShortDescription) != 0 {
|
||||
if len(sname) != 0 {
|
||||
sname += "."
|
||||
}
|
||||
|
||||
sname += group.ShortDescription
|
||||
}
|
||||
|
||||
sectionwritten := false
|
||||
comments := (options & IniIncludeComments) != IniNone
|
||||
|
||||
for _, option := range group.options {
|
||||
if option.isFunc() {
|
||||
continue
|
||||
}
|
||||
|
||||
if len(option.tag.Get("no-ini")) != 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
val := option.value
|
||||
|
||||
if (options&IniIncludeDefaults) == IniNone && option.valueIsDefault() {
|
||||
continue
|
||||
}
|
||||
|
||||
if !sectionwritten {
|
||||
fmt.Fprintf(writer, "[%s]\n", sname)
|
||||
sectionwritten = true
|
||||
}
|
||||
|
||||
if comments && len(option.Description) != 0 {
|
||||
fmt.Fprintf(writer, "; %s\n", option.Description)
|
||||
}
|
||||
|
||||
oname := optionIniName(option)
|
||||
|
||||
commentOption := (options&(IniIncludeDefaults|IniCommentDefaults)) == IniIncludeDefaults|IniCommentDefaults && option.valueIsDefault()
|
||||
|
||||
kind := val.Type().Kind()
|
||||
switch kind {
|
||||
case reflect.Slice:
|
||||
kind = val.Type().Elem().Kind()
|
||||
|
||||
if val.Len() == 0 {
|
||||
writeOption(writer, oname, kind, "", "", true, option.iniQuote)
|
||||
} else {
|
||||
for idx := 0; idx < val.Len(); idx++ {
|
||||
v, _ := convertToString(val.Index(idx), option.tag)
|
||||
|
||||
writeOption(writer, oname, kind, "", v, commentOption, option.iniQuote)
|
||||
}
|
||||
}
|
||||
case reflect.Map:
|
||||
kind = val.Type().Elem().Kind()
|
||||
|
||||
if val.Len() == 0 {
|
||||
writeOption(writer, oname, kind, "", "", true, option.iniQuote)
|
||||
} else {
|
||||
mkeys := val.MapKeys()
|
||||
keys := make([]string, len(val.MapKeys()))
|
||||
kkmap := make(map[string]reflect.Value)
|
||||
|
||||
for i, k := range mkeys {
|
||||
keys[i], _ = convertToString(k, option.tag)
|
||||
kkmap[keys[i]] = k
|
||||
}
|
||||
|
||||
sort.Strings(keys)
|
||||
|
||||
for _, k := range keys {
|
||||
v, _ := convertToString(val.MapIndex(kkmap[k]), option.tag)
|
||||
|
||||
writeOption(writer, oname, kind, k, v, commentOption, option.iniQuote)
|
||||
}
|
||||
}
|
||||
default:
|
||||
v, _ := convertToString(val, option.tag)
|
||||
|
||||
writeOption(writer, oname, kind, "", v, commentOption, option.iniQuote)
|
||||
}
|
||||
|
||||
if comments {
|
||||
fmt.Fprintln(writer)
|
||||
}
|
||||
}
|
||||
|
||||
if sectionwritten && !comments {
|
||||
fmt.Fprintln(writer)
|
||||
}
|
||||
}
|
||||
|
||||
func writeOption(writer io.Writer, optionName string, optionType reflect.Kind, optionKey string, optionValue string, commentOption bool, forceQuote bool) {
|
||||
if forceQuote || (optionType == reflect.String && !isPrint(optionValue)) {
|
||||
optionValue = strconv.Quote(optionValue)
|
||||
}
|
||||
|
||||
comment := ""
|
||||
if commentOption {
|
||||
comment = "; "
|
||||
}
|
||||
|
||||
fmt.Fprintf(writer, "%s%s =", comment, optionName)
|
||||
|
||||
if optionKey != "" {
|
||||
fmt.Fprintf(writer, " %s:%s", optionKey, optionValue)
|
||||
} else if optionValue != "" {
|
||||
fmt.Fprintf(writer, " %s", optionValue)
|
||||
}
|
||||
|
||||
fmt.Fprintln(writer)
|
||||
}
|
||||
|
||||
func writeCommandIni(command *Command, namespace string, writer io.Writer, options IniOptions) {
|
||||
command.eachGroup(func(group *Group) {
|
||||
writeGroupIni(command, group, namespace, writer, options)
|
||||
})
|
||||
|
||||
for _, c := range command.commands {
|
||||
var nns string
|
||||
|
||||
if len(namespace) != 0 {
|
||||
nns = c.Name + "." + nns
|
||||
} else {
|
||||
nns = c.Name
|
||||
}
|
||||
|
||||
writeCommandIni(c, nns, writer, options)
|
||||
}
|
||||
}
|
||||
|
||||
func writeIni(parser *IniParser, writer io.Writer, options IniOptions) {
|
||||
writeCommandIni(parser.parser.Command, "", writer, options)
|
||||
}
|
||||
|
||||
func writeIniToFile(parser *IniParser, filename string, options IniOptions) error {
|
||||
file, err := os.Create(filename)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
writeIni(parser, file, options)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readIniFromFile(filename string) (*ini, error) {
|
||||
file, err := os.Open(filename)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
return readIni(file, filename)
|
||||
}
|
||||
|
||||
func readIni(contents io.Reader, filename string) (*ini, error) {
|
||||
ret := &ini{
|
||||
File: filename,
|
||||
Sections: make(map[string]iniSection),
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(contents)
|
||||
|
||||
// Empty global section
|
||||
section := make(iniSection, 0, 10)
|
||||
sectionname := ""
|
||||
|
||||
ret.Sections[sectionname] = section
|
||||
|
||||
var lineno uint
|
||||
|
||||
for {
|
||||
line, err := readFullLine(reader)
|
||||
|
||||
if err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lineno++
|
||||
line = strings.TrimSpace(line)
|
||||
|
||||
// Skip empty lines and lines starting with ; (comments)
|
||||
if len(line) == 0 || line[0] == ';' || line[0] == '#' {
|
||||
continue
|
||||
}
|
||||
|
||||
if line[0] == '[' {
|
||||
if line[0] != '[' || line[len(line)-1] != ']' {
|
||||
return nil, &IniError{
|
||||
Message: "malformed section header",
|
||||
File: filename,
|
||||
LineNumber: lineno,
|
||||
}
|
||||
}
|
||||
|
||||
name := strings.TrimSpace(line[1 : len(line)-1])
|
||||
|
||||
if len(name) == 0 {
|
||||
return nil, &IniError{
|
||||
Message: "empty section name",
|
||||
File: filename,
|
||||
LineNumber: lineno,
|
||||
}
|
||||
}
|
||||
|
||||
sectionname = name
|
||||
section = ret.Sections[name]
|
||||
|
||||
if section == nil {
|
||||
section = make(iniSection, 0, 10)
|
||||
ret.Sections[name] = section
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// Parse option here
|
||||
keyval := strings.SplitN(line, "=", 2)
|
||||
|
||||
if len(keyval) != 2 {
|
||||
return nil, &IniError{
|
||||
Message: fmt.Sprintf("malformed key=value (%s)", line),
|
||||
File: filename,
|
||||
LineNumber: lineno,
|
||||
}
|
||||
}
|
||||
|
||||
name := strings.TrimSpace(keyval[0])
|
||||
value := strings.TrimSpace(keyval[1])
|
||||
quoted := false
|
||||
|
||||
if len(value) != 0 && value[0] == '"' {
|
||||
if v, err := strconv.Unquote(value); err == nil {
|
||||
value = v
|
||||
|
||||
quoted = true
|
||||
} else {
|
||||
return nil, &IniError{
|
||||
Message: err.Error(),
|
||||
File: filename,
|
||||
LineNumber: lineno,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
section = append(section, iniValue{
|
||||
Name: name,
|
||||
Value: value,
|
||||
Quoted: quoted,
|
||||
LineNumber: lineno,
|
||||
})
|
||||
|
||||
ret.Sections[sectionname] = section
|
||||
}
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func (i *IniParser) matchingGroups(name string) []*Group {
|
||||
if len(name) == 0 {
|
||||
var ret []*Group
|
||||
|
||||
i.parser.eachGroup(func(g *Group) {
|
||||
ret = append(ret, g)
|
||||
})
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
g := i.parser.groupByName(name)
|
||||
|
||||
if g != nil {
|
||||
return []*Group{g}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *IniParser) parse(ini *ini) error {
|
||||
p := i.parser
|
||||
|
||||
var quotesLookup = make(map[*Option]bool)
|
||||
|
||||
for name, section := range ini.Sections {
|
||||
groups := i.matchingGroups(name)
|
||||
|
||||
if len(groups) == 0 {
|
||||
return newErrorf(ErrUnknownGroup, "could not find option group `%s'", name)
|
||||
}
|
||||
|
||||
for _, inival := range section {
|
||||
var opt *Option
|
||||
|
||||
for _, group := range groups {
|
||||
opt = group.optionByName(inival.Name, func(o *Option, n string) bool {
|
||||
return strings.ToLower(o.tag.Get("ini-name")) == strings.ToLower(n)
|
||||
})
|
||||
|
||||
if opt != nil && len(opt.tag.Get("no-ini")) != 0 {
|
||||
opt = nil
|
||||
}
|
||||
|
||||
if opt != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if opt == nil {
|
||||
if (p.Options & IgnoreUnknown) == None {
|
||||
return &IniError{
|
||||
Message: fmt.Sprintf("unknown option: %s", inival.Name),
|
||||
File: ini.File,
|
||||
LineNumber: inival.LineNumber,
|
||||
}
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
pval := &inival.Value
|
||||
|
||||
if !opt.canArgument() && len(inival.Value) == 0 {
|
||||
pval = nil
|
||||
} else {
|
||||
if opt.value.Type().Kind() == reflect.Map {
|
||||
parts := strings.SplitN(inival.Value, ":", 2)
|
||||
|
||||
// only handle unquoting
|
||||
if len(parts) == 2 && parts[1][0] == '"' {
|
||||
if v, err := strconv.Unquote(parts[1]); err == nil {
|
||||
parts[1] = v
|
||||
|
||||
inival.Quoted = true
|
||||
} else {
|
||||
return &IniError{
|
||||
Message: err.Error(),
|
||||
File: ini.File,
|
||||
LineNumber: inival.LineNumber,
|
||||
}
|
||||
}
|
||||
|
||||
s := parts[0] + ":" + parts[1]
|
||||
|
||||
pval = &s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := opt.set(pval); err != nil {
|
||||
return &IniError{
|
||||
Message: err.Error(),
|
||||
File: ini.File,
|
||||
LineNumber: inival.LineNumber,
|
||||
}
|
||||
}
|
||||
|
||||
// either all INI values are quoted or only values who need quoting
|
||||
if _, ok := quotesLookup[opt]; !inival.Quoted || !ok {
|
||||
quotesLookup[opt] = inival.Quoted
|
||||
}
|
||||
|
||||
opt.tag.Set("_read-ini-name", inival.Name)
|
||||
}
|
||||
}
|
||||
|
||||
for opt, quoted := range quotesLookup {
|
||||
opt.iniQuote = quoted
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
731
Godeps/_workspace/src/github.com/jessevdk/go-flags/ini_test.go
generated
vendored
Normal file
731
Godeps/_workspace/src/github.com/jessevdk/go-flags/ini_test.go
generated
vendored
Normal file
@ -0,0 +1,731 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWriteIni(t *testing.T) {
|
||||
oldEnv := EnvSnapshot()
|
||||
defer oldEnv.Restore()
|
||||
os.Setenv("ENV_DEFAULT", "env-def")
|
||||
|
||||
var tests = []struct {
|
||||
args []string
|
||||
options IniOptions
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
[]string{"-vv", "--intmap=a:2", "--intmap", "b:3", "filename", "0", "command"},
|
||||
IniDefault,
|
||||
`[Application Options]
|
||||
; Show verbose debug information
|
||||
verbose = true
|
||||
verbose = true
|
||||
|
||||
; Test env-default1 value
|
||||
EnvDefault1 = env-def
|
||||
|
||||
; Test env-default2 value
|
||||
EnvDefault2 = env-def
|
||||
|
||||
[Other Options]
|
||||
; A map from string to int
|
||||
int-map = a:2
|
||||
int-map = b:3
|
||||
|
||||
`,
|
||||
},
|
||||
{
|
||||
[]string{"-vv", "--intmap=a:2", "--intmap", "b:3", "filename", "0", "command"},
|
||||
IniDefault | IniIncludeDefaults,
|
||||
`[Application Options]
|
||||
; Show verbose debug information
|
||||
verbose = true
|
||||
verbose = true
|
||||
|
||||
; A slice of pointers to string
|
||||
; PtrSlice =
|
||||
|
||||
EmptyDescription = false
|
||||
|
||||
; Test default value
|
||||
Default = "Some\nvalue"
|
||||
|
||||
; Test default array value
|
||||
DefaultArray = Some value
|
||||
DefaultArray = "Other\tvalue"
|
||||
|
||||
; Testdefault map value
|
||||
DefaultMap = another:value
|
||||
DefaultMap = some:value
|
||||
|
||||
; Test env-default1 value
|
||||
EnvDefault1 = env-def
|
||||
|
||||
; Test env-default2 value
|
||||
EnvDefault2 = env-def
|
||||
|
||||
; Option only available in ini
|
||||
only-ini =
|
||||
|
||||
[Other Options]
|
||||
; A slice of strings
|
||||
StringSlice = some
|
||||
StringSlice = value
|
||||
|
||||
; A map from string to int
|
||||
int-map = a:2
|
||||
int-map = b:3
|
||||
|
||||
[Subgroup]
|
||||
; This is a subgroup option
|
||||
Opt =
|
||||
|
||||
[Subsubgroup]
|
||||
; This is a subsubgroup option
|
||||
Opt =
|
||||
|
||||
[command]
|
||||
; Use for extra verbosity
|
||||
; ExtraVerbose =
|
||||
|
||||
`,
|
||||
},
|
||||
{
|
||||
[]string{"filename", "0", "command"},
|
||||
IniDefault | IniIncludeDefaults | IniCommentDefaults,
|
||||
`[Application Options]
|
||||
; Show verbose debug information
|
||||
; verbose =
|
||||
|
||||
; A slice of pointers to string
|
||||
; PtrSlice =
|
||||
|
||||
; EmptyDescription = false
|
||||
|
||||
; Test default value
|
||||
; Default = "Some\nvalue"
|
||||
|
||||
; Test default array value
|
||||
; DefaultArray = Some value
|
||||
; DefaultArray = "Other\tvalue"
|
||||
|
||||
; Testdefault map value
|
||||
; DefaultMap = another:value
|
||||
; DefaultMap = some:value
|
||||
|
||||
; Test env-default1 value
|
||||
EnvDefault1 = env-def
|
||||
|
||||
; Test env-default2 value
|
||||
EnvDefault2 = env-def
|
||||
|
||||
; Option only available in ini
|
||||
; only-ini =
|
||||
|
||||
[Other Options]
|
||||
; A slice of strings
|
||||
; StringSlice = some
|
||||
; StringSlice = value
|
||||
|
||||
; A map from string to int
|
||||
; int-map = a:1
|
||||
|
||||
[Subgroup]
|
||||
; This is a subgroup option
|
||||
; Opt =
|
||||
|
||||
[Subsubgroup]
|
||||
; This is a subsubgroup option
|
||||
; Opt =
|
||||
|
||||
[command]
|
||||
; Use for extra verbosity
|
||||
; ExtraVerbose =
|
||||
|
||||
`,
|
||||
},
|
||||
{
|
||||
[]string{"--default=New value", "--default-array=New value", "--default-map=new:value", "filename", "0", "command"},
|
||||
IniDefault | IniIncludeDefaults | IniCommentDefaults,
|
||||
`[Application Options]
|
||||
; Show verbose debug information
|
||||
; verbose =
|
||||
|
||||
; A slice of pointers to string
|
||||
; PtrSlice =
|
||||
|
||||
; EmptyDescription = false
|
||||
|
||||
; Test default value
|
||||
Default = New value
|
||||
|
||||
; Test default array value
|
||||
DefaultArray = New value
|
||||
|
||||
; Testdefault map value
|
||||
DefaultMap = new:value
|
||||
|
||||
; Test env-default1 value
|
||||
EnvDefault1 = env-def
|
||||
|
||||
; Test env-default2 value
|
||||
EnvDefault2 = env-def
|
||||
|
||||
; Option only available in ini
|
||||
; only-ini =
|
||||
|
||||
[Other Options]
|
||||
; A slice of strings
|
||||
; StringSlice = some
|
||||
; StringSlice = value
|
||||
|
||||
; A map from string to int
|
||||
; int-map = a:1
|
||||
|
||||
[Subgroup]
|
||||
; This is a subgroup option
|
||||
; Opt =
|
||||
|
||||
[Subsubgroup]
|
||||
; This is a subsubgroup option
|
||||
; Opt =
|
||||
|
||||
[command]
|
||||
; Use for extra verbosity
|
||||
; ExtraVerbose =
|
||||
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
var opts helpOptions
|
||||
|
||||
p := NewNamedParser("TestIni", Default)
|
||||
p.AddGroup("Application Options", "The application options", &opts)
|
||||
|
||||
_, err := p.ParseArgs(test.args)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
inip := NewIniParser(p)
|
||||
|
||||
var b bytes.Buffer
|
||||
inip.Write(&b, test.options)
|
||||
|
||||
got := b.String()
|
||||
expected := test.expected
|
||||
|
||||
msg := fmt.Sprintf("with arguments %+v and ini options %b", test.args, test.options)
|
||||
assertDiff(t, got, expected, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadIni(t *testing.T) {
|
||||
var opts helpOptions
|
||||
|
||||
p := NewNamedParser("TestIni", Default)
|
||||
p.AddGroup("Application Options", "The application options", &opts)
|
||||
|
||||
inip := NewIniParser(p)
|
||||
|
||||
inic := `
|
||||
; Show verbose debug information
|
||||
verbose = true
|
||||
verbose = true
|
||||
|
||||
DefaultMap = another:"value\n1"
|
||||
DefaultMap = some:value 2
|
||||
|
||||
[Application Options]
|
||||
; A slice of pointers to string
|
||||
; PtrSlice =
|
||||
|
||||
; Test default value
|
||||
Default = "New\nvalue"
|
||||
|
||||
; Test env-default1 value
|
||||
EnvDefault1 = New value
|
||||
|
||||
[Other Options]
|
||||
# A slice of strings
|
||||
StringSlice = "some\nvalue"
|
||||
StringSlice = another value
|
||||
|
||||
; A map from string to int
|
||||
int-map = a:2
|
||||
int-map = b:3
|
||||
|
||||
`
|
||||
|
||||
b := strings.NewReader(inic)
|
||||
err := inip.Parse(b)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %s", err)
|
||||
}
|
||||
|
||||
assertBoolArray(t, opts.Verbose, []bool{true, true})
|
||||
|
||||
if v := map[string]string{"another": "value\n1", "some": "value 2"}; !reflect.DeepEqual(opts.DefaultMap, v) {
|
||||
t.Fatalf("Expected %#v for DefaultMap but got %#v", v, opts.DefaultMap)
|
||||
}
|
||||
|
||||
assertString(t, opts.Default, "New\nvalue")
|
||||
|
||||
assertString(t, opts.EnvDefault1, "New value")
|
||||
|
||||
assertStringArray(t, opts.Other.StringSlice, []string{"some\nvalue", "another value"})
|
||||
|
||||
if v, ok := opts.Other.IntMap["a"]; !ok {
|
||||
t.Errorf("Expected \"a\" in Other.IntMap")
|
||||
} else if v != 2 {
|
||||
t.Errorf("Expected Other.IntMap[\"a\"] = 2, but got %v", v)
|
||||
}
|
||||
|
||||
if v, ok := opts.Other.IntMap["b"]; !ok {
|
||||
t.Errorf("Expected \"b\" in Other.IntMap")
|
||||
} else if v != 3 {
|
||||
t.Errorf("Expected Other.IntMap[\"b\"] = 3, but got %v", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadAndWriteIni(t *testing.T) {
|
||||
var tests = []struct {
|
||||
options IniOptions
|
||||
read string
|
||||
write string
|
||||
}{
|
||||
{
|
||||
IniIncludeComments,
|
||||
`[Application Options]
|
||||
; Show verbose debug information
|
||||
verbose = true
|
||||
verbose = true
|
||||
|
||||
; Test default value
|
||||
Default = "quote me"
|
||||
|
||||
; Test default array value
|
||||
DefaultArray = 1
|
||||
DefaultArray = "2"
|
||||
DefaultArray = 3
|
||||
|
||||
; Testdefault map value
|
||||
; DefaultMap =
|
||||
|
||||
; Test env-default1 value
|
||||
EnvDefault1 = env-def
|
||||
|
||||
; Test env-default2 value
|
||||
EnvDefault2 = env-def
|
||||
|
||||
[Other Options]
|
||||
; A slice of strings
|
||||
; StringSlice =
|
||||
|
||||
; A map from string to int
|
||||
int-map = a:2
|
||||
int-map = b:"3"
|
||||
|
||||
`,
|
||||
`[Application Options]
|
||||
; Show verbose debug information
|
||||
verbose = true
|
||||
verbose = true
|
||||
|
||||
; Test default value
|
||||
Default = "quote me"
|
||||
|
||||
; Test default array value
|
||||
DefaultArray = 1
|
||||
DefaultArray = 2
|
||||
DefaultArray = 3
|
||||
|
||||
; Testdefault map value
|
||||
; DefaultMap =
|
||||
|
||||
; Test env-default1 value
|
||||
EnvDefault1 = env-def
|
||||
|
||||
; Test env-default2 value
|
||||
EnvDefault2 = env-def
|
||||
|
||||
[Other Options]
|
||||
; A slice of strings
|
||||
; StringSlice =
|
||||
|
||||
; A map from string to int
|
||||
int-map = a:2
|
||||
int-map = b:3
|
||||
|
||||
`,
|
||||
},
|
||||
{
|
||||
IniIncludeComments,
|
||||
`[Application Options]
|
||||
; Show verbose debug information
|
||||
verbose = true
|
||||
verbose = true
|
||||
|
||||
; Test default value
|
||||
Default = "quote me"
|
||||
|
||||
; Test default array value
|
||||
DefaultArray = "1"
|
||||
DefaultArray = "2"
|
||||
DefaultArray = "3"
|
||||
|
||||
; Testdefault map value
|
||||
; DefaultMap =
|
||||
|
||||
; Test env-default1 value
|
||||
EnvDefault1 = env-def
|
||||
|
||||
; Test env-default2 value
|
||||
EnvDefault2 = env-def
|
||||
|
||||
[Other Options]
|
||||
; A slice of strings
|
||||
; StringSlice =
|
||||
|
||||
; A map from string to int
|
||||
int-map = a:"2"
|
||||
int-map = b:"3"
|
||||
|
||||
`,
|
||||
`[Application Options]
|
||||
; Show verbose debug information
|
||||
verbose = true
|
||||
verbose = true
|
||||
|
||||
; Test default value
|
||||
Default = "quote me"
|
||||
|
||||
; Test default array value
|
||||
DefaultArray = "1"
|
||||
DefaultArray = "2"
|
||||
DefaultArray = "3"
|
||||
|
||||
; Testdefault map value
|
||||
; DefaultMap =
|
||||
|
||||
; Test env-default1 value
|
||||
EnvDefault1 = env-def
|
||||
|
||||
; Test env-default2 value
|
||||
EnvDefault2 = env-def
|
||||
|
||||
[Other Options]
|
||||
; A slice of strings
|
||||
; StringSlice =
|
||||
|
||||
; A map from string to int
|
||||
int-map = a:"2"
|
||||
int-map = b:"3"
|
||||
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
var opts helpOptions
|
||||
|
||||
p := NewNamedParser("TestIni", Default)
|
||||
p.AddGroup("Application Options", "The application options", &opts)
|
||||
|
||||
inip := NewIniParser(p)
|
||||
|
||||
read := strings.NewReader(test.read)
|
||||
err := inip.Parse(read)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %s", err)
|
||||
}
|
||||
|
||||
var write bytes.Buffer
|
||||
inip.Write(&write, test.options)
|
||||
|
||||
got := write.String()
|
||||
|
||||
msg := fmt.Sprintf("with ini options %b", test.options)
|
||||
assertDiff(t, got, test.write, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadIniWrongQuoting(t *testing.T) {
|
||||
var tests = []struct {
|
||||
iniFile string
|
||||
lineNumber uint
|
||||
}{
|
||||
{
|
||||
iniFile: `Default = "New\nvalue`,
|
||||
lineNumber: 1,
|
||||
},
|
||||
{
|
||||
iniFile: `StringSlice = "New\nvalue`,
|
||||
lineNumber: 1,
|
||||
},
|
||||
{
|
||||
iniFile: `StringSlice = "New\nvalue"
|
||||
StringSlice = "Second\nvalue`,
|
||||
lineNumber: 2,
|
||||
},
|
||||
{
|
||||
iniFile: `DefaultMap = some:"value`,
|
||||
lineNumber: 1,
|
||||
},
|
||||
{
|
||||
iniFile: `DefaultMap = some:value
|
||||
DefaultMap = another:"value`,
|
||||
lineNumber: 2,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
var opts helpOptions
|
||||
|
||||
p := NewNamedParser("TestIni", Default)
|
||||
p.AddGroup("Application Options", "The application options", &opts)
|
||||
|
||||
inip := NewIniParser(p)
|
||||
|
||||
inic := test.iniFile
|
||||
|
||||
b := strings.NewReader(inic)
|
||||
err := inip.Parse(b)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("Expect error")
|
||||
}
|
||||
|
||||
iniError := err.(*IniError)
|
||||
|
||||
if iniError.LineNumber != test.lineNumber {
|
||||
t.Fatalf("Expect error on line %d", test.lineNumber)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIniCommands(t *testing.T) {
|
||||
var opts struct {
|
||||
Value string `short:"v" long:"value"`
|
||||
|
||||
Add struct {
|
||||
Name int `short:"n" long:"name" ini-name:"AliasName"`
|
||||
|
||||
Other struct {
|
||||
O string `short:"o" long:"other"`
|
||||
} `group:"Other Options"`
|
||||
} `command:"add"`
|
||||
}
|
||||
|
||||
p := NewNamedParser("TestIni", Default)
|
||||
p.AddGroup("Application Options", "The application options", &opts)
|
||||
|
||||
inip := NewIniParser(p)
|
||||
|
||||
inic := `[Application Options]
|
||||
value = some value
|
||||
|
||||
[add]
|
||||
AliasName = 5
|
||||
|
||||
[add.Other Options]
|
||||
other = subgroup
|
||||
|
||||
`
|
||||
|
||||
b := strings.NewReader(inic)
|
||||
err := inip.Parse(b)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %s", err)
|
||||
}
|
||||
|
||||
assertString(t, opts.Value, "some value")
|
||||
|
||||
if opts.Add.Name != 5 {
|
||||
t.Errorf("Expected opts.Add.Name to be 5, but got %v", opts.Add.Name)
|
||||
}
|
||||
|
||||
assertString(t, opts.Add.Other.O, "subgroup")
|
||||
|
||||
// Test writing it back
|
||||
buf := &bytes.Buffer{}
|
||||
|
||||
inip.Write(buf, IniDefault)
|
||||
|
||||
assertDiff(t, buf.String(), inic, "ini contents")
|
||||
}
|
||||
|
||||
func TestIniNoIni(t *testing.T) {
|
||||
var opts struct {
|
||||
Value string `short:"v" long:"value" no-ini:"yes"`
|
||||
}
|
||||
|
||||
p := NewNamedParser("TestIni", Default)
|
||||
p.AddGroup("Application Options", "The application options", &opts)
|
||||
|
||||
inip := NewIniParser(p)
|
||||
|
||||
inic := `[Application Options]
|
||||
value = some value
|
||||
`
|
||||
|
||||
b := strings.NewReader(inic)
|
||||
err := inip.Parse(b)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("Expected error")
|
||||
}
|
||||
|
||||
iniError := err.(*IniError)
|
||||
|
||||
if v := uint(2); iniError.LineNumber != v {
|
||||
t.Errorf("Expected opts.Add.Name to be %d, but got %d", v, iniError.LineNumber)
|
||||
}
|
||||
|
||||
if v := "unknown option: value"; iniError.Message != v {
|
||||
t.Errorf("Expected opts.Add.Name to be %s, but got %s", v, iniError.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIniParse(t *testing.T) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
if err != nil {
|
||||
t.Fatalf("Cannot create temporary file: %s", err)
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
|
||||
_, err = file.WriteString("value = 123")
|
||||
if err != nil {
|
||||
t.Fatalf("Cannot write to temporary file: %s", err)
|
||||
}
|
||||
|
||||
file.Close()
|
||||
|
||||
var opts struct {
|
||||
Value int `long:"value"`
|
||||
}
|
||||
|
||||
err = IniParse(file.Name(), &opts)
|
||||
if err != nil {
|
||||
t.Fatalf("Could not parse ini: %s", err)
|
||||
}
|
||||
|
||||
if opts.Value != 123 {
|
||||
t.Fatalf("Expected Value to be \"123\" but was \"%d\"", opts.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteFile(t *testing.T) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
if err != nil {
|
||||
t.Fatalf("Cannot create temporary file: %s", err)
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
|
||||
var opts struct {
|
||||
Value int `long:"value"`
|
||||
}
|
||||
|
||||
opts.Value = 123
|
||||
|
||||
p := NewParser(&opts, Default)
|
||||
ini := NewIniParser(p)
|
||||
|
||||
err = ini.WriteFile(file.Name(), IniIncludeDefaults)
|
||||
if err != nil {
|
||||
t.Fatalf("Could not write ini file: %s", err)
|
||||
}
|
||||
|
||||
found, err := ioutil.ReadFile(file.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("Could not read written ini file: %s", err)
|
||||
}
|
||||
|
||||
expected := "[Application Options]\nValue = 123\n\n"
|
||||
|
||||
assertDiff(t, string(found), expected, "ini content")
|
||||
}
|
||||
|
||||
func TestOverwriteRequiredOptions(t *testing.T) {
|
||||
var tests = []struct {
|
||||
args []string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
args: []string{"--value", "from CLI"},
|
||||
expected: []string{
|
||||
"from CLI",
|
||||
"from default",
|
||||
},
|
||||
},
|
||||
{
|
||||
args: []string{"--value", "from CLI", "--default", "from CLI"},
|
||||
expected: []string{
|
||||
"from CLI",
|
||||
"from CLI",
|
||||
},
|
||||
},
|
||||
{
|
||||
args: []string{"--config", "no file name"},
|
||||
expected: []string{
|
||||
"from INI",
|
||||
"from INI",
|
||||
},
|
||||
},
|
||||
{
|
||||
args: []string{"--value", "from CLI before", "--default", "from CLI before", "--config", "no file name"},
|
||||
expected: []string{
|
||||
"from INI",
|
||||
"from INI",
|
||||
},
|
||||
},
|
||||
{
|
||||
args: []string{"--value", "from CLI before", "--default", "from CLI before", "--config", "no file name", "--value", "from CLI after", "--default", "from CLI after"},
|
||||
expected: []string{
|
||||
"from CLI after",
|
||||
"from CLI after",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
var opts struct {
|
||||
Config func(s string) error `long:"config" no-ini:"true"`
|
||||
Value string `long:"value" required:"true"`
|
||||
Default string `long:"default" required:"true" default:"from default"`
|
||||
}
|
||||
|
||||
p := NewParser(&opts, Default)
|
||||
|
||||
opts.Config = func(s string) error {
|
||||
ini := NewIniParser(p)
|
||||
|
||||
return ini.Parse(bytes.NewBufferString("value = from INI\ndefault = from INI"))
|
||||
}
|
||||
|
||||
_, err := p.ParseArgs(test.args)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error %s with args %+v", err, test.args)
|
||||
}
|
||||
|
||||
if opts.Value != test.expected[0] {
|
||||
t.Fatalf("Expected Value to be \"%s\" but was \"%s\" with args %+v", test.expected[0], opts.Value, test.args)
|
||||
}
|
||||
|
||||
if opts.Default != test.expected[1] {
|
||||
t.Fatalf("Expected Default to be \"%s\" but was \"%s\" with args %+v", test.expected[1], opts.Default, test.args)
|
||||
}
|
||||
}
|
||||
}
|
85
Godeps/_workspace/src/github.com/jessevdk/go-flags/long_test.go
generated
vendored
Normal file
85
Godeps/_workspace/src/github.com/jessevdk/go-flags/long_test.go
generated
vendored
Normal file
@ -0,0 +1,85 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLong(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `long:"value"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "--value")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongArg(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value string `long:"value"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "--value", "value")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
||||
|
||||
func TestLongArgEqual(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value string `long:"value"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "--value=value")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
||||
|
||||
func TestLongDefault(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value string `long:"value" default:"value"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts)
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
||||
|
||||
func TestLongOptional(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value string `long:"value" optional:"yes" optional-value:"value"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "--value")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
||||
|
||||
func TestLongOptionalArg(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value string `long:"value" optional:"yes" optional-value:"value"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "--value", "no")
|
||||
|
||||
assertStringArray(t, ret, []string{"no"})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
||||
|
||||
func TestLongOptionalArgEqual(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value string `long:"value" optional:"yes" optional-value:"value"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "--value=value", "no")
|
||||
|
||||
assertStringArray(t, ret, []string{"no"})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
158
Godeps/_workspace/src/github.com/jessevdk/go-flags/man.go
generated
vendored
Normal file
158
Godeps/_workspace/src/github.com/jessevdk/go-flags/man.go
generated
vendored
Normal file
@ -0,0 +1,158 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func formatForMan(wr io.Writer, s string) {
|
||||
for {
|
||||
idx := strings.IndexRune(s, '`')
|
||||
|
||||
if idx < 0 {
|
||||
fmt.Fprintf(wr, "%s", s)
|
||||
break
|
||||
}
|
||||
|
||||
fmt.Fprintf(wr, "%s", s[:idx])
|
||||
|
||||
s = s[idx+1:]
|
||||
idx = strings.IndexRune(s, '\'')
|
||||
|
||||
if idx < 0 {
|
||||
fmt.Fprintf(wr, "%s", s)
|
||||
break
|
||||
}
|
||||
|
||||
fmt.Fprintf(wr, "\\fB%s\\fP", s[:idx])
|
||||
s = s[idx+1:]
|
||||
}
|
||||
}
|
||||
|
||||
func writeManPageOptions(wr io.Writer, grp *Group) {
|
||||
grp.eachGroup(func(group *Group) {
|
||||
for _, opt := range group.options {
|
||||
if !opt.canCli() {
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Fprintln(wr, ".TP")
|
||||
fmt.Fprintf(wr, "\\fB")
|
||||
|
||||
if opt.ShortName != 0 {
|
||||
fmt.Fprintf(wr, "-%c", opt.ShortName)
|
||||
}
|
||||
|
||||
if len(opt.LongName) != 0 {
|
||||
if opt.ShortName != 0 {
|
||||
fmt.Fprintf(wr, ", ")
|
||||
}
|
||||
|
||||
fmt.Fprintf(wr, "--%s", opt.LongNameWithNamespace())
|
||||
}
|
||||
|
||||
fmt.Fprintln(wr, "\\fP")
|
||||
if len(opt.Description) != 0 {
|
||||
formatForMan(wr, opt.Description)
|
||||
fmt.Fprintln(wr, "")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func writeManPageSubcommands(wr io.Writer, name string, root *Command) {
|
||||
commands := root.sortedCommands()
|
||||
|
||||
for _, c := range commands {
|
||||
var nn string
|
||||
|
||||
if len(name) != 0 {
|
||||
nn = name + " " + c.Name
|
||||
} else {
|
||||
nn = c.Name
|
||||
}
|
||||
|
||||
writeManPageCommand(wr, nn, root, c)
|
||||
}
|
||||
}
|
||||
|
||||
func writeManPageCommand(wr io.Writer, name string, root *Command, command *Command) {
|
||||
fmt.Fprintf(wr, ".SS %s\n", name)
|
||||
fmt.Fprintln(wr, command.ShortDescription)
|
||||
|
||||
if len(command.LongDescription) > 0 {
|
||||
fmt.Fprintln(wr, "")
|
||||
|
||||
cmdstart := fmt.Sprintf("The %s command", command.Name)
|
||||
|
||||
if strings.HasPrefix(command.LongDescription, cmdstart) {
|
||||
fmt.Fprintf(wr, "The \\fI%s\\fP command", command.Name)
|
||||
|
||||
formatForMan(wr, command.LongDescription[len(cmdstart):])
|
||||
fmt.Fprintln(wr, "")
|
||||
} else {
|
||||
formatForMan(wr, command.LongDescription)
|
||||
fmt.Fprintln(wr, "")
|
||||
}
|
||||
}
|
||||
|
||||
var usage string
|
||||
if us, ok := command.data.(Usage); ok {
|
||||
usage = us.Usage()
|
||||
} else if command.hasCliOptions() {
|
||||
usage = fmt.Sprintf("[%s-OPTIONS]", command.Name)
|
||||
}
|
||||
|
||||
var pre string
|
||||
if root.hasCliOptions() {
|
||||
pre = fmt.Sprintf("%s [OPTIONS] %s", root.Name, command.Name)
|
||||
} else {
|
||||
pre = fmt.Sprintf("%s %s", root.Name, command.Name)
|
||||
}
|
||||
|
||||
if len(usage) > 0 {
|
||||
fmt.Fprintf(wr, "\n\\fBUsage\\fP: %s %s\n\n", pre, usage)
|
||||
}
|
||||
|
||||
if len(command.Aliases) > 0 {
|
||||
fmt.Fprintf(wr, "\n\\fBAliases\\fP: %s\n\n", strings.Join(command.Aliases, ", "))
|
||||
}
|
||||
|
||||
writeManPageOptions(wr, command.Group)
|
||||
writeManPageSubcommands(wr, name, command)
|
||||
}
|
||||
|
||||
// WriteManPage writes a basic man page in groff format to the specified
|
||||
// writer.
|
||||
func (p *Parser) WriteManPage(wr io.Writer) {
|
||||
t := time.Now()
|
||||
|
||||
fmt.Fprintf(wr, ".TH %s 1 \"%s\"\n", p.Name, t.Format("2 January 2006"))
|
||||
fmt.Fprintln(wr, ".SH NAME")
|
||||
fmt.Fprintf(wr, "%s \\- %s\n", p.Name, p.ShortDescription)
|
||||
fmt.Fprintln(wr, ".SH SYNOPSIS")
|
||||
|
||||
usage := p.Usage
|
||||
|
||||
if len(usage) == 0 {
|
||||
usage = "[OPTIONS]"
|
||||
}
|
||||
|
||||
fmt.Fprintf(wr, "\\fB%s\\fP %s\n", p.Name, usage)
|
||||
fmt.Fprintln(wr, ".SH DESCRIPTION")
|
||||
|
||||
formatForMan(wr, p.LongDescription)
|
||||
fmt.Fprintln(wr, "")
|
||||
|
||||
fmt.Fprintln(wr, ".SH OPTIONS")
|
||||
|
||||
writeManPageOptions(wr, p.Command.Group)
|
||||
|
||||
if len(p.commands) > 0 {
|
||||
fmt.Fprintln(wr, ".SH COMMANDS")
|
||||
|
||||
writeManPageSubcommands(wr, "", p.Command)
|
||||
}
|
||||
}
|
97
Godeps/_workspace/src/github.com/jessevdk/go-flags/marshal_test.go
generated
vendored
Normal file
97
Godeps/_workspace/src/github.com/jessevdk/go-flags/marshal_test.go
generated
vendored
Normal file
@ -0,0 +1,97 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type marshalled bool
|
||||
|
||||
func (m *marshalled) UnmarshalFlag(value string) error {
|
||||
if value == "yes" {
|
||||
*m = true
|
||||
} else if value == "no" {
|
||||
*m = false
|
||||
} else {
|
||||
return fmt.Errorf("`%s' is not a valid value, please specify `yes' or `no'", value)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m marshalled) MarshalFlag() (string, error) {
|
||||
if m {
|
||||
return "yes", nil
|
||||
}
|
||||
|
||||
return "no", nil
|
||||
}
|
||||
|
||||
type marshalledError bool
|
||||
|
||||
func (m marshalledError) MarshalFlag() (string, error) {
|
||||
return "", newErrorf(ErrMarshal, "Failed to marshal")
|
||||
}
|
||||
|
||||
func TestUnmarshal(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value marshalled `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v=yes")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalDefault(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value marshalled `short:"v" default:"yes"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts)
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalOptional(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value marshalled `short:"v" optional:"yes" optional-value:"yes"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalError(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value marshalled `short:"v"`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrMarshal, fmt.Sprintf("invalid argument for flag `%cv' (expected flags.marshalled): `invalid' is not a valid value, please specify `yes' or `no'", defaultShortOptDelimiter), &opts, "-vinvalid")
|
||||
}
|
||||
|
||||
func TestMarshalError(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value marshalledError `short:"v"`
|
||||
}{}
|
||||
|
||||
p := NewParser(&opts, Default)
|
||||
o := p.Command.Groups()[0].Options()[0]
|
||||
|
||||
_, err := convertToString(o.value, o.tag)
|
||||
|
||||
assertError(t, err, ErrMarshal, "Failed to marshal")
|
||||
}
|
140
Godeps/_workspace/src/github.com/jessevdk/go-flags/multitag.go
generated
vendored
Normal file
140
Godeps/_workspace/src/github.com/jessevdk/go-flags/multitag.go
generated
vendored
Normal file
@ -0,0 +1,140 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type multiTag struct {
|
||||
value string
|
||||
cache map[string][]string
|
||||
}
|
||||
|
||||
func newMultiTag(v string) multiTag {
|
||||
return multiTag{
|
||||
value: v,
|
||||
}
|
||||
}
|
||||
|
||||
func (x *multiTag) scan() (map[string][]string, error) {
|
||||
v := x.value
|
||||
|
||||
ret := make(map[string][]string)
|
||||
|
||||
// This is mostly copied from reflect.StructTag.Get
|
||||
for v != "" {
|
||||
i := 0
|
||||
|
||||
// Skip whitespace
|
||||
for i < len(v) && v[i] == ' ' {
|
||||
i++
|
||||
}
|
||||
|
||||
v = v[i:]
|
||||
|
||||
if v == "" {
|
||||
break
|
||||
}
|
||||
|
||||
// Scan to colon to find key
|
||||
i = 0
|
||||
|
||||
for i < len(v) && v[i] != ' ' && v[i] != ':' && v[i] != '"' {
|
||||
i++
|
||||
}
|
||||
|
||||
if i >= len(v) {
|
||||
return nil, newErrorf(ErrTag, "expected `:' after key name, but got end of tag (in `%v`)", x.value)
|
||||
}
|
||||
|
||||
if v[i] != ':' {
|
||||
return nil, newErrorf(ErrTag, "expected `:' after key name, but got `%v' (in `%v`)", v[i], x.value)
|
||||
}
|
||||
|
||||
if i+1 >= len(v) {
|
||||
return nil, newErrorf(ErrTag, "expected `\"' to start tag value at end of tag (in `%v`)", x.value)
|
||||
}
|
||||
|
||||
if v[i+1] != '"' {
|
||||
return nil, newErrorf(ErrTag, "expected `\"' to start tag value, but got `%v' (in `%v`)", v[i+1], x.value)
|
||||
}
|
||||
|
||||
name := v[:i]
|
||||
v = v[i+1:]
|
||||
|
||||
// Scan quoted string to find value
|
||||
i = 1
|
||||
|
||||
for i < len(v) && v[i] != '"' {
|
||||
if v[i] == '\n' {
|
||||
return nil, newErrorf(ErrTag, "unexpected newline in tag value `%v' (in `%v`)", name, x.value)
|
||||
}
|
||||
|
||||
if v[i] == '\\' {
|
||||
i++
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
if i >= len(v) {
|
||||
return nil, newErrorf(ErrTag, "expected end of tag value `\"' at end of tag (in `%v`)", x.value)
|
||||
}
|
||||
|
||||
val, err := strconv.Unquote(v[:i+1])
|
||||
|
||||
if err != nil {
|
||||
return nil, newErrorf(ErrTag, "Malformed value of tag `%v:%v` => %v (in `%v`)", name, v[:i+1], err, x.value)
|
||||
}
|
||||
|
||||
v = v[i+1:]
|
||||
|
||||
ret[name] = append(ret[name], val)
|
||||
}
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func (x *multiTag) Parse() error {
|
||||
vals, err := x.scan()
|
||||
x.cache = vals
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (x *multiTag) cached() map[string][]string {
|
||||
if x.cache == nil {
|
||||
cache, _ := x.scan()
|
||||
|
||||
if cache == nil {
|
||||
cache = make(map[string][]string)
|
||||
}
|
||||
|
||||
x.cache = cache
|
||||
}
|
||||
|
||||
return x.cache
|
||||
}
|
||||
|
||||
func (x *multiTag) Get(key string) string {
|
||||
c := x.cached()
|
||||
|
||||
if v, ok := c[key]; ok {
|
||||
return v[len(v)-1]
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *multiTag) GetMany(key string) []string {
|
||||
c := x.cached()
|
||||
return c[key]
|
||||
}
|
||||
|
||||
func (x *multiTag) Set(key string, value string) {
|
||||
c := x.cached()
|
||||
c[key] = []string{value}
|
||||
}
|
||||
|
||||
func (x *multiTag) SetMany(key string, value []string) {
|
||||
c := x.cached()
|
||||
c[key] = value
|
||||
}
|
157
Godeps/_workspace/src/github.com/jessevdk/go-flags/option.go
generated
vendored
Normal file
157
Godeps/_workspace/src/github.com/jessevdk/go-flags/option.go
generated
vendored
Normal file
@ -0,0 +1,157 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Option flag information. Contains a description of the option, short and
|
||||
// long name as well as a default value and whether an argument for this
|
||||
// flag is optional.
|
||||
type Option struct {
|
||||
// The description of the option flag. This description is shown
|
||||
// automatically in the built-in help.
|
||||
Description string
|
||||
|
||||
// The short name of the option (a single character). If not 0, the
|
||||
// option flag can be 'activated' using -<ShortName>. Either ShortName
|
||||
// or LongName needs to be non-empty.
|
||||
ShortName rune
|
||||
|
||||
// The long name of the option. If not "", the option flag can be
|
||||
// activated using --<LongName>. Either ShortName or LongName needs
|
||||
// to be non-empty.
|
||||
LongName string
|
||||
|
||||
// The default value of the option.
|
||||
Default []string
|
||||
|
||||
// The optional environment default value key name.
|
||||
EnvDefaultKey string
|
||||
|
||||
// The optional delimiter string for EnvDefaultKey values.
|
||||
EnvDefaultDelim string
|
||||
|
||||
// If true, specifies that the argument to an option flag is optional.
|
||||
// When no argument to the flag is specified on the command line, the
|
||||
// value of Default will be set in the field this option represents.
|
||||
// This is only valid for non-boolean options.
|
||||
OptionalArgument bool
|
||||
|
||||
// The optional value of the option. The optional value is used when
|
||||
// the option flag is marked as having an OptionalArgument. This means
|
||||
// that when the flag is specified, but no option argument is given,
|
||||
// the value of the field this option represents will be set to
|
||||
// OptionalValue. This is only valid for non-boolean options.
|
||||
OptionalValue []string
|
||||
|
||||
// If true, the option _must_ be specified on the command line. If the
|
||||
// option is not specified, the parser will generate an ErrRequired type
|
||||
// error.
|
||||
Required bool
|
||||
|
||||
// A name for the value of an option shown in the Help as --flag [ValueName]
|
||||
ValueName string
|
||||
|
||||
// A mask value to show in the help instead of the default value. This
|
||||
// is useful for hiding sensitive information in the help, such as
|
||||
// passwords.
|
||||
DefaultMask string
|
||||
|
||||
// The group which the option belongs to
|
||||
group *Group
|
||||
|
||||
// The struct field which the option represents.
|
||||
field reflect.StructField
|
||||
|
||||
// The struct field value which the option represents.
|
||||
value reflect.Value
|
||||
|
||||
// Determines if the option will be always quoted in the INI output
|
||||
iniQuote bool
|
||||
|
||||
tag multiTag
|
||||
isSet bool
|
||||
}
|
||||
|
||||
// LongNameWithNamespace returns the option's long name with the group namespaces
|
||||
// prepended by walking up the option's group tree. Namespaces and the long name
|
||||
// itself are separated by the parser's namespace delimiter. If the long name is
|
||||
// empty an empty string is returned.
|
||||
func (option *Option) LongNameWithNamespace() string {
|
||||
if len(option.LongName) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
// fetch the namespace delimiter from the parser which is always at the
|
||||
// end of the group hierarchy
|
||||
namespaceDelimiter := ""
|
||||
g := option.group
|
||||
|
||||
for {
|
||||
if p, ok := g.parent.(*Parser); ok {
|
||||
namespaceDelimiter = p.NamespaceDelimiter
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
switch i := g.parent.(type) {
|
||||
case *Command:
|
||||
g = i.Group
|
||||
case *Group:
|
||||
g = i
|
||||
}
|
||||
}
|
||||
|
||||
// concatenate long name with namespace
|
||||
longName := option.LongName
|
||||
g = option.group
|
||||
|
||||
for g != nil {
|
||||
if g.Namespace != "" {
|
||||
longName = g.Namespace + namespaceDelimiter + longName
|
||||
}
|
||||
|
||||
switch i := g.parent.(type) {
|
||||
case *Command:
|
||||
g = i.Group
|
||||
case *Group:
|
||||
g = i
|
||||
case *Parser:
|
||||
g = nil
|
||||
}
|
||||
}
|
||||
|
||||
return longName
|
||||
}
|
||||
|
||||
// String converts an option to a human friendly readable string describing the
|
||||
// option.
|
||||
func (option *Option) String() string {
|
||||
var s string
|
||||
var short string
|
||||
|
||||
if option.ShortName != 0 {
|
||||
data := make([]byte, utf8.RuneLen(option.ShortName))
|
||||
utf8.EncodeRune(data, option.ShortName)
|
||||
short = string(data)
|
||||
|
||||
if len(option.LongName) != 0 {
|
||||
s = fmt.Sprintf("%s%s, %s%s",
|
||||
string(defaultShortOptDelimiter), short,
|
||||
defaultLongOptDelimiter, option.LongNameWithNamespace())
|
||||
} else {
|
||||
s = fmt.Sprintf("%s%s", string(defaultShortOptDelimiter), short)
|
||||
}
|
||||
} else if len(option.LongName) != 0 {
|
||||
s = fmt.Sprintf("%s%s", defaultLongOptDelimiter, option.LongNameWithNamespace())
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// Value returns the option value as an interface{}.
|
||||
func (option *Option) Value() interface{} {
|
||||
return option.value.Interface()
|
||||
}
|
182
Godeps/_workspace/src/github.com/jessevdk/go-flags/option_private.go
generated
vendored
Normal file
182
Godeps/_workspace/src/github.com/jessevdk/go-flags/option_private.go
generated
vendored
Normal file
@ -0,0 +1,182 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Set the value of an option to the specified value. An error will be returned
|
||||
// if the specified value could not be converted to the corresponding option
|
||||
// value type.
|
||||
func (option *Option) set(value *string) error {
|
||||
option.isSet = true
|
||||
|
||||
if option.isFunc() {
|
||||
return option.call(value)
|
||||
} else if value != nil {
|
||||
return convert(*value, option.value, option.tag)
|
||||
}
|
||||
|
||||
return convert("", option.value, option.tag)
|
||||
}
|
||||
|
||||
func (option *Option) canCli() bool {
|
||||
return option.ShortName != 0 || len(option.LongName) != 0
|
||||
}
|
||||
|
||||
func (option *Option) canArgument() bool {
|
||||
if u := option.isUnmarshaler(); u != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
return !option.isBool()
|
||||
}
|
||||
|
||||
func (option *Option) emptyValue() reflect.Value {
|
||||
tp := option.value.Type()
|
||||
|
||||
if tp.Kind() == reflect.Map {
|
||||
return reflect.MakeMap(tp)
|
||||
}
|
||||
|
||||
return reflect.Zero(tp)
|
||||
}
|
||||
|
||||
func (option *Option) empty() {
|
||||
if !option.isFunc() {
|
||||
option.value.Set(option.emptyValue())
|
||||
}
|
||||
}
|
||||
|
||||
func (option *Option) clearDefault() {
|
||||
usedDefault := option.Default
|
||||
if envKey := option.EnvDefaultKey; envKey != "" {
|
||||
// os.Getenv() makes no distinction between undefined and
|
||||
// empty values, so we use syscall.Getenv()
|
||||
if value, ok := syscall.Getenv(envKey); ok {
|
||||
if option.EnvDefaultDelim != "" {
|
||||
usedDefault = strings.Split(value,
|
||||
option.EnvDefaultDelim)
|
||||
} else {
|
||||
usedDefault = []string{value}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(usedDefault) > 0 {
|
||||
option.empty()
|
||||
|
||||
for _, d := range usedDefault {
|
||||
option.set(&d)
|
||||
}
|
||||
} else {
|
||||
tp := option.value.Type()
|
||||
|
||||
switch tp.Kind() {
|
||||
case reflect.Map:
|
||||
if option.value.IsNil() {
|
||||
option.empty()
|
||||
}
|
||||
case reflect.Slice:
|
||||
if option.value.IsNil() {
|
||||
option.empty()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (option *Option) valueIsDefault() bool {
|
||||
// Check if the value of the option corresponds to its
|
||||
// default value
|
||||
emptyval := option.emptyValue()
|
||||
|
||||
checkvalptr := reflect.New(emptyval.Type())
|
||||
checkval := reflect.Indirect(checkvalptr)
|
||||
|
||||
checkval.Set(emptyval)
|
||||
|
||||
if len(option.Default) != 0 {
|
||||
for _, v := range option.Default {
|
||||
convert(v, checkval, option.tag)
|
||||
}
|
||||
}
|
||||
|
||||
return reflect.DeepEqual(option.value.Interface(), checkval.Interface())
|
||||
}
|
||||
|
||||
func (option *Option) isUnmarshaler() Unmarshaler {
|
||||
v := option.value
|
||||
|
||||
for {
|
||||
if !v.CanInterface() {
|
||||
break
|
||||
}
|
||||
|
||||
i := v.Interface()
|
||||
|
||||
if u, ok := i.(Unmarshaler); ok {
|
||||
return u
|
||||
}
|
||||
|
||||
if !v.CanAddr() {
|
||||
break
|
||||
}
|
||||
|
||||
v = v.Addr()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (option *Option) isBool() bool {
|
||||
tp := option.value.Type()
|
||||
|
||||
for {
|
||||
switch tp.Kind() {
|
||||
case reflect.Bool:
|
||||
return true
|
||||
case reflect.Slice:
|
||||
return (tp.Elem().Kind() == reflect.Bool)
|
||||
case reflect.Func:
|
||||
return tp.NumIn() == 0
|
||||
case reflect.Ptr:
|
||||
tp = tp.Elem()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (option *Option) isFunc() bool {
|
||||
return option.value.Type().Kind() == reflect.Func
|
||||
}
|
||||
|
||||
func (option *Option) call(value *string) error {
|
||||
var retval []reflect.Value
|
||||
|
||||
if value == nil {
|
||||
retval = option.value.Call(nil)
|
||||
} else {
|
||||
tp := option.value.Type().In(0)
|
||||
|
||||
val := reflect.New(tp)
|
||||
val = reflect.Indirect(val)
|
||||
|
||||
if err := convert(*value, val, option.tag); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
retval = option.value.Call([]reflect.Value{val})
|
||||
}
|
||||
|
||||
if len(retval) == 1 && retval[0].Type() == reflect.TypeOf((*error)(nil)).Elem() {
|
||||
if retval[0].Interface() == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return retval[0].Interface().(error)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
45
Godeps/_workspace/src/github.com/jessevdk/go-flags/options_test.go
generated
vendored
Normal file
45
Godeps/_workspace/src/github.com/jessevdk/go-flags/options_test.go
generated
vendored
Normal file
@ -0,0 +1,45 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPassDoubleDash(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
}{}
|
||||
|
||||
p := NewParser(&opts, PassDoubleDash)
|
||||
ret, err := p.ParseArgs([]string{"-v", "--", "-v", "-g"})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
|
||||
assertStringArray(t, ret, []string{"-v", "-g"})
|
||||
}
|
||||
|
||||
func TestPassAfterNonOption(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
}{}
|
||||
|
||||
p := NewParser(&opts, PassAfterNonOption)
|
||||
ret, err := p.ParseArgs([]string{"-v", "arg", "-v", "-g"})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
|
||||
assertStringArray(t, ret, []string{"arg", "-v", "-g"})
|
||||
}
|
55
Godeps/_workspace/src/github.com/jessevdk/go-flags/optstyle_other.go
generated
vendored
Normal file
55
Godeps/_workspace/src/github.com/jessevdk/go-flags/optstyle_other.go
generated
vendored
Normal file
@ -0,0 +1,55 @@
|
||||
// +build !windows
|
||||
|
||||
package flags
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultShortOptDelimiter = '-'
|
||||
defaultLongOptDelimiter = "--"
|
||||
defaultNameArgDelimiter = '='
|
||||
)
|
||||
|
||||
func argumentIsOption(arg string) bool {
|
||||
return len(arg) > 0 && arg[0] == '-'
|
||||
}
|
||||
|
||||
// stripOptionPrefix returns the option without the prefix and whether or
|
||||
// not the option is a long option or not.
|
||||
func stripOptionPrefix(optname string) (prefix string, name string, islong bool) {
|
||||
if strings.HasPrefix(optname, "--") {
|
||||
return "--", optname[2:], true
|
||||
} else if strings.HasPrefix(optname, "-") {
|
||||
return "-", optname[1:], false
|
||||
}
|
||||
|
||||
return "", optname, false
|
||||
}
|
||||
|
||||
// splitOption attempts to split the passed option into a name and an argument.
|
||||
// When there is no argument specified, nil will be returned for it.
|
||||
func splitOption(prefix string, option string, islong bool) (string, string, *string) {
|
||||
pos := strings.Index(option, "=")
|
||||
|
||||
if (islong && pos >= 0) || (!islong && pos == 1) {
|
||||
rest := option[pos+1:]
|
||||
return option[:pos], "=", &rest
|
||||
}
|
||||
|
||||
return option, "", nil
|
||||
}
|
||||
|
||||
// addHelpGroup adds a new group that contains default help parameters.
|
||||
func (c *Command) addHelpGroup(showHelp func() error) *Group {
|
||||
var help struct {
|
||||
ShowHelp func() error `short:"h" long:"help" description:"Show this help message"`
|
||||
}
|
||||
|
||||
help.ShowHelp = showHelp
|
||||
ret, _ := c.AddGroup("Help Options", "", &help)
|
||||
ret.isBuiltinHelp = true
|
||||
|
||||
return ret
|
||||
}
|
90
Godeps/_workspace/src/github.com/jessevdk/go-flags/optstyle_windows.go
generated
vendored
Normal file
90
Godeps/_workspace/src/github.com/jessevdk/go-flags/optstyle_windows.go
generated
vendored
Normal file
@ -0,0 +1,90 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Windows uses a front slash for both short and long options. Also it uses
|
||||
// a colon for name/argument delimter.
|
||||
const (
|
||||
defaultShortOptDelimiter = '/'
|
||||
defaultLongOptDelimiter = "/"
|
||||
defaultNameArgDelimiter = ':'
|
||||
)
|
||||
|
||||
func argumentIsOption(arg string) bool {
|
||||
// Windows-style options allow front slash for the option
|
||||
// delimiter.
|
||||
return len(arg) > 0 && (arg[0] == '-' || arg[0] == '/')
|
||||
}
|
||||
|
||||
// stripOptionPrefix returns the option without the prefix and whether or
|
||||
// not the option is a long option or not.
|
||||
func stripOptionPrefix(optname string) (prefix string, name string, islong bool) {
|
||||
// Determine if the argument is a long option or not. Windows
|
||||
// typically supports both long and short options with a single
|
||||
// front slash as the option delimiter, so handle this situation
|
||||
// nicely.
|
||||
possplit := 0
|
||||
|
||||
if strings.HasPrefix(optname, "--") {
|
||||
possplit = 2
|
||||
islong = true
|
||||
} else if strings.HasPrefix(optname, "-") {
|
||||
possplit = 1
|
||||
islong = false
|
||||
} else if strings.HasPrefix(optname, "/") {
|
||||
possplit = 1
|
||||
islong = len(optname) > 2
|
||||
}
|
||||
|
||||
return optname[:possplit], optname[possplit:], islong
|
||||
}
|
||||
|
||||
// splitOption attempts to split the passed option into a name and an argument.
|
||||
// When there is no argument specified, nil will be returned for it.
|
||||
func splitOption(prefix string, option string, islong bool) (string, string, *string) {
|
||||
if len(option) == 0 {
|
||||
return option, "", nil
|
||||
}
|
||||
|
||||
// Windows typically uses a colon for the option name and argument
|
||||
// delimiter while POSIX typically uses an equals. Support both styles,
|
||||
// but don't allow the two to be mixed. That is to say /foo:bar and
|
||||
// --foo=bar are acceptable, but /foo=bar and --foo:bar are not.
|
||||
var pos int
|
||||
var sp string
|
||||
|
||||
if prefix == "/" {
|
||||
sp = ":"
|
||||
pos = strings.Index(option, sp)
|
||||
} else if len(prefix) > 0 {
|
||||
sp = "="
|
||||
pos = strings.Index(option, sp)
|
||||
}
|
||||
|
||||
if (islong && pos >= 0) || (!islong && pos == 1) {
|
||||
rest := option[pos+1:]
|
||||
return option[:pos], sp, &rest
|
||||
}
|
||||
|
||||
return option, "", nil
|
||||
}
|
||||
|
||||
// addHelpGroup adds a new group that contains default help parameters.
|
||||
func (c *Command) addHelpGroup(showHelp func() error) *Group {
|
||||
// Windows CLI applications typically use /? for help, so make both
|
||||
// that available as well as the POSIX style h and help.
|
||||
var help struct {
|
||||
ShowHelpWindows func() error `short:"?" description:"Show this help message"`
|
||||
ShowHelpPosix func() error `short:"h" long:"help" description:"Show this help message"`
|
||||
}
|
||||
|
||||
help.ShowHelpWindows = showHelp
|
||||
help.ShowHelpPosix = showHelp
|
||||
|
||||
ret, _ := c.AddGroup("Help Options", "", &help)
|
||||
ret.isBuiltinHelp = true
|
||||
|
||||
return ret
|
||||
}
|
249
Godeps/_workspace/src/github.com/jessevdk/go-flags/parser.go
generated
vendored
Normal file
249
Godeps/_workspace/src/github.com/jessevdk/go-flags/parser.go
generated
vendored
Normal file
@ -0,0 +1,249 @@
|
||||
// Copyright 2012 Jesse van den Kieboom. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package flags
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
)
|
||||
|
||||
// A Parser provides command line option parsing. It can contain several
|
||||
// option groups each with their own set of options.
|
||||
type Parser struct {
|
||||
// Embedded, see Command for more information
|
||||
*Command
|
||||
|
||||
// A usage string to be displayed in the help message.
|
||||
Usage string
|
||||
|
||||
// Option flags changing the behavior of the parser.
|
||||
Options Options
|
||||
|
||||
// NamespaceDelimiter separates group namespaces and option long names
|
||||
NamespaceDelimiter string
|
||||
|
||||
internalError error
|
||||
}
|
||||
|
||||
// Options provides parser options that change the behavior of the option
|
||||
// parser.
|
||||
type Options uint
|
||||
|
||||
const (
|
||||
// None indicates no options.
|
||||
None Options = 0
|
||||
|
||||
// HelpFlag adds a default Help Options group to the parser containing
|
||||
// -h and --help options. When either -h or --help is specified on the
|
||||
// command line, the parser will return the special error of type
|
||||
// ErrHelp. When PrintErrors is also specified, then the help message
|
||||
// will also be automatically printed to os.Stderr.
|
||||
HelpFlag = 1 << iota
|
||||
|
||||
// PassDoubleDash passes all arguments after a double dash, --, as
|
||||
// remaining command line arguments (i.e. they will not be parsed for
|
||||
// flags).
|
||||
PassDoubleDash
|
||||
|
||||
// IgnoreUnknown ignores any unknown options and passes them as
|
||||
// remaining command line arguments instead of generating an error.
|
||||
IgnoreUnknown
|
||||
|
||||
// PrintErrors prints any errors which occurred during parsing to
|
||||
// os.Stderr.
|
||||
PrintErrors
|
||||
|
||||
// PassAfterNonOption passes all arguments after the first non option
|
||||
// as remaining command line arguments. This is equivalent to strict
|
||||
// POSIX processing.
|
||||
PassAfterNonOption
|
||||
|
||||
// Default is a convenient default set of options which should cover
|
||||
// most of the uses of the flags package.
|
||||
Default = HelpFlag | PrintErrors | PassDoubleDash
|
||||
)
|
||||
|
||||
// Parse is a convenience function to parse command line options with default
|
||||
// settings. The provided data is a pointer to a struct representing the
|
||||
// default option group (named "Application Options"). For more control, use
|
||||
// flags.NewParser.
|
||||
func Parse(data interface{}) ([]string, error) {
|
||||
return NewParser(data, Default).Parse()
|
||||
}
|
||||
|
||||
// ParseArgs is a convenience function to parse command line options with default
|
||||
// settings. The provided data is a pointer to a struct representing the
|
||||
// default option group (named "Application Options"). The args argument is
|
||||
// the list of command line arguments to parse. If you just want to parse the
|
||||
// default program command line arguments (i.e. os.Args), then use flags.Parse
|
||||
// instead. For more control, use flags.NewParser.
|
||||
func ParseArgs(data interface{}, args []string) ([]string, error) {
|
||||
return NewParser(data, Default).ParseArgs(args)
|
||||
}
|
||||
|
||||
// NewParser creates a new parser. It uses os.Args[0] as the application
|
||||
// name and then calls Parser.NewNamedParser (see Parser.NewNamedParser for
|
||||
// more details). The provided data is a pointer to a struct representing the
|
||||
// default option group (named "Application Options"), or nil if the default
|
||||
// group should not be added. The options parameter specifies a set of options
|
||||
// for the parser.
|
||||
func NewParser(data interface{}, options Options) *Parser {
|
||||
p := NewNamedParser(path.Base(os.Args[0]), options)
|
||||
|
||||
if data != nil {
|
||||
g, err := p.AddGroup("Application Options", "", data)
|
||||
|
||||
if err == nil {
|
||||
g.parent = p
|
||||
}
|
||||
|
||||
p.internalError = err
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
// NewNamedParser creates a new parser. The appname is used to display the
|
||||
// executable name in the built-in help message. Option groups and commands can
|
||||
// be added to this parser by using AddGroup and AddCommand.
|
||||
func NewNamedParser(appname string, options Options) *Parser {
|
||||
p := &Parser{
|
||||
Command: newCommand(appname, "", "", nil),
|
||||
Options: options,
|
||||
NamespaceDelimiter: ".",
|
||||
}
|
||||
|
||||
p.Command.parent = p
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
// Parse parses the command line arguments from os.Args using Parser.ParseArgs.
|
||||
// For more detailed information see ParseArgs.
|
||||
func (p *Parser) Parse() ([]string, error) {
|
||||
return p.ParseArgs(os.Args[1:])
|
||||
}
|
||||
|
||||
// ParseArgs parses the command line arguments according to the option groups that
|
||||
// were added to the parser. On successful parsing of the arguments, the
|
||||
// remaining, non-option, arguments (if any) are returned. The returned error
|
||||
// indicates a parsing error and can be used with PrintError to display
|
||||
// contextual information on where the error occurred exactly.
|
||||
//
|
||||
// When the common help group has been added (AddHelp) and either -h or --help
|
||||
// was specified in the command line arguments, a help message will be
|
||||
// automatically printed. Furthermore, the special error type ErrHelp is returned.
|
||||
// It is up to the caller to exit the program if so desired.
|
||||
func (p *Parser) ParseArgs(args []string) ([]string, error) {
|
||||
if p.internalError != nil {
|
||||
return nil, p.internalError
|
||||
}
|
||||
|
||||
p.clearIsSet()
|
||||
|
||||
// Add built-in help group to all commands if necessary
|
||||
if (p.Options & HelpFlag) != None {
|
||||
p.addHelpGroups(p.showBuiltinHelp)
|
||||
}
|
||||
|
||||
compval := os.Getenv("GO_FLAGS_COMPLETION")
|
||||
|
||||
if len(compval) != 0 {
|
||||
comp := &completion{parser: p}
|
||||
|
||||
if compval == "verbose" {
|
||||
comp.ShowDescriptions = true
|
||||
}
|
||||
|
||||
comp.execute(args)
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
s := &parseState{
|
||||
args: args,
|
||||
retargs: make([]string, 0, len(args)),
|
||||
}
|
||||
|
||||
p.fillParseState(s)
|
||||
|
||||
for !s.eof() {
|
||||
arg := s.pop()
|
||||
|
||||
// When PassDoubleDash is set and we encounter a --, then
|
||||
// simply append all the rest as arguments and break out
|
||||
if (p.Options&PassDoubleDash) != None && arg == "--" {
|
||||
s.addArgs(s.args...)
|
||||
break
|
||||
}
|
||||
|
||||
if !argumentIsOption(arg) {
|
||||
// Note: this also sets s.err, so we can just check for
|
||||
// nil here and use s.err later
|
||||
if p.parseNonOption(s) != nil {
|
||||
break
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
prefix, optname, islong := stripOptionPrefix(arg)
|
||||
optname, _, argument := splitOption(prefix, optname, islong)
|
||||
|
||||
if islong {
|
||||
err = p.parseLong(s, optname, argument)
|
||||
} else {
|
||||
err = p.parseShort(s, optname, argument)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
ignoreUnknown := (p.Options & IgnoreUnknown) != None
|
||||
parseErr := wrapError(err)
|
||||
|
||||
if !(parseErr.Type == ErrUnknownFlag && ignoreUnknown) {
|
||||
s.err = parseErr
|
||||
break
|
||||
}
|
||||
|
||||
if ignoreUnknown {
|
||||
s.addArgs(arg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if s.err == nil {
|
||||
p.eachCommand(func(c *Command) {
|
||||
c.eachGroup(func(g *Group) {
|
||||
for _, option := range g.options {
|
||||
if option.isSet {
|
||||
continue
|
||||
}
|
||||
|
||||
option.clearDefault()
|
||||
}
|
||||
})
|
||||
}, true)
|
||||
|
||||
s.checkRequired(p)
|
||||
}
|
||||
|
||||
var reterr error
|
||||
|
||||
if s.err != nil {
|
||||
reterr = s.err
|
||||
} else if len(s.command.commands) != 0 && !s.command.SubcommandsOptional {
|
||||
reterr = s.estimateCommand()
|
||||
} else if cmd, ok := s.command.data.(Commander); ok {
|
||||
reterr = cmd.Execute(s.retargs)
|
||||
}
|
||||
|
||||
if reterr != nil {
|
||||
return append([]string{s.arg}, s.args...), p.printError(reterr)
|
||||
}
|
||||
|
||||
return s.retargs, nil
|
||||
}
|
337
Godeps/_workspace/src/github.com/jessevdk/go-flags/parser_private.go
generated
vendored
Normal file
337
Godeps/_workspace/src/github.com/jessevdk/go-flags/parser_private.go
generated
vendored
Normal file
@ -0,0 +1,337 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type parseState struct {
|
||||
arg string
|
||||
args []string
|
||||
retargs []string
|
||||
positional []*Arg
|
||||
err error
|
||||
|
||||
command *Command
|
||||
lookup lookup
|
||||
}
|
||||
|
||||
func (p *parseState) eof() bool {
|
||||
return len(p.args) == 0
|
||||
}
|
||||
|
||||
func (p *parseState) pop() string {
|
||||
if p.eof() {
|
||||
return ""
|
||||
}
|
||||
|
||||
p.arg = p.args[0]
|
||||
p.args = p.args[1:]
|
||||
|
||||
return p.arg
|
||||
}
|
||||
|
||||
func (p *parseState) peek() string {
|
||||
if p.eof() {
|
||||
return ""
|
||||
}
|
||||
|
||||
return p.args[0]
|
||||
}
|
||||
|
||||
func (p *parseState) checkRequired(parser *Parser) error {
|
||||
c := parser.Command
|
||||
|
||||
var required []*Option
|
||||
|
||||
for c != nil {
|
||||
c.eachGroup(func(g *Group) {
|
||||
for _, option := range g.options {
|
||||
if !option.isSet && option.Required {
|
||||
required = append(required, option)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
c = c.Active
|
||||
}
|
||||
|
||||
if len(required) == 0 {
|
||||
if len(p.positional) > 0 && p.command.ArgsRequired {
|
||||
var reqnames []string
|
||||
|
||||
for _, arg := range p.positional {
|
||||
if arg.isRemaining() {
|
||||
break
|
||||
}
|
||||
|
||||
reqnames = append(reqnames, "`"+arg.Name+"`")
|
||||
}
|
||||
|
||||
if len(reqnames) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var msg string
|
||||
|
||||
if len(reqnames) == 1 {
|
||||
msg = fmt.Sprintf("the required argument %s was not provided", reqnames[0])
|
||||
} else {
|
||||
msg = fmt.Sprintf("the required arguments %s and %s were not provided",
|
||||
strings.Join(reqnames[:len(reqnames)-1], ", "), reqnames[len(reqnames)-1])
|
||||
}
|
||||
|
||||
p.err = newError(ErrRequired, msg)
|
||||
return p.err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(required))
|
||||
|
||||
for _, k := range required {
|
||||
names = append(names, "`"+k.String()+"'")
|
||||
}
|
||||
|
||||
sort.Strings(names)
|
||||
|
||||
var msg string
|
||||
|
||||
if len(names) == 1 {
|
||||
msg = fmt.Sprintf("the required flag %s was not specified", names[0])
|
||||
} else {
|
||||
msg = fmt.Sprintf("the required flags %s and %s were not specified",
|
||||
strings.Join(names[:len(names)-1], ", "), names[len(names)-1])
|
||||
}
|
||||
|
||||
p.err = newError(ErrRequired, msg)
|
||||
return p.err
|
||||
}
|
||||
|
||||
func (p *parseState) estimateCommand() error {
|
||||
commands := p.command.sortedCommands()
|
||||
cmdnames := make([]string, len(commands))
|
||||
|
||||
for i, v := range commands {
|
||||
cmdnames[i] = v.Name
|
||||
}
|
||||
|
||||
var msg string
|
||||
var errtype ErrorType
|
||||
|
||||
if len(p.retargs) != 0 {
|
||||
c, l := closestChoice(p.retargs[0], cmdnames)
|
||||
msg = fmt.Sprintf("Unknown command `%s'", p.retargs[0])
|
||||
errtype = ErrUnknownCommand
|
||||
|
||||
if float32(l)/float32(len(c)) < 0.5 {
|
||||
msg = fmt.Sprintf("%s, did you mean `%s'?", msg, c)
|
||||
} else if len(cmdnames) == 1 {
|
||||
msg = fmt.Sprintf("%s. You should use the %s command",
|
||||
msg,
|
||||
cmdnames[0])
|
||||
} else {
|
||||
msg = fmt.Sprintf("%s. Please specify one command of: %s or %s",
|
||||
msg,
|
||||
strings.Join(cmdnames[:len(cmdnames)-1], ", "),
|
||||
cmdnames[len(cmdnames)-1])
|
||||
}
|
||||
} else {
|
||||
errtype = ErrCommandRequired
|
||||
|
||||
if len(cmdnames) == 1 {
|
||||
msg = fmt.Sprintf("Please specify the %s command", cmdnames[0])
|
||||
} else {
|
||||
msg = fmt.Sprintf("Please specify one command of: %s or %s",
|
||||
strings.Join(cmdnames[:len(cmdnames)-1], ", "),
|
||||
cmdnames[len(cmdnames)-1])
|
||||
}
|
||||
}
|
||||
|
||||
return newError(errtype, msg)
|
||||
}
|
||||
|
||||
func (p *Parser) parseOption(s *parseState, name string, option *Option, canarg bool, argument *string) (err error) {
|
||||
if !option.canArgument() {
|
||||
if argument != nil {
|
||||
return newErrorf(ErrNoArgumentForBool, "bool flag `%s' cannot have an argument", option)
|
||||
}
|
||||
|
||||
err = option.set(nil)
|
||||
} else if argument != nil || (canarg && !s.eof()) {
|
||||
var arg string
|
||||
|
||||
if argument != nil {
|
||||
arg = *argument
|
||||
} else {
|
||||
arg = s.pop()
|
||||
if argumentIsOption(arg) {
|
||||
return newErrorf(ErrExpectedArgument, "expected argument for flag `%s', but got option `%s'", option, arg)
|
||||
}
|
||||
}
|
||||
|
||||
if option.tag.Get("unquote") != "false" {
|
||||
arg, err = unquoteIfPossible(arg)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
err = option.set(&arg)
|
||||
}
|
||||
} else if option.OptionalArgument {
|
||||
option.empty()
|
||||
|
||||
for _, v := range option.OptionalValue {
|
||||
err = option.set(&v)
|
||||
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
err = newErrorf(ErrExpectedArgument, "expected argument for flag `%s'", option)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if _, ok := err.(*Error); !ok {
|
||||
err = newErrorf(ErrMarshal, "invalid argument for flag `%s' (expected %s): %s",
|
||||
option,
|
||||
option.value.Type(),
|
||||
err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *Parser) parseLong(s *parseState, name string, argument *string) error {
|
||||
if option := s.lookup.longNames[name]; option != nil {
|
||||
// Only long options that are required can consume an argument
|
||||
// from the argument list
|
||||
canarg := !option.OptionalArgument
|
||||
|
||||
return p.parseOption(s, name, option, canarg, argument)
|
||||
}
|
||||
|
||||
return newErrorf(ErrUnknownFlag, "unknown flag `%s'", name)
|
||||
}
|
||||
|
||||
func (p *Parser) splitShortConcatArg(s *parseState, optname string) (string, *string) {
|
||||
c, n := utf8.DecodeRuneInString(optname)
|
||||
|
||||
if n == len(optname) {
|
||||
return optname, nil
|
||||
}
|
||||
|
||||
first := string(c)
|
||||
|
||||
if option := s.lookup.shortNames[first]; option != nil && option.canArgument() {
|
||||
arg := optname[n:]
|
||||
return first, &arg
|
||||
}
|
||||
|
||||
return optname, nil
|
||||
}
|
||||
|
||||
func (p *Parser) parseShort(s *parseState, optname string, argument *string) error {
|
||||
if argument == nil {
|
||||
optname, argument = p.splitShortConcatArg(s, optname)
|
||||
}
|
||||
|
||||
for i, c := range optname {
|
||||
shortname := string(c)
|
||||
|
||||
if option := s.lookup.shortNames[shortname]; option != nil {
|
||||
// Only the last short argument can consume an argument from
|
||||
// the arguments list, and only if it's non optional
|
||||
canarg := (i+utf8.RuneLen(c) == len(optname)) && !option.OptionalArgument
|
||||
|
||||
if err := p.parseOption(s, shortname, option, canarg, argument); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return newErrorf(ErrUnknownFlag, "unknown flag `%s'", shortname)
|
||||
}
|
||||
|
||||
// Only the first option can have a concatted argument, so just
|
||||
// clear argument here
|
||||
argument = nil
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *parseState) addArgs(args ...string) error {
|
||||
for len(p.positional) > 0 && len(args) > 0 {
|
||||
arg := p.positional[0]
|
||||
|
||||
if err := convert(args[0], arg.value, arg.tag); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !arg.isRemaining() {
|
||||
p.positional = p.positional[1:]
|
||||
}
|
||||
|
||||
args = args[1:]
|
||||
}
|
||||
|
||||
p.retargs = append(p.retargs, args...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Parser) parseNonOption(s *parseState) error {
|
||||
if len(s.positional) > 0 {
|
||||
return s.addArgs(s.arg)
|
||||
}
|
||||
|
||||
if cmd := s.lookup.commands[s.arg]; cmd != nil {
|
||||
s.command.Active = cmd
|
||||
cmd.fillParseState(s)
|
||||
} else if (p.Options & PassAfterNonOption) != None {
|
||||
// If PassAfterNonOption is set then all remaining arguments
|
||||
// are considered positional
|
||||
if err := s.addArgs(s.arg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.addArgs(s.args...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.args = []string{}
|
||||
} else {
|
||||
return s.addArgs(s.arg)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Parser) showBuiltinHelp() error {
|
||||
var b bytes.Buffer
|
||||
|
||||
p.WriteHelp(&b)
|
||||
return newError(ErrHelp, b.String())
|
||||
}
|
||||
|
||||
func (p *Parser) printError(err error) error {
|
||||
if err != nil && (p.Options&PrintErrors) != None {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *Parser) clearIsSet() {
|
||||
p.eachCommand(func(c *Command) {
|
||||
c.eachGroup(func(g *Group) {
|
||||
for _, option := range g.options {
|
||||
option.isSet = false
|
||||
}
|
||||
})
|
||||
}, true)
|
||||
}
|
347
Godeps/_workspace/src/github.com/jessevdk/go-flags/parser_test.go
generated
vendored
Normal file
347
Godeps/_workspace/src/github.com/jessevdk/go-flags/parser_test.go
generated
vendored
Normal file
@ -0,0 +1,347 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type defaultOptions struct {
|
||||
Int int `long:"i"`
|
||||
IntDefault int `long:"id" default:"1"`
|
||||
|
||||
String string `long:"str"`
|
||||
StringDefault string `long:"strd" default:"abc"`
|
||||
StringNotUnquoted string `long:"strnot" unquote:"false"`
|
||||
|
||||
Time time.Duration `long:"t"`
|
||||
TimeDefault time.Duration `long:"td" default:"1m"`
|
||||
|
||||
Map map[string]int `long:"m"`
|
||||
MapDefault map[string]int `long:"md" default:"a:1"`
|
||||
|
||||
Slice []int `long:"s"`
|
||||
SliceDefault []int `long:"sd" default:"1" default:"2"`
|
||||
}
|
||||
|
||||
func TestDefaults(t *testing.T) {
|
||||
var tests = []struct {
|
||||
msg string
|
||||
args []string
|
||||
expected defaultOptions
|
||||
}{
|
||||
{
|
||||
msg: "no arguments, expecting default values",
|
||||
args: []string{},
|
||||
expected: defaultOptions{
|
||||
Int: 0,
|
||||
IntDefault: 1,
|
||||
|
||||
String: "",
|
||||
StringDefault: "abc",
|
||||
|
||||
Time: 0,
|
||||
TimeDefault: time.Minute,
|
||||
|
||||
Map: map[string]int{},
|
||||
MapDefault: map[string]int{"a": 1},
|
||||
|
||||
Slice: []int{},
|
||||
SliceDefault: []int{1, 2},
|
||||
},
|
||||
},
|
||||
{
|
||||
msg: "non-zero value arguments, expecting overwritten arguments",
|
||||
args: []string{"--i=3", "--id=3", "--str=def", "--strd=def", "--t=3ms", "--td=3ms", "--m=c:3", "--md=c:3", "--s=3", "--sd=3"},
|
||||
expected: defaultOptions{
|
||||
Int: 3,
|
||||
IntDefault: 3,
|
||||
|
||||
String: "def",
|
||||
StringDefault: "def",
|
||||
|
||||
Time: 3 * time.Millisecond,
|
||||
TimeDefault: 3 * time.Millisecond,
|
||||
|
||||
Map: map[string]int{"c": 3},
|
||||
MapDefault: map[string]int{"c": 3},
|
||||
|
||||
Slice: []int{3},
|
||||
SliceDefault: []int{3},
|
||||
},
|
||||
},
|
||||
{
|
||||
msg: "zero value arguments, expecting overwritten arguments",
|
||||
args: []string{"--i=0", "--id=0", "--str", "", "--strd=\"\"", "--t=0ms", "--td=0s", "--m=:0", "--md=:0", "--s=0", "--sd=0"},
|
||||
expected: defaultOptions{
|
||||
Int: 0,
|
||||
IntDefault: 0,
|
||||
|
||||
String: "",
|
||||
StringDefault: "",
|
||||
|
||||
Time: 0,
|
||||
TimeDefault: 0,
|
||||
|
||||
Map: map[string]int{"": 0},
|
||||
MapDefault: map[string]int{"": 0},
|
||||
|
||||
Slice: []int{0},
|
||||
SliceDefault: []int{0},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
var opts defaultOptions
|
||||
|
||||
_, err := ParseArgs(&opts, test.args)
|
||||
if err != nil {
|
||||
t.Fatalf("%s:\nUnexpected error: %v", test.msg, err)
|
||||
}
|
||||
|
||||
if opts.Slice == nil {
|
||||
opts.Slice = []int{}
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(opts, test.expected) {
|
||||
t.Errorf("%s:\nUnexpected options with arguments %+v\nexpected\n%+v\nbut got\n%+v\n", test.msg, test.args, test.expected, opts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnquoting(t *testing.T) {
|
||||
var tests = []struct {
|
||||
arg string
|
||||
err error
|
||||
value string
|
||||
}{
|
||||
{
|
||||
arg: "\"abc",
|
||||
err: strconv.ErrSyntax,
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
arg: "\"\"abc\"",
|
||||
err: strconv.ErrSyntax,
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
arg: "\"abc\"",
|
||||
err: nil,
|
||||
value: "abc",
|
||||
},
|
||||
{
|
||||
arg: "\"\\\"abc\\\"\"",
|
||||
err: nil,
|
||||
value: "\"abc\"",
|
||||
},
|
||||
{
|
||||
arg: "\"\\\"abc\"",
|
||||
err: nil,
|
||||
value: "\"abc",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
var opts defaultOptions
|
||||
|
||||
for _, delimiter := range []bool{false, true} {
|
||||
p := NewParser(&opts, None)
|
||||
|
||||
var err error
|
||||
if delimiter {
|
||||
_, err = p.ParseArgs([]string{"--str=" + test.arg, "--strnot=" + test.arg})
|
||||
} else {
|
||||
_, err = p.ParseArgs([]string{"--str", test.arg, "--strnot", test.arg})
|
||||
}
|
||||
|
||||
if test.err == nil {
|
||||
if err != nil {
|
||||
t.Fatalf("Expected no error but got: %v", err)
|
||||
}
|
||||
|
||||
if test.value != opts.String {
|
||||
t.Fatalf("Expected String to be %q but got %q", test.value, opts.String)
|
||||
}
|
||||
if q := strconv.Quote(test.value); q != opts.StringNotUnquoted {
|
||||
t.Fatalf("Expected StringDefault to be %q but got %q", q, opts.StringNotUnquoted)
|
||||
}
|
||||
} else {
|
||||
if err == nil {
|
||||
t.Fatalf("Expected error")
|
||||
} else if e, ok := err.(*Error); ok {
|
||||
if strings.HasPrefix(e.Message, test.err.Error()) {
|
||||
t.Fatalf("Expected error message to end with %q but got %v", test.err.Error(), e.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// envRestorer keeps a copy of a set of env variables and can restore the env from them
|
||||
type envRestorer struct {
|
||||
env map[string]string
|
||||
}
|
||||
|
||||
func (r *envRestorer) Restore() {
|
||||
os.Clearenv()
|
||||
for k, v := range r.env {
|
||||
os.Setenv(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// EnvSnapshot returns a snapshot of the currently set env variables
|
||||
func EnvSnapshot() *envRestorer {
|
||||
r := envRestorer{make(map[string]string)}
|
||||
for _, kv := range os.Environ() {
|
||||
parts := strings.SplitN(kv, "=", 2)
|
||||
if len(parts) != 2 {
|
||||
panic("got a weird env variable: " + kv)
|
||||
}
|
||||
r.env[parts[0]] = parts[1]
|
||||
}
|
||||
return &r
|
||||
}
|
||||
|
||||
type envDefaultOptions struct {
|
||||
Int int `long:"i" default:"1" env:"TEST_I"`
|
||||
Time time.Duration `long:"t" default:"1m" env:"TEST_T"`
|
||||
Map map[string]int `long:"m" default:"a:1" env:"TEST_M" env-delim:";"`
|
||||
Slice []int `long:"s" default:"1" default:"2" env:"TEST_S" env-delim:","`
|
||||
}
|
||||
|
||||
func TestEnvDefaults(t *testing.T) {
|
||||
var tests = []struct {
|
||||
msg string
|
||||
args []string
|
||||
expected envDefaultOptions
|
||||
env map[string]string
|
||||
}{
|
||||
{
|
||||
msg: "no arguments, no env, expecting default values",
|
||||
args: []string{},
|
||||
expected: envDefaultOptions{
|
||||
Int: 1,
|
||||
Time: time.Minute,
|
||||
Map: map[string]int{"a": 1},
|
||||
Slice: []int{1, 2},
|
||||
},
|
||||
},
|
||||
{
|
||||
msg: "no arguments, env defaults, expecting env default values",
|
||||
args: []string{},
|
||||
expected: envDefaultOptions{
|
||||
Int: 2,
|
||||
Time: 2 * time.Minute,
|
||||
Map: map[string]int{"a": 2, "b": 3},
|
||||
Slice: []int{4, 5, 6},
|
||||
},
|
||||
env: map[string]string{
|
||||
"TEST_I": "2",
|
||||
"TEST_T": "2m",
|
||||
"TEST_M": "a:2;b:3",
|
||||
"TEST_S": "4,5,6",
|
||||
},
|
||||
},
|
||||
{
|
||||
msg: "non-zero value arguments, expecting overwritten arguments",
|
||||
args: []string{"--i=3", "--t=3ms", "--m=c:3", "--s=3"},
|
||||
expected: envDefaultOptions{
|
||||
Int: 3,
|
||||
Time: 3 * time.Millisecond,
|
||||
Map: map[string]int{"c": 3},
|
||||
Slice: []int{3},
|
||||
},
|
||||
env: map[string]string{
|
||||
"TEST_I": "2",
|
||||
"TEST_T": "2m",
|
||||
"TEST_M": "a:2;b:3",
|
||||
"TEST_S": "4,5,6",
|
||||
},
|
||||
},
|
||||
{
|
||||
msg: "zero value arguments, expecting overwritten arguments",
|
||||
args: []string{"--i=0", "--t=0ms", "--m=:0", "--s=0"},
|
||||
expected: envDefaultOptions{
|
||||
Int: 0,
|
||||
Time: 0,
|
||||
Map: map[string]int{"": 0},
|
||||
Slice: []int{0},
|
||||
},
|
||||
env: map[string]string{
|
||||
"TEST_I": "2",
|
||||
"TEST_T": "2m",
|
||||
"TEST_M": "a:2;b:3",
|
||||
"TEST_S": "4,5,6",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
oldEnv := EnvSnapshot()
|
||||
defer oldEnv.Restore()
|
||||
|
||||
for _, test := range tests {
|
||||
var opts envDefaultOptions
|
||||
oldEnv.Restore()
|
||||
for envKey, envValue := range test.env {
|
||||
os.Setenv(envKey, envValue)
|
||||
}
|
||||
_, err := ParseArgs(&opts, test.args)
|
||||
if err != nil {
|
||||
t.Fatalf("%s:\nUnexpected error: %v", test.msg, err)
|
||||
}
|
||||
|
||||
if opts.Slice == nil {
|
||||
opts.Slice = []int{}
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(opts, test.expected) {
|
||||
t.Errorf("%s:\nUnexpected options with arguments %+v\nexpected\n%+v\nbut got\n%+v\n", test.msg, test.args, test.expected, opts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionAsArgument(t *testing.T) {
|
||||
var tests = []struct {
|
||||
args []string
|
||||
expectError bool
|
||||
errType ErrorType
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
// short option must not be accepted as argument
|
||||
args: []string{"--string-slice", "foobar", "--string-slice", "-o"},
|
||||
expectError: true,
|
||||
errType: ErrExpectedArgument,
|
||||
errMsg: "expected argument for flag `--string-slice', but got option `-o'",
|
||||
},
|
||||
{
|
||||
// long option must not be accepted as argument
|
||||
args: []string{"--string-slice", "foobar", "--string-slice", "--other-option"},
|
||||
expectError: true,
|
||||
errType: ErrExpectedArgument,
|
||||
errMsg: "expected argument for flag `--string-slice', but got option `--other-option'",
|
||||
},
|
||||
{
|
||||
// quoted and appended option should be accepted as argument (even if it looks like an option)
|
||||
args: []string{"--string-slice", "foobar", "--string-slice=\"--other-option\""},
|
||||
},
|
||||
}
|
||||
var opts struct {
|
||||
StringSlice []string `long:"string-slice"`
|
||||
OtherOption bool `long:"other-option" short:"o"`
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
if test.expectError {
|
||||
assertParseFail(t, test.errType, test.errMsg, &opts, test.args...)
|
||||
} else {
|
||||
assertParseSuccess(t, &opts, test.args...)
|
||||
}
|
||||
}
|
||||
}
|
81
Godeps/_workspace/src/github.com/jessevdk/go-flags/pointer_test.go
generated
vendored
Normal file
81
Godeps/_workspace/src/github.com/jessevdk/go-flags/pointer_test.go
generated
vendored
Normal file
@ -0,0 +1,81 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPointerBool(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value *bool `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if !*opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPointerString(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value *string `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v", "value")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertString(t, *opts.Value, "value")
|
||||
}
|
||||
|
||||
func TestPointerSlice(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value *[]string `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v", "value1", "-v", "value2")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertStringArray(t, *opts.Value, []string{"value1", "value2"})
|
||||
}
|
||||
|
||||
func TestPointerMap(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value *map[string]int `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v", "k1:2", "-v", "k2:-5")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if v, ok := (*opts.Value)["k1"]; !ok {
|
||||
t.Errorf("Expected key \"k1\" to exist")
|
||||
} else if v != 2 {
|
||||
t.Errorf("Expected \"k1\" to be 2, but got %#v", v)
|
||||
}
|
||||
|
||||
if v, ok := (*opts.Value)["k2"]; !ok {
|
||||
t.Errorf("Expected key \"k2\" to exist")
|
||||
} else if v != -5 {
|
||||
t.Errorf("Expected \"k2\" to be -5, but got %#v", v)
|
||||
}
|
||||
}
|
||||
|
||||
type PointerGroup struct {
|
||||
Value bool `short:"v"`
|
||||
}
|
||||
|
||||
func TestPointerGroup(t *testing.T) {
|
||||
var opts = struct {
|
||||
Group *PointerGroup `group:"Group Options"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if !opts.Group.Value {
|
||||
t.Errorf("Expected Group.Value to be true")
|
||||
}
|
||||
}
|
194
Godeps/_workspace/src/github.com/jessevdk/go-flags/short_test.go
generated
vendored
Normal file
194
Godeps/_workspace/src/github.com/jessevdk/go-flags/short_test.go
generated
vendored
Normal file
@ -0,0 +1,194 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestShort(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if !opts.Value {
|
||||
t.Errorf("Expected Value to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortTooLong(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"vv"`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrShortNameTooLong, "short names can only be 1 character long, not `vv'", &opts)
|
||||
}
|
||||
|
||||
func TestShortRequired(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v" required:"true"`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrRequired, fmt.Sprintf("the required flag `%cv' was not specified", defaultShortOptDelimiter), &opts)
|
||||
}
|
||||
|
||||
func TestShortMultiConcat(t *testing.T) {
|
||||
var opts = struct {
|
||||
V bool `short:"v"`
|
||||
O bool `short:"o"`
|
||||
F bool `short:"f"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-vo", "-f")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if !opts.V {
|
||||
t.Errorf("Expected V to be true")
|
||||
}
|
||||
|
||||
if !opts.O {
|
||||
t.Errorf("Expected O to be true")
|
||||
}
|
||||
|
||||
if !opts.F {
|
||||
t.Errorf("Expected F to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortMultiRequiredConcat(t *testing.T) {
|
||||
var opts = struct {
|
||||
V bool `short:"v" required:"true"`
|
||||
O bool `short:"o" required:"true"`
|
||||
F bool `short:"f" required:"true"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-vo", "-f")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
|
||||
if !opts.V {
|
||||
t.Errorf("Expected V to be true")
|
||||
}
|
||||
|
||||
if !opts.O {
|
||||
t.Errorf("Expected O to be true")
|
||||
}
|
||||
|
||||
if !opts.F {
|
||||
t.Errorf("Expected F to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortMultiSlice(t *testing.T) {
|
||||
var opts = struct {
|
||||
Values []bool `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v", "-v")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertBoolArray(t, opts.Values, []bool{true, true})
|
||||
}
|
||||
|
||||
func TestShortMultiSliceConcat(t *testing.T) {
|
||||
var opts = struct {
|
||||
Values []bool `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-vvv")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertBoolArray(t, opts.Values, []bool{true, true, true})
|
||||
}
|
||||
|
||||
func TestShortWithEqualArg(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value string `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v=value")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
||||
|
||||
func TestShortWithArg(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value string `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-vvalue")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
||||
|
||||
func TestShortArg(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value string `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-v", "value")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
||||
|
||||
func TestShortMultiWithEqualArg(t *testing.T) {
|
||||
var opts = struct {
|
||||
F []bool `short:"f"`
|
||||
Value string `short:"v"`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrExpectedArgument, fmt.Sprintf("expected argument for flag `%cv'", defaultShortOptDelimiter), &opts, "-ffv=value")
|
||||
}
|
||||
|
||||
func TestShortMultiArg(t *testing.T) {
|
||||
var opts = struct {
|
||||
F []bool `short:"f"`
|
||||
Value string `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-ffv", "value")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertBoolArray(t, opts.F, []bool{true, true})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
||||
|
||||
func TestShortMultiArgConcatFail(t *testing.T) {
|
||||
var opts = struct {
|
||||
F []bool `short:"f"`
|
||||
Value string `short:"v"`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrExpectedArgument, fmt.Sprintf("expected argument for flag `%cv'", defaultShortOptDelimiter), &opts, "-ffvvalue")
|
||||
}
|
||||
|
||||
func TestShortMultiArgConcat(t *testing.T) {
|
||||
var opts = struct {
|
||||
F []bool `short:"f"`
|
||||
Value string `short:"v"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-vff")
|
||||
|
||||
assertStringArray(t, ret, []string{})
|
||||
assertString(t, opts.Value, "ff")
|
||||
}
|
||||
|
||||
func TestShortOptional(t *testing.T) {
|
||||
var opts = struct {
|
||||
F []bool `short:"f"`
|
||||
Value string `short:"v" optional:"yes" optional-value:"value"`
|
||||
}{}
|
||||
|
||||
ret := assertParseSuccess(t, &opts, "-fv", "f")
|
||||
|
||||
assertStringArray(t, ret, []string{"f"})
|
||||
assertString(t, opts.Value, "value")
|
||||
}
|
38
Godeps/_workspace/src/github.com/jessevdk/go-flags/tag_test.go
generated
vendored
Normal file
38
Godeps/_workspace/src/github.com/jessevdk/go-flags/tag_test.go
generated
vendored
Normal file
@ -0,0 +1,38 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTagMissingColon(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrTag, "expected `:' after key name, but got end of tag (in `short`)", &opts, "")
|
||||
}
|
||||
|
||||
func TestTagMissingValue(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrTag, "expected `\"' to start tag value at end of tag (in `short:`)", &opts, "")
|
||||
}
|
||||
|
||||
func TestTagMissingQuote(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `short:"v`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrTag, "expected end of tag value `\"' at end of tag (in `short:\"v`)", &opts, "")
|
||||
}
|
||||
|
||||
func TestTagNewline(t *testing.T) {
|
||||
var opts = struct {
|
||||
Value bool `long:"verbose" description:"verbose
|
||||
something"`
|
||||
}{}
|
||||
|
||||
assertParseFail(t, ErrTag, "unexpected newline in tag value `description' (in `long:\"verbose\" description:\"verbose\nsomething\"`)", &opts, "")
|
||||
}
|
28
Godeps/_workspace/src/github.com/jessevdk/go-flags/termsize.go
generated
vendored
Normal file
28
Godeps/_workspace/src/github.com/jessevdk/go-flags/termsize.go
generated
vendored
Normal file
@ -0,0 +1,28 @@
|
||||
// +build !windows,!plan9,!solaris
|
||||
|
||||
package flags
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type winsize struct {
|
||||
row, col uint16
|
||||
xpixel, ypixel uint16
|
||||
}
|
||||
|
||||
func getTerminalColumns() int {
|
||||
ws := winsize{}
|
||||
|
||||
if tIOCGWINSZ != 0 {
|
||||
syscall.Syscall(syscall.SYS_IOCTL,
|
||||
uintptr(0),
|
||||
uintptr(tIOCGWINSZ),
|
||||
uintptr(unsafe.Pointer(&ws)))
|
||||
|
||||
return int(ws.col)
|
||||
}
|
||||
|
||||
return 80
|
||||
}
|
7
Godeps/_workspace/src/github.com/jessevdk/go-flags/termsize_linux.go
generated
vendored
Normal file
7
Godeps/_workspace/src/github.com/jessevdk/go-flags/termsize_linux.go
generated
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
// +build linux
|
||||
|
||||
package flags
|
||||
|
||||
const (
|
||||
tIOCGWINSZ = 0x5413
|
||||
)
|
7
Godeps/_workspace/src/github.com/jessevdk/go-flags/termsize_nosysioctl.go
generated
vendored
Normal file
7
Godeps/_workspace/src/github.com/jessevdk/go-flags/termsize_nosysioctl.go
generated
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
// +build windows plan9 solaris
|
||||
|
||||
package flags
|
||||
|
||||
func getTerminalColumns() int {
|
||||
return 80
|
||||
}
|
7
Godeps/_workspace/src/github.com/jessevdk/go-flags/termsize_other.go
generated
vendored
Normal file
7
Godeps/_workspace/src/github.com/jessevdk/go-flags/termsize_other.go
generated
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
// +build !darwin,!freebsd,!netbsd,!openbsd,!linux
|
||||
|
||||
package flags
|
||||
|
||||
const (
|
||||
tIOCGWINSZ = 0
|
||||
)
|
7
Godeps/_workspace/src/github.com/jessevdk/go-flags/termsize_unix.go
generated
vendored
Normal file
7
Godeps/_workspace/src/github.com/jessevdk/go-flags/termsize_unix.go
generated
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
// +build darwin freebsd netbsd openbsd
|
||||
|
||||
package flags
|
||||
|
||||
const (
|
||||
tIOCGWINSZ = 0x40087468
|
||||
)
|
66
Godeps/_workspace/src/github.com/jessevdk/go-flags/unknown_test.go
generated
vendored
Normal file
66
Godeps/_workspace/src/github.com/jessevdk/go-flags/unknown_test.go
generated
vendored
Normal file
@ -0,0 +1,66 @@
|
||||
package flags
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUnknownFlags(t *testing.T) {
|
||||
var opts = struct {
|
||||
Verbose []bool `short:"v" long:"verbose" description:"Verbose output"`
|
||||
}{}
|
||||
|
||||
args := []string{
|
||||
"-f",
|
||||
}
|
||||
|
||||
p := NewParser(&opts, 0)
|
||||
args, err := p.ParseArgs(args)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for unknown argument")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIgnoreUnknownFlags(t *testing.T) {
|
||||
var opts = struct {
|
||||
Verbose []bool `short:"v" long:"verbose" description:"Verbose output"`
|
||||
}{}
|
||||
|
||||
args := []string{
|
||||
"hello",
|
||||
"world",
|
||||
"-v",
|
||||
"--foo=bar",
|
||||
"--verbose",
|
||||
"-f",
|
||||
}
|
||||
|
||||
p := NewParser(&opts, IgnoreUnknown)
|
||||
args, err := p.ParseArgs(args)
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
exargs := []string{
|
||||
"hello",
|
||||
"world",
|
||||
"--foo=bar",
|
||||
"-f",
|
||||
}
|
||||
|
||||
issame := (len(args) == len(exargs))
|
||||
|
||||
if issame {
|
||||
for i := 0; i < len(args); i++ {
|
||||
if args[i] != exargs[i] {
|
||||
issame = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !issame {
|
||||
t.Fatalf("Expected %v but got %v", exargs, args)
|
||||
}
|
||||
}
|
24
Godeps/_workspace/src/github.com/jmoiron/sqlx/.gitignore
generated
vendored
Normal file
24
Godeps/_workspace/src/github.com/jmoiron/sqlx/.gitignore
generated
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
tags
|
||||
environ
|
23
Godeps/_workspace/src/github.com/jmoiron/sqlx/LICENSE
generated
vendored
Normal file
23
Godeps/_workspace/src/github.com/jmoiron/sqlx/LICENSE
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
Copyright (c) 2013, 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.
|
||||
|
258
Godeps/_workspace/src/github.com/jmoiron/sqlx/README.md
generated
vendored
Normal file
258
Godeps/_workspace/src/github.com/jmoiron/sqlx/README.md
generated
vendored
Normal file
@ -0,0 +1,258 @@
|
||||
#sqlx
|
||||
|
||||
[![Build Status](https://drone.io/github.com/jmoiron/sqlx/status.png)](https://drone.io/github.com/jmoiron/sqlx/latest) [![Godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/jmoiron/sqlx) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/jmoiron/sqlx/master/LICENSE)
|
||||
|
||||
sqlx is a library which provides a set of extensions on go's standard
|
||||
`database/sql` library. The sqlx versions of `sql.DB`, `sql.TX`, `sql.Stmt`,
|
||||
et al. all leave the underlying interfaces untouched, so that their interfaces
|
||||
are a superset on the standard ones. This makes it relatively painless to
|
||||
integrate existing codebases using database/sql with sqlx.
|
||||
|
||||
Major additional concepts are:
|
||||
|
||||
* Marshal rows into structs (with embedded struct support), maps, and slices
|
||||
* Named parameter support including prepared statements
|
||||
* `Get` and `Select` to go quickly from query to struct/slice
|
||||
* `LoadFile` for executing statements from a file
|
||||
|
||||
There is now some [fairly comprehensive documentation](http://jmoiron.github.io/sqlx/) for sqlx.
|
||||
You can also read the usage below for a quick sample on how sqlx works, or check out the [API
|
||||
documentation on godoc](http://godoc.org/github.com/jmoiron/sqlx).
|
||||
|
||||
## Recent Changes
|
||||
|
||||
The ability to use basic types as Select and Get destinations was added. This
|
||||
is only valid when there is one column in the result set, and both functions
|
||||
return an error if this isn't the case. This allows for much simpler patterns
|
||||
of access for single column results:
|
||||
|
||||
```go
|
||||
var count int
|
||||
err := db.Get(&count, "SELECT count(*) FROM person;")
|
||||
|
||||
var names []string
|
||||
err := db.Select(&names, "SELECT name FROM person;")
|
||||
```
|
||||
|
||||
See the note on Scannability at the bottom of this README for some more info.
|
||||
|
||||
### Backwards Compatibility
|
||||
|
||||
There is no Go1-like promise of absolute stability, but I take the issue
|
||||
seriously and will maintain the library in a compatible state unless vital
|
||||
bugs prevent me from doing so. Since [#59](https://github.com/jmoiron/sqlx/issues/59) and [#60](https://github.com/jmoiron/sqlx/issues/60) necessitated
|
||||
breaking behavior, a wider API cleanup was done at the time of fixing.
|
||||
|
||||
## install
|
||||
|
||||
go get github.com/jmoiron/sqlx
|
||||
|
||||
## issues
|
||||
|
||||
Row headers can be ambiguous (`SELECT 1 AS a, 2 AS a`), and the result of
|
||||
`Columns()` can have duplicate names on queries like:
|
||||
|
||||
```sql
|
||||
SELECT a.id, a.name, b.id, b.name FROM foos AS a JOIN foos AS b ON a.parent = b.id;
|
||||
```
|
||||
|
||||
making a struct or map destination ambiguous. Use `AS` in your queries
|
||||
to give rows distinct names, `rows.Scan` to scan them manually, or
|
||||
`SliceScan` to get a slice of results.
|
||||
|
||||
## usage
|
||||
|
||||
Below is an example which shows some common use cases for sqlx. Check
|
||||
[sqlx_test.go](https://github.com/jmoiron/sqlx/blob/master/sqlx_test.go) for more
|
||||
usage.
|
||||
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
_ "github.com/lib/pq"
|
||||
"database/sql"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"log"
|
||||
)
|
||||
|
||||
var schema = `
|
||||
CREATE TABLE person (
|
||||
first_name text,
|
||||
last_name text,
|
||||
email text
|
||||
);
|
||||
|
||||
CREATE TABLE place (
|
||||
country text,
|
||||
city text NULL,
|
||||
telcode integer
|
||||
)`
|
||||
|
||||
type Person struct {
|
||||
FirstName string `db:"first_name"`
|
||||
LastName string `db:"last_name"`
|
||||
Email string
|
||||
}
|
||||
|
||||
type Place struct {
|
||||
Country string
|
||||
City sql.NullString
|
||||
TelCode int
|
||||
}
|
||||
|
||||
func main() {
|
||||
// this connects & tries a simple 'SELECT 1', panics on error
|
||||
// use sqlx.Open() for sql.Open() semantics
|
||||
db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
// exec the schema or fail; multi-statement Exec behavior varies between
|
||||
// database drivers; pq will exec them all, sqlite3 won't, ymmv
|
||||
db.MustExec(schema)
|
||||
|
||||
tx := db.MustBegin()
|
||||
tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "Jason", "Moiron", "jmoiron@jmoiron.net")
|
||||
tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "John", "Doe", "johndoeDNE@gmail.net")
|
||||
tx.MustExec("INSERT INTO place (country, city, telcode) VALUES ($1, $2, $3)", "United States", "New York", "1")
|
||||
tx.MustExec("INSERT INTO place (country, telcode) VALUES ($1, $2)", "Hong Kong", "852")
|
||||
tx.MustExec("INSERT INTO place (country, telcode) VALUES ($1, $2)", "Singapore", "65")
|
||||
// Named queries can use structs, so if you have an existing struct (i.e. person := &Person{}) that you have populated, you can pass it in as &person
|
||||
tx.NamedExec("INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)", &Person{"Jane", "Citizen", "jane.citzen@example.com"})
|
||||
tx.Commit()
|
||||
|
||||
// Query the database, storing results in a []Person (wrapped in []interface{})
|
||||
people := []Person{}
|
||||
db.Select(&people, "SELECT * FROM person ORDER BY first_name ASC")
|
||||
jason, john := people[0], people[1]
|
||||
|
||||
fmt.Printf("%#v\n%#v", jason, john)
|
||||
// Person{FirstName:"Jason", LastName:"Moiron", Email:"jmoiron@jmoiron.net"}
|
||||
// Person{FirstName:"John", LastName:"Doe", Email:"johndoeDNE@gmail.net"}
|
||||
|
||||
// You can also get a single result, a la QueryRow
|
||||
jason = Person{}
|
||||
err = db.Get(&jason, "SELECT * FROM person WHERE first_name=$1", "Jason")
|
||||
fmt.Printf("%#v\n", jason)
|
||||
// Person{FirstName:"Jason", LastName:"Moiron", Email:"jmoiron@jmoiron.net"}
|
||||
|
||||
// if you have null fields and use SELECT *, you must use sql.Null* in your struct
|
||||
places := []Place{}
|
||||
err := db.Select(&places, "SELECT * FROM place ORDER BY telcode ASC")
|
||||
if err != nil {
|
||||
fmt.Printf(err)
|
||||
return
|
||||
}
|
||||
usa, singsing, honkers = places[0], places[1], places[2]
|
||||
|
||||
fmt.Printf("%#v\n%#v\n%#v\n", usa, singsing, honkers)
|
||||
// Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1}
|
||||
// Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65}
|
||||
// Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852}
|
||||
|
||||
// Loop through rows using only one struct
|
||||
place := Place{}
|
||||
rows, err := db.Queryx("SELECT * FROM place")
|
||||
for rows.Next() {
|
||||
err := rows.StructScan(&place)
|
||||
if err != nil {
|
||||
log.Fataln(err)
|
||||
}
|
||||
fmt.Printf("%#v\n", place)
|
||||
}
|
||||
// Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1}
|
||||
// Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852}
|
||||
// Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65}
|
||||
|
||||
// Named queries, using `:name` as the bindvar. Automatic bindvar support
|
||||
// which takes into account the dbtype based on the driverName on sqlx.Open/Connect
|
||||
_, err = db.NamedExec(`INSERT INTO person (first_name,last_name,email) VALUES (:first,:last,:email)`,
|
||||
map[string]interface{}{
|
||||
"first": "Bin",
|
||||
"last": "Smuth",
|
||||
"email": "bensmith@allblacks.nz",
|
||||
})
|
||||
|
||||
// Selects Mr. Smith from the database
|
||||
rows, err := db.NamedQuery(`SELECT * FROM person WHERE first_name=:fn`, map[string]interface{}{"fn": "Bin"})
|
||||
|
||||
// Named queries can also use structs. Their bind names follow the same rules
|
||||
// as the name -> db mapping, so struct fields are lowercased and the `db` tag
|
||||
// is taken into consideration.
|
||||
rows, err := db.NamedQuery(`SELECT * FROM person WHERE first_name=:first_name`, jason)
|
||||
}
|
||||
```
|
||||
|
||||
## Scannability
|
||||
|
||||
Get and Select are able to take base types, so the following is now possible:
|
||||
|
||||
```go
|
||||
var name string
|
||||
db.Get(&name, "SELECT first_name FROM person WHERE id=$1", 10)
|
||||
|
||||
var ids []int64
|
||||
db.Select(&ids, "SELECT id FROM person LIMIT 20;")
|
||||
```
|
||||
|
||||
This can get complicated with destination types which are structs, like `sql.NullString`. Because of this, straightforward rules for *scannability* had to be developed. Iff something is "Scannable", then it is used directly in `rows.Scan`; if it's not, then the standard sqlx struct rules apply.
|
||||
|
||||
Something is scannable if any of the following are true:
|
||||
|
||||
* It is not a struct, ie. `reflect.ValueOf(v).Kind() != reflect.Struct`
|
||||
* It implements the `sql.Scanner` interface
|
||||
* It has no exported fields (eg. `time.Time`)
|
||||
|
||||
## embedded structs
|
||||
|
||||
Scan targets obey Go attribute rules directly, including nested embedded structs. Older versions of sqlx would attempt to also descend into non-embedded structs, but this is no longer supported.
|
||||
|
||||
Go makes *accessing* '[ambiguous selectors](http://play.golang.org/p/MGRxdjLaUc)' a compile time error, defining structs with ambiguous selectors is legal. Sqlx will decide which field to use on a struct based on a breadth first search of the struct and any structs it embeds, as specified by the order of the fields as accessible by `reflect`, which generally means in source-order. This means that sqlx chooses the outer-most, top-most matching name for targets, even when the selector might technically be ambiguous.
|
||||
|
||||
## scan safety
|
||||
|
||||
By default, scanning into structs requires the structs to have fields for all of the
|
||||
columns in the query. This was done for a few reasons:
|
||||
|
||||
* A mistake in naming during development could lead you to believe that data is
|
||||
being written to a field when actually it can't be found and it is being dropped
|
||||
* This behavior mirrors the behavior of the Go compiler with respect to unused
|
||||
variables
|
||||
* Selecting more data than you need is wasteful (more data on the wire, more time
|
||||
marshalling, etc)
|
||||
|
||||
Unlike Marshallers in the stdlib, the programmer scanning an sql result into a struct
|
||||
will generally have a full understanding of what the underlying data model is *and*
|
||||
full control over the SQL statement.
|
||||
|
||||
Despite this, there are use cases where it's convenient to be able to ignore unknown
|
||||
columns. In most of these cases, you might be better off with `ScanSlice`, but where
|
||||
you want to still use structs, there is now the `Unsafe` method. Its usage is most
|
||||
simply shown in an example:
|
||||
|
||||
```go
|
||||
db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
type Person {
|
||||
Name string
|
||||
}
|
||||
var p Person
|
||||
|
||||
// This fails, because there is no destination for location in Person
|
||||
err = db.Get(&p, "SELECT name, location FROM person LIMIT 1")
|
||||
|
||||
udb := db.Unsafe()
|
||||
|
||||
// This succeeds and just sets `Name` in the p struct
|
||||
err = udb.Get(&p, "SELECT name, location FROM person LIMIT 1")
|
||||
```
|
||||
|
||||
The `Unsafe` method is implemented on `Tx`, `DB`, and `Stmt`. When you use an unsafe
|
||||
`Tx` or `DB` to create a new `Tx` or `Stmt`, those inherit its lack of safety.
|
||||
|
84
Godeps/_workspace/src/github.com/jmoiron/sqlx/bind.go
generated
vendored
Normal file
84
Godeps/_workspace/src/github.com/jmoiron/sqlx/bind.go
generated
vendored
Normal file
@ -0,0 +1,84 @@
|
||||
package sqlx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Bindvar types supported by Rebind, BindMap and BindStruct.
|
||||
const (
|
||||
UNKNOWN = iota
|
||||
QUESTION
|
||||
DOLLAR
|
||||
NAMED
|
||||
)
|
||||
|
||||
// BindType returns the bindtype for a given database given a drivername.
|
||||
func BindType(driverName string) int {
|
||||
switch driverName {
|
||||
case "postgres":
|
||||
return DOLLAR
|
||||
case "mysql":
|
||||
return QUESTION
|
||||
case "sqlite":
|
||||
return QUESTION
|
||||
case "oci8":
|
||||
return NAMED
|
||||
}
|
||||
return UNKNOWN
|
||||
}
|
||||
|
||||
// FIXME: this should be able to be tolerant of escaped ?'s in queries without
|
||||
// losing much speed, and should be to avoid confusion.
|
||||
|
||||
// FIXME: this is now produces the wrong results for oracle's NAMED bindtype
|
||||
|
||||
// Rebind a query from the default bindtype (QUESTION) to the target bindtype.
|
||||
func Rebind(bindType int, query string) string {
|
||||
if bindType != DOLLAR {
|
||||
return query
|
||||
}
|
||||
|
||||
qb := []byte(query)
|
||||
// Add space enough for 10 params before we have to allocate
|
||||
rqb := make([]byte, 0, len(qb)+10)
|
||||
j := 1
|
||||
for _, b := range qb {
|
||||
if b == '?' {
|
||||
rqb = append(rqb, '$')
|
||||
for _, b := range strconv.Itoa(j) {
|
||||
rqb = append(rqb, byte(b))
|
||||
}
|
||||
j++
|
||||
} else {
|
||||
rqb = append(rqb, b)
|
||||
}
|
||||
}
|
||||
return string(rqb)
|
||||
}
|
||||
|
||||
// Experimental implementation of Rebind which uses a bytes.Buffer. The code is
|
||||
// much simpler and should be more resistant to odd unicode, but it is twice as
|
||||
// slow. Kept here for benchmarking purposes and to possibly replace Rebind if
|
||||
// problems arise with its somewhat naive handling of unicode.
|
||||
|
||||
func rebindBuff(bindType int, query string) string {
|
||||
if bindType != DOLLAR {
|
||||
return query
|
||||
}
|
||||
|
||||
b := make([]byte, 0, len(query))
|
||||
rqb := bytes.NewBuffer(b)
|
||||
j := 1
|
||||
for _, r := range query {
|
||||
if r == '?' {
|
||||
rqb.WriteRune('$')
|
||||
rqb.WriteString(strconv.Itoa(j))
|
||||
j++
|
||||
} else {
|
||||
rqb.WriteRune(r)
|
||||
}
|
||||
}
|
||||
|
||||
return rqb.String()
|
||||
}
|
12
Godeps/_workspace/src/github.com/jmoiron/sqlx/doc.go
generated
vendored
Normal file
12
Godeps/_workspace/src/github.com/jmoiron/sqlx/doc.go
generated
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
// Package sqlx provides general purpose extensions to database/sql.
|
||||
//
|
||||
// It is intended to seamlessly wrap database/sql and provide convenience
|
||||
// methods which are useful in the development of database driven applications.
|
||||
// None of the underlying database/sql methods are changed. Instead all extended
|
||||
// behavior is implemented through new methods defined on wrapper types.
|
||||
//
|
||||
// Additions include scanning into structs, named query support, rebinding
|
||||
// queries for different drivers, convenient shorthands for common error handling
|
||||
// and more.
|
||||
//
|
||||
package sqlx
|
322
Godeps/_workspace/src/github.com/jmoiron/sqlx/named.go
generated
vendored
Normal file
322
Godeps/_workspace/src/github.com/jmoiron/sqlx/named.go
generated
vendored
Normal file
@ -0,0 +1,322 @@
|
||||
package sqlx
|
||||
|
||||
// Named Query Support
|
||||
//
|
||||
// * BindMap - bind query bindvars to map/struct args
|
||||
// * NamedExec, NamedQuery - named query w/ struct or map
|
||||
// * NamedStmt - a pre-compiled named query which is a prepared statement
|
||||
//
|
||||
// Internal Interfaces:
|
||||
//
|
||||
// * compileNamedQuery - rebind a named query, returning a query and list of names
|
||||
// * bindArgs, bindMapArgs, bindAnyArgs - given a list of names, return an arglist
|
||||
//
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"unicode"
|
||||
|
||||
"github.com/jmoiron/sqlx/reflectx"
|
||||
)
|
||||
|
||||
// NamedStmt is a prepared statement that executes named queries. Prepare it
|
||||
// how you would execute a NamedQuery, but pass in a struct or map when executing.
|
||||
type NamedStmt struct {
|
||||
Params []string
|
||||
QueryString string
|
||||
Stmt *Stmt
|
||||
}
|
||||
|
||||
// Close closes the named statement.
|
||||
func (n *NamedStmt) Close() error {
|
||||
return n.Stmt.Close()
|
||||
}
|
||||
|
||||
// Exec executes a named statement using the struct passed.
|
||||
func (n *NamedStmt) Exec(arg interface{}) (sql.Result, error) {
|
||||
args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper)
|
||||
if err != nil {
|
||||
return *new(sql.Result), err
|
||||
}
|
||||
return n.Stmt.Exec(args...)
|
||||
}
|
||||
|
||||
// Query executes a named statement using the struct argument, returning rows.
|
||||
func (n *NamedStmt) Query(arg interface{}) (*sql.Rows, error) {
|
||||
args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return n.Stmt.Query(args...)
|
||||
}
|
||||
|
||||
// QueryRow executes a named statement against the database. Because sqlx cannot
|
||||
// create a *sql.Row with an error condition pre-set for binding errors, sqlx
|
||||
// returns a *sqlx.Row instead.
|
||||
func (n *NamedStmt) QueryRow(arg interface{}) *Row {
|
||||
args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper)
|
||||
if err != nil {
|
||||
return &Row{err: err}
|
||||
}
|
||||
return n.Stmt.QueryRowx(args...)
|
||||
}
|
||||
|
||||
// MustExec execs a NamedStmt, panicing on error
|
||||
func (n *NamedStmt) MustExec(arg interface{}) sql.Result {
|
||||
res, err := n.Exec(arg)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// Queryx using this NamedStmt
|
||||
func (n *NamedStmt) Queryx(arg interface{}) (*Rows, error) {
|
||||
r, err := n.Query(arg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Rows{Rows: r, Mapper: n.Stmt.Mapper}, err
|
||||
}
|
||||
|
||||
// QueryRowx this NamedStmt. Because of limitations with QueryRow, this is
|
||||
// an alias for QueryRow.
|
||||
func (n *NamedStmt) QueryRowx(arg interface{}) *Row {
|
||||
return n.QueryRow(arg)
|
||||
}
|
||||
|
||||
// Select using this NamedStmt
|
||||
func (n *NamedStmt) Select(dest interface{}, arg interface{}) error {
|
||||
rows, err := n.Query(arg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// if something happens here, we want to make sure the rows are Closed
|
||||
defer rows.Close()
|
||||
return scanAll(rows, dest, false)
|
||||
}
|
||||
|
||||
// Get using this NamedStmt
|
||||
func (n *NamedStmt) Get(dest interface{}, arg interface{}) error {
|
||||
r := n.QueryRowx(arg)
|
||||
return r.scanAny(dest, false)
|
||||
}
|
||||
|
||||
// A union interface of preparer and binder, required to be able to prepare
|
||||
// named statements (as the bindtype must be determined).
|
||||
type namedPreparer interface {
|
||||
Preparer
|
||||
binder
|
||||
}
|
||||
|
||||
func prepareNamed(p namedPreparer, query string) (*NamedStmt, error) {
|
||||
bindType := BindType(p.DriverName())
|
||||
q, args, err := compileNamedQuery([]byte(query), bindType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stmt, err := Preparex(p, q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &NamedStmt{
|
||||
QueryString: q,
|
||||
Params: args,
|
||||
Stmt: stmt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func bindAnyArgs(names []string, arg interface{}, m *reflectx.Mapper) ([]interface{}, error) {
|
||||
if maparg, ok := arg.(map[string]interface{}); ok {
|
||||
return bindMapArgs(names, maparg)
|
||||
}
|
||||
return bindArgs(names, arg, m)
|
||||
}
|
||||
|
||||
// private interface to generate a list of interfaces from a given struct
|
||||
// type, given a list of names to pull out of the struct. Used by public
|
||||
// BindStruct interface.
|
||||
func bindArgs(names []string, arg interface{}, m *reflectx.Mapper) ([]interface{}, error) {
|
||||
arglist := make([]interface{}, 0, len(names))
|
||||
|
||||
// grab the indirected value of arg
|
||||
v := reflect.ValueOf(arg)
|
||||
for v = reflect.ValueOf(arg); v.Kind() == reflect.Ptr; {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
fields := m.TraversalsByName(v.Type(), names)
|
||||
for i, t := range fields {
|
||||
if len(t) == 0 {
|
||||
fmt.Println(fields, names)
|
||||
return arglist, fmt.Errorf("could not find name %s in %#v", names[i], arg)
|
||||
}
|
||||
val := reflectx.FieldByIndexesReadOnly(v, t)
|
||||
arglist = append(arglist, val.Interface())
|
||||
}
|
||||
|
||||
return arglist, nil
|
||||
}
|
||||
|
||||
// like bindArgs, but for maps.
|
||||
func bindMapArgs(names []string, arg map[string]interface{}) ([]interface{}, error) {
|
||||
arglist := make([]interface{}, 0, len(names))
|
||||
|
||||
for _, name := range names {
|
||||
val, ok := arg[name]
|
||||
if !ok {
|
||||
return arglist, fmt.Errorf("could not find name %s in %#v", name, arg)
|
||||
}
|
||||
arglist = append(arglist, val)
|
||||
}
|
||||
return arglist, nil
|
||||
}
|
||||
|
||||
// bindStruct binds a named parameter query with fields from a struct argument.
|
||||
// The rules for binding field names to parameter names follow the same
|
||||
// conventions as for StructScan, including obeying the `db` struct tags.
|
||||
func bindStruct(bindType int, query string, arg interface{}, m *reflectx.Mapper) (string, []interface{}, error) {
|
||||
bound, names, err := compileNamedQuery([]byte(query), bindType)
|
||||
if err != nil {
|
||||
return "", []interface{}{}, err
|
||||
}
|
||||
|
||||
arglist, err := bindArgs(names, arg, m)
|
||||
if err != nil {
|
||||
return "", []interface{}{}, err
|
||||
}
|
||||
|
||||
return bound, arglist, nil
|
||||
}
|
||||
|
||||
// bindMap binds a named parameter query with a map of arguments.
|
||||
func bindMap(bindType int, query string, args map[string]interface{}) (string, []interface{}, error) {
|
||||
bound, names, err := compileNamedQuery([]byte(query), bindType)
|
||||
if err != nil {
|
||||
return "", []interface{}{}, err
|
||||
}
|
||||
|
||||
arglist, err := bindMapArgs(names, args)
|
||||
return bound, arglist, err
|
||||
}
|
||||
|
||||
// -- Compilation of Named Queries
|
||||
|
||||
// Allow digits and letters in bind params; additionally runes are
|
||||
// checked against underscores, meaning that bind params can have be
|
||||
// alphanumeric with underscores. Mind the difference between unicode
|
||||
// digits and numbers, where '5' is a digit but '五' is not.
|
||||
var allowedBindRunes = []*unicode.RangeTable{unicode.Letter, unicode.Digit}
|
||||
|
||||
// FIXME: this function isn't safe for unicode named params, as a failing test
|
||||
// can testify. This is not a regression but a failure of the original code
|
||||
// as well. It should be modified to range over runes in a string rather than
|
||||
// bytes, even though this is less convenient and slower. Hopefully the
|
||||
// addition of the prepared NamedStmt (which will only do this once) will make
|
||||
// up for the slightly slower ad-hoc NamedExec/NamedQuery.
|
||||
|
||||
// compile a NamedQuery into an unbound query (using the '?' bindvar) and
|
||||
// a list of names.
|
||||
func compileNamedQuery(qs []byte, bindType int) (query string, names []string, err error) {
|
||||
names = make([]string, 0, 10)
|
||||
rebound := make([]byte, 0, len(qs))
|
||||
|
||||
inName := false
|
||||
last := len(qs) - 1
|
||||
currentVar := 1
|
||||
name := make([]byte, 0, 10)
|
||||
|
||||
for i, b := range qs {
|
||||
// a ':' while we're in a name is an error
|
||||
if b == ':' {
|
||||
// if this is the second ':' in a '::' escape sequence, append a ':'
|
||||
if inName && i > 0 && qs[i-1] == ':' {
|
||||
rebound = append(rebound, ':')
|
||||
inName = false
|
||||
continue
|
||||
} else if inName {
|
||||
err = errors.New("unexpected `:` while reading named param at " + strconv.Itoa(i))
|
||||
return query, names, err
|
||||
}
|
||||
inName = true
|
||||
name = []byte{}
|
||||
// if we're in a name, and this is an allowed character, continue
|
||||
} else if inName && (unicode.IsOneOf(allowedBindRunes, rune(b)) || b == '_') && i != last {
|
||||
// append the byte to the name if we are in a name and not on the last byte
|
||||
name = append(name, b)
|
||||
// if we're in a name and it's not an allowed character, the name is done
|
||||
} else if inName {
|
||||
inName = false
|
||||
// if this is the final byte of the string and it is part of the name, then
|
||||
// make sure to add it to the name
|
||||
if i == last && unicode.IsOneOf(allowedBindRunes, rune(b)) {
|
||||
name = append(name, b)
|
||||
}
|
||||
// add the string representation to the names list
|
||||
names = append(names, string(name))
|
||||
// add a proper bindvar for the bindType
|
||||
switch bindType {
|
||||
// oracle only supports named type bind vars even for positional
|
||||
case NAMED:
|
||||
rebound = append(rebound, ':')
|
||||
rebound = append(rebound, name...)
|
||||
case QUESTION, UNKNOWN:
|
||||
rebound = append(rebound, '?')
|
||||
case DOLLAR:
|
||||
rebound = append(rebound, '$')
|
||||
for _, b := range strconv.Itoa(currentVar) {
|
||||
rebound = append(rebound, byte(b))
|
||||
}
|
||||
currentVar++
|
||||
}
|
||||
// add this byte to string unless it was not part of the name
|
||||
if i != last {
|
||||
rebound = append(rebound, b)
|
||||
} else if !unicode.IsOneOf(allowedBindRunes, rune(b)) {
|
||||
rebound = append(rebound, b)
|
||||
}
|
||||
} else {
|
||||
// this is a normal byte and should just go onto the rebound query
|
||||
rebound = append(rebound, b)
|
||||
}
|
||||
}
|
||||
|
||||
return string(rebound), names, err
|
||||
}
|
||||
|
||||
// Bind binds a struct or a map to a query with named parameters.
|
||||
func BindNamed(bindType int, query string, arg interface{}) (string, []interface{}, error) {
|
||||
return bindNamedMapper(bindType, query, arg, mapper())
|
||||
}
|
||||
|
||||
func bindNamedMapper(bindType int, query string, arg interface{}, m *reflectx.Mapper) (string, []interface{}, error) {
|
||||
if maparg, ok := arg.(map[string]interface{}); ok {
|
||||
return bindMap(bindType, query, maparg)
|
||||
}
|
||||
return bindStruct(bindType, query, arg, m)
|
||||
}
|
||||
|
||||
// NamedQuery binds a named query and then runs Query on the result using the
|
||||
// provided Ext (sqlx.Tx, sqlx.Db). It works with both structs and with
|
||||
// map[string]interface{} types.
|
||||
func NamedQuery(e Ext, query string, arg interface{}) (*Rows, error) {
|
||||
q, args, err := bindNamedMapper(BindType(e.DriverName()), query, arg, mapperFor(e))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return e.Queryx(q, args...)
|
||||
}
|
||||
|
||||
// NamedExec uses BindStruct to get a query executable by the driver and
|
||||
// then runs Exec on the result. Returns an error from the binding
|
||||
// or the query excution itself.
|
||||
func NamedExec(e Ext, query string, arg interface{}) (sql.Result, error) {
|
||||
q, args, err := bindNamedMapper(BindType(e.DriverName()), query, arg, mapperFor(e))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return e.Exec(q, args...)
|
||||
}
|
227
Godeps/_workspace/src/github.com/jmoiron/sqlx/named_test.go
generated
vendored
Normal file
227
Godeps/_workspace/src/github.com/jmoiron/sqlx/named_test.go
generated
vendored
Normal file
@ -0,0 +1,227 @@
|
||||
package sqlx
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCompileQuery(t *testing.T) {
|
||||
table := []struct {
|
||||
Q, R, D, N string
|
||||
V []string
|
||||
}{
|
||||
// basic test for named parameters, invalid char ',' terminating
|
||||
{
|
||||
Q: `INSERT INTO foo (a,b,c,d) VALUES (:name, :age, :first, :last)`,
|
||||
R: `INSERT INTO foo (a,b,c,d) VALUES (?, ?, ?, ?)`,
|
||||
D: `INSERT INTO foo (a,b,c,d) VALUES ($1, $2, $3, $4)`,
|
||||
N: `INSERT INTO foo (a,b,c,d) VALUES (:name, :age, :first, :last)`,
|
||||
V: []string{"name", "age", "first", "last"},
|
||||
},
|
||||
// This query tests a named parameter ending the string as well as numbers
|
||||
{
|
||||
Q: `SELECT * FROM a WHERE first_name=:name1 AND last_name=:name2`,
|
||||
R: `SELECT * FROM a WHERE first_name=? AND last_name=?`,
|
||||
D: `SELECT * FROM a WHERE first_name=$1 AND last_name=$2`,
|
||||
N: `SELECT * FROM a WHERE first_name=:name1 AND last_name=:name2`,
|
||||
V: []string{"name1", "name2"},
|
||||
},
|
||||
{
|
||||
Q: `SELECT "::foo" FROM a WHERE first_name=:name1 AND last_name=:name2`,
|
||||
R: `SELECT ":foo" FROM a WHERE first_name=? AND last_name=?`,
|
||||
D: `SELECT ":foo" FROM a WHERE first_name=$1 AND last_name=$2`,
|
||||
N: `SELECT ":foo" FROM a WHERE first_name=:name1 AND last_name=:name2`,
|
||||
V: []string{"name1", "name2"},
|
||||
},
|
||||
{
|
||||
Q: `SELECT 'a::b::c' || first_name, '::::ABC::_::' FROM person WHERE first_name=:first_name AND last_name=:last_name`,
|
||||
R: `SELECT 'a:b:c' || first_name, '::ABC:_:' FROM person WHERE first_name=? AND last_name=?`,
|
||||
D: `SELECT 'a:b:c' || first_name, '::ABC:_:' FROM person WHERE first_name=$1 AND last_name=$2`,
|
||||
N: `SELECT 'a:b:c' || first_name, '::ABC:_:' FROM person WHERE first_name=:first_name AND last_name=:last_name`,
|
||||
V: []string{"first_name", "last_name"},
|
||||
},
|
||||
/* This unicode awareness test sadly fails, because of our byte-wise worldview.
|
||||
* We could certainly iterate by Rune instead, though it's a great deal slower,
|
||||
* it's probably the RightWay(tm)
|
||||
{
|
||||
Q: `INSERT INTO foo (a,b,c,d) VALUES (:あ, :b, :キコ, :名前)`,
|
||||
R: `INSERT INTO foo (a,b,c,d) VALUES (?, ?, ?, ?)`,
|
||||
D: `INSERT INTO foo (a,b,c,d) VALUES ($1, $2, $3, $4)`,
|
||||
N: []string{"name", "age", "first", "last"},
|
||||
},
|
||||
*/
|
||||
}
|
||||
|
||||
for _, test := range table {
|
||||
qr, names, err := compileNamedQuery([]byte(test.Q), QUESTION)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if qr != test.R {
|
||||
t.Errorf("expected %s, got %s", test.R, qr)
|
||||
}
|
||||
if len(names) != len(test.V) {
|
||||
t.Errorf("expected %#v, got %#v", test.V, names)
|
||||
} else {
|
||||
for i, name := range names {
|
||||
if name != test.V[i] {
|
||||
t.Errorf("expected %dth name to be %s, got %s", i+1, test.V[i], name)
|
||||
}
|
||||
}
|
||||
}
|
||||
qd, _, _ := compileNamedQuery([]byte(test.Q), DOLLAR)
|
||||
if qd != test.D {
|
||||
t.Errorf("\nexpected: `%s`\ngot: `%s`", test.D, qd)
|
||||
}
|
||||
|
||||
qq, _, _ := compileNamedQuery([]byte(test.Q), NAMED)
|
||||
if qq != test.N {
|
||||
t.Errorf("\nexpected: `%s`\ngot: `%s`\n(len: %d vs %d)", test.N, qq, len(test.N), len(qq))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Test struct {
|
||||
t *testing.T
|
||||
}
|
||||
|
||||
func (t Test) Error(err error, msg ...interface{}) {
|
||||
if err != nil {
|
||||
if len(msg) == 0 {
|
||||
t.t.Error(err)
|
||||
} else {
|
||||
t.t.Error(msg...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t Test) Errorf(err error, format string, args ...interface{}) {
|
||||
if err != nil {
|
||||
t.t.Errorf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNamedQueries(t *testing.T) {
|
||||
RunWithSchema(defaultSchema, t, func(db *DB, t *testing.T) {
|
||||
loadDefaultFixture(db, t)
|
||||
test := Test{t}
|
||||
var ns *NamedStmt
|
||||
var err error
|
||||
|
||||
// Check that invalid preparations fail
|
||||
ns, err = db.PrepareNamed("SELECT * FROM person WHERE first_name=:first:name")
|
||||
if err == nil {
|
||||
t.Error("Expected an error with invalid prepared statement.")
|
||||
}
|
||||
|
||||
ns, err = db.PrepareNamed("invalid sql")
|
||||
if err == nil {
|
||||
t.Error("Expected an error with invalid prepared statement.")
|
||||
}
|
||||
|
||||
// Check closing works as anticipated
|
||||
ns, err = db.PrepareNamed("SELECT * FROM person WHERE first_name=:first_name")
|
||||
test.Error(err)
|
||||
err = ns.Close()
|
||||
test.Error(err)
|
||||
|
||||
ns, err = db.PrepareNamed(`
|
||||
SELECT first_name, last_name, email
|
||||
FROM person WHERE first_name=:first_name AND email=:email`)
|
||||
test.Error(err)
|
||||
|
||||
// test Queryx w/ uses Query
|
||||
p := Person{FirstName: "Jason", LastName: "Moiron", Email: "jmoiron@jmoiron.net"}
|
||||
|
||||
rows, err := ns.Queryx(p)
|
||||
test.Error(err)
|
||||
for rows.Next() {
|
||||
var p2 Person
|
||||
rows.StructScan(&p2)
|
||||
if p.FirstName != p2.FirstName {
|
||||
t.Errorf("got %s, expected %s", p.FirstName, p2.FirstName)
|
||||
}
|
||||
if p.LastName != p2.LastName {
|
||||
t.Errorf("got %s, expected %s", p.LastName, p2.LastName)
|
||||
}
|
||||
if p.Email != p2.Email {
|
||||
t.Errorf("got %s, expected %s", p.Email, p2.Email)
|
||||
}
|
||||
}
|
||||
|
||||
// test Select
|
||||
people := make([]Person, 0, 5)
|
||||
err = ns.Select(&people, p)
|
||||
test.Error(err)
|
||||
|
||||
if len(people) != 1 {
|
||||
t.Errorf("got %d results, expected %d", len(people), 1)
|
||||
}
|
||||
if p.FirstName != people[0].FirstName {
|
||||
t.Errorf("got %s, expected %s", p.FirstName, people[0].FirstName)
|
||||
}
|
||||
if p.LastName != people[0].LastName {
|
||||
t.Errorf("got %s, expected %s", p.LastName, people[0].LastName)
|
||||
}
|
||||
if p.Email != people[0].Email {
|
||||
t.Errorf("got %s, expected %s", p.Email, people[0].Email)
|
||||
}
|
||||
|
||||
// test Exec
|
||||
ns, err = db.PrepareNamed(`
|
||||
INSERT INTO person (first_name, last_name, email)
|
||||
VALUES (:first_name, :last_name, :email)`)
|
||||
test.Error(err)
|
||||
|
||||
js := Person{
|
||||
FirstName: "Julien",
|
||||
LastName: "Savea",
|
||||
Email: "jsavea@ab.co.nz",
|
||||
}
|
||||
_, err = ns.Exec(js)
|
||||
test.Error(err)
|
||||
|
||||
// Make sure we can pull him out again
|
||||
p2 := Person{}
|
||||
db.Get(&p2, db.Rebind("SELECT * FROM person WHERE email=?"), js.Email)
|
||||
if p2.Email != js.Email {
|
||||
t.Errorf("expected %s, got %s", js.Email, p2.Email)
|
||||
}
|
||||
|
||||
// test Txn NamedStmts
|
||||
tx := db.MustBegin()
|
||||
txns := tx.NamedStmt(ns)
|
||||
|
||||
// We're going to add Steven in this txn
|
||||
sl := Person{
|
||||
FirstName: "Steven",
|
||||
LastName: "Luatua",
|
||||
Email: "sluatua@ab.co.nz",
|
||||
}
|
||||
|
||||
_, err = txns.Exec(sl)
|
||||
test.Error(err)
|
||||
// then rollback...
|
||||
tx.Rollback()
|
||||
// looking for Steven after a rollback should fail
|
||||
err = db.Get(&p2, db.Rebind("SELECT * FROM person WHERE email=?"), sl.Email)
|
||||
if err != sql.ErrNoRows {
|
||||
t.Errorf("expected no rows error, got %v", err)
|
||||
}
|
||||
|
||||
// now do the same, but commit
|
||||
tx = db.MustBegin()
|
||||
txns = tx.NamedStmt(ns)
|
||||
_, err = txns.Exec(sl)
|
||||
test.Error(err)
|
||||
tx.Commit()
|
||||
|
||||
// looking for Steven after a Commit should succeed
|
||||
err = db.Get(&p2, db.Rebind("SELECT * FROM person WHERE email=?"), sl.Email)
|
||||
test.Error(err)
|
||||
if p2.Email != sl.Email {
|
||||
t.Errorf("expected %s, got %s", sl.Email, p2.Email)
|
||||
}
|
||||
|
||||
})
|
||||
}
|
17
Godeps/_workspace/src/github.com/jmoiron/sqlx/reflectx/README.md
generated
vendored
Normal file
17
Godeps/_workspace/src/github.com/jmoiron/sqlx/reflectx/README.md
generated
vendored
Normal file
@ -0,0 +1,17 @@
|
||||
# reflectx
|
||||
|
||||
The sqlx package has special reflect needs. In particular, it needs to:
|
||||
|
||||
* be able to map a name to a field
|
||||
* understand embedded structs
|
||||
* understand mapping names to fields by a particular tag
|
||||
* user specified name -> field mapping functions
|
||||
|
||||
These behaviors mimic the behaviors by the standard library marshallers and also the
|
||||
behavior of standard Go accessors.
|
||||
|
||||
The first two are amply taken care of by `Reflect.Value.FieldByName`, and the third is
|
||||
addressed by `Reflect.Value.FieldByNameFunc`, but these don't quite understand struct
|
||||
tags in the ways that are vital to most marshalers, and they are slow.
|
||||
|
||||
This reflectx package extends reflect to achieve these goals.
|
250
Godeps/_workspace/src/github.com/jmoiron/sqlx/reflectx/reflect.go
generated
vendored
Normal file
250
Godeps/_workspace/src/github.com/jmoiron/sqlx/reflectx/reflect.go
generated
vendored
Normal file
@ -0,0 +1,250 @@
|
||||
// Package reflect implements extensions to the standard reflect lib suitable
|
||||
// for implementing marshaling and unmarshaling packages. The main Mapper type
|
||||
// allows for Go-compatible named atribute access, including accessing embedded
|
||||
// struct attributes and the ability to use functions and struct tags to
|
||||
// customize field names.
|
||||
//
|
||||
package reflectx
|
||||
|
||||
import "sync"
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
type fieldMap map[string][]int
|
||||
|
||||
// Mapper is a general purpose mapper of names to struct fields. A Mapper
|
||||
// behaves like most marshallers, optionally obeying a field tag for name
|
||||
// mapping and a function to provide a basic mapping of fields to names.
|
||||
type Mapper struct {
|
||||
cache map[reflect.Type]fieldMap
|
||||
tagName string
|
||||
mapFunc func(string) string
|
||||
mutex sync.Mutex
|
||||
}
|
||||
|
||||
// NewMapper returns a new mapper which optionally obeys the field tag given
|
||||
// by tagName. If tagName is the empty string, it is ignored.
|
||||
func NewMapper(tagName string) *Mapper {
|
||||
return &Mapper{
|
||||
cache: make(map[reflect.Type]fieldMap),
|
||||
tagName: tagName,
|
||||
}
|
||||
}
|
||||
|
||||
// NewMapperFunc returns a new mapper which optionally obeys a field tag and
|
||||
// a struct field name mapper func given by f. Tags will take precedence, but
|
||||
// for any other field, the mapped name will be f(field.Name)
|
||||
func NewMapperFunc(tagName string, f func(string) string) *Mapper {
|
||||
return &Mapper{
|
||||
cache: make(map[reflect.Type]fieldMap),
|
||||
tagName: tagName,
|
||||
mapFunc: f,
|
||||
}
|
||||
}
|
||||
|
||||
// TypeMap returns a mapping of field strings to int slices representing
|
||||
// the traversal down the struct to reach the field.
|
||||
func (m *Mapper) TypeMap(t reflect.Type) fieldMap {
|
||||
m.mutex.Lock()
|
||||
mapping, ok := m.cache[t]
|
||||
if !ok {
|
||||
mapping = getMapping(t, m.tagName, m.mapFunc)
|
||||
m.cache[t] = mapping
|
||||
}
|
||||
m.mutex.Unlock()
|
||||
return mapping
|
||||
}
|
||||
|
||||
// FieldMap returns the mapper's mapping of field names to reflect values. Panics
|
||||
// if v's Kind is not Struct, or v is not Indirectable to a struct kind.
|
||||
func (m *Mapper) FieldMap(v reflect.Value) map[string]reflect.Value {
|
||||
v = reflect.Indirect(v)
|
||||
mustBe(v, reflect.Struct)
|
||||
|
||||
r := map[string]reflect.Value{}
|
||||
nm := m.TypeMap(v.Type())
|
||||
for tagName, indexes := range nm {
|
||||
r[tagName] = FieldByIndexes(v, indexes)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// FieldByName returns a field by the its mapped name as a reflect.Value.
|
||||
// Panics if v's Kind is not Struct or v is not Indirectable to a struct Kind.
|
||||
// Returns zero Value if the name is not found.
|
||||
func (m *Mapper) FieldByName(v reflect.Value, name string) reflect.Value {
|
||||
v = reflect.Indirect(v)
|
||||
mustBe(v, reflect.Struct)
|
||||
|
||||
nm := m.TypeMap(v.Type())
|
||||
traversal, ok := nm[name]
|
||||
if !ok {
|
||||
return *new(reflect.Value)
|
||||
}
|
||||
return FieldByIndexes(v, traversal)
|
||||
}
|
||||
|
||||
// FieldsByName returns a slice of values corresponding to the slice of names
|
||||
// for the value. Panics if v's Kind is not Struct or v is not Indirectable
|
||||
// to a struct Kind. Returns zero Value for each name not found.
|
||||
func (m *Mapper) FieldsByName(v reflect.Value, names []string) []reflect.Value {
|
||||
v = reflect.Indirect(v)
|
||||
mustBe(v, reflect.Struct)
|
||||
|
||||
nm := m.TypeMap(v.Type())
|
||||
|
||||
vals := make([]reflect.Value, 0, len(names))
|
||||
for _, name := range names {
|
||||
traversal, ok := nm[name]
|
||||
if !ok {
|
||||
vals = append(vals, *new(reflect.Value))
|
||||
} else {
|
||||
vals = append(vals, FieldByIndexes(v, traversal))
|
||||
}
|
||||
}
|
||||
return vals
|
||||
}
|
||||
|
||||
// Traversals by name returns a slice of int slices which represent the struct
|
||||
// traversals for each mapped name. Panics if t is not a struct or Indirectable
|
||||
// to a struct. Returns empty int slice for each name not found.
|
||||
func (m *Mapper) TraversalsByName(t reflect.Type, names []string) [][]int {
|
||||
t = Deref(t)
|
||||
mustBe(t, reflect.Struct)
|
||||
nm := m.TypeMap(t)
|
||||
|
||||
r := make([][]int, 0, len(names))
|
||||
for _, name := range names {
|
||||
traversal, ok := nm[name]
|
||||
if !ok {
|
||||
r = append(r, []int{})
|
||||
} else {
|
||||
r = append(r, traversal)
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// FieldByIndexes returns a value for a particular struct traversal.
|
||||
func FieldByIndexes(v reflect.Value, indexes []int) reflect.Value {
|
||||
for _, i := range indexes {
|
||||
v = reflect.Indirect(v).Field(i)
|
||||
// if this is a pointer, it's possible it is nil
|
||||
if v.Kind() == reflect.Ptr && v.IsNil() {
|
||||
alloc := reflect.New(Deref(v.Type()))
|
||||
v.Set(alloc)
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// FieldByIndexesReadOnly returns a value for a particular struct traversal,
|
||||
// but is not concerned with allocating nil pointers because the value is
|
||||
// going to be used for reading and not setting.
|
||||
func FieldByIndexesReadOnly(v reflect.Value, indexes []int) reflect.Value {
|
||||
for _, i := range indexes {
|
||||
v = reflect.Indirect(v).Field(i)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Deref is Indirect for reflect.Types
|
||||
func Deref(t reflect.Type) reflect.Type {
|
||||
if t.Kind() == reflect.Ptr {
|
||||
t = t.Elem()
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// -- helpers & utilities --
|
||||
|
||||
type Kinder interface {
|
||||
Kind() reflect.Kind
|
||||
}
|
||||
|
||||
// mustBe checks a value against a kind, panicing with a reflect.ValueError
|
||||
// if the kind isn't that which is required.
|
||||
func mustBe(v Kinder, expected reflect.Kind) {
|
||||
k := v.Kind()
|
||||
if k != expected {
|
||||
panic(&reflect.ValueError{Method: methodName(), Kind: k})
|
||||
}
|
||||
}
|
||||
|
||||
// methodName is returns the caller of the function calling methodName
|
||||
func methodName() string {
|
||||
pc, _, _, _ := runtime.Caller(2)
|
||||
f := runtime.FuncForPC(pc)
|
||||
if f == nil {
|
||||
return "unknown method"
|
||||
}
|
||||
return f.Name()
|
||||
}
|
||||
|
||||
type typeQueue struct {
|
||||
t reflect.Type
|
||||
p []int
|
||||
}
|
||||
|
||||
// A copying append that creates a new slice each time.
|
||||
func apnd(is []int, i int) []int {
|
||||
x := make([]int, len(is)+1)
|
||||
for p, n := range is {
|
||||
x[p] = n
|
||||
}
|
||||
x[len(x)-1] = i
|
||||
return x
|
||||
}
|
||||
|
||||
// getMapping returns a mapping for the t type, using the tagName and the mapFunc
|
||||
// to determine the canonical names of fields.
|
||||
func getMapping(t reflect.Type, tagName string, mapFunc func(string) string) fieldMap {
|
||||
queue := []typeQueue{}
|
||||
queue = append(queue, typeQueue{Deref(t), []int{}})
|
||||
m := fieldMap{}
|
||||
for len(queue) != 0 {
|
||||
// pop the first item off of the queue
|
||||
tq := queue[0]
|
||||
queue = queue[1:]
|
||||
// iterate through all of its fields
|
||||
for fieldPos := 0; fieldPos < tq.t.NumField(); fieldPos++ {
|
||||
f := tq.t.Field(fieldPos)
|
||||
|
||||
name := f.Tag.Get(tagName)
|
||||
if len(name) == 0 {
|
||||
if mapFunc != nil {
|
||||
name = mapFunc(f.Name)
|
||||
} else {
|
||||
name = f.Name
|
||||
}
|
||||
}
|
||||
|
||||
// if the name is "-", disabled via a tag, skip it
|
||||
if name == "-" {
|
||||
continue
|
||||
}
|
||||
|
||||
// skip unexported fields
|
||||
if len(f.PkgPath) != 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// bfs search of anonymous embedded structs
|
||||
if f.Anonymous {
|
||||
queue = append(queue, typeQueue{Deref(f.Type), apnd(tq.p, fieldPos)})
|
||||
continue
|
||||
}
|
||||
|
||||
// if the name is shadowed by an earlier identical name in the search, skip it
|
||||
if _, ok := m[name]; ok {
|
||||
continue
|
||||
}
|
||||
// add it to the map at the current position
|
||||
m[name] = apnd(tq.p, fieldPos)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
216
Godeps/_workspace/src/github.com/jmoiron/sqlx/reflectx/reflect_test.go
generated
vendored
Normal file
216
Godeps/_workspace/src/github.com/jmoiron/sqlx/reflectx/reflect_test.go
generated
vendored
Normal file
@ -0,0 +1,216 @@
|
||||
package reflectx
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func ival(v reflect.Value) int {
|
||||
return v.Interface().(int)
|
||||
}
|
||||
|
||||
func TestBasic(t *testing.T) {
|
||||
type Foo struct {
|
||||
A int
|
||||
B int
|
||||
C int
|
||||
}
|
||||
|
||||
f := Foo{1, 2, 3}
|
||||
fv := reflect.ValueOf(f)
|
||||
m := NewMapper("")
|
||||
|
||||
v := m.FieldByName(fv, "A")
|
||||
if ival(v) != f.A {
|
||||
t.Errorf("Expecting %d, got %d", ival(v), f.A)
|
||||
}
|
||||
v = m.FieldByName(fv, "B")
|
||||
if ival(v) != f.B {
|
||||
t.Errorf("Expecting %d, got %d", f.B, ival(v))
|
||||
}
|
||||
v = m.FieldByName(fv, "C")
|
||||
if ival(v) != f.C {
|
||||
t.Errorf("Expecting %d, got %d", f.C, ival(v))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbedded(t *testing.T) {
|
||||
type Foo struct {
|
||||
A int
|
||||
}
|
||||
|
||||
type Bar struct {
|
||||
Foo
|
||||
B int
|
||||
}
|
||||
|
||||
type Baz struct {
|
||||
A int
|
||||
Bar
|
||||
}
|
||||
|
||||
m := NewMapper("")
|
||||
|
||||
z := Baz{}
|
||||
z.A = 1
|
||||
z.B = 2
|
||||
z.Bar.Foo.A = 3
|
||||
zv := reflect.ValueOf(z)
|
||||
|
||||
v := m.FieldByName(zv, "A")
|
||||
if ival(v) != z.A {
|
||||
t.Errorf("Expecting %d, got %d", ival(v), z.A)
|
||||
}
|
||||
v = m.FieldByName(zv, "B")
|
||||
if ival(v) != z.B {
|
||||
t.Errorf("Expecting %d, got %d", ival(v), z.B)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapping(t *testing.T) {
|
||||
type Person struct {
|
||||
ID int
|
||||
Name string
|
||||
WearsGlasses bool `db:"wears_glasses"`
|
||||
}
|
||||
|
||||
m := NewMapperFunc("db", strings.ToLower)
|
||||
p := Person{1, "Jason", true}
|
||||
mapping := m.TypeMap(reflect.TypeOf(p))
|
||||
|
||||
for _, key := range []string{"id", "name", "wears_glasses"} {
|
||||
if _, ok := mapping[key]; !ok {
|
||||
t.Errorf("Expecting to find key %s in mapping but did not.", key)
|
||||
}
|
||||
}
|
||||
|
||||
type SportsPerson struct {
|
||||
Weight int
|
||||
Age int
|
||||
Person
|
||||
}
|
||||
s := SportsPerson{Weight: 100, Age: 30, Person: p}
|
||||
mapping = m.TypeMap(reflect.TypeOf(s))
|
||||
for _, key := range []string{"id", "name", "wears_glasses", "weight", "age"} {
|
||||
if _, ok := mapping[key]; !ok {
|
||||
t.Errorf("Expecting to find key %s in mapping but did not.", key)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
type RugbyPlayer struct {
|
||||
Position int
|
||||
IsIntense bool `db:"is_intense"`
|
||||
IsAllBlack bool `db:"-"`
|
||||
SportsPerson
|
||||
}
|
||||
r := RugbyPlayer{12, true, false, s}
|
||||
mapping = m.TypeMap(reflect.TypeOf(r))
|
||||
for _, key := range []string{"id", "name", "wears_glasses", "weight", "age", "position", "is_intense"} {
|
||||
if _, ok := mapping[key]; !ok {
|
||||
t.Errorf("Expecting to find key %s in mapping but did not.", key)
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := mapping["isallblack"]; ok {
|
||||
t.Errorf("Expecting to ignore `IsAllBlack` field")
|
||||
}
|
||||
|
||||
type EmbeddedLiteral struct {
|
||||
Embedded struct {
|
||||
Person string
|
||||
Position int
|
||||
}
|
||||
IsIntense bool
|
||||
}
|
||||
|
||||
e := EmbeddedLiteral{}
|
||||
mapping = m.TypeMap(reflect.TypeOf(e))
|
||||
//fmt.Printf("Mapping: %#v\n", mapping)
|
||||
|
||||
//f := FieldByIndexes(reflect.ValueOf(e), mapping["isintense"])
|
||||
//fmt.Println(f, f.Interface())
|
||||
|
||||
//tbn := m.TraversalsByName(reflect.TypeOf(e), []string{"isintense"})
|
||||
//fmt.Printf("%#v\n", tbn)
|
||||
|
||||
}
|
||||
|
||||
type E1 struct {
|
||||
A int
|
||||
}
|
||||
type E2 struct {
|
||||
E1
|
||||
B int
|
||||
}
|
||||
type E3 struct {
|
||||
E2
|
||||
C int
|
||||
}
|
||||
type E4 struct {
|
||||
E3
|
||||
D int
|
||||
}
|
||||
|
||||
func BenchmarkFieldNameL1(b *testing.B) {
|
||||
e4 := E4{D: 1}
|
||||
for i := 0; i < b.N; i++ {
|
||||
v := reflect.ValueOf(e4)
|
||||
f := v.FieldByName("D")
|
||||
if f.Interface().(int) != 1 {
|
||||
b.Fatal("Wrong value.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFieldNameL4(b *testing.B) {
|
||||
e4 := E4{}
|
||||
e4.A = 1
|
||||
for i := 0; i < b.N; i++ {
|
||||
v := reflect.ValueOf(e4)
|
||||
f := v.FieldByName("A")
|
||||
if f.Interface().(int) != 1 {
|
||||
b.Fatal("Wrong value.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFieldPosL1(b *testing.B) {
|
||||
e4 := E4{D: 1}
|
||||
for i := 0; i < b.N; i++ {
|
||||
v := reflect.ValueOf(e4)
|
||||
f := v.Field(1)
|
||||
if f.Interface().(int) != 1 {
|
||||
b.Fatal("Wrong value.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFieldPosL4(b *testing.B) {
|
||||
e4 := E4{}
|
||||
e4.A = 1
|
||||
for i := 0; i < b.N; i++ {
|
||||
v := reflect.ValueOf(e4)
|
||||
f := v.Field(0)
|
||||
f = f.Field(0)
|
||||
f = f.Field(0)
|
||||
f = f.Field(0)
|
||||
if f.Interface().(int) != 1 {
|
||||
b.Fatal("Wrong value.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFieldByIndexL4(b *testing.B) {
|
||||
e4 := E4{}
|
||||
e4.A = 1
|
||||
idx := []int{0, 0, 0, 0}
|
||||
for i := 0; i < b.N; i++ {
|
||||
v := reflect.ValueOf(e4)
|
||||
f := FieldByIndexes(v, idx)
|
||||
if f.Interface().(int) != 1 {
|
||||
b.Fatal("Wrong value.")
|
||||
}
|
||||
}
|
||||
}
|
986
Godeps/_workspace/src/github.com/jmoiron/sqlx/sqlx.go
generated
vendored
Normal file
986
Godeps/_workspace/src/github.com/jmoiron/sqlx/sqlx.go
generated
vendored
Normal file
@ -0,0 +1,986 @@
|
||||
package sqlx
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"io/ioutil"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/jmoiron/sqlx/reflectx"
|
||||
)
|
||||
|
||||
// Although the NameMapper is convenient, in practice it should not
|
||||
// be relied on except for application code. If you are writing a library
|
||||
// that uses sqlx, you should be aware that the name mappings you expect
|
||||
// can be overridded by your user's application.
|
||||
|
||||
// NameMapper is used to map column names to struct field names. By default,
|
||||
// it uses strings.ToLower to lowercase struct field names. It can be set
|
||||
// to whatever you want, but it is encouraged to be set before sqlx is used
|
||||
// as name-to-field mappings are cached after first use on a type.
|
||||
var NameMapper = strings.ToLower
|
||||
var origMapper = reflect.ValueOf(NameMapper)
|
||||
|
||||
// Rather than creating on init, this is created when necessary so that
|
||||
// importers have time to customize the NameMapper.
|
||||
var mpr *reflectx.Mapper
|
||||
|
||||
// mapper returns a valid mapper using the configured NameMapper func.
|
||||
func mapper() *reflectx.Mapper {
|
||||
if mpr == nil {
|
||||
mpr = reflectx.NewMapperFunc("db", NameMapper)
|
||||
} else if origMapper != reflect.ValueOf(NameMapper) {
|
||||
// if NameMapper has changed, create a new mapper
|
||||
mpr = reflectx.NewMapperFunc("db", NameMapper)
|
||||
origMapper = reflect.ValueOf(NameMapper)
|
||||
}
|
||||
return mpr
|
||||
}
|
||||
|
||||
// isScannable takes the reflect.Type and the actual dest value and returns
|
||||
// whether or not it's Scannable. Something is scannable if:
|
||||
// * it is not a struct
|
||||
// * it implements sql.Scanner
|
||||
// * it has no exported fields
|
||||
func isScannable(t reflect.Type) bool {
|
||||
if reflect.PtrTo(t).Implements(_scannerInterface) {
|
||||
return true
|
||||
}
|
||||
if t.Kind() != reflect.Struct {
|
||||
return true
|
||||
}
|
||||
|
||||
// it's not important that we use the right mapper for this particular object,
|
||||
// we're only concerned on how many exported fields this struct has
|
||||
m := mapper()
|
||||
if len(m.TypeMap(t)) == 0 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ColScanner is an interface used by MapScan and SliceScan
|
||||
type ColScanner interface {
|
||||
Columns() ([]string, error)
|
||||
Scan(dest ...interface{}) error
|
||||
Err() error
|
||||
}
|
||||
|
||||
// Queryer is an interface used by Get and Select
|
||||
type Queryer interface {
|
||||
Query(query string, args ...interface{}) (*sql.Rows, error)
|
||||
Queryx(query string, args ...interface{}) (*Rows, error)
|
||||
QueryRowx(query string, args ...interface{}) *Row
|
||||
}
|
||||
|
||||
// Execer is an interface used by MustExec and LoadFile
|
||||
type Execer interface {
|
||||
Exec(query string, args ...interface{}) (sql.Result, error)
|
||||
}
|
||||
|
||||
// Binder is an interface for something which can bind queries (Tx, DB)
|
||||
type binder interface {
|
||||
DriverName() string
|
||||
Rebind(string) string
|
||||
BindNamed(string, interface{}) (string, []interface{}, error)
|
||||
}
|
||||
|
||||
// Ext is a union interface which can bind, query, and exec, used by
|
||||
// NamedQuery and NamedExec.
|
||||
type Ext interface {
|
||||
binder
|
||||
Queryer
|
||||
Execer
|
||||
}
|
||||
|
||||
// Preparer is an interface used by Preparex.
|
||||
type Preparer interface {
|
||||
Prepare(query string) (*sql.Stmt, error)
|
||||
}
|
||||
|
||||
// determine if any of our extensions are unsafe
|
||||
func isUnsafe(i interface{}) bool {
|
||||
switch i.(type) {
|
||||
case Row:
|
||||
return i.(Row).unsafe
|
||||
case *Row:
|
||||
return i.(*Row).unsafe
|
||||
case Rows:
|
||||
return i.(Rows).unsafe
|
||||
case *Rows:
|
||||
return i.(*Rows).unsafe
|
||||
case Stmt:
|
||||
return i.(Stmt).unsafe
|
||||
case qStmt:
|
||||
return i.(qStmt).Stmt.unsafe
|
||||
case *qStmt:
|
||||
return i.(*qStmt).Stmt.unsafe
|
||||
case DB:
|
||||
return i.(DB).unsafe
|
||||
case *DB:
|
||||
return i.(*DB).unsafe
|
||||
case Tx:
|
||||
return i.(Tx).unsafe
|
||||
case *Tx:
|
||||
return i.(*Tx).unsafe
|
||||
case sql.Rows, *sql.Rows:
|
||||
return false
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func mapperFor(i interface{}) *reflectx.Mapper {
|
||||
switch i.(type) {
|
||||
case DB:
|
||||
return i.(DB).Mapper
|
||||
case *DB:
|
||||
return i.(*DB).Mapper
|
||||
case Tx:
|
||||
return i.(Tx).Mapper
|
||||
case *Tx:
|
||||
return i.(*Tx).Mapper
|
||||
default:
|
||||
return mapper()
|
||||
}
|
||||
}
|
||||
|
||||
var _scannerInterface = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
|
||||
var _valuerInterface = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
|
||||
|
||||
// Row is a reimplementation of sql.Row in order to gain access to the underlying
|
||||
// sql.Rows.Columns() data, necessary for StructScan.
|
||||
type Row struct {
|
||||
err error
|
||||
unsafe bool
|
||||
rows *sql.Rows
|
||||
Mapper *reflectx.Mapper
|
||||
}
|
||||
|
||||
// Scan is a fixed implementation of sql.Row.Scan, which does not discard the
|
||||
// underlying error from the internal rows object if it exists.
|
||||
func (r *Row) Scan(dest ...interface{}) error {
|
||||
if r.err != nil {
|
||||
return r.err
|
||||
}
|
||||
|
||||
// TODO(bradfitz): for now we need to defensively clone all
|
||||
// []byte that the driver returned (not permitting
|
||||
// *RawBytes in Rows.Scan), since we're about to close
|
||||
// the Rows in our defer, when we return from this function.
|
||||
// the contract with the driver.Next(...) interface is that it
|
||||
// can return slices into read-only temporary memory that's
|
||||
// only valid until the next Scan/Close. But the TODO is that
|
||||
// for a lot of drivers, this copy will be unnecessary. We
|
||||
// should provide an optional interface for drivers to
|
||||
// implement to say, "don't worry, the []bytes that I return
|
||||
// from Next will not be modified again." (for instance, if
|
||||
// they were obtained from the network anyway) But for now we
|
||||
// don't care.
|
||||
defer r.rows.Close()
|
||||
for _, dp := range dest {
|
||||
if _, ok := dp.(*sql.RawBytes); ok {
|
||||
return errors.New("sql: RawBytes isn't allowed on Row.Scan")
|
||||
}
|
||||
}
|
||||
|
||||
if !r.rows.Next() {
|
||||
if err := r.rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
err := r.rows.Scan(dest...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Make sure the query can be processed to completion with no errors.
|
||||
if err := r.rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Columns returns the underlying sql.Rows.Columns(), or the deferred error usually
|
||||
// returned by Row.Scan()
|
||||
func (r *Row) Columns() ([]string, error) {
|
||||
if r.err != nil {
|
||||
return []string{}, r.err
|
||||
}
|
||||
return r.rows.Columns()
|
||||
}
|
||||
|
||||
// Err returns the error encountered while scanning.
|
||||
func (r *Row) Err() error {
|
||||
return r.err
|
||||
}
|
||||
|
||||
// DB is a wrapper around sql.DB which keeps track of the driverName upon Open,
|
||||
// used mostly to automatically bind named queries using the right bindvars.
|
||||
type DB struct {
|
||||
*sql.DB
|
||||
driverName string
|
||||
unsafe bool
|
||||
Mapper *reflectx.Mapper
|
||||
}
|
||||
|
||||
// NewDb returns a new sqlx DB wrapper for a pre-existing *sql.DB. The
|
||||
// driverName of the original database is required for named query support.
|
||||
func NewDb(db *sql.DB, driverName string) *DB {
|
||||
return &DB{DB: db, driverName: driverName, Mapper: mapper()}
|
||||
}
|
||||
|
||||
// DriverName returns the driverName passed to the Open function for this DB.
|
||||
func (db *DB) DriverName() string {
|
||||
return db.driverName
|
||||
}
|
||||
|
||||
// Open is the same as sql.Open, but returns an *sqlx.DB instead.
|
||||
func Open(driverName, dataSourceName string) (*DB, error) {
|
||||
db, err := sql.Open(driverName, dataSourceName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &DB{DB: db, driverName: driverName, Mapper: mapper()}, err
|
||||
}
|
||||
|
||||
// MustOpen is the same as sql.Open, but returns an *sqlx.DB instead and panics on error.
|
||||
func MustOpen(driverName, dataSourceName string) *DB {
|
||||
db, err := Open(driverName, dataSourceName)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
// MapperFunc sets a new mapper for this db using the default sqlx struct tag
|
||||
// and the provided mapper function.
|
||||
func (db *DB) MapperFunc(mf func(string) string) {
|
||||
db.Mapper = reflectx.NewMapperFunc("db", mf)
|
||||
}
|
||||
|
||||
// Rebind transforms a query from QUESTION to the DB driver's bindvar type.
|
||||
func (db *DB) Rebind(query string) string {
|
||||
return Rebind(BindType(db.driverName), query)
|
||||
}
|
||||
|
||||
// Unsafe returns a version of DB which will silently succeed to scan when
|
||||
// columns in the SQL result have no fields in the destination struct.
|
||||
// sqlx.Stmt and sqlx.Tx which are created from this DB will inherit its
|
||||
// safety behavior.
|
||||
func (db *DB) Unsafe() *DB {
|
||||
return &DB{DB: db.DB, driverName: db.driverName, unsafe: true, Mapper: db.Mapper}
|
||||
}
|
||||
|
||||
// BindNamed binds a query using the DB driver's bindvar type.
|
||||
func (db *DB) BindNamed(query string, arg interface{}) (string, []interface{}, error) {
|
||||
return BindNamed(BindType(db.driverName), query, arg)
|
||||
}
|
||||
|
||||
// NamedQuery using this DB.
|
||||
func (db *DB) NamedQuery(query string, arg interface{}) (*Rows, error) {
|
||||
return NamedQuery(db, query, arg)
|
||||
}
|
||||
|
||||
// NamedExec using this DB.
|
||||
func (db *DB) NamedExec(query string, arg interface{}) (sql.Result, error) {
|
||||
return NamedExec(db, query, arg)
|
||||
}
|
||||
|
||||
// Select using this DB.
|
||||
func (db *DB) Select(dest interface{}, query string, args ...interface{}) error {
|
||||
return Select(db, dest, query, args...)
|
||||
}
|
||||
|
||||
// Get using this DB.
|
||||
func (db *DB) Get(dest interface{}, query string, args ...interface{}) error {
|
||||
return Get(db, dest, query, args...)
|
||||
}
|
||||
|
||||
// MustBegin starts a transaction, and panics on error. Returns an *sqlx.Tx instead
|
||||
// of an *sql.Tx.
|
||||
func (db *DB) MustBegin() *Tx {
|
||||
tx, err := db.Beginx()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return tx
|
||||
}
|
||||
|
||||
// Beginx begins a transaction and returns an *sqlx.Tx instead of an *sql.Tx.
|
||||
func (db *DB) Beginx() (*Tx, error) {
|
||||
tx, err := db.DB.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Tx{Tx: tx, driverName: db.driverName, unsafe: db.unsafe, Mapper: db.Mapper}, err
|
||||
}
|
||||
|
||||
// Queryx queries the database and returns an *sqlx.Rows.
|
||||
func (db *DB) Queryx(query string, args ...interface{}) (*Rows, error) {
|
||||
r, err := db.DB.Query(query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Rows{Rows: r, unsafe: db.unsafe, Mapper: db.Mapper}, err
|
||||
}
|
||||
|
||||
// QueryRowx queries the database and returns an *sqlx.Row.
|
||||
func (db *DB) QueryRowx(query string, args ...interface{}) *Row {
|
||||
rows, err := db.DB.Query(query, args...)
|
||||
return &Row{rows: rows, err: err, unsafe: db.unsafe, Mapper: db.Mapper}
|
||||
}
|
||||
|
||||
// MustExec (panic) runs MustExec using this database.
|
||||
func (db *DB) MustExec(query string, args ...interface{}) sql.Result {
|
||||
return MustExec(db, query, args...)
|
||||
}
|
||||
|
||||
// Preparex returns an sqlx.Stmt instead of a sql.Stmt
|
||||
func (db *DB) Preparex(query string) (*Stmt, error) {
|
||||
return Preparex(db, query)
|
||||
}
|
||||
|
||||
// PrepareNamed returns an sqlx.NamedStmt
|
||||
func (db *DB) PrepareNamed(query string) (*NamedStmt, error) {
|
||||
return prepareNamed(db, query)
|
||||
}
|
||||
|
||||
// Tx is an sqlx wrapper around sql.Tx with extra functionality
|
||||
type Tx struct {
|
||||
*sql.Tx
|
||||
driverName string
|
||||
unsafe bool
|
||||
Mapper *reflectx.Mapper
|
||||
}
|
||||
|
||||
// DriverName returns the driverName used by the DB which began this transaction.
|
||||
func (tx *Tx) DriverName() string {
|
||||
return tx.driverName
|
||||
}
|
||||
|
||||
// Rebind a query within a transaction's bindvar type.
|
||||
func (tx *Tx) Rebind(query string) string {
|
||||
return Rebind(BindType(tx.driverName), query)
|
||||
}
|
||||
|
||||
// Unsafe returns a version of Tx which will silently succeed to scan when
|
||||
// columns in the SQL result have no fields in the destination struct.
|
||||
func (tx *Tx) Unsafe() *Tx {
|
||||
return &Tx{Tx: tx.Tx, driverName: tx.driverName, unsafe: true, Mapper: tx.Mapper}
|
||||
}
|
||||
|
||||
// BindNamed binds a query within a transaction's bindvar type.
|
||||
func (tx *Tx) BindNamed(query string, arg interface{}) (string, []interface{}, error) {
|
||||
return BindNamed(BindType(tx.driverName), query, arg)
|
||||
}
|
||||
|
||||
// NamedQuery within a transaction.
|
||||
func (tx *Tx) NamedQuery(query string, arg interface{}) (*Rows, error) {
|
||||
return NamedQuery(tx, query, arg)
|
||||
}
|
||||
|
||||
// NamedExec a named query within a transaction.
|
||||
func (tx *Tx) NamedExec(query string, arg interface{}) (sql.Result, error) {
|
||||
return NamedExec(tx, query, arg)
|
||||
}
|
||||
|
||||
// Select within a transaction.
|
||||
func (tx *Tx) Select(dest interface{}, query string, args ...interface{}) error {
|
||||
return Select(tx, dest, query, args...)
|
||||
}
|
||||
|
||||
// Queryx within a transaction.
|
||||
func (tx *Tx) Queryx(query string, args ...interface{}) (*Rows, error) {
|
||||
r, err := tx.Tx.Query(query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Rows{Rows: r, unsafe: tx.unsafe, Mapper: tx.Mapper}, err
|
||||
}
|
||||
|
||||
// QueryRowx within a transaction.
|
||||
func (tx *Tx) QueryRowx(query string, args ...interface{}) *Row {
|
||||
rows, err := tx.Tx.Query(query, args...)
|
||||
return &Row{rows: rows, err: err, unsafe: tx.unsafe, Mapper: tx.Mapper}
|
||||
}
|
||||
|
||||
// Get within a transaction.
|
||||
func (tx *Tx) Get(dest interface{}, query string, args ...interface{}) error {
|
||||
return Get(tx, dest, query, args...)
|
||||
}
|
||||
|
||||
// MustExec runs MustExec within a transaction.
|
||||
func (tx *Tx) MustExec(query string, args ...interface{}) sql.Result {
|
||||
return MustExec(tx, query, args...)
|
||||
}
|
||||
|
||||
// Preparex a statement within a transaction.
|
||||
func (tx *Tx) Preparex(query string) (*Stmt, error) {
|
||||
return Preparex(tx, query)
|
||||
}
|
||||
|
||||
// Stmtx returns a version of the prepared statement which runs within a transaction. Provided
|
||||
// stmt can be either *sql.Stmt or *sqlx.Stmt.
|
||||
func (tx *Tx) Stmtx(stmt interface{}) *Stmt {
|
||||
var st sql.Stmt
|
||||
var s *sql.Stmt
|
||||
switch stmt.(type) {
|
||||
case sql.Stmt:
|
||||
st = stmt.(sql.Stmt)
|
||||
s = &st
|
||||
case Stmt:
|
||||
s = stmt.(Stmt).Stmt
|
||||
case *Stmt:
|
||||
s = stmt.(*Stmt).Stmt
|
||||
case *sql.Stmt:
|
||||
s = stmt.(*sql.Stmt)
|
||||
}
|
||||
return &Stmt{Stmt: tx.Stmt(s), Mapper: tx.Mapper}
|
||||
}
|
||||
|
||||
// NamedStmt returns a version of the prepared statement which runs within a transaction.
|
||||
func (tx *Tx) NamedStmt(stmt *NamedStmt) *NamedStmt {
|
||||
return &NamedStmt{
|
||||
QueryString: stmt.QueryString,
|
||||
Params: stmt.Params,
|
||||
Stmt: tx.Stmtx(stmt.Stmt),
|
||||
}
|
||||
}
|
||||
|
||||
// PrepareNamed returns an sqlx.NamedStmt
|
||||
func (tx *Tx) PrepareNamed(query string) (*NamedStmt, error) {
|
||||
return prepareNamed(tx, query)
|
||||
}
|
||||
|
||||
// Stmt is an sqlx wrapper around sql.Stmt with extra functionality
|
||||
type Stmt struct {
|
||||
*sql.Stmt
|
||||
unsafe bool
|
||||
Mapper *reflectx.Mapper
|
||||
}
|
||||
|
||||
// Unsafe returns a version of Stmt which will silently succeed to scan when
|
||||
// columns in the SQL result have no fields in the destination struct.
|
||||
func (s *Stmt) Unsafe() *Stmt {
|
||||
return &Stmt{Stmt: s.Stmt, unsafe: true, Mapper: s.Mapper}
|
||||
}
|
||||
|
||||
// Select using the prepared statement.
|
||||
func (s *Stmt) Select(dest interface{}, args ...interface{}) error {
|
||||
return Select(&qStmt{*s}, dest, "", args...)
|
||||
}
|
||||
|
||||
// Get using the prepared statement.
|
||||
func (s *Stmt) Get(dest interface{}, args ...interface{}) error {
|
||||
return Get(&qStmt{*s}, dest, "", args...)
|
||||
}
|
||||
|
||||
// MustExec (panic) using this statement. Note that the query portion of the error
|
||||
// output will be blank, as Stmt does not expose its query.
|
||||
func (s *Stmt) MustExec(args ...interface{}) sql.Result {
|
||||
return MustExec(&qStmt{*s}, "", args...)
|
||||
}
|
||||
|
||||
// QueryRowx using this statement.
|
||||
func (s *Stmt) QueryRowx(args ...interface{}) *Row {
|
||||
qs := &qStmt{*s}
|
||||
return qs.QueryRowx("", args...)
|
||||
}
|
||||
|
||||
// Queryx using this statement.
|
||||
func (s *Stmt) Queryx(args ...interface{}) (*Rows, error) {
|
||||
qs := &qStmt{*s}
|
||||
return qs.Queryx("", args...)
|
||||
}
|
||||
|
||||
// qStmt is an unexposed wrapper which lets you use a Stmt as a Queryer & Execer by
|
||||
// implementing those interfaces and ignoring the `query` argument.
|
||||
type qStmt struct{ Stmt }
|
||||
|
||||
func (q *qStmt) Query(query string, args ...interface{}) (*sql.Rows, error) {
|
||||
return q.Stmt.Query(args...)
|
||||
}
|
||||
|
||||
func (q *qStmt) Queryx(query string, args ...interface{}) (*Rows, error) {
|
||||
r, err := q.Stmt.Query(args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Rows{Rows: r, unsafe: q.Stmt.unsafe, Mapper: q.Stmt.Mapper}, err
|
||||
}
|
||||
|
||||
func (q *qStmt) QueryRowx(query string, args ...interface{}) *Row {
|
||||
rows, err := q.Stmt.Query(args...)
|
||||
return &Row{rows: rows, err: err, unsafe: q.Stmt.unsafe, Mapper: q.Stmt.Mapper}
|
||||
}
|
||||
|
||||
func (q *qStmt) Exec(query string, args ...interface{}) (sql.Result, error) {
|
||||
return q.Stmt.Exec(args...)
|
||||
}
|
||||
|
||||
// Rows is a wrapper around sql.Rows which caches costly reflect operations
|
||||
// during a looped StructScan
|
||||
type Rows struct {
|
||||
*sql.Rows
|
||||
unsafe bool
|
||||
Mapper *reflectx.Mapper
|
||||
// these fields cache memory use for a rows during iteration w/ structScan
|
||||
started bool
|
||||
fields [][]int
|
||||
values []interface{}
|
||||
}
|
||||
|
||||
// SliceScan using this Rows.
|
||||
func (r *Rows) SliceScan() ([]interface{}, error) {
|
||||
return SliceScan(r)
|
||||
}
|
||||
|
||||
// MapScan using this Rows.
|
||||
func (r *Rows) MapScan(dest map[string]interface{}) error {
|
||||
return MapScan(r, dest)
|
||||
}
|
||||
|
||||
// StructScan is like sql.Rows.Scan, but scans a single Row into a single Struct.
|
||||
// Use this and iterate over Rows manually when the memory load of Select() might be
|
||||
// prohibitive. *Rows.StructScan caches the reflect work of matching up column
|
||||
// positions to fields to avoid that overhead per scan, which means it is not safe
|
||||
// to run StructScan on the same Rows instance with different struct types.
|
||||
func (r *Rows) StructScan(dest interface{}) error {
|
||||
v := reflect.ValueOf(dest)
|
||||
|
||||
if v.Kind() != reflect.Ptr {
|
||||
return errors.New("must pass a pointer, not a value, to StructScan destination")
|
||||
}
|
||||
|
||||
v = reflect.Indirect(v)
|
||||
|
||||
if !r.started {
|
||||
columns, err := r.Columns()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m := r.Mapper
|
||||
|
||||
r.fields = m.TraversalsByName(v.Type(), columns)
|
||||
// if we are not unsafe and are missing fields, return an error
|
||||
if f, err := missingFields(r.fields); err != nil && !r.unsafe {
|
||||
return fmt.Errorf("missing destination name %s", columns[f])
|
||||
}
|
||||
r.values = make([]interface{}, len(columns))
|
||||
r.started = true
|
||||
}
|
||||
|
||||
err := fieldsByTraversal(v, r.fields, r.values, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// scan into the struct field pointers and append to our results
|
||||
err = r.Scan(r.values...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.Err()
|
||||
}
|
||||
|
||||
// Connect to a database and verify with a ping.
|
||||
func Connect(driverName, dataSourceName string) (*DB, error) {
|
||||
db, err := Open(driverName, dataSourceName)
|
||||
if err != nil {
|
||||
return db, err
|
||||
}
|
||||
err = db.Ping()
|
||||
return db, err
|
||||
}
|
||||
|
||||
// MustConnect connects to a database and panics on error.
|
||||
func MustConnect(driverName, dataSourceName string) *DB {
|
||||
db, err := Connect(driverName, dataSourceName)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
// Preparex prepares a statement.
|
||||
func Preparex(p Preparer, query string) (*Stmt, error) {
|
||||
s, err := p.Prepare(query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Stmt{Stmt: s, unsafe: isUnsafe(p), Mapper: mapperFor(p)}, err
|
||||
}
|
||||
|
||||
// Select executes a query using the provided Queryer, and StructScans each row
|
||||
// into dest, which must be a slice. If the slice elements are scannable, then
|
||||
// the result set must have only one column. Otherwise, StructScan is used.
|
||||
// The *sql.Rows are closed automatically.
|
||||
func Select(q Queryer, dest interface{}, query string, args ...interface{}) error {
|
||||
rows, err := q.Queryx(query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// if something happens here, we want to make sure the rows are Closed
|
||||
defer rows.Close()
|
||||
return scanAll(rows, dest, false)
|
||||
}
|
||||
|
||||
// Get does a QueryRow using the provided Queryer, and scans the resulting row
|
||||
// to dest. If dest is scannable, the result must only have one column. Otherwise,
|
||||
// StructScan is used. Get will return sql.ErrNoRows like row.Scan would.
|
||||
func Get(q Queryer, dest interface{}, query string, args ...interface{}) error {
|
||||
r := q.QueryRowx(query, args...)
|
||||
return r.scanAny(dest, false)
|
||||
}
|
||||
|
||||
// LoadFile exec's every statement in a file (as a single call to Exec).
|
||||
// LoadFile may return a nil *sql.Result if errors are encountered locating or
|
||||
// reading the file at path. LoadFile reads the entire file into memory, so it
|
||||
// is not suitable for loading large data dumps, but can be useful for initializing
|
||||
// schemas or loading indexes.
|
||||
//
|
||||
// FIXME: this does not really work with multi-statement files for mattn/go-sqlite3
|
||||
// or the go-mysql-driver/mysql drivers; pq seems to be an exception here. Detecting
|
||||
// this by requiring something with DriverName() and then attempting to split the
|
||||
// queries will be difficult to get right, and its current driver-specific behavior
|
||||
// is deemed at least not complex in its incorrectness.
|
||||
func LoadFile(e Execer, path string) (*sql.Result, error) {
|
||||
realpath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
contents, err := ioutil.ReadFile(realpath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := e.Exec(string(contents))
|
||||
return &res, err
|
||||
}
|
||||
|
||||
// MustExec execs the query using e and panics if there was an error.
|
||||
func MustExec(e Execer, query string, args ...interface{}) sql.Result {
|
||||
res, err := e.Exec(query, args...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// SliceScan using this Rows.
|
||||
func (r *Row) SliceScan() ([]interface{}, error) {
|
||||
return SliceScan(r)
|
||||
}
|
||||
|
||||
// MapScan using this Rows.
|
||||
func (r *Row) MapScan(dest map[string]interface{}) error {
|
||||
return MapScan(r, dest)
|
||||
}
|
||||
|
||||
func (r *Row) scanAny(dest interface{}, structOnly bool) error {
|
||||
if r.err != nil {
|
||||
return r.err
|
||||
}
|
||||
defer r.rows.Close()
|
||||
|
||||
v := reflect.ValueOf(dest)
|
||||
if v.Kind() != reflect.Ptr {
|
||||
return errors.New("must pass a pointer, not a value, to StructScan destination")
|
||||
}
|
||||
if v.IsNil() {
|
||||
return errors.New("nil pointer passed to StructScan destination")
|
||||
}
|
||||
|
||||
base := reflectx.Deref(v.Type())
|
||||
scannable := isScannable(base)
|
||||
|
||||
if structOnly && scannable {
|
||||
return structOnlyError(base)
|
||||
}
|
||||
|
||||
columns, err := r.Columns()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if scannable && len(columns) > 1 {
|
||||
return fmt.Errorf("scannable dest type %s with >1 columns (%d) in result", base.Kind(), len(columns))
|
||||
}
|
||||
|
||||
if scannable {
|
||||
return r.Scan(dest)
|
||||
}
|
||||
|
||||
m := r.Mapper
|
||||
|
||||
fields := m.TraversalsByName(v.Type(), columns)
|
||||
// if we are not unsafe and are missing fields, return an error
|
||||
if f, err := missingFields(fields); err != nil && !r.unsafe {
|
||||
return fmt.Errorf("missing destination name %s", columns[f])
|
||||
}
|
||||
values := make([]interface{}, len(columns))
|
||||
|
||||
err = fieldsByTraversal(v, fields, values, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// scan into the struct field pointers and append to our results
|
||||
return r.Scan(values...)
|
||||
}
|
||||
|
||||
// StructScan a single Row into dest.
|
||||
func (r *Row) StructScan(dest interface{}) error {
|
||||
return r.scanAny(dest, true)
|
||||
}
|
||||
|
||||
// SliceScan a row, returning a []interface{} with values similar to MapScan.
|
||||
// This function is primarly intended for use where the number of columns
|
||||
// is not known. Because you can pass an []interface{} directly to Scan,
|
||||
// it's recommended that you do that as it will not have to allocate new
|
||||
// slices per row.
|
||||
func SliceScan(r ColScanner) ([]interface{}, error) {
|
||||
// ignore r.started, since we needn't use reflect for anything.
|
||||
columns, err := r.Columns()
|
||||
if err != nil {
|
||||
return []interface{}{}, err
|
||||
}
|
||||
|
||||
values := make([]interface{}, len(columns))
|
||||
for i := range values {
|
||||
values[i] = new(interface{})
|
||||
}
|
||||
|
||||
err = r.Scan(values...)
|
||||
|
||||
if err != nil {
|
||||
return values, err
|
||||
}
|
||||
|
||||
for i := range columns {
|
||||
values[i] = *(values[i].(*interface{}))
|
||||
}
|
||||
|
||||
return values, r.Err()
|
||||
}
|
||||
|
||||
// MapScan scans a single Row into the dest map[string]interface{}.
|
||||
// Use this to get results for SQL that might not be under your control
|
||||
// (for instance, if you're building an interface for an SQL server that
|
||||
// executes SQL from input). Please do not use this as a primary interface!
|
||||
// This will modify the map sent to it in place, so reuse the same map with
|
||||
// care. Columns which occur more than once in the result will overwrite
|
||||
// eachother!
|
||||
func MapScan(r ColScanner, dest map[string]interface{}) error {
|
||||
// ignore r.started, since we needn't use reflect for anything.
|
||||
columns, err := r.Columns()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
values := make([]interface{}, len(columns))
|
||||
for i := range values {
|
||||
values[i] = new(interface{})
|
||||
}
|
||||
|
||||
err = r.Scan(values...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, column := range columns {
|
||||
dest[column] = *(values[i].(*interface{}))
|
||||
}
|
||||
|
||||
return r.Err()
|
||||
}
|
||||
|
||||
type rowsi interface {
|
||||
Close() error
|
||||
Columns() ([]string, error)
|
||||
Err() error
|
||||
Next() bool
|
||||
Scan(...interface{}) error
|
||||
}
|
||||
|
||||
// structOnlyError returns an error appropriate for type when a non-scannable
|
||||
// struct is expected but something else is given
|
||||
func structOnlyError(t reflect.Type) error {
|
||||
isStruct := t.Kind() == reflect.Struct
|
||||
isScanner := reflect.PtrTo(t).Implements(_scannerInterface)
|
||||
if !isStruct {
|
||||
return fmt.Errorf("expected %s but got %s", reflect.Struct, t.Kind())
|
||||
}
|
||||
if isScanner {
|
||||
return fmt.Errorf("structscan expects a struct dest but the provided struct type %s implements scanner", t.Name())
|
||||
}
|
||||
return fmt.Errorf("expected a struct, but struct %s has no exported fields", t.Name())
|
||||
}
|
||||
|
||||
// scanAll scans all rows into a destination, which must be a slice of any
|
||||
// type. If the destination slice type is a Struct, then StructScan will be
|
||||
// used on each row. If the destination is some other kind of base type, then
|
||||
// each row must only have one column which can scan into that type. This
|
||||
// allows you to do something like:
|
||||
//
|
||||
// rows, _ := db.Query("select id from people;")
|
||||
// var ids []int
|
||||
// scanAll(rows, &ids, false)
|
||||
//
|
||||
// and ids will be a list of the id results. I realize that this is a desirable
|
||||
// interface to expose to users, but for now it will only be exposed via changes
|
||||
// to `Get` and `Select`. The reason that this has been implemented like this is
|
||||
// this is the only way to not duplicate reflect work in the new API while
|
||||
// maintaining backwards compatibility.
|
||||
func scanAll(rows rowsi, dest interface{}, structOnly bool) error {
|
||||
var v, vp reflect.Value
|
||||
|
||||
value := reflect.ValueOf(dest)
|
||||
|
||||
// json.Unmarshal returns errors for these
|
||||
if value.Kind() != reflect.Ptr {
|
||||
return errors.New("must pass a pointer, not a value, to StructScan destination")
|
||||
}
|
||||
if value.IsNil() {
|
||||
return errors.New("nil pointer passed to StructScan destination")
|
||||
}
|
||||
direct := reflect.Indirect(value)
|
||||
|
||||
slice, err := baseType(value.Type(), reflect.Slice)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
isPtr := slice.Elem().Kind() == reflect.Ptr
|
||||
base := reflectx.Deref(slice.Elem())
|
||||
scannable := isScannable(base)
|
||||
|
||||
if structOnly && scannable {
|
||||
return structOnlyError(base)
|
||||
}
|
||||
|
||||
columns, err := rows.Columns()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// if it's a base type make sure it only has 1 column; if not return an error
|
||||
if scannable && len(columns) > 1 {
|
||||
return fmt.Errorf("non-struct dest type %s with >1 columns (%d)", base.Kind(), len(columns))
|
||||
}
|
||||
|
||||
if !scannable {
|
||||
var values []interface{}
|
||||
var m *reflectx.Mapper
|
||||
|
||||
switch rows.(type) {
|
||||
case *Rows:
|
||||
m = rows.(*Rows).Mapper
|
||||
default:
|
||||
m = mapper()
|
||||
}
|
||||
|
||||
fields := m.TraversalsByName(base, columns)
|
||||
// if we are not unsafe and are missing fields, return an error
|
||||
if f, err := missingFields(fields); err != nil && !isUnsafe(rows) {
|
||||
return fmt.Errorf("missing destination name %s", columns[f])
|
||||
}
|
||||
values = make([]interface{}, len(columns))
|
||||
|
||||
for rows.Next() {
|
||||
// create a new struct type (which returns PtrTo) and indirect it
|
||||
vp = reflect.New(base)
|
||||
v = reflect.Indirect(vp)
|
||||
|
||||
err = fieldsByTraversal(v, fields, values, true)
|
||||
|
||||
// scan into the struct field pointers and append to our results
|
||||
err = rows.Scan(values...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if isPtr {
|
||||
direct.Set(reflect.Append(direct, vp))
|
||||
} else {
|
||||
direct.Set(reflect.Append(direct, v))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for rows.Next() {
|
||||
vp = reflect.New(base)
|
||||
err = rows.Scan(vp.Interface())
|
||||
// append
|
||||
if isPtr {
|
||||
direct.Set(reflect.Append(direct, vp))
|
||||
} else {
|
||||
direct.Set(reflect.Append(direct, reflect.Indirect(vp)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
// FIXME: StructScan was the very first bit of API in sqlx, and now unfortunately
|
||||
// it doesn't really feel like it's named properly. There is an incongruency
|
||||
// between this and the way that StructScan (which might better be ScanStruct
|
||||
// anyway) works on a rows object.
|
||||
|
||||
// StructScan all rows from an sql.Rows or an sqlx.Rows into the dest slice.
|
||||
// StructScan will scan in the entire rows result, so if you need do not want to
|
||||
// allocate structs for the entire result, use Queryx and see sqlx.Rows.StructScan.
|
||||
// If rows is sqlx.Rows, it will use its mapper, otherwise it will use the default.
|
||||
func StructScan(rows rowsi, dest interface{}) error {
|
||||
return scanAll(rows, dest, true)
|
||||
|
||||
}
|
||||
|
||||
// reflect helpers
|
||||
|
||||
func baseType(t reflect.Type, expected reflect.Kind) (reflect.Type, error) {
|
||||
t = reflectx.Deref(t)
|
||||
if t.Kind() != expected {
|
||||
return nil, fmt.Errorf("expected %s but got %s", expected, t.Kind())
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// fieldsByName fills a values interface with fields from the passed value based
|
||||
// on the traversals in int. If ptrs is true, return addresses instead of values.
|
||||
// We write this instead of using FieldsByName to save allocations and map lookups
|
||||
// when iterating over many rows. Empty traversals will get an interface pointer.
|
||||
// Because of the necessity of requesting ptrs or values, it's considered a bit too
|
||||
// specialized for inclusion in reflectx itself.
|
||||
func fieldsByTraversal(v reflect.Value, traversals [][]int, values []interface{}, ptrs bool) error {
|
||||
v = reflect.Indirect(v)
|
||||
if v.Kind() != reflect.Struct {
|
||||
return errors.New("argument not a struct")
|
||||
}
|
||||
|
||||
for i, traversal := range traversals {
|
||||
if len(traversal) == 0 {
|
||||
values[i] = new(interface{})
|
||||
continue
|
||||
}
|
||||
f := reflectx.FieldByIndexes(v, traversal)
|
||||
if ptrs {
|
||||
values[i] = f.Addr().Interface()
|
||||
} else {
|
||||
values[i] = f.Interface()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func missingFields(transversals [][]int) (field int, err error) {
|
||||
for i, t := range transversals {
|
||||
if len(t) == 0 {
|
||||
return i, errors.New("missing field")
|
||||
}
|
||||
}
|
||||
return 0, nil
|
||||
}
|
1311
Godeps/_workspace/src/github.com/jmoiron/sqlx/sqlx_test.go
generated
vendored
Normal file
1311
Godeps/_workspace/src/github.com/jmoiron/sqlx/sqlx_test.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
5
Godeps/_workspace/src/github.com/jmoiron/sqlx/types/README.md
generated
vendored
Normal file
5
Godeps/_workspace/src/github.com/jmoiron/sqlx/types/README.md
generated
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
# types
|
||||
|
||||
The types package provides some useful types which implement the `sql.Scanner`
|
||||
and `driver.Valuer` interfaces, suitable for use as scan and value targets with
|
||||
database/sql.
|
95
Godeps/_workspace/src/github.com/jmoiron/sqlx/types/types.go
generated
vendored
Normal file
95
Godeps/_workspace/src/github.com/jmoiron/sqlx/types/types.go
generated
vendored
Normal file
@ -0,0 +1,95 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
type GzippedText []byte
|
||||
|
||||
func (g GzippedText) Value() (driver.Value, error) {
|
||||
b := make([]byte, 0, len(g))
|
||||
buf := bytes.NewBuffer(b)
|
||||
w := gzip.NewWriter(buf)
|
||||
w.Write(g)
|
||||
w.Close()
|
||||
return buf.Bytes(), nil
|
||||
|
||||
}
|
||||
|
||||
func (g *GzippedText) Scan(src interface{}) error {
|
||||
var source []byte
|
||||
switch src.(type) {
|
||||
case string:
|
||||
source = []byte(src.(string))
|
||||
case []byte:
|
||||
source = src.([]byte)
|
||||
default:
|
||||
return errors.New("Incompatible type for GzippedText")
|
||||
}
|
||||
reader, err := gzip.NewReader(bytes.NewReader(source))
|
||||
defer reader.Close()
|
||||
b, err := ioutil.ReadAll(reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*g = GzippedText(b)
|
||||
return nil
|
||||
}
|
||||
|
||||
// JsonText is a json.RawMessage, which is a []byte underneath.
|
||||
// Value() validates the json format in the source, and returns an error if
|
||||
// the json is not valid. Scan does no validation. JsonText additionally
|
||||
// implements `Unmarshal`, which unmarshals the json within to an interface{}
|
||||
type JsonText json.RawMessage
|
||||
|
||||
// Returns the *j as the JSON encoding of j.
|
||||
func (j *JsonText) MarshalJSON() ([]byte, error) {
|
||||
return *j, nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON sets *j to a copy of data
|
||||
func (j *JsonText) UnmarshalJSON(data []byte) error {
|
||||
if j == nil {
|
||||
return errors.New("JsonText: UnmarshalJSON on nil pointer")
|
||||
}
|
||||
*j = append((*j)[0:0], data...)
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
// Value returns j as a value. This does a validating unmarshal into another
|
||||
// RawMessage. If j is invalid json, it returns an error.
|
||||
func (j JsonText) Value() (driver.Value, error) {
|
||||
var m json.RawMessage
|
||||
var err = j.Unmarshal(&m)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
return []byte(j), nil
|
||||
}
|
||||
|
||||
// Scan stores the src in *j. No validation is done.
|
||||
func (j *JsonText) Scan(src interface{}) error {
|
||||
var source []byte
|
||||
switch src.(type) {
|
||||
case string:
|
||||
source = []byte(src.(string))
|
||||
case []byte:
|
||||
source = src.([]byte)
|
||||
default:
|
||||
return errors.New("Incompatible type for JsonText")
|
||||
}
|
||||
*j = JsonText(append((*j)[0:0], source...))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Unmarshal unmarshal's the json in j to v, as in json.Unmarshal.
|
||||
func (j *JsonText) Unmarshal(v interface{}) error {
|
||||
return json.Unmarshal([]byte(*j), v)
|
||||
}
|
42
Godeps/_workspace/src/github.com/jmoiron/sqlx/types/types_test.go
generated
vendored
Normal file
42
Godeps/_workspace/src/github.com/jmoiron/sqlx/types/types_test.go
generated
vendored
Normal file
@ -0,0 +1,42 @@
|
||||
package types
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGzipText(t *testing.T) {
|
||||
g := GzippedText("Hello, world")
|
||||
v, err := g.Value()
|
||||
if err != nil {
|
||||
t.Errorf("Was not expecting an error")
|
||||
}
|
||||
err = (&g).Scan(v)
|
||||
if err != nil {
|
||||
t.Errorf("Was not expecting an error")
|
||||
}
|
||||
if string(g) != "Hello, world" {
|
||||
t.Errorf("Was expecting the string we sent in (Hello World), got %s", string(g))
|
||||
}
|
||||
}
|
||||
|
||||
func TestJsonText(t *testing.T) {
|
||||
j := JsonText(`{"foo": 1, "bar": 2}`)
|
||||
v, err := j.Value()
|
||||
if err != nil {
|
||||
t.Errorf("Was not expecting an error")
|
||||
}
|
||||
err = (&j).Scan(v)
|
||||
if err != nil {
|
||||
t.Errorf("Was not expecting an error")
|
||||
}
|
||||
m := map[string]interface{}{}
|
||||
j.Unmarshal(&m)
|
||||
|
||||
if m["foo"].(float64) != 1 || m["bar"].(float64) != 2 {
|
||||
t.Errorf("Expected valid json but got some garbage instead? %#v", m)
|
||||
}
|
||||
|
||||
j = JsonText(`{"foo": 1, invalid, false}`)
|
||||
v, err = j.Value()
|
||||
if err == nil {
|
||||
t.Errorf("Was expecting invalid json to fail!")
|
||||
}
|
||||
}
|
6
Godeps/_workspace/src/github.com/julienschmidt/httprouter/.travis.yml
generated
vendored
Normal file
6
Godeps/_workspace/src/github.com/julienschmidt/httprouter/.travis.yml
generated
vendored
Normal file
@ -0,0 +1,6 @@
|
||||
language: go
|
||||
go:
|
||||
- 1.1
|
||||
- 1.2
|
||||
- 1.3
|
||||
- tip
|
24
Godeps/_workspace/src/github.com/julienschmidt/httprouter/LICENSE
generated
vendored
Normal file
24
Godeps/_workspace/src/github.com/julienschmidt/httprouter/LICENSE
generated
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
Copyright (c) 2013 Julien Schmidt. 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.
|
||||
* The names of the contributors may not 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 JULIEN SCHMIDT 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.
|
234
Godeps/_workspace/src/github.com/julienschmidt/httprouter/README.md
generated
vendored
Normal file
234
Godeps/_workspace/src/github.com/julienschmidt/httprouter/README.md
generated
vendored
Normal file
@ -0,0 +1,234 @@
|
||||
# HttpRouter [![Build Status](https://travis-ci.org/julienschmidt/httprouter.png?branch=master)](https://travis-ci.org/julienschmidt/httprouter) [![GoDoc](http://godoc.org/github.com/julienschmidt/httprouter?status.png)](http://godoc.org/github.com/julienschmidt/httprouter)
|
||||
|
||||
HttpRouter is a lightweight high performance HTTP request router
|
||||
(also called *multiplexer* or just *mux* for short) for [Go](http://golang.org/).
|
||||
|
||||
In contrast to the default mux of Go's net/http package, this router supports
|
||||
variables in the routing pattern and matches against the request method.
|
||||
It also scales better.
|
||||
|
||||
The router is optimized for best performance and a small memory footprint.
|
||||
It scales well even with very long paths and a large number of routes.
|
||||
A compressing dynamic trie (radix tree) structure is used for efficient matching.
|
||||
|
||||
## Features
|
||||
**Zero Garbage:** The matching and dispatching process generates zero bytes of
|
||||
garbage. In fact, the only heap allocations that are made, is by building the
|
||||
slice of the key-value pairs for path parameters. If the request path contains
|
||||
no parameters, not a single heap allocation is necessary.
|
||||
|
||||
**Best Performance:** [Benchmarks speak for themselves](https://github.com/julienschmidt/go-http-routing-benchmark).
|
||||
See below for technical details of the implementation.
|
||||
|
||||
**Parameters in your routing pattern:** Stop parsing the requested URL path,
|
||||
just give the path segment a name and the router delivers the dynamic value to
|
||||
you. Because of the design of the router, path parameters are very cheap.
|
||||
|
||||
**Only explicit matches:** With other routers, like [http.ServeMux](http://golang.org/pkg/net/http/#ServeMux),
|
||||
a requested URL path could match multiple patterns. Therefore they have some
|
||||
awkward pattern priority rules, like *longest match* or *first registered,
|
||||
first matched*. By design of this router, a request can only match exactly one
|
||||
or no route. As a result, there are also no unintended matches, which makes it
|
||||
great for SEO and improves the user experience.
|
||||
|
||||
**Stop caring about trailing slashes:** Choose the URL style you like, the
|
||||
router automatically redirects the client if a trailing slash is missing or if
|
||||
there is one extra. Of course it only does so, if the new path has a handler.
|
||||
If you don't like it, you can turn off this behavior.
|
||||
|
||||
**Path auto-correction:** Besides detecting the missing or additional trailing
|
||||
slash at no extra cost, the router can also fix wrong cases and remove
|
||||
superfluous path elements (like `../` or `//`).
|
||||
Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users?
|
||||
HttpRouter can help him by making a case-insensitive look-up and redirecting him
|
||||
to the correct URL.
|
||||
|
||||
**No more server crashes:** You can set a PanicHandler to deal with panics
|
||||
occurring during handling a HTTP request. The router then recovers and lets the
|
||||
PanicHandler log what happened and deliver a nice error page.
|
||||
|
||||
Of course you can also set a **custom NotFound handler** and **serve static files**.
|
||||
|
||||
## Usage
|
||||
This is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/julienschmidt/httprouter) for details.
|
||||
|
||||
Let's start with a trivial example:
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"net/http"
|
||||
"log"
|
||||
)
|
||||
|
||||
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
fmt.Fprint(w, "Welcome!\n")
|
||||
}
|
||||
|
||||
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
|
||||
}
|
||||
|
||||
func main() {
|
||||
router := httprouter.New()
|
||||
router.GET("/", Index)
|
||||
router.GET("/hello/:name", Hello)
|
||||
|
||||
log.Fatal(http.ListenAndServe(":8080", router))
|
||||
}
|
||||
```
|
||||
|
||||
### Named parameters
|
||||
As you can see, `:name` is a *named parameter*.
|
||||
The values are accessible via `httprouter.Params`, which is just a slice of `httprouter.Param`s.
|
||||
You can get the value of a parameter either by its index in the slice, or by using the `ByName(name)` method:
|
||||
`:name` can be retrived by `ByName("name")`.
|
||||
|
||||
Named parameters only match a single path segment:
|
||||
```
|
||||
Pattern: /user/:user
|
||||
|
||||
/user/gordon match
|
||||
/user/you match
|
||||
/user/gordon/profile no match
|
||||
/user/ no match
|
||||
```
|
||||
|
||||
**Note:** Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns `/user/new` and `/user/:user` for the same request method at the same time. The routing of different request methods is independent from each other.
|
||||
|
||||
### Catch-All parameters
|
||||
The second type are *catch-all* parameters and have the form `*name`.
|
||||
Like the name suggests, they match everything.
|
||||
Therefore they must always be at the **end** of the pattern:
|
||||
```
|
||||
Pattern: /src/*filepath
|
||||
|
||||
/src/ match
|
||||
/src/somefile.go match
|
||||
/src/subdir/somefile.go match
|
||||
```
|
||||
|
||||
## How does it work?
|
||||
The router relies on a tree structure which makes heavy use of *common prefixes*,
|
||||
it is basically a *compact* [*prefix tree*](http://en.wikipedia.org/wiki/Trie)
|
||||
(or just [*Radix tree*](http://en.wikipedia.org/wiki/Radix_tree)).
|
||||
Nodes with a common prefix also share a common parent. Here is a short example
|
||||
what the routing tree for the `GET` request method could look like:
|
||||
|
||||
```
|
||||
Priority Path Handle
|
||||
9 \ *<1>
|
||||
3 ├s nil
|
||||
2 |├earch\ *<2>
|
||||
1 |└upport\ *<3>
|
||||
2 ├blog\ *<4>
|
||||
1 | └:post nil
|
||||
1 | └\ *<5>
|
||||
2 ├about-us\ *<6>
|
||||
1 | └team\ *<7>
|
||||
1 └contact\ *<8>
|
||||
```
|
||||
Every `*<num>` represents the memory address of a handler function (a pointer).
|
||||
If you follow a path trough the tree from the root to the leaf, you get the
|
||||
complete route path, e.g `\blog\:post\`, where `:post` is just a placeholder
|
||||
([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a
|
||||
tree structure also allows us to use dynamic parts like the `:post` parameter,
|
||||
since we actually match against the routing patterns instead of just comparing
|
||||
hashes. [As benchmarks show](https://github.com/julienschmidt/go-http-routing-benchmark),
|
||||
this works very well and efficient.
|
||||
|
||||
Since URL paths have a hierarchical structure and make use only of a limited set
|
||||
of characters (byte values), it is very likely that there are a lot of common
|
||||
prefixes. This allows us to easily reduce the routing into ever smaller problems.
|
||||
Moreover the router manages a separate tree for every request method.
|
||||
For one thing it is more space efficient than holding a method->handle map in
|
||||
every single node, for another thing is also allows us to greatly reduce the
|
||||
routing problem before even starting the look-up in the prefix-tree.
|
||||
|
||||
For even better scalability, the child nodes on each tree level are ordered by
|
||||
priority, where the priority is just the number of handles registered in sub
|
||||
nodes (children, grandchildren, and so on..).
|
||||
This helps in two ways:
|
||||
|
||||
1. Nodes which are part of the most routing paths are evaluated first. This
|
||||
helps to make as much routes as possible to be reachable as fast as possible.
|
||||
2. It is some sort of cost compensation. The longest reachable path (highest
|
||||
cost) can always be evaluated first. The following scheme visualizes the tree
|
||||
structure. Nodes are evaluated from top to bottom and from left to right.
|
||||
|
||||
```
|
||||
├------------
|
||||
├---------
|
||||
├-----
|
||||
├----
|
||||
├--
|
||||
├--
|
||||
└-
|
||||
```
|
||||
|
||||
|
||||
## Why doesn't this work with http.Handler?
|
||||
**It does!** The router itself implements the http.Handler interface.
|
||||
Moreover the router provides convenient [adapters for http.Handler](http://godoc.org/github.com/julienschmidt/httprouter#Router.Handler)s and [http.HandlerFunc](http://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc)s
|
||||
which allows them to be used as a [httprouter.Handle](http://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) when registering a route.
|
||||
The only disadvantage is, that no parameter values can be retrieved when a
|
||||
http.Handler or http.HandlerFunc is used, since there is no efficient way to
|
||||
pass the values with the existing function parameters.
|
||||
Therefore [httprouter.Handle](http://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) has a third function parameter.
|
||||
|
||||
Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up.
|
||||
|
||||
|
||||
## Where can I find Middleware *X*?
|
||||
This package just provides a very efficient request router with a few extra
|
||||
features. The router is just a [http.Handler](http://golang.org/pkg/net/http/#Handler),
|
||||
you can chain any http.Handler compatible middleware before the router,
|
||||
for example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers).
|
||||
Or you could [just write your own](http://justinas.org/writing-http-middleware-in-go/),
|
||||
it's very easy!
|
||||
|
||||
Alternatively, you could try [a framework building upon HttpRouter](#web-frameworks-building-upon-httprouter).
|
||||
|
||||
Here is a quick example: Does your server serve multiple domains / hosts?
|
||||
You want to use sub-domains?
|
||||
Define a router per host!
|
||||
```go
|
||||
// We need an object that implements the http.Handler interface.
|
||||
// Therefore we need a type for which we implement the ServeHTTP method.
|
||||
// We just use a map here, in which we map host names (with port) to http.Handlers
|
||||
type HostSwitch map[string]http.Handler
|
||||
|
||||
// Implement the ServerHTTP method on our new type
|
||||
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// Check if a http.Handler is registered for the given host.
|
||||
// If yes, use it to handle the request.
|
||||
if handler := hs[r.Host]; handler != nil {
|
||||
handler.ServeHTTP(w, r)
|
||||
} else {
|
||||
// Handle host names for wich no handler is registered
|
||||
http.Error(w, "Forbidden", 403) // Or Redirect?
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Initialize a router as usual
|
||||
router := httprouter.New()
|
||||
router.GET("/", Index)
|
||||
router.GET("/hello/:name", Hello)
|
||||
|
||||
// Make a new HostSwitch and insert the router (our http handler)
|
||||
// for example.com and port 12345
|
||||
hs := make(HostSwitch)
|
||||
hs["example.com:12345"] = router
|
||||
|
||||
// Use the HostSwitch to listen and serve on port 12345
|
||||
log.Fatal(http.ListenAndServe(":12345", hs))
|
||||
}
|
||||
```
|
||||
|
||||
## Web Frameworks building upon HttpRouter
|
||||
If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package:
|
||||
* [Gin](https://github.com/gin-gonic/gin): Features a martini-like API with much better performance
|
||||
* [Hikaru](https://github.com/najeira/hikaru): Supports standalone and Google AppEngine
|
123
Godeps/_workspace/src/github.com/julienschmidt/httprouter/path.go
generated
vendored
Normal file
123
Godeps/_workspace/src/github.com/julienschmidt/httprouter/path.go
generated
vendored
Normal file
@ -0,0 +1,123 @@
|
||||
// Copyright 2013 Julien Schmidt. All rights reserved.
|
||||
// Based on the path package, Copyright 2009 The Go Authors.
|
||||
// Use of this source code is governed by a BSD-style license that can be found
|
||||
// in the LICENSE file.
|
||||
|
||||
package httprouter
|
||||
|
||||
// CleanPath is the URL version of path.Clean, it returns a canonical URL path
|
||||
// for p, eliminating . and .. elements.
|
||||
//
|
||||
// The following rules are applied iteratively until no further processing can
|
||||
// be done:
|
||||
// 1. Replace multiple slashes with a single slash.
|
||||
// 2. Eliminate each . path name element (the current directory).
|
||||
// 3. Eliminate each inner .. path name element (the parent directory)
|
||||
// along with the non-.. element that precedes it.
|
||||
// 4. Eliminate .. elements that begin a rooted path:
|
||||
// that is, replace "/.." by "/" at the beginning of a path.
|
||||
//
|
||||
// If the result of this process is an empty string, "/" is returned
|
||||
func CleanPath(p string) string {
|
||||
// Turn empty string into "/"
|
||||
if p == "" {
|
||||
return "/"
|
||||
}
|
||||
|
||||
n := len(p)
|
||||
var buf []byte
|
||||
|
||||
// Invariants:
|
||||
// reading from path; r is index of next byte to process.
|
||||
// writing to buf; w is index of next byte to write.
|
||||
|
||||
// path must start with '/'
|
||||
r := 1
|
||||
w := 1
|
||||
|
||||
if p[0] != '/' {
|
||||
r = 0
|
||||
buf = make([]byte, n+1)
|
||||
buf[0] = '/'
|
||||
}
|
||||
|
||||
trailing := n > 2 && p[n-1] == '/'
|
||||
|
||||
// A bit more clunky without a 'lazybuf' like the path package, but the loop
|
||||
// gets completely inlined (bufApp). So in contrast to the path package this
|
||||
// loop has no expensive function calls (except 1x make)
|
||||
|
||||
for r < n {
|
||||
switch {
|
||||
case p[r] == '/':
|
||||
// empty path element, trailing slash is added after the end
|
||||
r++
|
||||
|
||||
case p[r] == '.' && r+1 == n:
|
||||
trailing = true
|
||||
r++
|
||||
|
||||
case p[r] == '.' && p[r+1] == '/':
|
||||
// . element
|
||||
r++
|
||||
|
||||
case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):
|
||||
// .. element: remove to last /
|
||||
r += 2
|
||||
|
||||
if w > 1 {
|
||||
// can backtrack
|
||||
w--
|
||||
|
||||
if buf == nil {
|
||||
for w > 1 && p[w] != '/' {
|
||||
w--
|
||||
}
|
||||
} else {
|
||||
for w > 1 && buf[w] != '/' {
|
||||
w--
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
// real path element.
|
||||
// add slash if needed
|
||||
if w > 1 {
|
||||
bufApp(&buf, p, w, '/')
|
||||
w++
|
||||
}
|
||||
|
||||
// copy element
|
||||
for r < n && p[r] != '/' {
|
||||
bufApp(&buf, p, w, p[r])
|
||||
w++
|
||||
r++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// re-append trailing slash
|
||||
if trailing && w > 1 {
|
||||
bufApp(&buf, p, w, '/')
|
||||
w++
|
||||
}
|
||||
|
||||
if buf == nil {
|
||||
return p[:w]
|
||||
}
|
||||
return string(buf[:w])
|
||||
}
|
||||
|
||||
// internal helper to lazily create a buffer if necessary
|
||||
func bufApp(buf *[]byte, s string, w int, c byte) {
|
||||
if *buf == nil {
|
||||
if s[w] == c {
|
||||
return
|
||||
}
|
||||
|
||||
*buf = make([]byte, len(s))
|
||||
copy(*buf, s[:w])
|
||||
}
|
||||
(*buf)[w] = c
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user