87 Commits
1.0.0 ... 1.0.4

Author SHA1 Message Date
codeskyblue
1b217ca440 remove 1g limit 2017-09-11 13:40:05 +08:00
codeskyblue
7587b8067a add travis and goreleaser 2017-09-11 12:59:02 +08:00
codeskyblue
2b7fb84a5e update doc 2017-09-11 12:56:04 +08:00
codeskyblue
963f2ddb32 update doc 2017-08-31 23:35:42 +08:00
codeskyblue
3ff2620ba5 return json response when upload 2017-06-14 23:06:24 +08:00
Wei
22c83d8f2d Reword README
Fixed a few English language problem.
2017-06-08 23:47:45 +08:00
codeskyblue
cab407a098 sync to new androidbinary lib 2017-06-01 17:00:23 +08:00
codeskyblue
4d21cd5dd8 fix js error 2017-05-22 23:00:40 +08:00
codeskyblue
26cb73de1c remove useless console.log 2017-05-22 22:41:41 +08:00
codeskyblue
caef8c0fbd make qrcode page large 2017-05-22 19:11:34 +08:00
codeskyblue
ea3d3fdcef wechat is support appstore link now, no need to show wechat redirect page anymore 2017-05-22 17:06:41 +08:00
codeskyblue
4d2c5587d6 remove temp file associated with form after uploaded 2017-05-19 16:04:24 +08:00
codeskyblue
6b3f0f0ae6 quick hot fix androidbinary panic bug 2017-05-17 14:59:32 +08:00
codeskyblue
28e9a2c0ca fix little bug 2017-05-17 10:46:35 +08:00
codeskyblue
e5677bec86 close #18 support show folder size 2017-05-17 10:28:00 +08:00
codeskyblue
a1b16115df update api 2017-05-16 21:41:41 +08:00
codeskyblue
5439149b09 update vendor 2017-05-16 21:34:30 +08:00
codeskyblue
332276f6db disable auto recover 2017-05-11 17:07:05 +08:00
codeskyblue
66c45e1c6e add remove all upload button 2017-05-11 16:50:20 +08:00
codeskyblue
68654f8bd3 add some log 2017-05-11 16:47:17 +08:00
codeskyblue
a95e38802d prevent out of memory 2017-05-11 16:20:37 +08:00
codeskyblue
e063187656 add missing package 2017-05-09 17:17:53 +08:00
codeskyblue
892546343a fix parse apk panic 2017-05-09 17:10:58 +08:00
codeskyblue
dc3b5695d4 remove 1.5 test 2017-05-09 16:42:17 +08:00
codeskyblue
f8ee0c0459 add api -/apk/info/:path-of-apk 2017-05-09 16:38:29 +08:00
codeskyblue
947bbe9efa fix #16 2017-02-14 13:10:31 +08:00
codeskyblue
9af2b5b5f6 fix #8 2016-12-22 14:42:24 +08:00
codeskyblue
7e1387a787 fix display login logic. 2016-12-22 12:05:34 +08:00
codeskyblue
ff1f38c494 add openid support2 2016-12-22 11:46:29 +08:00
codeskyblue
de1d2ba243 Merge branch 'master' of https://github.com/codeskyblue/gohttpserver 2016-12-21 15:47:12 +08:00
codeskyblue
2ab2c553b6 add accessTables support 2016-12-21 15:47:03 +08:00
codeskyblue
6889309af7 format index.tmpl.html code 2016-12-21 15:15:17 +08:00
codeskyblue
61758ec3ce add HEAD support, close #10 2016-09-21 20:20:13 +08:00
codeskyblue
7a1831c6ec fix breadcrumb when path is /somedir/, got different feeling of /somedir 2016-08-26 13:34:08 +08:00
codeskyblue
31cafdfd16 fix make index error 2016-08-24 11:26:10 +08:00
codeskyblue
859574f1e0 fix search path error when root not . 2016-08-12 11:02:54 +08:00
codeskyblue
b4efbd1b6b remove some useless code 2016-08-06 22:25:08 +08:00
codeskyblue
a7fc7054c5 format size in browser 2016-08-05 22:15:57 +08:00
codeskyblue
9dd2d6da30 add relevent link 2016-08-05 17:36:13 +08:00
codeskyblue
ad85705599 use fontawesome copy icon 2016-08-05 17:23:13 +08:00
codeskyblue
b94703f6b9 fix sort 2016-08-05 17:13:29 +08:00
codeskyblue
acad061682 sort by time desc 2016-08-05 16:53:44 +08:00
codeskyblue
d89a841bfb add clipboard support 2016-08-05 13:42:52 +08:00
codeskyblue
b6a2908b68 load js when load finished 2016-08-05 11:22:24 +08:00
codeskyblue
37b71cb7bf add history back button 2016-08-05 11:13:25 +08:00
codeskyblue
644cbbcfd6 close preview now 2016-08-04 20:02:12 +08:00
codeskyblue
f9b2518734 load preview file 2016-08-04 19:59:00 +08:00
codeskyblue
479db243a5 fix when EX_LDFLAGS not null 2016-08-04 09:46:24 +08:00
codeskyblue
22c048eb3a update icon 2016-08-04 09:44:37 +08:00
codeskyblue
8a195449c8 add confirm for delete, not finish yet 2016-08-04 07:53:39 +08:00
codeskyblue
35f8ec889a update green style css 2016-08-03 23:02:45 +08:00
codeskyblue
9d65aad7d7 close #3 2016-08-03 22:57:45 +08:00
codeskyblue
acf4be706b fix sort error 2016-08-03 15:48:51 +08:00
codeskyblue
575884440d support deletable 2016-08-03 14:54:26 +08:00
codeskyblue
c9237c8627 fix fix 2016-08-03 10:18:54 +08:00
codeskyblue
bb4ac43d67 fix google analytics 2016-08-03 10:12:59 +08:00
codeskyblue
7fd04ea15d add scroll up 2016-08-03 09:41:38 +08:00
codeskyblue
b444194496 fix root and addr default error 2016-08-02 16:06:44 +08:00
codeskyblue
07e001fc4d add conf support, thanks to <http://git.oschina.net/sparon> 2016-08-02 16:01:15 +08:00
codeskyblue
de1deaac3d can open or close formNow time now 2016-08-02 14:43:15 +08:00
codeskyblue
fa7b583962 update deps 2016-08-02 14:02:43 +08:00
codeskyblue
17cd98c75e add modtime, for download when click download 2016-08-02 14:02:23 +08:00
codeskyblue
43cb263853 support .ghs.yml add google analytics 2016-08-02 13:34:02 +08:00
codeskyblue
2a229b80ab reload file list disable cache 2016-08-01 20:08:18 +08:00
codeskyblue
5641c9e8ff show qrcode for all file 2016-08-01 16:37:30 +08:00
codeskyblue
48ecbf43ab html also let support qrcode 2016-08-01 16:15:42 +08:00
codeskyblue
d5fc4b6153 not let qrcode jump 2016-08-01 16:06:45 +08:00
codeskyblue
29a8557e98 fix js error 2016-08-01 15:59:09 +08:00
codeskyblue
c957548d7b add ex_ldflags 2016-08-01 15:34:41 +08:00
codeskyblue
a7c6d06479 short code 2016-08-01 15:07:13 +08:00
codeskyblue
c8768d3c21 add css test type 2016-08-01 14:53:20 +08:00
codeskyblue
cdda0a01a5 update index 2016-08-01 14:50:24 +08:00
codeskyblue
17a7f658c9 use heroku plistproxy as default proxy 2016-08-01 14:02:24 +08:00
codeskyblue
01a7c39709 add binary release 2016-08-01 11:19:50 +08:00
codeskyblue
7dba3a4c7d change --xproxy to --xheaders 2016-08-01 10:42:32 +08:00
codeskyblue
8944cc072e add plist proxy 2016-08-01 10:24:06 +08:00
codeskyblue
4f958f1c24 update search algorighm 2016-08-01 09:37:59 +08:00
codeskyblue
3fb6620065 Merge branch 'master' of https://github.com/codeskyblue/gohttpserver 2016-08-01 09:21:01 +08:00
codeskyblue
a1aac2bedc fix on windows -r R: error but -r R:/ ok 2016-08-01 09:20:58 +08:00
codeskyblue
8cb2b90e66 update css 2016-07-31 22:53:22 +08:00
codeskyblue
cf2366df85 fix multi index 2016-07-31 22:28:09 +08:00
codeskyblue
ff1067f9f7 add making fs index support, to speed up search 2016-07-31 19:31:05 +08:00
codeskyblue
d3a12f7c69 add execute for build.sh 2016-07-31 18:11:52 +08:00
codeskyblue
2f1b55892a add file search support 2016-07-31 11:47:02 +08:00
codeskyblue
d7e808cd4f fix spell error 2016-07-31 10:33:45 +08:00
codeskyblue
1c3a1d28da add dev version 2016-07-31 10:22:55 +08:00
codeskyblue
a1c1c0f987 add auto tag version support 2016-07-31 10:19:32 +08:00
157 changed files with 26287 additions and 1122 deletions

View File

@@ -2,11 +2,12 @@ desc: Auto generated by fswatch [gohttp-vue]
triggers:
- name: ""
pattens:
- '!.git/'
- '**/*.go'
- '**/*.tmpl.html'
env:
DEBUG: "1"
cmd: (killall gohttpserver; true) && go build && ./gohttpserver --upload&
cmd: go build && ./gohttpserver --upload --root testdata
shell: true
delay: 100ms
signal: KILL

2
.ghs.yml Normal file
View File

@@ -0,0 +1,2 @@
upload: true
delete: false

39
.goreleaser.yml Normal file
View File

@@ -0,0 +1,39 @@
project_name: gohttpserver
release:
github:
owner: codeskyblue
name: gohttpserver
brew:
install: bin.install "gohttpserver"
builds:
- goos:
- linux
- darwin
- windows
goarch:
- amd64
- "386"
goarm:
- "6"
main: .
ldflags: -s -w -X main.VERSION={{.Version}}
flags: -tags bindata
binary: gohttpserver
archive:
format: tar.gz
name_template: '{{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{
.Arm }}{{ end }}'
files:
- licence*
- LICENCE*
- license*
- LICENSE*
- readme*
- README*
- changelog*
- CHANGELOG*
- .ghs.yml
snapshot:
name_template: SNAPSHOT-{{ .Commit }}
checksum:
name_template: '{{ .ProjectName }}_{{ .Version }}_checksums.txt'

View File

@@ -1,9 +1,14 @@
language: go
go:
- 1.5
- 1.6
- 1.7
env:
global:
- GO15VENDOREXPERIMENT=1
script:
- go test -v
# .travis.yml
after_success:
- go get github.com/jteeuwen/go-bindata/...
- go get github.com/elazarl/go-bindata-assetfs/...
- test -n "$TRAVIS_TAG" && go-bindata-assetfs -tags bindata res/...
- test -n "$TRAVIS_TAG" && curl -sL https://git.io/goreleaser | bash

63
Godeps/Godeps.json generated
View File

@@ -1,24 +1,24 @@
{
"ImportPath": "github.com/codeskyblue/gohttpserver",
"GoVersion": "go1.6",
"GoVersion": "go1.7",
"GodepVersion": "v74",
"Deps": [
{
"ImportPath": "github.com/DHowett/go-plist",
"Rev": "f4bf55d2395500aacc17eedcebc5f139336b4312"
"Rev": "fd61394c0abc85ba629ff8471fa35d4309cd6609"
},
{
"ImportPath": "github.com/alecthomas/kingpin",
"Comment": "v2.1.3",
"Rev": "aef28d186e59d39ed537473dfce4472108ea1045"
"Comment": "v2.2.0",
"Rev": "92b2733684bc5f1971162349ce098fe0d070e2a9"
},
{
"ImportPath": "github.com/alecthomas/template",
"Rev": "b867cc6ab45cece8143cfcc6fc9c77cf3f2c23c0"
"Rev": "a0175ee3bccc567396460bf5acd36800cb10c49c"
},
{
"ImportPath": "github.com/alecthomas/template/parse",
"Rev": "b867cc6ab45cece8143cfcc6fc9c77cf3f2c23c0"
"Rev": "a0175ee3bccc567396460bf5acd36800cb10c49c"
},
{
"ImportPath": "github.com/alecthomas/units",
@@ -28,28 +28,67 @@
"ImportPath": "github.com/codeskyblue/dockerignore",
"Rev": "de82dee623d9207f906d327172149cba50427a88"
},
{
"ImportPath": "github.com/codeskyblue/openid-go",
"Rev": "0d30842b2fb4704849cd07f6fba862a7a9f4b403"
},
{
"ImportPath": "github.com/go-yaml/yaml",
"Rev": "e4d366fc3c7938e2958e662b4258c7a89e1f0e3e"
},
{
"ImportPath": "github.com/goji/httpauth",
"Rev": "2da839ab0f4df05a6db5eb277995589dadbd4fb9"
},
{
"ImportPath": "github.com/gorilla/context",
"Comment": "v1.1-4-gaed02d1",
"Rev": "aed02d124ae4a0e94fea4541c8effd05bf0c8296"
"Comment": "v1.1-8-g0b6087c",
"Rev": "0b6087c0035ecc2ecddef2451329bca7f36192ab"
},
{
"ImportPath": "github.com/gorilla/handlers",
"Comment": "v1.1-10-g801d6e3",
"Rev": "801d6e3b008914ee888c9ab9b1b379b9a56fbf44"
"Comment": "v1.1-14-g3a5767c",
"Rev": "3a5767ca75ece5f7f1440b1d16975247f8d8b221"
},
{
"ImportPath": "github.com/gorilla/mux",
"Comment": "v1.1-15-gd391bea",
"Rev": "d391bea3118c9fc17a88d62c9189bb791255e0ef"
"Comment": "v1.1-27-g757bef9",
"Rev": "757bef944d0f21880861c2dd9c871ca543023cba"
},
{
"ImportPath": "github.com/gorilla/securecookie",
"Comment": "v1.1-5-gfa5329f",
"Rev": "fa5329f913702981df43dcb2a380bac429c810b5"
},
{
"ImportPath": "github.com/gorilla/sessions",
"Comment": "v1.1",
"Rev": "ca9ada44574153444b00d3fd9c8559e4cc95f896"
},
{
"ImportPath": "github.com/mash/go-accesslog",
"Rev": "9ba8e13f36087d6cb83d9a9f17f9e8da137d5ee9"
},
{
"ImportPath": "github.com/pkg/errors",
"Comment": "v0.8.0-1-g839d9e9",
"Rev": "839d9e913e063e28dfd0e6c7b7512793e0a48be9"
},
{
"ImportPath": "github.com/shogo82148/androidbinary",
"Rev": "2fb750de4ec6a45853fcc5f85694eab47e1007f9"
},
{
"ImportPath": "github.com/shogo82148/androidbinary/apk",
"Rev": "2fb750de4ec6a45853fcc5f85694eab47e1007f9"
},
{
"ImportPath": "golang.org/x/net/html",
"Rev": "a625e3953219464fdd5611bb48bf87c927717295"
},
{
"ImportPath": "golang.org/x/net/html/atom",
"Rev": "a625e3953219464fdd5611bb48bf87c927717295"
}
]
}

124
README.md
View File

@@ -1,20 +1,21 @@
# gohttpserver
[![Build Status](https://travis-ci.org/codeskyblue/gohttpserver.svg?branch=master)](https://travis-ci.org/codeskyblue/gohttpserver)
Make the best HTTP File Server. Better UI, upload support, apple&android install package qrcode generate.
- Goal: Make the best HTTP File Server.
- Features: Human-friendly UI, file uploading support, direct QR-code generation for Apple & Android install package.
[Demo site](https://gohttpserver.herokuapp.com/)
- 目标: 做最好的HTTP文件服务器
- 功能: 人性化的UI体验文件的上传支持安卓和苹果安装包的二维码直接生成。
**Binaries** can be downloaded from [this repo releases](https://github.com/codeskyblue/gohttpserver/releases/)
## Notes
If using go1.5, ensure you set GO15VENDOREXPERIMENT=1
Upload size now limited to 1G
## Screenshots
![screen](screenshot.png)
![screen](testdata/filetypes/gohttpserver.gif)
## Features
1. [x] Support QRCode code generate
@@ -35,16 +36,22 @@ Upload size now limited to 1G
1. [ ] Offline download
1. [ ] Code file preview
1. [ ] Edit file support
1. [ ] Global file search
1. [x] Global file search
1. [x] Hidden work `download` and `qrcode` in small screen
1. [x] Theme select support
1. [x] OK to working behide Nginx
1. [ ] \.htaccess support
1. [x] \.ghs.yml support (like \.htaccess)
1. [ ] Calculate md5sum and sha
1. [ ] Folder upload
1. [ ] Support sort by size or modified time
1. [ ] Add version info into index page
1. [ ] Add api `/-/stat/some.(apk|ipa)` to get detail info
1. [x] Add version info into index page
1. [ ] Add api `/-/info/some.(apk|ipa)` to get detail info
1. [x] Add api `/-/apk/info/some.apk` to get android package info
1. [x] Auto tag version
1. [x] Custom title support
1. [x] Support setting from conf file
1. [x] Quick copy download link
1. [x] Show folder size
## Installation
```
@@ -54,27 +61,86 @@ go build && ./gohttpserver
```
## Usage
Listen port 8000 on all interface, and enable upload
Listen on port 8000 of all interfaces, and enable file uploading.
```
./gohttpserver -r ./ --addr :8000 --upload
```
## Authentication options
- Enable basic http authentication
```sh
$ gohttpserver --auth-type http --auth-http username:password
```
- Use openid auth
```sh
$ gohttpserver --auth-type openid --auth-openid https://login.example-hostname.com/openid/
```
The openid returns url using "http" instead of "https", but I am not planing to fix this currently.
## Advanced usage
Add access rule by creating a `.ghs.yml` file under a sub-directory. An example:
```yaml
---
upload: false
delete: false
users:
- email: "codeskyblue@codeskyblue.com"
delete: true
upload: true
```
In this case, if openid auth is enabled and user "codeskyblue@codeskyblue.com" has logged in, he/she can delete/upload files under the directory where the `.ghs.yml` file exits.
For example, in the following directory hierarchy, users can delete/uploade files in directory `foo`, but he/she cannot do this in directory `bar`.
```
root -
|-- foo
| |-- .ghs.yml
| `-- world.txt
`-- bar
`-- hello.txt
```
User can specify config file name with `--conf`, see [example config.yml](testdata/config.yml).
To specify which files is hidden and which file is visible, add the following lines to `.ghs.yml`
```yaml
accessTables:
- regex: block.file
allow: false
- regex: visual.file
allow: true
```
### ipa plist proxy
This is used for server which not https enabled.
This is used for server on which https is enabled. default use <https://plistproxy.herokuapp.com/plist>
```
./gohttpserver --plistproxy=https://someproxyhost.com/
```
Proxy web site should have ability, when request `https://proxyhost.com/www.github.com`
return the same page as request from `http://www.github.com`
Test if proxy works:
```sh
$ http POST https://proxyhost.com/plist < app.plist
{
"key": "18f99211"
}
$ http GET https://proxyhost.com/plist/18f99211
# show the app.plist content
```
### Upload with CURL
For example, upload a file named `foo.txt` to directory `somedir`
PS: max upload size limited to 1G (hard coded)
```sh
$ curl -F file=@foo.txt localhost:8000/somedir
```
@@ -82,6 +148,12 @@ $ curl -F file=@foo.txt localhost:8000/somedir
## FAQ
- [How to generate self signed certificate with openssl](http://stackoverflow.com/questions/10175812/how-to-create-a-self-signed-certificate-with-openssl)
### How the query is formated
The search query follows common format rules just like Google. Keywords are seperated with space(s), keywords with prefix `-` will be excluded in search results.
1. `hello world` means must contains `hello` and `world`
1. `hello -world` means must contains `hello` but not contains `world`
## Developer Guide
Depdencies are managed by godep
@@ -91,7 +163,7 @@ go get github.com/jteeuwen/go-bindata/...
go get github.com/elazarl/go-bindata-assetfs/...
```
Theme are all defined in [res/themes](res/themes) directory. Now only two, black and green.
Theme are all defined in [res/themes](res/themes) directory. Now only two themes are available, "black" and "green".
## How to build single binary release
```sh
@@ -99,21 +171,25 @@ go-bindata-assetfs -tags bindata res/...
go build -tags bindata
```
That's all. ^_^
## Reference Web sites
* <https://vuejs.org.cn/>
* Core lib Vue <https://vuejs.org.cn/>
* Icon from <http://www.easyicon.net/558394-file_explorer_icon.html>
* <https://github.com/elazarl/go-bindata-assetfs>
* Code Highlight <https://craig.is/making/rainbows>
* Markdown-JS <https://github.com/showdownjs/showdown>
* <https://github.com/sindresorhus/github-markdown-css>
* Markdown Parser <https://github.com/showdownjs/showdown>
* Markdown CSS <https://github.com/sindresorhus/github-markdown-css>
* Upload support <http://www.dropzonejs.com/>
* ScrollUp <https://markgoodyear.com/2013/01/scrollup-jquery-plugin/>
* Clipboard <https://clipboardjs.com/>
* Underscore <http://underscorejs.org/>
**Go Libraries**
* <https://github.com/elazarl/go-bindata-assetfs>
* <http://www.gorillatoolkit.org/pkg/handlers>
* <http://www.dropzonejs.com/>
## History
The first version is <https://github.com/codeskyblue/gohttp>
The old version is hosted at <https://github.com/codeskyblue/gohttp>
## LICENSE
This project is under license [MIT](LICENSE)
This project is licensed under [MIT](LICENSE).

24
build.sh Normal file → Executable file
View File

@@ -2,13 +2,35 @@
set -eu
VERSION=$(git describe --abbrev=0 --tags)
REVCNT=$(git rev-list --count HEAD)
DEVCNT=$(git rev-list --count $VERSION)
if test $REVCNT != $DEVCNT
then
VERSION="$VERSION.dev$(expr $REVCNT - $DEVCNT)"
fi
echo "VER: $VERSION"
GITCOMMIT=$(git rev-parse HEAD)
BUILDTIME=$(date -u +%Y/%m/%d-%H:%M:%S)
LDFLAGS="-X main.VERSION=$VERSION -X main.BUILDTIME=$BUILDTIME -X main.GITCOMMIT=$GITCOMMIT"
if [[ -n "${EX_LDFLAGS:-""}" ]]
then
LDFLAGS="$LDFLAGS $EX_LDFLAGS"
fi
build() {
echo "$1 $2 ..."
GOOS=$1 GOARCH=$2 go build -tags bindata -o dist/gohttpserver-${3:-""}
GOOS=$1 GOARCH=$2 go build \
-tags bindata \
-ldflags "$LDFLAGS" \
-o dist/gohttpserver-${3:-""}
}
go-bindata-assetfs -tags bindata res/...
build linux arm linux-arm
build darwin amd64 mac-amd64
build linux amd64 linux-amd64
build linux 386 linux-386

View File

@@ -1,6 +1,7 @@
package main
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
@@ -10,105 +11,234 @@ import (
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"regexp"
"github.com/go-yaml/yaml"
"github.com/gorilla/mux"
"github.com/shogo82148/androidbinary/apk"
)
type HTTPStaticServer struct {
Root string
Theme string
Upload bool
PlistProxy string
type ApkInfo struct {
PackageName string `json:"packageName"`
MainActivity string `json:"mainActivity"`
Version struct {
Code int `json:"code"`
Name string `json:"name"`
} `json:"version"`
}
m *mux.Router
type IndexFileItem struct {
Path string
Info os.FileInfo
}
type HTTPStaticServer struct {
Root string
Upload bool
Delete bool
Title string
Theme string
PlistProxy string
GoogleTrackerId string
AuthType string
indexes []IndexFileItem
m *mux.Router
}
func NewHTTPStaticServer(root string) *HTTPStaticServer {
if root == "" {
root = "."
root = "./"
}
root = filepath.ToSlash(root)
if !strings.HasSuffix(root, "/") {
root = root + "/"
}
log.Printf("root path: %s\n", root)
m := mux.NewRouter()
s := &HTTPStaticServer{
Root: root,
Theme: "black",
m: m,
}
go func() {
time.Sleep(1 * time.Second)
for {
startTime := time.Now()
log.Println("Started making search index")
s.makeIndex()
log.Printf("Completed search index in %v", time.Since(startTime))
//time.Sleep(time.Second * 1)
time.Sleep(time.Minute * 10)
}
}()
m.HandleFunc("/-/status", s.hStatus)
m.HandleFunc("/-/raw/{path:.*}", s.hFileOrDirectory)
m.HandleFunc("/-/zip/{path:.*}", s.hZip)
m.HandleFunc("/-/unzip/{zip_path:.*}/-/{path:.*}", s.hUnzip)
m.HandleFunc("/-/json/{path:.*}", s.hJSONList)
// routers for Apple *.ipa
m.HandleFunc("/-/ipa/plist/{path:.*}", s.hPlist)
m.HandleFunc("/-/ipa/link/{path:.*}", s.hIpaLink)
// TODO: /ipa/info
m.HandleFunc("/-/info/{path:.*}", s.hInfo)
m.HandleFunc("/{path:.*}", s.hIndex).Methods("GET")
m.HandleFunc("/{path:.*}", s.hIndex).Methods("GET", "HEAD")
m.HandleFunc("/{path:.*}", s.hUpload).Methods("POST")
m.HandleFunc("/{path:.*}", s.hDelete).Methods("DELETE")
return s
}
func (s *HTTPStaticServer) EnableUpload() {
s.Upload = true
s.m.HandleFunc("/{path:.*}", s.hUpload).Methods("POST")
}
func (s *HTTPStaticServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.m.ServeHTTP(w, r)
}
func (s *HTTPStaticServer) hIndex(w http.ResponseWriter, r *http.Request) {
path := mux.Vars(r)["path"]
relPath := filepath.Join(s.Root, path)
if r.FormValue("raw") == "false" || isDir(relPath) {
if r.Method == "HEAD" {
return
}
tmpl.ExecuteTemplate(w, "index", s)
} else {
if r.FormValue("download") == "true" {
w.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(filepath.Base(path)))
}
http.ServeFile(w, r, relPath)
}
}
func (s *HTTPStaticServer) hStatus(w http.ResponseWriter, r *http.Request) {
data, _ := json.MarshalIndent(s, "", " ")
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
func (s *HTTPStaticServer) hUpload(w http.ResponseWriter, req *http.Request) {
err := req.ParseMultipartForm(1 << 30) // max memory 1G
func (s *HTTPStaticServer) hDelete(w http.ResponseWriter, req *http.Request) {
// only can delete file now
path := mux.Vars(req)["path"]
auth := s.readAccessConf(path)
log.Printf("%#v", auth)
if !auth.canDelete(req) {
http.Error(w, "Delete forbidden", http.StatusForbidden)
return
}
err := os.Remove(filepath.Join(s.Root, path))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(req.MultipartForm.File["file"]) == 0 {
http.Error(w, "Need multipart file", http.StatusInternalServerError)
http.Error(w, err.Error(), 500)
return
}
w.Write([]byte("Success"))
}
func (s *HTTPStaticServer) hUpload(w http.ResponseWriter, req *http.Request) {
path := mux.Vars(req)["path"]
dirpath := filepath.Join(s.Root, path)
for _, mfile := range req.MultipartForm.File["file"] {
file, err := mfile.Open()
defer file.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
dst, err := os.Create(filepath.Join(dirpath, mfile.Filename)) // BUG(ssx): There is a leak here
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
log.Println("Handle upload file:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// check auth
auth := s.readAccessConf(path)
if !auth.canUpload(req) {
http.Error(w, "Upload forbidden", http.StatusForbidden)
return
}
w.Write([]byte("Upload success"))
file, header, err := req.FormFile("file")
if err != nil {
log.Println("Parse form file:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer func() {
file.Close()
req.MultipartForm.RemoveAll() // Seen from go source code, req.MultipartForm not nil after call FormFile(..)
}()
dstPath := filepath.Join(dirpath, header.Filename)
dst, err := os.Create(dstPath)
if err != nil {
log.Println("Create file:", err)
http.Error(w, "File create "+err.Error(), http.StatusInternalServerError)
return
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
log.Println("Handle upload file:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json;charset=utf-8")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"destination": dstPath,
})
}
func (s *HTTPStaticServer) hIndex(w http.ResponseWriter, r *http.Request) {
type FileJSONInfo struct {
Name string `json:"name"`
Type string `json:"type"`
Size int64 `json:"size"`
Path string `json:"path"`
ModTime int64 `json:"mtime"`
Extra interface{} `json:"extra,omitempty"`
}
// path should be absolute
func parseApkInfo(path string) (ai *ApkInfo) {
defer func() {
if err := recover(); err != nil {
log.Println("parse-apk-info panic:", err)
}
}()
apkf, err := apk.OpenFile(path)
if err != nil {
return
}
ai = &ApkInfo{}
ai.MainActivity, _ = apkf.MainAcitivty()
ai.PackageName = apkf.PackageName()
ai.Version.Code = apkf.Manifest().VersionCode
ai.Version.Name = apkf.Manifest().VersionName
return
}
func (s *HTTPStaticServer) hInfo(w http.ResponseWriter, r *http.Request) {
path := mux.Vars(r)["path"]
relPath := filepath.Join(s.Root, path)
finfo, err := os.Stat(relPath)
if err == nil && finfo.IsDir() {
tmpl.ExecuteTemplate(w, "index", s)
// tmpl.Execute(w, s)
} else {
http.ServeFile(w, r, relPath)
if !isFile(relPath) {
http.Error(w, "Not a file", 403)
return
}
fi, err := os.Stat(relPath)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
fji := &FileJSONInfo{
Name: fi.Name(),
Size: fi.Size(),
Path: path,
ModTime: fi.ModTime().UnixNano() / 1e6,
}
ext := filepath.Ext(path)
switch ext {
case ".md":
fji.Type = "markdown"
case ".apk":
fji.Type = "apk"
fji.Extra = parseApkInfo(relPath)
default:
fji.Type = "text"
}
data, _ := json.Marshal(fji)
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
func (s *HTTPStaticServer) hZip(w http.ResponseWriter, r *http.Request) {
@@ -176,8 +306,16 @@ func (s *HTTPStaticServer) hPlist(w http.ResponseWriter, r *http.Request) {
func (s *HTTPStaticServer) hIpaLink(w http.ResponseWriter, r *http.Request) {
path := mux.Vars(r)["path"]
plistUrl := genURLStr(r, "/-/ipa/plist/"+path).String()
if s.PlistProxy != "" {
plistUrl = strings.TrimSuffix(s.PlistProxy, "/") + "/" + r.Host + "/-/ipa/plist/" + path
if r.TLS == nil {
// send plist to plistproxy and get a https link
httpPlistLink := "http://" + r.Host + "/-/ipa/plist/" + path
url, err := s.genPlistLink(httpPlistLink)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
plistUrl = url
//plistUrl = strings.TrimSuffix(s.PlistProxy, "/") + "/" + r.Host + "/-/ipa/plist/" + path
}
w.Header().Set("Content-Type", "text/html")
@@ -190,57 +328,291 @@ func (s *HTTPStaticServer) hIpaLink(w http.ResponseWriter, r *http.Request) {
// plistUrl)))
}
func (s *HTTPStaticServer) genPlistLink(httpPlistLink string) (plistUrl string, err error) {
// Maybe need a proxy, a little slowly now.
pp := s.PlistProxy
if pp == "" {
pp = defaultPlistProxy
}
resp, err := http.Get(httpPlistLink)
if err != nil {
return
}
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
retData, err := http.Post(pp, "text/xml", bytes.NewBuffer(data))
if err != nil {
return
}
defer retData.Body.Close()
jsonData, _ := ioutil.ReadAll(retData.Body)
var ret map[string]string
if err = json.Unmarshal(jsonData, &ret); err != nil {
return
}
plistUrl = pp + "/" + ret["key"]
return
}
func (s *HTTPStaticServer) hFileOrDirectory(w http.ResponseWriter, r *http.Request) {
path := mux.Vars(r)["path"]
log.Println("Path:", s.Root, path)
http.ServeFile(w, r, filepath.Join(s.Root, path))
}
type ListResponse struct {
Name string `json:"name"`
Path string `json:"path"`
Type string `json:"type"`
Size string `json:"size"`
type HTTPFileInfo struct {
Name string `json:"name"`
Path string `json:"path"`
Type string `json:"type"`
Size int64 `json:"size"`
ModTime int64 `json:"mtime"`
}
type AccessTable struct {
Regex string `yaml:"regex"`
Allow bool `yaml:"allow"`
}
type UserControl struct {
Email string
// Access bool
Upload bool
Delete bool
}
type AccessConf struct {
Upload bool `yaml:"upload" json:"upload"`
Delete bool `yaml:"delete" json:"delete"`
Users []UserControl `yaml:"users" json:"users"`
AccessTables []AccessTable `yaml:"accessTables"`
}
var reCache = make(map[string]*regexp.Regexp)
func (c *AccessConf) canAccess(fileName string) bool {
for _, table := range c.AccessTables {
pattern, ok := reCache[table.Regex]
if !ok {
pattern, _ = regexp.Compile(table.Regex)
reCache[table.Regex] = pattern
}
// skip wrong format regex
if pattern == nil {
continue
}
if pattern.MatchString(fileName) {
return table.Allow
}
}
return true
}
func (c *AccessConf) canDelete(r *http.Request) bool {
session, err := store.Get(r, defaultSessionName)
if err != nil {
return c.Delete
}
val := session.Values["user"]
if val == nil {
return c.Delete
}
userInfo := val.(*UserInfo)
for _, rule := range c.Users {
if rule.Email == userInfo.Email {
return rule.Delete
}
}
return c.Delete
}
func (c *AccessConf) canUpload(r *http.Request) bool {
session, err := store.Get(r, defaultSessionName)
if err != nil {
return c.Upload
}
val := session.Values["user"]
if val == nil {
return c.Upload
}
userInfo := val.(*UserInfo)
for _, rule := range c.Users {
if rule.Email == userInfo.Email {
return rule.Upload
}
}
return c.Upload
}
func (s *HTTPStaticServer) hJSONList(w http.ResponseWriter, r *http.Request) {
path := mux.Vars(r)["path"]
lrs := make([]ListResponse, 0)
fd, err := os.Open(filepath.Join(s.Root, path))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
defer fd.Close()
requestPath := mux.Vars(r)["path"]
localPath := filepath.Join(s.Root, requestPath)
search := r.FormValue("search")
auth := s.readAccessConf(requestPath)
auth.Upload = auth.canUpload(r)
auth.Delete = auth.canDelete(r)
files, err := fd.Readdir(-1)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
for _, file := range files {
lr := ListResponse{
Name: file.Name(),
Path: filepath.Join(path, file.Name()), // lstrip "/"
// path string -> info os.FileInfo
fileInfoMap := make(map[string]os.FileInfo, 0)
if search != "" {
results := s.findIndex(search)
if len(results) > 50 { // max 50
results = results[:50]
}
if file.IsDir() {
fileName := deepPath(filepath.Join(s.Root, path), file.Name())
lr.Name = fileName
lr.Path = filepath.Join(path, fileName)
for _, item := range results {
if filepath.HasPrefix(item.Path, requestPath) {
fileInfoMap[item.Path] = item.Info
}
}
} else {
infos, err := ioutil.ReadDir(localPath)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
for _, info := range infos {
fileInfoMap[filepath.Join(requestPath, info.Name())] = info
}
}
// turn file list -> json
lrs := make([]HTTPFileInfo, 0)
for path, info := range fileInfoMap {
if !auth.canAccess(info.Name()) {
continue
}
lr := HTTPFileInfo{
Name: info.Name(),
Path: path,
ModTime: info.ModTime().UnixNano() / 1e6,
}
if search != "" {
name, err := filepath.Rel(requestPath, path)
if err != nil {
log.Println(requestPath, path, err)
}
lr.Name = filepath.ToSlash(name) // fix for windows
}
if info.IsDir() {
name := deepPath(localPath, info.Name())
lr.Name = name
lr.Path = filepath.Join(filepath.Dir(path), name)
lr.Type = "dir"
lr.Size = "-"
lr.Size = s.historyDirSize(lr.Path)
} else {
lr.Type = "file"
lr.Size = formatSize(file)
lr.Size = info.Size() // formatSize(info)
}
lrs = append(lrs, lr)
}
data, _ := json.Marshal(lrs)
data, _ := json.Marshal(map[string]interface{}{
"files": lrs,
"auth": auth,
})
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
var dirSizeMap = make(map[string]int64)
func (s *HTTPStaticServer) makeIndex() error {
var indexes = make([]IndexFileItem, 0)
var err = filepath.Walk(s.Root, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Printf("WARN: Visit path: %s error: %v", strconv.Quote(path), err)
return filepath.SkipDir
// return err
}
if info.IsDir() {
return nil
}
path, _ = filepath.Rel(s.Root, path)
path = filepath.ToSlash(path)
indexes = append(indexes, IndexFileItem{path, info})
return nil
})
s.indexes = indexes
dirSizeMap = make(map[string]int64)
return err
}
func (s *HTTPStaticServer) historyDirSize(dir string) int64 {
var size int64
if size, ok := dirSizeMap[dir]; ok {
return size
}
for _, fitem := range s.indexes {
if filepath.HasPrefix(fitem.Path, dir) {
size += fitem.Info.Size()
}
}
dirSizeMap[dir] = size
return size
}
func (s *HTTPStaticServer) findIndex(text string) []IndexFileItem {
ret := make([]IndexFileItem, 0)
for _, item := range s.indexes {
ok := true
// search algorithm, space for AND
for _, keyword := range strings.Fields(text) {
needContains := true
if strings.HasPrefix(keyword, "-") {
needContains = false
keyword = keyword[1:]
}
if keyword == "" {
continue
}
ok = (needContains == strings.Contains(strings.ToLower(item.Path), strings.ToLower(keyword)))
if !ok {
break
}
}
if ok {
ret = append(ret, item)
}
}
return ret
}
func (s *HTTPStaticServer) defaultAccessConf() AccessConf {
return AccessConf{
Upload: s.Upload,
Delete: s.Delete,
}
}
func (s *HTTPStaticServer) readAccessConf(requestPath string) (ac AccessConf) {
requestPath = filepath.Clean(requestPath)
if requestPath == "/" || requestPath == "" || requestPath == "." {
ac = s.defaultAccessConf()
} else {
parentPath := filepath.Dir(requestPath)
ac = s.readAccessConf(parentPath)
}
relPath := filepath.Join(s.Root, requestPath)
if isFile(relPath) {
relPath = filepath.Dir(relPath)
}
cfgFile := filepath.Join(relPath, ".ghs.yml")
data, err := ioutil.ReadFile(cfgFile)
if err != nil {
if os.IsNotExist(err) {
return
}
log.Printf("Err read .ghs.yml: %v", err)
}
err = yaml.Unmarshal(data, &ac)
if err != nil {
log.Printf("Err format .ghs.yml: %v", err)
}
return
}
func deepPath(basedir, name string) string {
isDir := true
// loop max 5, incase of for loop not finished
@@ -251,10 +623,20 @@ func deepPath(basedir, name string) string {
break
}
if finfos[0].IsDir() {
name = filepath.Join(name, finfos[0].Name())
name = filepath.ToSlash(filepath.Join(name, finfos[0].Name()))
} else {
break
}
}
return name
}
func isFile(path string) bool {
info, err := os.Stat(path)
return err == nil && info.Mode().IsRegular()
}
func isDir(path string) bool {
info, err := os.Stat(path)
return err == nil && info.Mode().IsDir()
}

176
main.go
View File

@@ -1,72 +1,157 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"text/template"
"github.com/alecthomas/kingpin"
"github.com/go-yaml/yaml"
"github.com/goji/httpauth"
"github.com/gorilla/handlers"
accesslog "github.com/mash/go-accesslog"
)
type Configure struct {
Addr string
Root string
HttpAuth string
Cert string
Key string
Cors bool
Theme string
XProxy bool
Upload bool
PlistProxy *url.URL
Conf *os.File `yaml:"-"`
Addr string `yaml:"addr"`
Root string `yaml:"root"`
HTTPAuth string `yaml:"httpauth"`
Cert string `yaml:"cert"`
Key string `yaml:"key"`
Cors bool `yaml:"cors"`
Theme string `yaml:"theme"`
XHeaders bool `yaml:"xheaders"`
Upload bool `yaml:"upload"`
Delete bool `yaml:"delete"`
PlistProxy string `yaml:"plistproxy"`
Title string `yaml:"title"`
Debug bool `yaml:"debug"`
GoogleTrackerId string `yaml:"google-tracker-id"`
Auth struct {
Type string `yaml:"type"`
OpenID string `yaml:"openid"`
HTTP string `yaml:"http"`
} `yaml:"auth"`
}
type logger struct {
}
type logger struct{}
func (l logger) Log(record accesslog.LogRecord) {
log.Printf("%s [code %d] %s", record.Method, record.Status, record.Uri)
log.Printf("%s - %s %d %s", record.Ip, record.Method, record.Status, record.Uri)
}
var (
gcfg = Configure{}
l = logger{}
defaultPlistProxy = "https://plistproxy.herokuapp.com/plist"
defaultOpenID = "https://some-hostname.com/openid/"
gcfg = Configure{}
l = logger{}
VERSION = "unknown"
BUILDTIME = "unknown time"
GITCOMMIT = "unknown git commit"
SITE = "https://github.com/codeskyblue/gohttpserver"
)
func parseFlags() {
func versionMessage() string {
t := template.Must(template.New("version").Parse(`GoHTTPServer
Version: {{.Version}}
Go version: {{.GoVersion}}
OS/Arch: {{.OSArch}}
Git commit: {{.GitCommit}}
Built: {{.Built}}
Site: {{.Site}}`))
buf := bytes.NewBuffer(nil)
t.Execute(buf, map[string]interface{}{
"Version": VERSION,
"GoVersion": runtime.Version(),
"OSArch": runtime.GOOS + "/" + runtime.GOARCH,
"GitCommit": GITCOMMIT,
"Built": BUILDTIME,
"Site": SITE,
})
return buf.String()
}
func parseFlags() error {
// initial default conf
gcfg.Root = "./"
gcfg.Addr = ":8000"
gcfg.Theme = "black"
gcfg.PlistProxy = defaultPlistProxy
gcfg.Auth.OpenID = defaultOpenID
gcfg.GoogleTrackerId = "UA-81205425-2"
gcfg.Title = "Go HTTP File Server"
kingpin.HelpFlag.Short('h')
kingpin.Flag("root", "root directory").Short('r').Default("./").StringVar(&gcfg.Root)
kingpin.Flag("addr", "listen address").Short('a').Default(":8000").StringVar(&gcfg.Addr)
kingpin.Version(versionMessage())
kingpin.Flag("conf", "config file path, yaml format").FileVar(&gcfg.Conf)
kingpin.Flag("root", "root directory, default ./").Short('r').StringVar(&gcfg.Root)
kingpin.Flag("addr", "listen address, default :8000").Short('a').StringVar(&gcfg.Addr)
kingpin.Flag("cert", "tls cert.pem path").StringVar(&gcfg.Cert)
kingpin.Flag("key", "tls key.pem path").StringVar(&gcfg.Key)
kingpin.Flag("auth-type", "Auth type <http|openid>").StringVar(&gcfg.Auth.Type)
kingpin.Flag("auth-http", "HTTP basic auth (ex: user:pass)").StringVar(&gcfg.Auth.HTTP)
kingpin.Flag("auth-openid", "OpenID auth identity url").StringVar(&gcfg.Auth.OpenID)
kingpin.Flag("theme", "web theme, one of <black|green>").StringVar(&gcfg.Theme)
kingpin.Flag("upload", "enable upload support").BoolVar(&gcfg.Upload)
kingpin.Flag("delete", "enable delete support").BoolVar(&gcfg.Delete)
kingpin.Flag("xheaders", "used when behide nginx").BoolVar(&gcfg.XHeaders)
kingpin.Flag("cors", "enable cross-site HTTP request").BoolVar(&gcfg.Cors)
kingpin.Flag("httpauth", "HTTP basic auth (ex: user:pass)").Default("").StringVar(&gcfg.HttpAuth)
kingpin.Flag("theme", "web theme, one of <black|green>").Default("black").StringVar(&gcfg.Theme)
kingpin.Flag("xproxy", "Used when behide proxy like nginx").BoolVar(&gcfg.XProxy)
kingpin.Flag("upload", "Enable upload support").BoolVar(&gcfg.Upload)
kingpin.Flag("plistproxy", "IPA Plist file proxy, https needed").Short('p').URLVar(&gcfg.PlistProxy)
kingpin.Flag("debug", "enable debug mode").BoolVar(&gcfg.Debug)
kingpin.Flag("plistproxy", "plist proxy when server is not https").Short('p').StringVar(&gcfg.PlistProxy)
kingpin.Flag("title", "server title").StringVar(&gcfg.Title)
kingpin.Flag("google-tracker-id", "set to empty to disable it").StringVar(&gcfg.GoogleTrackerId)
kingpin.Parse()
kingpin.Parse() // first parse conf
if gcfg.Conf != nil {
defer func() {
kingpin.Parse() // command line priority high than conf
}()
ymlData, err := ioutil.ReadAll(gcfg.Conf)
if err != nil {
return err
}
return yaml.Unmarshal(ymlData, &gcfg)
}
return nil
}
func main() {
parseFlags()
if err := parseFlags(); err != nil {
log.Fatal(err)
}
if gcfg.Debug {
data, _ := yaml.Marshal(gcfg)
fmt.Printf("--- config ---\n%s\n", string(data))
}
log.SetFlags(log.Lshortfile | log.LstdFlags)
ss := NewHTTPStaticServer(gcfg.Root)
ss.Theme = gcfg.Theme
ss.Title = gcfg.Title
ss.GoogleTrackerId = gcfg.GoogleTrackerId
ss.Upload = gcfg.Upload
ss.Delete = gcfg.Delete
ss.AuthType = gcfg.Auth.Type
log.Println(gcfg.PlistProxy)
if gcfg.Upload {
ss.EnableUpload()
}
if gcfg.PlistProxy != nil {
gcfg.PlistProxy.Scheme = "https"
ss.PlistProxy = gcfg.PlistProxy.String()
if gcfg.PlistProxy != "" {
u, err := url.Parse(gcfg.PlistProxy)
if err != nil {
log.Fatal(err)
}
u.Scheme = "https"
ss.PlistProxy = u.String()
}
var hdlr http.Handler = ss
@@ -74,22 +159,37 @@ func main() {
hdlr = accesslog.NewLoggingHandler(hdlr, l)
// HTTP Basic Authentication
userpass := strings.SplitN(gcfg.HttpAuth, ":", 2)
if len(userpass) == 2 {
user, pass := userpass[0], userpass[1]
hdlr = httpauth.SimpleBasicAuth(user, pass)(hdlr)
userpass := strings.SplitN(gcfg.Auth.HTTP, ":", 2)
switch gcfg.Auth.Type {
case "http":
if len(userpass) == 2 {
user, pass := userpass[0], userpass[1]
hdlr = httpauth.SimpleBasicAuth(user, pass)(hdlr)
}
case "openid":
handleOpenID(false) // FIXME(ssx): set secure default to false
}
// CORS
if gcfg.Cors {
hdlr = handlers.CORS()(hdlr)
}
if gcfg.XProxy {
if gcfg.XHeaders {
hdlr = handlers.ProxyHeaders(hdlr)
}
http.Handle("/", hdlr)
http.HandleFunc("/-/sysinfo", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
data, _ := json.Marshal(map[string]interface{}{
"version": VERSION,
})
w.Write(data)
})
log.Printf("Listening on addr: %s\n", strconv.Quote(gcfg.Addr))
if !strings.Contains(gcfg.Addr, ":") {
gcfg.Addr = ":" + gcfg.Addr
}
log.Printf("listening on %s\n", strconv.Quote(gcfg.Addr))
var err error
if gcfg.Key != "" && gcfg.Cert != "" {

111
openid-login.go Normal file
View File

@@ -0,0 +1,111 @@
package main
import (
"encoding/gob"
"encoding/json"
"io"
"log"
"net/http"
"strings"
openid "github.com/codeskyblue/openid-go"
"github.com/gorilla/sessions"
)
var (
nonceStore = openid.NewSimpleNonceStore()
discoveryCache = openid.NewSimpleDiscoveryCache()
store = sessions.NewCookieStore([]byte("something-very-secret"))
defaultSessionName = "ghs-session"
)
type UserInfo struct {
Id string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
NickName string `json:"nickName"`
}
type M map[string]interface{}
func init() {
gob.Register(&UserInfo{})
gob.Register(&M{})
}
func handleOpenID(secure bool) {
http.HandleFunc("/-/login", func(w http.ResponseWriter, r *http.Request) {
nextUrl := r.FormValue("next")
referer := r.Referer()
if nextUrl == "" && strings.Contains(referer, "://"+r.Host) {
nextUrl = referer
}
scheme := "http"
if secure {
scheme = "https"
}
if url, err := openid.RedirectURL("https://login.netease.com/openid",
scheme+"://"+r.Host+"/-/openidcallback?next="+nextUrl, ""); err == nil {
http.Redirect(w, r, url, 303)
} else {
log.Println("Should not got error here:", err)
}
})
http.HandleFunc("/-/openidcallback", func(w http.ResponseWriter, r *http.Request) {
id, err := openid.Verify("http://"+r.Host+r.URL.String(), discoveryCache, nonceStore)
if err != nil {
io.WriteString(w, "Authentication check failed.")
return
}
session, err := store.Get(r, defaultSessionName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user := &UserInfo{
Id: id,
Email: r.FormValue("openid.sreg.email"),
Name: r.FormValue("openid.sreg.fullname"),
NickName: r.FormValue("openid.sreg.nickname"),
}
session.Values["user"] = user
if err := session.Save(r, w); err != nil {
log.Println("session save error:", err)
}
nextUrl := r.FormValue("next")
if nextUrl == "" {
nextUrl = "/"
}
http.Redirect(w, r, nextUrl, 302)
})
http.HandleFunc("/-/user", func(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, defaultSessionName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
val := session.Values["user"]
w.Header().Set("Content-Type", "application/json; charset=utf-8")
data, _ := json.Marshal(val)
w.Write(data)
})
http.HandleFunc("/-/logout", func(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, defaultSessionName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
delete(session.Values, "user")
session.Options.MaxAge = -1
nextUrl := r.FormValue("next")
_ = session.Save(r, w)
if nextUrl == "" {
nextUrl = r.Referer()
}
http.Redirect(w, r, nextUrl, 302)
})
}

View File

@@ -0,0 +1,15 @@
/* Image style */
#scrollUp {
/*background-image: url("../imgs/top.png");*/
bottom: 5px;
right: 20px;
width: 38px;
/* Width of image */
height: 38px;
/* Height of image */
}
#scrollUp:after {
content: "Scroll to top";
}

View File

@@ -6,7 +6,9 @@ body {
margin-bottom: 1em;
}
/* Not used */
div.dropzone {
display: block;
/*text-align: center;*/
@@ -18,3 +20,15 @@ div.dropzone {
font-size: 20px;
position: relative;
}
.qrcode-title {
font-size: 0.8em;
}
.clearfix::after {
clear: both;
}
#qrcodeCanvas {
padding-right: 20px;
}

BIN
res/imgs/top.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 698 B

View File

@@ -2,181 +2,262 @@
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>gohttp server</title>
<link rel="shortcut icon" type="image/png" href="/-/res/favicon.png" />
<link rel="stylesheet" type="text/css" href="/-/res/bootstrap-3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/-/res/font-awesome-4.6.3/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="/-/res/css/github-markdown.css">
<link rel="stylesheet" type="text/css" href="/-/res/css/dropzone.css">
<link rel="stylesheet" type="text/css" href="/-/res/css/style.css">
<link rel="stylesheet" type="text/css" href="/-/res/themes/[[.Theme]].css">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>gohttp server</title>
<link rel="shortcut icon" type="image/png" href="/-/res/favicon.png" />
<link rel="stylesheet" type="text/css" href="/-/res/bootstrap-3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/-/res/font-awesome-4.6.3/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="/-/res/css/github-markdown.css">
<link rel="stylesheet" type="text/css" href="/-/res/css/dropzone.css">
<link rel="stylesheet" type="text/css" href="/-/res/css/scrollUp-image.css">
<link rel="stylesheet" type="text/css" href="/-/res/css/style.css">
<link rel="stylesheet" type="text/css" href="/-/res/themes/[[.Theme]].css">
</head>
<body id="app">
<nav class="navbar navbar-inverse">
<div class="container">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Go HTTP File Server</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-2">
<ul class="nav navbar-nav">
<li><a href="{{.dir}}">{{.dir}}</a></li>
</ul>
<form class="navbar-form navbar-right">
<div class="input-group">
<input type="text" name="search" class="form-control" placeholder="Not finished.">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
<ul id="nav-right-bar" class="nav navbar-nav navbar-right">
</ul>
</div>
</div>
</div>
</nav>
<nav class="navbar navbar-default">
<div class="container">
<div class="col-md-12">
<ol class="breadcrumb">
<li>
<a v-on:click='changePath("/", $event)' href="/"><i class="fa fa-home"></i></a>
</li>
<li v-for="bc in breadcrumb.slice(0, breadcrumb.length-1)">
<a v-on:click='changePath(bc.path, $event)' href="{{bc.path}}">{{bc.name}}</a>
</li>
<li v-if="breadcrumb.length >= 1">
{{breadcrumb.slice(-1)[0].name}}
</li>
</ol>
<table class="table table-hover">
<thead>
<tr colspan=3>
<td>
<button class="btn btn-xs btn-default" v-on:click='toggleHidden()'>
Show hidden <i class="fa" v-bind:class='showHidden ? "fa-eye" : "fa-eye-slash"'></i>
</button>
[[ if .Upload ]]
<button class="btn btn-xs btn-default" data-toggle="modal" data-target="#upload-modal">
Upload file <i class="fa fa-upload"></i>
</button>
[[ end ]]
</td>
</tr>
<tr>
<th>Name</th>
<th>Size</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="f in computedFiles">
<td>
<a v-on:click='clickFileOrDir(f, $event)' href="/{{f.path}}">
<i style="padding-right: 0.5em" class="fa" v-bind:class='genFileClass(f)'></i> {{f.name}}
</a>
</td>
<td>{{f.size}}</td>
<td style="text-align: left">
<template v-if="f.type == 'dir'">
<a class="btn btn-default btn-xs" href="/-/zip/{{f.path}}">
Archieve Zip
<span class="glyphicon glyphicon-download-alt"></span>
</a>
</template>
<template v-if="f.type == 'file'">
<a class="btn btn-default btn-xs" href="/-/raw/{{f.path}}?download=true">
<span class="hidden-xs">Download</span>
<span class="glyphicon glyphicon-download-alt"></span>
</a>
<a class="btn btn-default btn-xs" v-if="shouldHaveQrcode(f.name)
" v-on:click="genQrcode(f.name)" href="#">
<span class="hidden-xs">QRCode</span>
<span class="glyphicon glyphicon-qrcode"></span>
</a>
</template>
</td>
</tr>
</tbody>
</table>
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">[[.Title]]</a>
</div>
<div class="col-md-12" id="preview" v-if="previewFile">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" style="font-weight: normal">
<i class="fa" v-bind:class='genFileClass(previewFile)'></i>
{{previewFile.name}}
</h3>
</div>
<div class="panel-body">
<article class="markdown-body">{{{previewFile.contentHTML }}}
</article>
</div>
</div>
</div>
<div class="col-md-12" id="content">
<!-- Small qrcode modal -->
<div id="qrcode-modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">
<span id="qrcode-title"></span>
<a style="font-size: 0.6em" href="#" id="qrcode-link">[view]</a>
</h4>
</div>
<div class="modal-body">
<div id="qrcodeCanvas"></div>
</div>
</div>
</div>
</div>
<!-- Upload modal-->
<div id="upload-modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">
<i class="fa fa-upload"></i> File upload
</h4>
</div>
<div class="modal-body">
<form action="#" class="dropzone" id="my-dropzone"></form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div id="footer" class="pull-right" style="margin: 2em 1em">
<a href="https://github.com/codeskyblue/gohttpserver">gohttpserver</a>, written by <a href="https://github.com/codeskyblue">codeskyblue</a>. 2016. go 1.6
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-2">
<ul class="nav navbar-nav">
<li class="hidden-xs">
<a href="javascript:void(0)" v-on:click='genQrcode(location.pathname)'>
View in Phone
<span class="glyphicon glyphicon-qrcode"></span>
</a>
</li>
[[if eq .AuthType "openid"]]
<li class="hidden-xs">
<a href="/-/logout" v-if="user.email">
<span v-text="user.name"></span>
<span class="glyphicon glyphicon-indent-left"></span>
</a>
<a href="/-/login" v-else>
Login
<span class="glyphicon glyphicon-user"></span>
</a>
</li>
[[end]]
</ul>
<form class="navbar-form navbar-right">
<div class="input-group">
<input type="text" name="search" class="form-control" placeholder="Search text" v-bind:value="search" autofocus>
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
<ul id="nav-right-bar" class="nav navbar-nav navbar-right">
</ul>
</div>
</div>
</div>
<script src="/-/res/js/jquery-3.1.0.min.js"></script>
<script src="/-/res/js/jquery.qrcode.js"></script>
<script src="/-/res/js/qrcode.js"></script>
<script src="/-/res/js/vue-1.0.min.js"></script>
<script src="/-/res/js/showdown-1.4.2.min.js"></script>
<script src="/-/res/js/dropzone.js"></script>
<script src="/-/res/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="/-/res/js/index.js"></script>
</nav>
<div class="container">
<div class="col-md-12">
<ol class="breadcrumb">
<li>
<a v-on:click='changePath("/", $event)' href="/"><i class="fa fa-home"></i></a>
</li>
<li v-for="bc in breadcrumb.slice(0, breadcrumb.length-1)">
<a v-on:click='changePath(bc.path, $event)' href="{{bc.path}}">{{bc.name}}</a>
</li>
<li v-if="breadcrumb.length >= 1">
{{breadcrumb.slice(-1)[0].name}}
</li>
</ol>
<table class="table table-hover" v-if="!previewMode">
<thead>
<tr>
<td colspan=4>
<!-- <button class="btn btn-xs btn-default" v-on:click='toggleHidden()'>
Back <i class="fa" v-bind:class='showHidden ? "fa-eye" : "fa-eye-slash"'></i>
</button> -->
<button class="btn btn-xs btn-default" onclick="history.back()">
Back <i class="fa fa-arrow-left"></i>
</button>
<button class="btn btn-xs btn-default" v-on:click='toggleHidden()'>
Hidden <i class="fa" v-bind:class='showHidden ? "fa-eye" : "fa-eye-slash"'></i>
</button>
<button class="btn btn-xs btn-default" v-if="auth.upload" data-toggle="modal" data-target="#upload-modal">
Upload <i class="fa fa-upload"></i>
</button>
</td>
</tr>
<tr>
<th>Name</th>
<th>Size</th>
<th class="hidden-xs">
<span style="cursor: pointer" v-on:click='mtimeTypeFromNow = !mtimeTypeFromNow'>ModTime</span>
</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="f in computedFiles">
<td>
<a v-on:click='clickFileOrDir(f, $event)' href="/{{f.path + (f.type == 'dir' ? '' : '')}}">
<!-- ?raw=false -->
<i style="padding-right: 0.5em" class="fa" v-bind:class='genFileClass(f)'></i> {{f.name}}
</a>
</td>
<td><span v-if="f.type == 'dir'">~</span> {{f.size | formatBytes}}</td>
<td class="hidden-xs">{{formatTime(f.mtime)}}</td>
<td style="text-align: left">
<template v-if="f.type == 'dir'">
<a class="btn btn-default btn-xs" href="/-/zip/{{f.path}}">
<span class="hidden-xs">Archive</span> Zip
<span class="glyphicon glyphicon-download-alt"></span>
</a>
</template>
<template v-if="f.type == 'file'">
<a class="btn btn-default btn-xs hidden-xs" href="/{{f.path}}?download=true">
<span class="hidden-xs">Download</span>
<span class="glyphicon glyphicon-download-alt"></span>
</a>
<button class="btn btn-default btn-xs bstooltip" data-trigger="manual" data-title="Copied!" data-clipboard-text="{{genDownloadURL(f)}}">
<i class="fa fa-copy"></i>
</button>
<button class="btn btn-default btn-xs" v-on:click="showInfo(f)">
<span class="glyphicon glyphicon-info-sign"></span>
</button>
<button class="btn btn-default btn-xs hidden-xs" v-on:click="genQrcode(f.name)">
<span v-if="shouldHaveQrcode(f.name)">QRCode</span>
<span class="glyphicon glyphicon-qrcode"></span>
</button>
<a class="btn btn-default btn-xs visible-xs" v-if="shouldHaveQrcode(f.name)" href="{{genInstallURL(f.name)}}">
Install <i class="fa fa-cube"></i>
</a>
<button class="btn btn-default btn-xs" v-if="auth.delete" v-on:click="deletePathConfirm(f, $event)">
<span style="color:#CC3300" class="glyphicon glyphicon-trash"></span>
</button>
</template>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12" id="preview" v-if="preview.filename">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" style="font-weight: normal">
<i class="fa" v-bind:class='genFileClass(previewFile)'></i> {{preview.filename}}
</h3>
</div>
<div class="panel-body">
<article class="markdown-body">{{{preview.contentHTML }}}
</article>
</div>
</div>
</div>
<div class="col-md-12" id="content">
<!-- Small qrcode modal -->
<div id="qrcode-modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">
<span id="qrcode-title"></span>
<a style="font-size: 0.6em" href="#" id="qrcode-link">[view]</a>
</h4>
</div>
<div class="modal-body clearfix">
<div id="qrcodeCanvas" class="pull-left"></div>
<div id="qrcodeRight" class="pull-left">
<p>
<a href="#">下载链接</a>
</p>
</div>
</div>
</div>
</div>
</div>
<!-- Upload modal-->
<div id="upload-modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">
<i class="fa fa-upload"></i> File upload
</h4>
</div>
<div class="modal-body">
<form action="#" class="dropzone" id="upload-form"></form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" @click="removeAllUploads">RemoveAll</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- File info modal -->
<div id="file-info-modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">
<span id="file-info-title"></span>
</h4>
</div>
<div class="modal-body">
<pre id="file-info-content"></pre>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div id="footer" class="pull-right" style="margin: 2em 1em">
<a href="https://github.com/codeskyblue/gohttpserver">gohttpserver (ver:{{version}})</a>, written by <a href="https://github.com/codeskyblue">codeskyblue</a>. Copyright 2016-2017. go1.7
</div>
</div>
</div>
<script src="/-/res/js/jquery-3.1.0.min.js"></script>
<script src="/-/res/js/jquery.qrcode.js"></script>
<script src="/-/res/js/jquery.scrollUp.min.js"></script>
<script src="/-/res/js/qrcode.js"></script>
<script src="/-/res/js/vue-1.0.min.js"></script>
<script src="/-/res/js/showdown-1.6.4.min.js"></script>
<script src="/-/res/js/moment.min.js"></script>
<script src="/-/res/js/dropzone.js"></script>
<script src="/-/res/js/underscore-min.js"></script>
<script src="/-/res/js/clipboard-1.5.12.min.js"></script>
<script src="/-/res/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="/-/res/js/index.js"></script>
[[if .GoogleTrackerId ]]
<script>
(function(i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function() {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', '[[.GoogleTrackerId]]', 'auto');
ga('send', 'pageview');
</script>
[[ end ]]
</body>
</html>
</html>

View File

@@ -1,71 +1,71 @@
<html>
<head>
<title>[[.Name]] install</title>
<meta http-equiv="Content-Type" content="text/HTML; charset=utf-8">
<meta content="target-densitydpi=device-dpi,width=640" name="viewport" id="viewport">
<link rel="shortcut icon" type="image/png" href="/-/res/favicon.png" />
<script type="text/javascript" src="/-/res/js/ua-parser.min.js"></script>
<script type="text/javascript">
<title>[[.Name]] install</title>
<meta http-equiv="Content-Type" content="text/HTML; charset=utf-8">
<meta content="target-densitydpi=device-dpi,width=640" name="viewport" id="viewport">
<link rel="shortcut icon" type="image/png" href="/-/res/favicon.png" />
<script type="text/javascript" src="/-/res/js/ua-parser.min.js"></script>
<script type="text/javascript">
function showById(name) {
document.getElementById(name).style.display = 'block';
document.getElementById(name).style.display = 'block';
}
function checkBrowerAndDownload() {
var parser = new UAParser();
var os_info = parser.getOS();
console.log(os_info)
var parser = new UAParser();
var os_info = parser.getOS();
console.log(os_info)
if (navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger") {
showById('wechat');
return;
}
var plistLink = "[[.PlistLink]]";
var ipaInstallLink = 'itms-services://?action=download-manifest&url=' + plistLink;
var plistLink = "[[.PlistLink]]";
var ipaInstallLink = 'itms-services://?action=download-manifest&url=' + plistLink;
document.getElementById('itms-link').href = ipaInstallLink;
document.getElementById('itms-link').href = ipaInstallLink;
if (os_info.name == 'Android') {
return;
} else if (os_info.name == 'iOS') {
showById('safari');
location.href = ipaInstallLink;
return;
} else {
showById('browser');
return;
}
// wechat is support AppStore link now.
if (navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger") {
showById('safari');
location.href = ipaInstallLink;
return;
} else if (os_info.name == 'Android') {
showById("android");
return;
} else if (os_info.name == 'iOS') {
showById('safari');
location.href = ipaInstallLink;
return;
} else {
showById('browser');
return;
}
}
</script>
</script>
</head>
<body>
<style>
<style>
#wechat {
position: relative;
width: 640px;
margin: 0 auto;
background: #fff;
overflow: hidden;
min-height: 777px;
position: relative;
width: 640px;
margin: 0 auto;
background: #fff;
overflow: hidden;
min-height: 777px;
}
</style>
<div id="wechat" style="display: none">
<img style='width: 100%;position: relative;' src='/-/res/imgs/wx.png' />
</div>
<div id="browser" style="display: none">
This is IPA install page, you should open this link with your iPhone.
</div>
<div id="safari" style="display: none">
If install not started soon, click <a id="itms-link" href="#">here</a>
</div>
<div id="android" style="display: none">
This is IPA install page, not for android.
</div>
<script type="text/javascript">
</style>
<div id="wechat" style="display: none">
<img style='width: 100%;position: relative;' src='/-/res/imgs/wx.png' />
</div>
<div id="browser" style="display: none">
This is IPA install page, you should open this link with your iPhone.
</div>
<div id="safari" style="display: none">
If install not started soon, click <a id="itms-link" href="#">here</a>
</div>
<div id="android" style="display: none">
This is IPA install page, not for android.
</div>
<script type="text/javascript">
checkBrowerAndDownload();
</script>
</script>
</body>
</html>
</html>

7
res/js/clipboard-1.5.12.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,216 +1,377 @@
jQuery('#qrcodeCanvas').qrcode({
text: "http://jetienne.com/"
});
function getExtention(fname) {
return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
}
function pathJoin(parts, sep) {
var separator = sep || '/';
var replace = new RegExp(separator + '{1,}', 'g');
return parts.join(separator).replace(replace, separator);
}
var vm = new Vue({
el: "#app",
data: {
message: "Hello vue.js",
breadcrumb: [],
showHidden: false,
previewFile: null,
files: [{
name: "loading ...",
path: "",
size: "...",
type: "dir",
}]
},
computed: {
computedFiles: function() {
var that = this;
this.previewFile = null;
var files = this.files.filter(function(f) {
if (f.name == 'README.md') {
that.previewFile = {
name: f.name,
path: f.path,
size: f.size,
type: 'markdown',
contentHTML: '',
}
}
if (!that.showHidden && f.name.slice(0, 1) === '.') {
return false;
}
return true;
});
// console.log(this.previewFile)
if (this.previewFile) {
var name = this.previewFile.name; // For now only README.md
console.log(pathJoin([location.pathname, 'README.md']))
$.ajax({
url: pathJoin([location.pathname, 'README.md']),
method: 'GET',
success: function(res) {
var converter = new showdown.Converter({
tables: true,
omitExtraWLInCodeBlocks: true,
parseImgDimensions: true,
simplifiedAutoLink: true,
literalMidWordUnderscores: true,
tasklists: true,
ghCodeBlocks: true,
smoothLivePreview: true,
});
var html = converter.makeHtml(res);
that.previewFile.contentHTML = html;
},
error: function(err) {
console.log(err)
}
})
}
return files;
},
},
methods: {
toggleHidden: function() {
this.showHidden = !this.showHidden;
},
genQrcode: function(text) {
var urlPath = location.protocol + "//" + pathJoin([location.host, location.pathname, text]);
$("#qrcode-title").html(text);
$("#qrcode-link").attr("href", urlPath);
if (getExtention(text) == "ipa") {
urlPath = location.protocol + "//" + pathJoin([location.host, "/-/ipa/link", location.pathname, text]);
console.log(urlPath)
}
$('#qrcodeCanvas').empty().qrcode({
text: urlPath
});
$("#qrcode-modal").modal("show");
},
shouldHaveQrcode: function(name) {
return ['apk', 'ipa'].indexOf(getExtention(name)) !== -1;
},
genFileClass: function(f) {
if (f.type == "dir") {
if (f.name == '.git') {
return 'fa-git-square';
}
return "fa-folder-open";
}
var ext = getExtention(f.name);
switch (ext) {
case "go":
case "py":
case "js":
case "java":
case "c":
case "cpp":
case "h":
return "fa-file-code-o";
case "pdf":
return "fa-file-pdf-o";
case "zip":
return "fa-file-zip-o";
case "mp3":
case "wav":
return "fa-file-audio-o";
case "jpg":
case "png":
case "gif":
case "jpeg":
case "tiff":
return "fa-file-picture-o";
case "ipa":
return "fa-apple";
case "apk":
return "fa-android";
case "exe":
return "fa-windows";
}
return "fa-file-text-o"
},
clickFileOrDir: function(f, e) {
if (f.type == "file") {
return true;
}
var reqPath = pathJoin([location.pathname, f.name]);
loadDirectory(reqPath);
e.preventDefault()
},
changePath: function(reqPath, e) {
loadDirectory(reqPath);
e.preventDefault()
},
updateBreadcrumb: function() {
var pathname = decodeURI(location.pathname || "/");
var parts = pathname.split('/');
this.breadcrumb = [];
if (pathname == "/") {
return this.breadcrumb;
}
var i = 2;
for (; i <= parts.length; i += 1) {
var name = parts[i - 1];
var path = parts.slice(0, i).join('/');
this.breadcrumb.push({
name: name + (i == parts.length ? ' /' : ''),
path: path
})
}
return this.breadcrumb;
}
}
})
window.onpopstate = function(event) {
var pathname = decodeURI(location.pathname)
loadFileList()
}
function loadDirectory(reqPath) {
window.history.pushState({}, "", reqPath);
loadFileList()
}
function loadFileList() {
$.getJSON("/-/json" + location.pathname, function(res) {
// console.log(res)
res.sort(function(a, b) {
var obj2n = function(v) {
return v.type == "dir" ? 0 : 1;
}
return obj2n(a) - obj2n(b);
})
vm.files = res;
})
vm.updateBreadcrumb();
// if (Dropzone.options.myDropzone) {
// Dropzone.options.myDropzone.url = location.pathname;
// }
}
// For page first loading
loadFileList()
Dropzone.options.myDropzone = {
// url: location.pathname,
paramName: "file",
maxFilesize: 1024,
addRemoveLinks: true,
init: function() {
this.on("uploadprogress", function(file, progress) {
console.log("File progress", progress);
});
this.on("complete", function(file) {
loadFileList()
})
}
}
jQuery('#qrcodeCanvas').qrcode({
text: "http://jetienne.com/"
});
Dropzone.autoDiscover = false;
function getExtention(fname) {
return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
}
function pathJoin(parts, sep) {
var separator = sep || '/';
var replace = new RegExp(separator + '{1,}', 'g');
return parts.join(separator).replace(replace, separator);
}
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = decodeURI(window.location.search).substr(1).match(reg);
if (r != null) return r[2].replace(/\+/g, ' ');
return null;
}
var vm = new Vue({
el: "#app",
data: {
user: {
email: "",
name: "",
},
location: window.location,
breadcrumb: [],
showHidden: false,
previewMode: false,
preview: {
filename: '',
filetype: '',
filesize: 0,
contentHTML: '',
},
version: "loading",
mtimeTypeFromNow: false, // or fromNow
auth: {},
search: getQueryString("search"),
files: [{
name: "loading ...",
path: "",
size: "...",
type: "dir",
}],
myDropzone: null,
},
computed: {
computedFiles: function() {
var that = this;
that.preview.filename = null;
var files = this.files.filter(function(f) {
if (f.name == 'README.md') {
that.preview.filename = f.name;
}
if (!that.showHidden && f.name.slice(0, 1) === '.') {
return false;
}
return true;
});
// console.log(this.previewFile)
if (this.preview.filename) {
var name = this.preview.filename; // For now only README.md
console.log(pathJoin([location.pathname, 'README.md']))
$.ajax({
url: pathJoin([location.pathname, 'README.md']),
method: 'GET',
success: function(res) {
var converter = new showdown.Converter({
tables: true,
omitExtraWLInCodeBlocks: true,
parseImgDimensions: true,
simplifiedAutoLink: true,
literalMidWordUnderscores: true,
tasklists: true,
ghCodeBlocks: true,
smoothLivePreview: true,
simplifiedAutoLink: true,
strikethrough: true,
});
var html = converter.makeHtml(res);
that.preview.contentHTML = html;
},
error: function(err) {
console.log(err)
}
})
}
return files;
},
},
created: function() {
$.ajax({
url: "/-/user",
method: "get",
dataType: "json",
success: function(ret) {
if (ret) {
this.user.email = ret.email;
this.user.name = ret.name;
}
}.bind(this)
})
this.myDropzone = new Dropzone("#upload-form", {
paramName: "file",
maxFilesize: 10240,
addRemoveLinks: true,
init: function() {
this.on("uploadprogress", function(file, progress) {
// console.log("File progress", progress);
});
this.on("complete", function(file) {
console.log("reload file list")
loadFileList()
})
}
});
},
methods: {
formatTime: function(timestamp) {
var m = moment(timestamp);
if (this.mtimeTypeFromNow) {
return m.fromNow();
}
return m.format('YYYY-MM-DD HH:mm:ss');
},
toggleHidden: function() {
this.showHidden = !this.showHidden;
},
removeAllUploads: function() {
this.myDropzone.removeAllFiles();
},
genInstallURL: function(name) {
var urlPath;
if (getExtention(name) == "ipa") {
urlPath = location.protocol + "//" + pathJoin([location.host, "/-/ipa/link", location.pathname, name]);
} else {
urlPath = location.protocol + "//" + pathJoin([location.host, location.pathname, name]);
}
return encodeURI(urlPath);
},
genQrcode: function(name, title) {
var installURL = this.genInstallURL(name);
$("#qrcode-title").html(title || name);
$("#qrcode-link").attr("href", installURL);
$('#qrcodeCanvas').empty().qrcode({
text: installURL
});
$("#qrcodeRight a").attr("href", encodeURI(location.origin + pathJoin([location.pathname, name])));
$("#qrcode-modal").modal("show");
},
genDownloadURL: function(f) {
return location.origin + "/" + f.path;
},
shouldHaveQrcode: function(name) {
return ['apk', 'ipa'].indexOf(getExtention(name)) !== -1;
},
genFileClass: function(f) {
if (f.type == "dir") {
if (f.name == '.git') {
return 'fa-git-square';
}
return "fa-folder-open";
}
var ext = getExtention(f.name);
switch (ext) {
case "go":
case "py":
case "js":
case "java":
case "c":
case "cpp":
case "h":
return "fa-file-code-o";
case "pdf":
return "fa-file-pdf-o";
case "zip":
return "fa-file-zip-o";
case "mp3":
case "wav":
return "fa-file-audio-o";
case "jpg":
case "png":
case "gif":
case "jpeg":
case "tiff":
return "fa-file-picture-o";
case "ipa":
case "dmg":
return "fa-apple";
case "apk":
return "fa-android";
case "exe":
return "fa-windows";
}
return "fa-file-text-o"
},
clickFileOrDir: function(f, e) {
// TODO: fix here tomorrow
if (f.type == "file") {
return true;
}
var reqPath = pathJoin([location.pathname, f.name]);
loadFileOrDir(reqPath);
e.preventDefault()
},
changePath: function(reqPath, e) {
loadFileOrDir(reqPath);
e.preventDefault()
},
showInfo: function(f) {
console.log(f);
$.ajax({
url: pathJoin(["/-/info", location.pathname, f.name]),
method: "GET",
success: function(res) {
$("#file-info-title").text(f.name);
$("#file-info-content").text(JSON.stringify(res, null, 4));
$("#file-info-modal").modal("show");
// console.log(JSON.stringify(res, null, 4));
}
})
},
deletePathConfirm: function(f, e) {
// confirm
e.preventDefault();
$.ajax({
url: pathJoin([location.pathname, f.name]),
method: 'DELETE',
success: function(res) {
loadFileList()
},
error: function(err) {
alert(err.responseText);
}
});
},
updateBreadcrumb: function() {
var pathname = decodeURI(location.pathname || "/");
var parts = pathname.split('/');
this.breadcrumb = [];
if (pathname == "/") {
return this.breadcrumb;
}
var i = 2;
for (; i <= parts.length; i += 1) {
var name = parts[i - 1];
if (!name) {
continue;
}
var path = parts.slice(0, i).join('/');
this.breadcrumb.push({
name: name + (i == parts.length ? ' /' : ''),
path: path
})
}
return this.breadcrumb;
},
loadPreviewFile: function(filepath, e) {
if (e) {
e.preventDefault() // may be need a switch
}
var that = this;
$.getJSON(pathJoin(['/-/info', location.pathname]))
.then(function(res) {
console.log(res);
that.preview.filename = res.name;
that.preview.filesize = res.size;
return $.ajax({
url: '/' + res.path,
dataType: 'text',
});
})
.then(function(res) {
console.log(res)
that.preview.contentHTML = '<pre>' + res + '</pre>';
console.log("Finally")
})
.done(function(res) {
console.log("done", res)
});
},
loadAll: function() {
// TODO: move loadFileList here
},
}
})
window.onpopstate = function(event) {
var pathname = decodeURI(location.pathname)
loadFileList()
}
function loadFileOrDir(reqPath) {
window.history.pushState({}, "", reqPath);
loadFileList(reqPath)
}
function loadFileList(pathname) {
var pathname = pathname || location.pathname;
// console.log("load filelist:", pathname)
if (getQueryString("raw") !== "false") { // not a file preview
$.ajax({
url: pathJoin(["/-/json", pathname]),
dataType: "json",
cache: false,
success: function(res) {
res.files = _.sortBy(res.files, function(f) {
var weight = f.type == 'dir' ? 1000 : 1;
return -weight * f.mtime;
})
vm.files = res.files;
vm.auth = res.auth;
},
error: function(err) {
console.error(err)
},
});
}
vm.updateBreadcrumb();
vm.previewMode = getQueryString("raw") == "false";
if (vm.previewMode) {
vm.loadPreviewFile();
}
}
Vue.filter('fromNow', function(value) {
return moment(value).fromNow();
})
Vue.filter('formatBytes', function(value) {
var bytes = parseFloat(value);
if (bytes < 0) return "-";
else if (bytes < 1024) return bytes + " B";
else if (bytes < 1048576) return (bytes / 1024).toFixed(0) + " KB";
else if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + " MB";
else return (bytes / 1073741824).toFixed(1) + " GB";
})
$(function() {
$.scrollUp({
scrollText: '', // text are defined in css
});
// For page first loading
loadFileList(location.pathname + location.search)
// update version
$.getJSON("/-/sysinfo", function(res) {
vm.version = res.version;
})
var clipboard = new Clipboard('.btn');
clipboard.on('success', function(e) {
console.info('Action:', e.action);
console.info('Text:', e.text);
console.info('Trigger:', e.trigger);
$(e.trigger)
.tooltip('show')
.mouseleave(function() {
$(this).tooltip('hide');
})
e.clearSelection();
});
});

7
res/js/jquery.scrollUp.min.js vendored Normal file
View File

@@ -0,0 +1,7 @@
/*!
* scrollup v2.4.1
* Url: http://markgoodyear.com/labs/scrollup/
* Copyright (c) Mark Goodyear — @markgdyr — http://markgoodyear.com
* License: MIT
*/
!function(l,o,e){"use strict";l.fn.scrollUp=function(o){l.data(e.body,"scrollUp")||(l.data(e.body,"scrollUp",!0),l.fn.scrollUp.init(o))},l.fn.scrollUp.init=function(r){var s,t,c,i,n,a,d,p=l.fn.scrollUp.settings=l.extend({},l.fn.scrollUp.defaults,r),f=!1;switch(d=p.scrollTrigger?l(p.scrollTrigger):l("<a/>",{id:p.scrollName,href:"#top"}),p.scrollTitle&&d.attr("title",p.scrollTitle),d.appendTo("body"),p.scrollImg||p.scrollTrigger||d.html(p.scrollText),d.css({display:"none",position:"fixed",zIndex:p.zIndex}),p.activeOverlay&&l("<div/>",{id:p.scrollName+"-active"}).css({position:"absolute",top:p.scrollDistance+"px",width:"100%",borderTop:"1px dotted"+p.activeOverlay,zIndex:p.zIndex}).appendTo("body"),p.animation){case"fade":s="fadeIn",t="fadeOut",c=p.animationSpeed;break;case"slide":s="slideDown",t="slideUp",c=p.animationSpeed;break;default:s="show",t="hide",c=0}i="top"===p.scrollFrom?p.scrollDistance:l(e).height()-l(o).height()-p.scrollDistance,n=l(o).scroll(function(){l(o).scrollTop()>i?f||(d[s](c),f=!0):f&&(d[t](c),f=!1)}),p.scrollTarget?"number"==typeof p.scrollTarget?a=p.scrollTarget:"string"==typeof p.scrollTarget&&(a=Math.floor(l(p.scrollTarget).offset().top)):a=0,d.click(function(o){o.preventDefault(),l("html, body").animate({scrollTop:a},p.scrollSpeed,p.easingType)})},l.fn.scrollUp.defaults={scrollName:"scrollUp",scrollDistance:300,scrollFrom:"top",scrollSpeed:300,easingType:"linear",animation:"fade",animationSpeed:200,scrollTrigger:!1,scrollTarget:!1,scrollText:"Scroll to top",scrollTitle:!1,scrollImg:!1,activeOverlay:!1,zIndex:2147483647},l.fn.scrollUp.destroy=function(r){l.removeData(e.body,"scrollUp"),l("#"+l.fn.scrollUp.settings.scrollName).remove(),l("#"+l.fn.scrollUp.settings.scrollName+"-active").remove(),l.fn.jquery.split(".")[1]>=7?l(o).off("scroll",r):l(o).unbind("scroll",r)},l.scrollUp=l.fn.scrollUp}(jQuery,window,document);

File diff suppressed because one or more lines are too long

7
res/js/moment.min.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

5
res/js/showdown-1.6.4.min.js vendored Normal file

File diff suppressed because one or more lines are too long

6
res/js/underscore-min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -6,4 +6,18 @@ td>a {
.navbar {
border-radius: 0px;
background-color: #101010;
border-color: #101010;
}
.navbar .navbar-brand {
color: #9d9d9d;
}
.navbar .navbar-brand:hover {
color: #fff;
}
.navbar-default ul.navbar-nav>li>a:hover {
color: #fff;
}

View File

@@ -13,15 +13,19 @@ a:hover {
font-weight: bold;
}
.navbar-inverse {
.navbar {
background-color: #1b926c;
border-color: #1fa67a;
}
.navbar-inverse .navbar-brand {
.navbar .navbar-brand {
color: white;
}
.navbar {
border-radius: 0px;
}
.navbar-default ul.navbar-nav>li>a {
color: white;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

View File

@@ -2,6 +2,7 @@
# coding: utf-8
import time
import hashlib
import tornado
import tornado.ioloop
@@ -39,11 +40,34 @@ class ProxyHandler(tornado.web.RequestHandler):
self.write(response.body)
self.finish()
class PlistStoreHandler(tornado.web.RequestHandler):
db = {}
def post(self):
body = self.request.body
if len(body) > 5000:
self.set_status(500)
self.finish("request body too long")
m = hashlib.md5()
m.update(body)
key = m.hexdigest()[8:16]
self.db[key] = body
self.write({'key': key})
def get(self):
key = self.get_argument('key')
value = self.db.get(key)
if value is None:
raise tornado.web.HTTPError(404)
self.set_header('Content-Type', 'text/xml')
self.finish(value)
def make_app(debug=True):
return tornado.web.Application([
(r"/", MainHandler),
(r"/proxy/(.*)", ProxyHandler),
(r"/plist", PlistStoreHandler),
], debug=debug)
@@ -51,4 +75,4 @@ if __name__ == "__main__":
app = make_app()
tornado.options.parse_command_line()
app.listen(options.port)
ioloop.IOLoop.current().start()
ioloop.IOLoop.current().start()

7
testdata/config.yml vendored Normal file
View File

@@ -0,0 +1,7 @@
---
addr: ":4000"
title: "hello world"
theme: green
debug: true
xheaders: true
cors: true

7
testdata/deletable/.ghs.yml vendored Normal file
View File

@@ -0,0 +1,7 @@
upload: true
delete: true
accessTables:
- regex: block.file
allow: false
- regex: visual.file
allow: true

0
testdata/deletable/block.file vendored Normal file
View File

0
testdata/deletable/other.file vendored Normal file
View File

0
testdata/deletable/visual.file vendored Normal file
View File

BIN
testdata/filetypes/gohttpserver.gif vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 816 KiB

6
testdata/filetypes/page.html vendored Normal file
View File

@@ -0,0 +1,6 @@
<html>
<title>Haha</title>
<body>
<h1>Hello world</h1>
</body>
</html>

4
testdata/filetypes/style.css vendored Normal file
View File

@@ -0,0 +1,4 @@
body {
background-color: red;
}

6
testdata/uploadable/.ghs.yml vendored Normal file
View File

@@ -0,0 +1,6 @@
---
upload: true
users:
- email: "user@example.com"
upload: true
delete: true

View File

View File

@@ -1,28 +1,25 @@
package main
import (
"fmt"
"net/http"
"os"
"strconv"
"strings"
)
func formatSize(file os.FileInfo) string {
if file.IsDir() {
return "-"
}
size := file.Size()
switch {
case size > 1024*1024:
return fmt.Sprintf("%.1f MB", float64(size)/1024/1024)
case size > 1024:
return fmt.Sprintf("%.1f KB", float64(size)/1024)
default:
return strconv.Itoa(int(size)) + " B"
}
return ""
}
// func formatSize(file os.FileInfo) string {
// if file.IsDir() {
// return "-"
// }
// size := file.Size()
// switch {
// case size > 1024*1024:
// return fmt.Sprintf("%.1f MB", float64(size)/1024/1024)
// case size > 1024:
// return fmt.Sprintf("%.1f KB", float64(size)/1024)
// default:
// return strconv.Itoa(int(size)) + " B"
// }
// return ""
// }
func getRealIP(req *http.Request) string {
xip := req.Header.Get("X-Real-IP")
@@ -37,8 +34,7 @@ func SublimeContains(s, substr string) bool {
if len(rsubstr) > len(rs) {
return false
}
// abcdefg
// df
var ok = true
var i, j = 0, 0
for ; i < len(rsubstr); i++ {

View File

@@ -327,12 +327,13 @@ func newBplistGenerator(w io.Writer) *bplistGenerator {
}
type bplistParser struct {
reader io.ReadSeeker
version int
buf []byte
objrefs map[uint64]*plistValue
offtable []uint64
trailer bplistTrailer
reader io.ReadSeeker
version int
buf []byte
objrefs map[uint64]*plistValue
offtable []uint64
trailer bplistTrailer
trailerOffset int64
}
func (p *bplistParser) parseDocument() (pval *plistValue, parseError error) {
@@ -370,7 +371,7 @@ func (p *bplistParser) parseDocument() (pval *plistValue, parseError error) {
}
p.objrefs = make(map[uint64]*plistValue)
_, err = p.reader.Seek(-32, 2)
p.trailerOffset, err = p.reader.Seek(-32, 2)
if err != nil && err != io.EOF {
panic(err)
}
@@ -380,6 +381,13 @@ func (p *bplistParser) parseDocument() (pval *plistValue, parseError error) {
panic(err)
}
if p.trailer.NumObjects > uint64(math.Pow(2, 8*float64(p.trailer.ObjectRefSize))) {
panic(fmt.Errorf("binary property list contains more objects (%v) than its object ref size (%v bytes) can support", p.trailer.NumObjects, p.trailer.ObjectRefSize))
}
if p.trailer.TopObject >= p.trailer.NumObjects {
panic(fmt.Errorf("top object index %v is out of range (only %v objects exist)", p.trailer.TopObject, p.trailer.NumObjects))
}
p.offtable = make([]uint64, p.trailer.NumObjects)
// SEEK_SET
@@ -390,6 +398,9 @@ func (p *bplistParser) parseDocument() (pval *plistValue, parseError error) {
for i := uint64(0); i < p.trailer.NumObjects; i++ {
off := p.readSizedInt(int(p.trailer.OffsetIntSize))
if off >= uint64(p.trailerOffset) {
panic(fmt.Errorf("object %v starts beyond end of plist trailer (%v vs %v)", i, off, p.trailerOffset))
}
p.offtable[i] = off
}
@@ -450,8 +461,14 @@ func (p *bplistParser) valueAtOffset(off uint64) *plistValue {
func (p *bplistParser) parseTagAtOffset(off int64) *plistValue {
var tag uint8
p.reader.Seek(off, 0)
binary.Read(p.reader, binary.BigEndian, &tag)
_, err := p.reader.Seek(off, 0)
if err != nil {
panic(err)
}
err = binary.Read(p.reader, binary.BigEndian, &tag)
if err != nil {
panic(err)
}
switch tag & 0xF0 {
case bpTagNull:
@@ -489,12 +506,18 @@ func (p *bplistParser) parseTagAtOffset(off int64) *plistValue {
return &plistValue{Date, time}
case bpTagData:
cnt := p.countForTag(tag)
if int64(cnt) > p.trailerOffset-int64(off) {
panic(fmt.Errorf("data at %x longer than file (%v bytes, max is %v)", off, cnt, p.trailerOffset-int64(off)))
}
bytes := make([]byte, cnt)
binary.Read(p.reader, binary.BigEndian, bytes)
return &plistValue{Data, bytes}
case bpTagASCIIString, bpTagUTF16String:
cnt := p.countForTag(tag)
if int64(cnt) > p.trailerOffset-int64(off) {
panic(fmt.Errorf("string at %x longer than file (%v bytes, max is %v)", off, cnt, p.trailerOffset-int64(off)))
}
if tag&0xF0 == bpTagASCIIString {
bytes := make([]byte, cnt)
@@ -516,11 +539,33 @@ func (p *bplistParser) parseTagAtOffset(off int64) *plistValue {
indices := make([]uint64, cnt*2)
for i := uint64(0); i < cnt*2; i++ {
idx := p.readSizedInt(int(p.trailer.ObjectRefSize))
if idx >= p.trailer.NumObjects {
panic(fmt.Errorf("dictionary contains invalid entry index %d (max %d)", idx, p.trailer.NumObjects))
}
indices[i] = idx
}
for i := uint64(0); i < cnt; i++ {
kval := p.valueAtOffset(p.offtable[indices[i]])
subvalues[kval.value.(string)] = p.valueAtOffset(p.offtable[indices[i+cnt]])
keyOffset := p.offtable[indices[i]]
valueOffset := p.offtable[indices[i+cnt]]
if keyOffset == uint64(off) {
panic(fmt.Errorf("dictionary contains self-referential key %x (index %d)", off, i))
}
if valueOffset == uint64(off) {
panic(fmt.Errorf("dictionary contains self-referential value %x (index %d)", off, i))
}
kval := p.valueAtOffset(keyOffset)
if kval == nil || kval.kind != String {
panic(fmt.Errorf("dictionary contains non-string key at index %d", i))
}
key, ok := kval.value.(string)
if !ok {
panic(fmt.Errorf("string-type plist value contains non-string at index %d", i))
}
subvalues[key] = p.valueAtOffset(valueOffset)
}
return &plistValue{Dictionary, &dictionary{m: subvalues}}
@@ -530,10 +575,20 @@ func (p *bplistParser) parseTagAtOffset(off int64) *plistValue {
arr := make([]*plistValue, cnt)
indices := make([]uint64, cnt)
for i := uint64(0); i < cnt; i++ {
indices[i] = p.readSizedInt(int(p.trailer.ObjectRefSize))
idx := p.readSizedInt(int(p.trailer.ObjectRefSize))
if idx >= p.trailer.NumObjects {
panic(fmt.Errorf("array contains invalid entry index %d (max %d)", idx, p.trailer.NumObjects))
}
indices[i] = idx
}
for i := uint64(0); i < cnt; i++ {
arr[i] = p.valueAtOffset(p.offtable[indices[i]])
valueOffset := p.offtable[indices[i]]
if valueOffset == uint64(off) {
panic(fmt.Errorf("array contains self-referential value %x (index %d)", off, i))
}
arr[i] = p.valueAtOffset(valueOffset)
}
return &plistValue{Array, arr}

17
vendor/github.com/DHowett/go-plist/fuzz.go generated vendored Normal file
View File

@@ -0,0 +1,17 @@
// +build gofuzz
package plist
import (
"bytes"
)
func Fuzz(data []byte) int {
buf := bytes.NewReader(data)
var obj interface{}
if err := NewDecoder(buf).Decode(&obj); err != nil {
return 0
}
return 1
}

View File

@@ -477,7 +477,7 @@ func (p *textPlistParser) parseArray() *plistValue {
}
func (p *textPlistParser) parseGNUStepValue(v []byte) *plistValue {
if len(v) < 2 {
if len(v) < 3 {
panic(errors.New("invalid GNUStep extended value"))
}
typ := v[1]
@@ -525,6 +525,10 @@ func (p *textPlistParser) parsePlistValue() *plistValue {
}
bytes = bytes[:len(bytes)-1]
if len(bytes) == 0 {
panic(errors.New("invalid empty angle-bracketed element"))
}
if bytes[0] == '*' {
p.format = GNUStepFormat
return p.parseGNUStepValue(bytes)

View File

@@ -16,3 +16,10 @@ func (w *countedWriter) Write(p []byte) (int, error) {
func (w *countedWriter) BytesWritten() int {
return w.nbytes
}
func unsignedGetBase(s string) (string, int) {
if len(s) > 1 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') {
return s[2:], 16
}
return s, 10
}

View File

@@ -198,11 +198,17 @@ func (p *xmlPlistParser) parseXMLElement(element xml.StartElement) *plistValue {
}
s := string(charData)
if len(s) == 0 {
panic(errors.New("invalid empty <integer/>"))
}
if s[0] == '-' {
n := mustParseInt(string(charData), 10, 64)
s, base := unsignedGetBase(s[1:])
n := mustParseInt("-"+s, base, 64)
return &plistValue{Integer, signedInt{uint64(n), true}}
} else {
n := mustParseUint(string(charData), 10, 64)
s, base := unsignedGetBase(s)
n := mustParseUint(s, base, 64)
return &plistValue{Integer, signedInt{n, false}}
}
case "real":

View File

@@ -1,4 +1,4 @@
# Kingpin - A Go (golang) command line and flag parser [![Build Status](https://travis-ci.org/alecthomas/kingpin.png)](https://travis-ci.org/alecthomas/kingpin)
# Kingpin - A Go (golang) command line and flag parser [![](https://godoc.org/github.com/alecthomas/kingpin?status.svg)](http://godoc.org/github.com/alecthomas/kingpin) [![Build Status](https://travis-ci.org/alecthomas/kingpin.png)](https://travis-ci.org/alecthomas/kingpin)
<!-- MarkdownTOC -->
@@ -19,9 +19,12 @@
- [Displaying errors and usage information](#displaying-errors-and-usage-information)
- [Sub-commands](#sub-commands)
- [Custom Parsers](#custom-parsers)
- [Repeatable flags](#repeatable-flags)
- [Boolean Values](#boolean-values)
- [Default Values](#default-values)
- [Place-holders in Help](#place-holders-in-help)
- [Consuming all remaining arguments](#consuming-all-remaining-arguments)
- [Bash/ZSH Shell Completion](#bashzsh-shell-completion)
- [Supporting -h for help](#supporting--h-for-help)
- [Custom help](#custom-help)
@@ -51,7 +54,7 @@ func main() {
}
```
More [examples](https://github.com/alecthomas/kingpin/tree/master/examples) are available.
More [examples](https://github.com/alecthomas/kingpin/tree/master/_examples) are available.
Second to parsing, providing the user with useful help is probably the most
important thing a command-line parser does. Kingpin tries to provide detailed
@@ -71,7 +74,7 @@ contextual help if `--help` is encountered at any point in the command line
- POSIX-style short flag combining (`-a -b` -> `-ab`).
- Short-flag+parameter combining (`-a parm` -> `-aparm`).
- Read command-line from files (`@<file>`).
- Automatically generate man pages (`--man-page`).
- Automatically generate man pages (`--help-man`).
## User-visible changes between v1 and v2
@@ -135,7 +138,7 @@ $ go get gopkg.in/alecthomas/kingpin.v1
- *2015-09-19* -- Stable v2.1.0 release.
- Added `command.Default()` to specify a default command to use if no other
command matches. This allows for convenient user shortcuts.
- Exposed `HelpFlag` and `VersionFlag` for further cusomisation.
- Exposed `HelpFlag` and `VersionFlag` for further customisation.
- `Action()` and `PreAction()` added and both now support an arbitrary
number of callbacks.
- `kingpin.SeparateOptionalFlagsUsageTemplate`.
@@ -421,12 +424,26 @@ You would use it like so:
headers = HTTPHeader(kingpin.Flag("header", "Add a HTTP header to the request.").Short('H'))
```
### Repeatable flags
Depending on the `Value` they hold, some flags may be repeated. The
`IsCumulative() bool` function on `Value` tells if it's safe to call `Set()`
multiple times or if an error should be raised if several values are passed.
The built-in `Value`s returning slices and maps, as well as `Counter` are
examples of `Value`s that make a flag repeatable.
### Boolean values
Boolean values are uniquely managed by Kingpin. Each boolean flag will have a negative complement:
`--<name>` and `--no-<name>`.
### Default Values
The default value is the zero value for a type. This can be overridden with
the `Default(value)` function on flags and arguments. This function accepts a
string, which is parsed by the value itself, so it *must* be compliant with
the format expected.
the `Default(value...)` function on flags and arguments. This function accepts
one or several strings, which are parsed by the value itself, so they *must*
be compliant with the format expected.
### Place-holders in Help
@@ -451,13 +468,13 @@ IP addresses as positional arguments:
./cmd ping 10.1.1.1 192.168.1.1
Kingpin supports this by having `Value` provide a `IsCumulative() bool`
function. If this function exists and returns true, the value parser will be
called repeatedly for every remaining argument.
Such arguments are similar to [repeatable flags](#repeatable-flags), but for
arguments. Therefore they use the same `IsCumulative() bool` function on the
underlying `Value`, so the built-in `Value`s for which the `Set()` function
can be called several times will consume multiple arguments.
Examples of this are the `Strings()` and `StringMap()` values.
To implement the above example we might do something like this:
To implement the above example with a custom `Value`, we might do something
like this:
```go
type ipList []net.IP
@@ -492,9 +509,103 @@ And use it like so:
ips := IPList(kingpin.Arg("ips", "IP addresses to ping."))
```
### Bash/ZSH Shell Completion
By default, all flags and commands/subcommands generate completions
internally.
Out of the box, CLI tools using kingpin should be able to take advantage
of completion hinting for flags and commands. By specifying
`--completion-bash` as the first argument, your CLI tool will show
possible subcommands. By ending your argv with `--`, hints for flags
will be shown.
To allow your end users to take advantage you must package a
`/etc/bash_completion.d` script with your distribution (or the equivalent
for your target platform/shell). An alternative is to instruct your end
user to source a script from their `bash_profile` (or equivalent).
Fortunately Kingpin makes it easy to generate or source a script for use
with end users shells. `./yourtool --completion-script-bash` and
`./yourtool --completion-script-zsh` will generate these scripts for you.
**Installation by Package**
For the best user experience, you should bundle your pre-created
completion script with your CLI tool and install it inside
`/etc/bash_completion.d` (or equivalent). A good suggestion is to add
this as an automated step to your build pipeline, in the implementation
is improved for bug fixed.
**Installation by `bash_profile`**
Alternatively, instruct your users to add an additional statement to
their `bash_profile` (or equivalent):
```
eval "$(your-cli-tool --completion-script-bash)"
```
Or for ZSH
```
eval "$(your-cli-tool --completion-script-zsh)"
```
#### Additional API
To provide more flexibility, a completion option API has been
exposed for flags to allow user defined completion options, to extend
completions further than just EnumVar/Enum.
**Provide Static Options**
When using an `Enum` or `EnumVar`, users are limited to only the options
given. Maybe we wish to hint possible options to the user, but also
allow them to provide their own custom option. `HintOptions` gives
this functionality to flags.
```
app := kingpin.New("completion", "My application with bash completion.")
app.Flag("port", "Provide a port to connect to").
Required().
HintOptions("80", "443", "8080").
IntVar(&c.port)
```
**Provide Dynamic Options**
Consider the case that you needed to read a local database or a file to
provide suggestions. You can dynamically generate the options
```
func listHosts(args []string) []string {
// Provide a dynamic list of hosts from a hosts file or otherwise
// for bash completion. In this example we simply return static slice.
// You could use this functionality to reach into a hosts file to provide
// completion for a list of known hosts.
return []string{"sshhost.example", "webhost.example", "ftphost.example"}
}
app := kingpin.New("completion", "My application with bash completion.")
app.Flag("flag-1", "").HintAction(listHosts).String()
```
**EnumVar/Enum**
When using `Enum` or `EnumVar`, any provided options will be automatically
used for bash autocompletion. However, if you wish to provide a subset or
different options, you can use `HintOptions` or `HintAction` which will override
the default completion options for `Enum`/`EnumVar`.
**Examples**
You can see an in depth example of the completion API within
`examples/completion/main.go`
### Supporting -h for help
`kingpin.CommandLine.HelpFlag.Short('-h')`
`kingpin.CommandLine.HelpFlag.Short('h')`
### Custom help

View File

@@ -21,10 +21,7 @@ type ApplicationValidator func(*Application) error
// An Application contains the definitions of flags, arguments and commands
// for an application.
type Application struct {
*flagGroup
*argGroup
*cmdGroup
actionMixin
cmdMixin
initialized bool
Name string
@@ -38,6 +35,7 @@ type Application struct {
terminate func(status int) // See Terminate()
noInterspersed bool // can flags be interspersed with args (or must they come first)
defaultEnvars bool
completion bool
// Help flag. Exposed for user customisation.
HelpFlag *FlagClause
@@ -50,19 +48,23 @@ type Application struct {
// New creates a new Kingpin application instance.
func New(name, help string) *Application {
a := &Application{
flagGroup: newFlagGroup(),
argGroup: newArgGroup(),
Name: name,
Help: help,
writer: os.Stderr,
usageTemplate: DefaultUsageTemplate,
terminate: os.Exit,
}
a.flagGroup = newFlagGroup()
a.argGroup = newArgGroup()
a.cmdGroup = newCmdGroup(a)
a.HelpFlag = a.Flag("help", "Show context-sensitive help (also try --help-long and --help-man).")
a.HelpFlag.Bool()
a.Flag("help-long", "Generate long help.").Hidden().PreAction(a.generateLongHelp).Bool()
a.Flag("help-man", "Generate a man page.").Hidden().PreAction(a.generateManPage).Bool()
a.Flag("completion-bash", "Output possible completions for the given args.").Hidden().BoolVar(&a.completion)
a.Flag("completion-script-bash", "Generate completion script for bash.").Hidden().PreAction(a.generateBashCompletionScript).Bool()
a.Flag("completion-script-zsh", "Generate completion script for ZSH.").Hidden().PreAction(a.generateZSHCompletionScript).Bool()
return a
}
@@ -84,6 +86,24 @@ func (a *Application) generateManPage(c *ParseContext) error {
return nil
}
func (a *Application) generateBashCompletionScript(c *ParseContext) error {
a.Writer(os.Stdout)
if err := a.UsageForContextWithTemplate(c, 2, BashCompletionTemplate); err != nil {
return err
}
a.terminate(0)
return nil
}
func (a *Application) generateZSHCompletionScript(c *ParseContext) error {
a.Writer(os.Stdout)
if err := a.UsageForContextWithTemplate(c, 2, ZshCompletionTemplate); err != nil {
return err
}
a.terminate(0)
return nil
}
// DefaultEnvars configures all flags (that do not already have an associated
// envar) to use a default environment variable in the form "<app>_<flag>".
//
@@ -145,17 +165,48 @@ func (a *Application) parseContext(ignoreDefault bool, args []string) (*ParseCon
// This will populate all flag and argument values, call all callbacks, and so
// on.
func (a *Application) Parse(args []string) (command string, err error) {
context, err := a.ParseContext(args)
if err != nil {
context, parseErr := a.ParseContext(args)
selected := []string{}
var setValuesErr error
if context == nil {
// Since we do not throw error immediately, there could be a case
// where a context returns nil. Protect against that.
return "", parseErr
}
if err = a.setDefaults(context); err != nil {
return "", err
}
a.maybeHelp(context)
if !context.EOL() {
return "", fmt.Errorf("unexpected argument '%s'", context.Peek())
selected, setValuesErr = a.setValues(context)
if err = a.applyPreActions(context, !a.completion); err != nil {
return "", err
}
command, err = a.execute(context)
if err == ErrCommandNotSpecified {
a.writeUsage(context, nil)
if a.completion {
a.generateBashCompletion(context)
a.terminate(0)
} else {
if parseErr != nil {
return "", parseErr
}
a.maybeHelp(context)
if !context.EOL() {
return "", fmt.Errorf("unexpected argument '%s'", context.Peek())
}
if setValuesErr != nil {
return "", setValuesErr
}
command, err = a.execute(context, selected)
if err == ErrCommandNotSpecified {
a.writeUsage(context, nil)
}
}
return command, err
}
@@ -173,34 +224,13 @@ func (a *Application) writeUsage(context *ParseContext, err error) {
func (a *Application) maybeHelp(context *ParseContext) {
for _, element := range context.Elements {
if flag, ok := element.Clause.(*FlagClause); ok && flag == a.HelpFlag {
// Re-parse the command-line ignoring defaults, so that help works correctly.
context, _ = a.parseContext(true, context.rawArgs)
a.writeUsage(context, nil)
}
}
}
// findCommandFromArgs finds a command (if any) from the given command line arguments.
func (a *Application) findCommandFromArgs(args []string) (command string, err error) {
if err := a.init(); err != nil {
return "", err
}
context := tokenize(args, false)
if _, err := a.parse(context); err != nil {
return "", err
}
return a.findCommandFromContext(context), nil
}
// findCommandFromContext finds a command (if any) from a parsed context.
func (a *Application) findCommandFromContext(context *ParseContext) string {
commands := []string{}
for _, element := range context.Elements {
if c, ok := element.Clause.(*CmdClause); ok {
commands = append(commands, c.name)
}
}
return strings.Join(commands, " ")
}
// Version adds a --version flag for displaying the application version.
func (a *Application) Version(version string) *Application {
a.version = version
@@ -325,22 +355,8 @@ func checkDuplicateFlags(current *CmdClause, flagGroups []*flagGroup) error {
return nil
}
func (a *Application) execute(context *ParseContext) (string, error) {
func (a *Application) execute(context *ParseContext, selected []string) (string, error) {
var err error
selected := []string{}
if err = a.setDefaults(context); err != nil {
return "", err
}
selected, err = a.setValues(context)
if err != nil {
return "", err
}
if err = a.applyPreActions(context); err != nil {
return "", err
}
if err = a.validateRequired(context); err != nil {
return "", err
@@ -379,22 +395,16 @@ func (a *Application) setDefaults(context *ParseContext) error {
// Check required flags and set defaults.
for _, flag := range context.flags.long {
if flagElements[flag.name] == nil {
// Set defaults, if any.
if flag.defaultValue != "" {
if err := flag.value.Set(flag.defaultValue); err != nil {
return err
}
if err := flag.setDefault(); err != nil {
return err
}
}
}
for _, arg := range context.arguments.args {
if argElements[arg.name] == nil {
// Set defaults, if any.
if arg.defaultValue != "" {
if err := arg.value.Set(arg.defaultValue); err != nil {
return err
}
if err := arg.setDefault(); err != nil {
return err
}
}
}
@@ -429,7 +439,7 @@ func (a *Application) validateRequired(context *ParseContext) error {
for _, arg := range context.arguments.args {
if argElements[arg.name] == nil {
if arg.required {
if arg.needsValue() {
return fmt.Errorf("required argument '%s' not provided", arg.name)
}
}
@@ -439,13 +449,22 @@ func (a *Application) validateRequired(context *ParseContext) error {
func (a *Application) setValues(context *ParseContext) (selected []string, err error) {
// Set all arg and flag values.
var lastCmd *CmdClause
var (
lastCmd *CmdClause
flagSet = map[string]struct{}{}
)
for _, element := range context.Elements {
switch clause := element.Clause.(type) {
case *FlagClause:
if _, ok := flagSet[clause.name]; ok {
if v, ok := clause.value.(repeatableFlag); !ok || !v.IsCumulative() {
return nil, fmt.Errorf("flag '%s' cannot be repeated", clause.name)
}
}
if err = clause.value.Set(*element.Value); err != nil {
return
}
flagSet[clause.name] = struct{}{}
case *ArgClause:
if err = clause.value.Set(*element.Value); err != nil {
@@ -486,18 +505,21 @@ func (a *Application) applyValidators(context *ParseContext) (err error) {
return err
}
func (a *Application) applyPreActions(context *ParseContext) error {
func (a *Application) applyPreActions(context *ParseContext, dispatch bool) error {
if err := a.actionMixin.applyPreActions(context); err != nil {
return err
}
// Dispatch to actions.
for _, element := range context.Elements {
if applier, ok := element.Clause.(actionApplier); ok {
if err := applier.applyPreActions(context); err != nil {
return err
if dispatch {
for _, element := range context.Elements {
if applier, ok := element.Clause.(actionApplier); ok {
if err := applier.applyPreActions(context); err != nil {
return err
}
}
}
}
return nil
}
@@ -558,6 +580,83 @@ func (a *Application) FatalIfError(err error, format string, args ...interface{}
}
}
func (a *Application) completionOptions(context *ParseContext) []string {
args := context.rawArgs
var (
currArg string
prevArg string
target cmdMixin
)
numArgs := len(args)
if numArgs > 1 {
args = args[1:]
currArg = args[len(args)-1]
}
if numArgs > 2 {
prevArg = args[len(args)-2]
}
target = a.cmdMixin
if context.SelectedCommand != nil {
// A subcommand was in use. We will use it as the target
target = context.SelectedCommand.cmdMixin
}
if (currArg != "" && strings.HasPrefix(currArg, "--")) || strings.HasPrefix(prevArg, "--") {
// Perform completion for A flag. The last/current argument started with "-"
var (
flagName string // The name of a flag if given (could be half complete)
flagValue string // The value assigned to a flag (if given) (could be half complete)
)
if strings.HasPrefix(prevArg, "--") && !strings.HasPrefix(currArg, "--") {
// Matches: ./myApp --flag value
// Wont Match: ./myApp --flag --
flagName = prevArg[2:] // Strip the "--"
flagValue = currArg
} else if strings.HasPrefix(currArg, "--") {
// Matches: ./myApp --flag --
// Matches: ./myApp --flag somevalue --
// Matches: ./myApp --
flagName = currArg[2:] // Strip the "--"
}
options, flagMatched, valueMatched := target.FlagCompletion(flagName, flagValue)
if valueMatched {
// Value Matched. Show cmdCompletions
return target.CmdCompletion(context)
}
// Add top level flags if we're not at the top level and no match was found.
if context.SelectedCommand != nil && flagMatched == false {
topOptions, topFlagMatched, topValueMatched := a.FlagCompletion(flagName, flagValue)
if topValueMatched {
// Value Matched. Back to cmdCompletions
return target.CmdCompletion(context)
}
if topFlagMatched {
// Top level had a flag which matched the input. Return it's options.
options = topOptions
} else {
// Add top level flags
options = append(options, topOptions...)
}
}
return options
}
// Perform completion for sub commands and arguments.
return target.CmdCompletion(context)
}
func (a *Application) generateBashCompletion(context *ParseContext) {
options := a.completionOptions(context)
fmt.Printf("%s", strings.Join(options, "\n"))
}
func envarTransform(name string) string {
return strings.ToUpper(envarTransformRegexp.ReplaceAllString(name, "_"))
}

View File

@@ -1,6 +1,8 @@
package kingpin
import "fmt"
import (
"fmt"
)
type argGroup struct {
args []*ArgClause
@@ -14,6 +16,19 @@ func (a *argGroup) have() bool {
return len(a.args) > 0
}
// GetArg gets an argument definition.
//
// This allows existing arguments to be modified after definition but before parsing. Useful for
// modular applications.
func (a *argGroup) GetArg(name string) *ArgClause {
for _, arg := range a.args {
if arg.name == name {
return arg
}
}
return nil
}
func (a *argGroup) Arg(name, help string) *ArgClause {
arg := newArg(name, help)
a.args = append(a.args, arg)
@@ -51,10 +66,12 @@ func (a *argGroup) init() error {
type ArgClause struct {
actionMixin
parserMixin
name string
help string
defaultValue string
required bool
completionsMixin
envarMixin
name string
help string
defaultValues []string
required bool
}
func newArg(name, help string) *ArgClause {
@@ -65,6 +82,38 @@ func newArg(name, help string) *ArgClause {
return a
}
func (a *ArgClause) setDefault() error {
if a.HasEnvarValue() {
if v, ok := a.value.(remainderArg); !ok || !v.IsCumulative() {
// Use the value as-is
return a.value.Set(a.GetEnvarValue())
} else {
for _, value := range a.GetSplitEnvarValue() {
if err := a.value.Set(value); err != nil {
return err
}
}
return nil
}
}
if len(a.defaultValues) > 0 {
for _, defaultValue := range a.defaultValues {
if err := a.value.Set(defaultValue); err != nil {
return err
}
}
return nil
}
return nil
}
func (a *ArgClause) needsValue() bool {
haveDefault := len(a.defaultValues) > 0
return a.required && !(haveDefault || a.HasEnvarValue())
}
func (a *ArgClause) consumesRemainder() bool {
if r, ok := a.value.(remainderArg); ok {
return r.IsCumulative()
@@ -78,9 +127,26 @@ func (a *ArgClause) Required() *ArgClause {
return a
}
// Default value for this argument. It *must* be parseable by the value of the argument.
func (a *ArgClause) Default(value string) *ArgClause {
a.defaultValue = value
// Default values for this argument. They *must* be parseable by the value of the argument.
func (a *ArgClause) Default(values ...string) *ArgClause {
a.defaultValues = values
return a
}
// Envar overrides the default value(s) for a flag from an environment variable,
// if it is set. Several default values can be provided by using new lines to
// separate them.
func (a *ArgClause) Envar(name string) *ArgClause {
a.envar = name
a.noEnvar = false
return a
}
// NoEnvar forces environment variable defaults to be disabled for this flag.
// Most useful in conjunction with app.DefaultEnvars().
func (a *ArgClause) NoEnvar() *ArgClause {
a.envar = ""
a.noEnvar = true
return a
}
@@ -94,8 +160,22 @@ func (a *ArgClause) PreAction(action Action) *ArgClause {
return a
}
// HintAction registers a HintAction (function) for the arg to provide completions
func (a *ArgClause) HintAction(action HintAction) *ArgClause {
a.addHintAction(action)
return a
}
// HintOptions registers any number of options for the flag to provide completions
func (a *ArgClause) HintOptions(options ...string) *ArgClause {
a.addHintAction(func() []string {
return options
})
return a
}
func (a *ArgClause) init() error {
if a.required && a.defaultValue != "" {
if a.required && len(a.defaultValues) > 0 {
return fmt.Errorf("required argument '%s' with unusable default value", a.name)
}
if a.value == nil {

View File

@@ -5,6 +5,92 @@ import (
"strings"
)
type cmdMixin struct {
*flagGroup
*argGroup
*cmdGroup
actionMixin
}
// CmdCompletion returns completion options for arguments, if that's where
// parsing left off, or commands if there aren't any unsatisfied args.
func (c *cmdMixin) CmdCompletion(context *ParseContext) []string {
var options []string
// Count args already satisfied - we won't complete those, and add any
// default commands' alternatives, since they weren't listed explicitly
// and the user may want to explicitly list something else.
argsSatisfied := 0
for _, el := range context.Elements {
switch clause := el.Clause.(type) {
case *ArgClause:
if el.Value != nil && *el.Value != "" {
argsSatisfied++
}
case *CmdClause:
options = append(options, clause.completionAlts...)
default:
}
}
if argsSatisfied < len(c.argGroup.args) {
// Since not all args have been satisfied, show options for the current one
options = append(options, c.argGroup.args[argsSatisfied].resolveCompletions()...)
} else {
// If all args are satisfied, then go back to completing commands
for _, cmd := range c.cmdGroup.commandOrder {
if !cmd.hidden {
options = append(options, cmd.name)
}
}
}
return options
}
func (c *cmdMixin) FlagCompletion(flagName string, flagValue string) (choices []string, flagMatch bool, optionMatch bool) {
// Check if flagName matches a known flag.
// If it does, show the options for the flag
// Otherwise, show all flags
options := []string{}
for _, flag := range c.flagGroup.flagOrder {
// Loop through each flag and determine if a match exists
if flag.name == flagName {
// User typed entire flag. Need to look for flag options.
options = flag.resolveCompletions()
if len(options) == 0 {
// No Options to Choose From, Assume Match.
return options, true, true
}
// Loop options to find if the user specified value matches
isPrefix := false
matched := false
for _, opt := range options {
if flagValue == opt {
matched = true
} else if strings.HasPrefix(opt, flagValue) {
isPrefix = true
}
}
// Matched Flag Directly
// Flag Value Not Prefixed, and Matched Directly
return options, true, !isPrefix && matched
}
if !flag.hidden {
options = append(options, "--"+flag.name)
}
}
// No Flag directly matched.
return options, false, false
}
type cmdGroup struct {
app *Application
parent *CmdClause
@@ -21,6 +107,22 @@ func (c *cmdGroup) defaultSubcommand() *CmdClause {
return nil
}
func (c *cmdGroup) cmdNames() []string {
names := make([]string, 0, len(c.commandOrder))
for _, cmd := range c.commandOrder {
names = append(names, cmd.name)
}
return names
}
// GetArg gets a command definition.
//
// This allows existing commands to be modified after definition but before parsing. Useful for
// modular applications.
func (c *cmdGroup) GetCommand(name string) *CmdClause {
return c.commands[name]
}
func newCmdGroup(app *Application) *cmdGroup {
return &cmdGroup{
app: app,
@@ -59,6 +161,12 @@ func (c *cmdGroup) init() error {
return fmt.Errorf("duplicate command %q", cmd.name)
}
seen[cmd.name] = true
for _, alias := range cmd.aliases {
if seen[alias] {
return fmt.Errorf("alias duplicates existing command %q", alias)
}
c.commands[alias] = cmd
}
if err := cmd.init(); err != nil {
return err
}
@@ -78,27 +186,32 @@ type CmdClauseValidator func(*CmdClause) error
// A CmdClause is a single top-level command. It encapsulates a set of flags
// and either subcommands or positional arguments.
type CmdClause struct {
actionMixin
*flagGroup
*argGroup
*cmdGroup
app *Application
name string
help string
isDefault bool
validator CmdClauseValidator
hidden bool
cmdMixin
app *Application
name string
aliases []string
help string
isDefault bool
validator CmdClauseValidator
hidden bool
completionAlts []string
}
func newCommand(app *Application, name, help string) *CmdClause {
c := &CmdClause{
flagGroup: newFlagGroup(),
argGroup: newArgGroup(),
cmdGroup: newCmdGroup(app),
app: app,
name: name,
help: help,
app: app,
name: name,
help: help,
}
c.flagGroup = newFlagGroup()
c.argGroup = newArgGroup()
c.cmdGroup = newCmdGroup(app)
return c
}
// Add an Alias for this command.
func (c *CmdClause) Alias(name string) *CmdClause {
c.aliases = append(c.aliases, name)
return c
}

33
vendor/github.com/alecthomas/kingpin/completions.go generated vendored Normal file
View File

@@ -0,0 +1,33 @@
package kingpin
// HintAction is a function type who is expected to return a slice of possible
// command line arguments.
type HintAction func() []string
type completionsMixin struct {
hintActions []HintAction
builtinHintActions []HintAction
}
func (a *completionsMixin) addHintAction(action HintAction) {
a.hintActions = append(a.hintActions, action)
}
// Allow adding of HintActions which are added internally, ie, EnumVar
func (a *completionsMixin) addHintActionBuiltin(action HintAction) {
a.builtinHintActions = append(a.builtinHintActions, action)
}
func (a *completionsMixin) resolveCompletions() []string {
var hints []string
options := a.builtinHintActions
if len(a.hintActions) > 0 {
// User specified their own hintActions. Use those instead.
options = a.hintActions
}
for _, hintAction := range options {
hints = append(hints, hintAction()...)
}
return hints
}

45
vendor/github.com/alecthomas/kingpin/envar.go generated vendored Normal file
View File

@@ -0,0 +1,45 @@
package kingpin
import (
"os"
"regexp"
)
var (
envVarValuesSeparator = "\r?\n"
envVarValuesTrimmer = regexp.MustCompile(envVarValuesSeparator + "$")
envVarValuesSplitter = regexp.MustCompile(envVarValuesSeparator)
)
type envarMixin struct {
envar string
noEnvar bool
}
func (e *envarMixin) HasEnvarValue() bool {
return e.GetEnvarValue() != ""
}
func (e *envarMixin) GetEnvarValue() string {
if e.noEnvar || e.envar == "" {
return ""
}
return os.Getenv(e.envar)
}
func (e *envarMixin) GetSplitEnvarValue() []string {
values := make([]string, 0)
envarValue := e.GetEnvarValue()
if envarValue == "" {
return values
}
// Split by new line to extract multiple values, if any.
trimmed := envVarValuesTrimmer.ReplaceAllString(envarValue, "")
for _, value := range envVarValuesSplitter.Split(trimmed, -1) {
values = append(values, value)
}
return values
}

View File

@@ -2,7 +2,6 @@ package kingpin
import (
"fmt"
"os"
"strings"
)
@@ -14,19 +13,17 @@ type flagGroup struct {
func newFlagGroup() *flagGroup {
return &flagGroup{
short: make(map[string]*FlagClause),
long: make(map[string]*FlagClause),
short: map[string]*FlagClause{},
long: map[string]*FlagClause{},
}
}
func (f *flagGroup) merge(o *flagGroup) {
for _, flag := range o.flagOrder {
if flag.shorthand != 0 {
f.short[string(flag.shorthand)] = flag
}
f.long[flag.name] = flag
f.flagOrder = append(f.flagOrder, flag)
}
// GetFlag gets a flag definition.
//
// This allows existing flags to be modified after definition but before parsing. Useful for
// modular applications.
func (f *flagGroup) GetFlag(name string) *FlagClause {
return f.long[name]
}
// Flag defines a new flag with the given long name and help.
@@ -38,6 +35,9 @@ func (f *flagGroup) Flag(name, help string) *FlagClause {
}
func (f *flagGroup) init(defaultEnvarPrefix string) error {
if err := f.checkDuplicates(); err != nil {
return err
}
for _, flag := range f.long {
if defaultEnvarPrefix != "" && !flag.noEnvar && flag.envar == "" {
flag.envar = envarTransform(defaultEnvarPrefix + "_" + flag.name)
@@ -52,6 +52,24 @@ func (f *flagGroup) init(defaultEnvarPrefix string) error {
return nil
}
func (f *flagGroup) checkDuplicates() error {
seenShort := map[byte]bool{}
seenLong := map[string]bool{}
for _, flag := range f.flagOrder {
if flag.shorthand != 0 {
if _, ok := seenShort[flag.shorthand]; ok {
return fmt.Errorf("duplicate short flag -%c", flag.shorthand)
}
seenShort[flag.shorthand] = true
}
if _, ok := seenLong[flag.name]; ok {
return fmt.Errorf("duplicate long flag --%s", flag.name)
}
seenLong[flag.name] = true
}
return nil
}
func (f *flagGroup) parse(context *ParseContext) (*FlagClause, error) {
var token *Token
@@ -71,11 +89,14 @@ loop:
name := token.Value
if token.Type == TokenLong {
if strings.HasPrefix(name, "no-") {
name = name[3:]
invert = true
}
flag, ok = f.long[name]
if !ok {
if strings.HasPrefix(name, "no-") {
name = name[3:]
invert = true
}
flag, ok = f.long[name]
}
if !ok {
return nil, fmt.Errorf("unknown long flag '%s'", flagToken)
}
@@ -119,28 +140,18 @@ loop:
return nil, nil
}
func (f *flagGroup) visibleFlags() int {
count := 0
for _, flag := range f.long {
if !flag.hidden {
count++
}
}
return count
}
// FlagClause is a fluid interface used to build flags.
type FlagClause struct {
parserMixin
actionMixin
name string
shorthand byte
help string
envar string
noEnvar bool
defaultValue string
placeholder string
hidden bool
completionsMixin
envarMixin
name string
shorthand byte
help string
defaultValues []string
placeholder string
hidden bool
}
func newFlag(name, help string) *FlagClause {
@@ -151,34 +162,47 @@ func newFlag(name, help string) *FlagClause {
return f
}
func (f *FlagClause) needsValue() bool {
return f.required && f.defaultValue == ""
func (f *FlagClause) setDefault() error {
if f.HasEnvarValue() {
if v, ok := f.value.(repeatableFlag); !ok || !v.IsCumulative() {
// Use the value as-is
return f.value.Set(f.GetEnvarValue())
} else {
for _, value := range f.GetSplitEnvarValue() {
if err := f.value.Set(value); err != nil {
return err
}
}
return nil
}
}
if len(f.defaultValues) > 0 {
for _, defaultValue := range f.defaultValues {
if err := f.value.Set(defaultValue); err != nil {
return err
}
}
return nil
}
return nil
}
func (f *FlagClause) formatPlaceHolder() string {
if f.placeholder != "" {
return f.placeholder
}
if f.defaultValue != "" {
if _, ok := f.value.(*stringValue); ok {
return fmt.Sprintf("%q", f.defaultValue)
}
return f.defaultValue
}
return strings.ToUpper(f.name)
func (f *FlagClause) needsValue() bool {
haveDefault := len(f.defaultValues) > 0
return f.required && !(haveDefault || f.HasEnvarValue())
}
func (f *FlagClause) init() error {
if f.required && f.defaultValue != "" {
if f.required && len(f.defaultValues) > 0 {
return fmt.Errorf("required flag '--%s' with default value that will never be used", f.name)
}
if f.value == nil {
return fmt.Errorf("no type defined for --%s (eg. .String())", f.name)
}
if !f.noEnvar && f.envar != "" {
if v := os.Getenv(f.envar); v != "" {
f.defaultValue = v
}
if v, ok := f.value.(repeatableFlag); (!ok || !v.IsCumulative()) && len(f.defaultValues) > 1 {
return fmt.Errorf("invalid default for '--%s', expecting single value", f.name)
}
return nil
}
@@ -194,9 +218,37 @@ func (f *FlagClause) PreAction(action Action) *FlagClause {
return f
}
// Default value for this flag. It *must* be parseable by the value of the flag.
func (f *FlagClause) Default(value string) *FlagClause {
f.defaultValue = value
// HintAction registers a HintAction (function) for the flag to provide completions
func (a *FlagClause) HintAction(action HintAction) *FlagClause {
a.addHintAction(action)
return a
}
// HintOptions registers any number of options for the flag to provide completions
func (a *FlagClause) HintOptions(options ...string) *FlagClause {
a.addHintAction(func() []string {
return options
})
return a
}
func (a *FlagClause) EnumVar(target *string, options ...string) {
a.parserMixin.EnumVar(target, options...)
a.addHintActionBuiltin(func() []string {
return options
})
}
func (a *FlagClause) Enum(options ...string) (target *string) {
a.addHintActionBuiltin(func() []string {
return options
})
return a.parserMixin.Enum(options...)
}
// Default values for this flag. They *must* be parseable by the value of the flag.
func (f *FlagClause) Default(values ...string) *FlagClause {
f.defaultValues = values
return f
}
@@ -205,8 +257,9 @@ func (f *FlagClause) OverrideDefaultFromEnvar(envar string) *FlagClause {
return f.Envar(envar)
}
// Envar overrides the default value for a flag from an environment variable,
// if it is set.
// Envar overrides the default value(s) for a flag from an environment variable,
// if it is set. Several default values can be provided by using new lines to
// separate them.
func (f *FlagClause) Envar(name string) *FlagClause {
f.envar = name
f.noEnvar = false

View File

@@ -1,4 +1,4 @@
// +build !linux,!freebsd,!darwin,!dragonfly,!netbsd,!openbsd
// +build appengine !linux,!freebsd,!darwin,!dragonfly,!netbsd,!openbsd
package kingpin

View File

@@ -1,4 +1,4 @@
// +build linux freebsd darwin dragonfly netbsd openbsd
// +build !appengine,linux freebsd darwin dragonfly netbsd openbsd
package kingpin

View File

@@ -37,7 +37,7 @@ type FlagModel struct {
Name string
Help string
Short rune
Default string
Default []string
Envar string
PlaceHolder string
Required bool
@@ -60,11 +60,15 @@ func (f *FlagModel) FormatPlaceHolder() string {
if f.PlaceHolder != "" {
return f.PlaceHolder
}
if f.Default != "" {
if _, ok := f.Value.(*stringValue); ok {
return strconv.Quote(f.Default)
if len(f.Default) > 0 {
ellipsis := ""
if len(f.Default) > 1 {
ellipsis = "..."
}
return f.Default
if _, ok := f.Value.(*stringValue); ok {
return strconv.Quote(f.Default[0]) + ellipsis
}
return f.Default[0] + ellipsis
}
return strings.ToUpper(f.Name)
}
@@ -91,7 +95,8 @@ func (a *ArgGroupModel) ArgSummary() string {
type ArgModel struct {
Name string
Help string
Default string
Default []string
Envar string
Required bool
Value Value
}
@@ -116,6 +121,7 @@ func (c *CmdGroupModel) FlattenedCommands() (out []*CmdModel) {
type CmdModel struct {
Name string
Aliases []string
Help string
FullCommand string
Depth int
@@ -164,7 +170,8 @@ func (a *ArgClause) Model() *ArgModel {
return &ArgModel{
Name: a.name,
Help: a.help,
Default: a.defaultValue,
Default: a.defaultValues,
Envar: a.envar,
Required: a.required,
Value: a.value,
}
@@ -183,7 +190,7 @@ func (f *FlagClause) Model() *FlagModel {
Name: f.name,
Help: f.help,
Short: rune(f.shorthand),
Default: f.defaultValue,
Default: f.defaultValues,
Envar: f.envar,
PlaceHolder: f.placeholder,
Required: f.required,
@@ -207,6 +214,7 @@ func (c *CmdClause) Model() *CmdModel {
}
return &CmdModel{
Name: c.name,
Aliases: c.aliases,
Help: c.help,
Depth: depth,
Hidden: c.hidden,

View File

@@ -92,6 +92,7 @@ type ParseContext struct {
peek []*Token
argi int // Index of current command-line arg we're processing.
args []string
rawArgs []string
flags *flagGroup
arguments *argGroup
argumenti int // Cursor into arguments
@@ -125,6 +126,7 @@ func tokenize(args []string, ignoreDefault bool) *ParseContext {
return &ParseContext{
ignoreDefault: ignoreDefault,
args: args,
rawArgs: args,
flags: newFlagGroup(),
arguments: newArgGroup(),
}
@@ -295,6 +297,7 @@ loop:
if flag, err := context.flags.parse(context); err != nil {
if !ignoreDefault {
if cmd := cmds.defaultSubcommand(); cmd != nil {
cmd.completionAlts = cmds.cmdNames()
context.matchedCmd(cmd)
cmds = cmd.cmdGroup
break
@@ -312,6 +315,7 @@ loop:
if !ok {
if !ignoreDefault {
if cmd = cmds.defaultSubcommand(); cmd != nil {
cmd.completionAlts = cmds.cmdNames()
selectedDefault = true
}
}
@@ -322,6 +326,7 @@ loop:
if cmd == HelpCommand {
ignoreDefault = true
}
cmd.completionAlts = nil
context.matchedCmd(cmd)
cmds = cmd.cmdGroup
if !selectedDefault {
@@ -350,6 +355,7 @@ loop:
// Move to innermost default command.
for !ignoreDefault {
if cmd := cmds.defaultSubcommand(); cmd != nil {
cmd.completionAlts = cmds.cmdNames()
context.matchedCmd(cmd)
cmds = cmd.cmdGroup
} else {
@@ -363,9 +369,9 @@ loop:
// Set defaults for all remaining args.
for arg := context.nextArg(); arg != nil && !arg.consumesRemainder(); arg = context.nextArg() {
if arg.defaultValue != "" {
if err := arg.value.Set(arg.defaultValue); err != nil {
return fmt.Errorf("invalid default value '%s' for argument '%s'", arg.defaultValue, arg.name)
for _, defaultValue := range arg.defaultValues {
if err := arg.value.Set(defaultValue); err != nil {
return fmt.Errorf("invalid default value '%s' for argument '%s'", defaultValue, arg.name)
}
}
}

View File

@@ -199,3 +199,14 @@ func (p *parserMixin) Enums(options ...string) (target *[]string) {
func (p *parserMixin) EnumsVar(target *[]string, options ...string) {
p.SetValue(newEnumsFlag(target, options...))
}
// A Counter increments a number each time it is encountered.
func (p *parserMixin) Counter() (target *int) {
target = new(int)
p.CounterVar(target)
return
}
func (p *parserMixin) CounterVar(target *int) {
p.SetValue(newCounterValue(target))
}

View File

@@ -37,8 +37,8 @@ Args:
{{.Context.Args|ArgsToTwoColumns|FormatTwoColumns}}
{{end}}\
{{if .Context.SelectedCommand}}\
{{if len .Context.SelectedCommand.Commands}}\
Subcommands:
{{if .Context.SelectedCommand.Commands}}\
{{template "FormatCommands" .Context.SelectedCommand}}
{{end}}\
{{else if .App.Commands}}\
@@ -231,3 +231,32 @@ Commands:
{{template "FormatCommands" .App}}
{{end}}\
`
var BashCompletionTemplate = `
_{{.App.Name}}_bash_autocomplete() {
local cur prev opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
opts=$( ${COMP_WORDS[0]} --completion-bash ${COMP_WORDS[@]:1:$COMP_CWORD} )
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _{{.App.Name}}_bash_autocomplete {{.App.Name}}
`
var ZshCompletionTemplate = `
#compdef {{.App.Name}}
autoload -U compinit && compinit
autoload -U bashcompinit && bashcompinit
_{{.App.Name}}_bash_autocomplete() {
local cur prev opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
opts=$( ${COMP_WORDS[0]} --completion-bash ${COMP_WORDS[@]:1:$COMP_CWORD} )
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _{{.App.Name}}_bash_autocomplete {{.App.Name}}
`

View File

@@ -87,6 +87,9 @@ func formatFlag(haveShort bool, flag *FlagModel) string {
if !flag.IsBoolFlag() {
flagString += fmt.Sprintf("=%s", flag.FormatPlaceHolder())
}
if v, ok := flag.Value.(repeatableFlag); ok && v.IsCumulative() {
flagString += " ..."
}
return flagString
}
@@ -118,7 +121,7 @@ func (a *Application) UsageForContextWithTemplate(context *ParseContext, indent
"Wrap": func(indent int, s string) string {
buf := bytes.NewBuffer(nil)
indentText := strings.Repeat(" ", indent)
doc.ToText(buf, s, indentText, indentText, width)
doc.ToText(buf, s, indentText, " "+indentText, width-indent)
return buf.String()
},
"FormatFlag": formatFlag,
@@ -180,8 +183,8 @@ func (a *Application) UsageForContextWithTemplate(context *ParseContext, indent
"FormatAppUsage": formatAppUsage,
"FormatCommandUsage": formatCmdUsage,
"IsCumulative": func(value Value) bool {
_, ok := value.(remainderArg)
return ok
r, ok := value.(remainderArg)
return ok && r.IsCumulative()
},
"Char": func(c rune) string {
return string(c)

View File

@@ -53,6 +53,12 @@ type remainderArg interface {
IsCumulative() bool
}
// Optional interface for flags that can be repeated.
type repeatableFlag interface {
Value
IsCumulative() bool
}
type accumulator struct {
element func(value interface{}) Value
typ reflect.Type
@@ -96,6 +102,10 @@ func (a *accumulator) Set(value string) error {
return nil
}
func (a *accumulator) Get() interface{} {
return a.slice.Interface()
}
func (a *accumulator) IsCumulative() bool {
return true
}
@@ -136,6 +146,11 @@ func (s *stringMapValue) Set(value string) error {
(*s)[parts[0]] = parts[1]
return nil
}
func (s *stringMapValue) Get() interface{} {
return (map[string]string)(*s)
}
func (s *stringMapValue) String() string {
return fmt.Sprintf("%s", map[string]string(*s))
}
@@ -160,6 +175,10 @@ func (i *ipValue) Set(value string) error {
}
}
func (i *ipValue) Get() interface{} {
return (net.IP)(*i)
}
func (i *ipValue) String() string {
return (*net.IP)(i).String()
}
@@ -182,6 +201,10 @@ func (i *tcpAddrValue) Set(value string) error {
}
}
func (t *tcpAddrValue) Get() interface{} {
return (*net.TCPAddr)(*t.addr)
}
func (i *tcpAddrValue) String() string {
return (*i.addr).String()
}
@@ -212,6 +235,10 @@ func (e *fileStatValue) Set(value string) error {
return nil
}
func (f *fileStatValue) Get() interface{} {
return (string)(*f.path)
}
func (e *fileStatValue) String() string {
return *e.path
}
@@ -237,6 +264,10 @@ func (f *fileValue) Set(value string) error {
}
}
func (f *fileValue) Get() interface{} {
return (*os.File)(*f.f)
}
func (f *fileValue) String() string {
if *f.f == nil {
return "<nil>"
@@ -262,6 +293,10 @@ func (u *urlValue) Set(value string) error {
}
}
func (u *urlValue) Get() interface{} {
return (*url.URL)(*u.u)
}
func (u *urlValue) String() string {
if *u.u == nil {
return "<nil>"
@@ -285,6 +320,10 @@ func (u *urlListValue) Set(value string) error {
}
}
func (u *urlListValue) Get() interface{} {
return ([]*url.URL)(*u)
}
func (u *urlListValue) String() string {
out := []string{}
for _, url := range *u {
@@ -320,6 +359,10 @@ func (a *enumValue) Set(value string) error {
return fmt.Errorf("enum value must be one of %s, got '%s'", strings.Join(a.options, ","), value)
}
func (e *enumValue) Get() interface{} {
return (string)(*e.value)
}
// -- []string Enum Value
type enumsValue struct {
value *[]string
@@ -343,6 +386,10 @@ func (s *enumsValue) Set(value string) error {
return fmt.Errorf("enum value must be one of %s, got '%s'", strings.Join(s.options, ","), value)
}
func (e *enumsValue) Get() interface{} {
return ([]string)(*e.value)
}
func (s *enumsValue) String() string {
return strings.Join(*s.value, ",")
}
@@ -389,3 +436,31 @@ func newExistingDirValue(target *string) *fileStatValue {
func newExistingFileOrDirValue(target *string) *fileStatValue {
return newFileStatValue(target, func(s os.FileInfo) error { return nil })
}
type counterValue int
func newCounterValue(n *int) *counterValue {
return (*counterValue)(n)
}
func (c *counterValue) Set(s string) error {
*c++
return nil
}
func (c *counterValue) Get() interface{} { return (int)(*c) }
func (c *counterValue) IsBoolFlag() bool { return true }
func (c *counterValue) String() string { return fmt.Sprintf("%d", *c) }
func (c *counterValue) IsCumulative() bool { return true }
func resolveHost(value string) (net.IP, error) {
if ip := net.ParseIP(value); ip != nil {
return ip, nil
} else {
if addr, err := net.ResolveIPAddr("ip", value); err != nil {
return nil, err
} else {
return addr.IP, nil
}
}
}

View File

@@ -1,6 +1,6 @@
[
{"type": "bool", "parser": "strconv.ParseBool(s)"},
{"type": "string", "parser": "s, error(nil)", "format": "string(*f)", "plural": "Strings"},
{"type": "string", "parser": "s, error(nil)", "format": "string(*f.v)", "plural": "Strings"},
{"type": "uint", "parser": "strconv.ParseUint(s, 0, 64)", "plural": "Uints"},
{"type": "uint8", "parser": "strconv.ParseUint(s, 0, 8)"},
{"type": "uint16", "parser": "strconv.ParseUint(s, 0, 16)"},
@@ -18,5 +18,8 @@
{"name": "TCPAddr", "Type": "*net.TCPAddr", "plural": "TCPList", "no_value_parser": true},
{"name": "ExistingFile", "Type": "string", "plural": "ExistingFiles", "no_value_parser": true},
{"name": "ExistingDir", "Type": "string", "plural": "ExistingDirs", "no_value_parser": true},
{"name": "ExistingFileOrDir", "Type": "string", "plural": "ExistingFilesOrDirs", "no_value_parser": true}
{"name": "ExistingFileOrDir", "Type": "string", "plural": "ExistingFilesOrDirs", "no_value_parser": true},
{"name": "Regexp", "Type": "*regexp.Regexp", "parser": "regexp.Compile(s)"},
{"name": "ResolvedIP", "Type": "net.IP", "parser": "resolveHost(s)", "help": "Resolve a hostname or IP to an IP."},
{"name": "HexBytes", "Type": "[]byte", "parser": "hex.DecodeString(s)", "help": "Bytes as a hex string."}
]

View File

@@ -1,8 +1,10 @@
package kingpin
import (
"encoding/hex"
"fmt"
"net"
"regexp"
"strconv"
"time"
)
@@ -10,19 +12,21 @@ import (
// This file is autogenerated by "go generate .". Do not modify.
// -- bool Value
type boolValue bool
type boolValue struct{ v *bool }
func newBoolValue(p *bool) *boolValue {
return (*boolValue)(p)
return &boolValue{p}
}
func (f *boolValue) Set(s string) error {
v, err := strconv.ParseBool(s)
*f = boolValue(v)
if err == nil {
*f.v = (bool)(v)
}
return err
}
func (f *boolValue) Get() interface{} { return bool(*f) }
func (f *boolValue) Get() interface{} { return (bool)(*f.v) }
func (f *boolValue) String() string { return fmt.Sprintf("%v", *f) }
@@ -45,25 +49,29 @@ func (p *parserMixin) BoolList() (target *[]bool) {
}
func (p *parserMixin) BoolListVar(target *[]bool) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newBoolValue(v.(*bool)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newBoolValue(v.(*bool))
}))
}
// -- string Value
type stringValue string
type stringValue struct{ v *string }
func newStringValue(p *string) *stringValue {
return (*stringValue)(p)
return &stringValue{p}
}
func (f *stringValue) Set(s string) error {
v, err := s, error(nil)
*f = stringValue(v)
if err == nil {
*f.v = (string)(v)
}
return err
}
func (f *stringValue) Get() interface{} { return string(*f) }
func (f *stringValue) Get() interface{} { return (string)(*f.v) }
func (f *stringValue) String() string { return string(*f) }
func (f *stringValue) String() string { return string(*f.v) }
// String parses the next command-line value as string.
func (p *parserMixin) String() (target *string) {
@@ -84,23 +92,27 @@ func (p *parserMixin) Strings() (target *[]string) {
}
func (p *parserMixin) StringsVar(target *[]string) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newStringValue(v.(*string)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newStringValue(v.(*string))
}))
}
// -- uint Value
type uintValue uint
type uintValue struct{ v *uint }
func newUintValue(p *uint) *uintValue {
return (*uintValue)(p)
return &uintValue{p}
}
func (f *uintValue) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 64)
*f = uintValue(v)
if err == nil {
*f.v = (uint)(v)
}
return err
}
func (f *uintValue) Get() interface{} { return uint(*f) }
func (f *uintValue) Get() interface{} { return (uint)(*f.v) }
func (f *uintValue) String() string { return fmt.Sprintf("%v", *f) }
@@ -123,23 +135,27 @@ func (p *parserMixin) Uints() (target *[]uint) {
}
func (p *parserMixin) UintsVar(target *[]uint) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newUintValue(v.(*uint)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newUintValue(v.(*uint))
}))
}
// -- uint8 Value
type uint8Value uint8
type uint8Value struct{ v *uint8 }
func newUint8Value(p *uint8) *uint8Value {
return (*uint8Value)(p)
return &uint8Value{p}
}
func (f *uint8Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 8)
*f = uint8Value(v)
if err == nil {
*f.v = (uint8)(v)
}
return err
}
func (f *uint8Value) Get() interface{} { return uint8(*f) }
func (f *uint8Value) Get() interface{} { return (uint8)(*f.v) }
func (f *uint8Value) String() string { return fmt.Sprintf("%v", *f) }
@@ -162,23 +178,27 @@ func (p *parserMixin) Uint8List() (target *[]uint8) {
}
func (p *parserMixin) Uint8ListVar(target *[]uint8) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newUint8Value(v.(*uint8)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newUint8Value(v.(*uint8))
}))
}
// -- uint16 Value
type uint16Value uint16
type uint16Value struct{ v *uint16 }
func newUint16Value(p *uint16) *uint16Value {
return (*uint16Value)(p)
return &uint16Value{p}
}
func (f *uint16Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 16)
*f = uint16Value(v)
if err == nil {
*f.v = (uint16)(v)
}
return err
}
func (f *uint16Value) Get() interface{} { return uint16(*f) }
func (f *uint16Value) Get() interface{} { return (uint16)(*f.v) }
func (f *uint16Value) String() string { return fmt.Sprintf("%v", *f) }
@@ -201,23 +221,27 @@ func (p *parserMixin) Uint16List() (target *[]uint16) {
}
func (p *parserMixin) Uint16ListVar(target *[]uint16) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newUint16Value(v.(*uint16)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newUint16Value(v.(*uint16))
}))
}
// -- uint32 Value
type uint32Value uint32
type uint32Value struct{ v *uint32 }
func newUint32Value(p *uint32) *uint32Value {
return (*uint32Value)(p)
return &uint32Value{p}
}
func (f *uint32Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 32)
*f = uint32Value(v)
if err == nil {
*f.v = (uint32)(v)
}
return err
}
func (f *uint32Value) Get() interface{} { return uint32(*f) }
func (f *uint32Value) Get() interface{} { return (uint32)(*f.v) }
func (f *uint32Value) String() string { return fmt.Sprintf("%v", *f) }
@@ -240,23 +264,27 @@ func (p *parserMixin) Uint32List() (target *[]uint32) {
}
func (p *parserMixin) Uint32ListVar(target *[]uint32) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newUint32Value(v.(*uint32)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newUint32Value(v.(*uint32))
}))
}
// -- uint64 Value
type uint64Value uint64
type uint64Value struct{ v *uint64 }
func newUint64Value(p *uint64) *uint64Value {
return (*uint64Value)(p)
return &uint64Value{p}
}
func (f *uint64Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 64)
*f = uint64Value(v)
if err == nil {
*f.v = (uint64)(v)
}
return err
}
func (f *uint64Value) Get() interface{} { return uint64(*f) }
func (f *uint64Value) Get() interface{} { return (uint64)(*f.v) }
func (f *uint64Value) String() string { return fmt.Sprintf("%v", *f) }
@@ -279,23 +307,27 @@ func (p *parserMixin) Uint64List() (target *[]uint64) {
}
func (p *parserMixin) Uint64ListVar(target *[]uint64) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newUint64Value(v.(*uint64)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newUint64Value(v.(*uint64))
}))
}
// -- int Value
type intValue int
type intValue struct{ v *int }
func newIntValue(p *int) *intValue {
return (*intValue)(p)
return &intValue{p}
}
func (f *intValue) Set(s string) error {
v, err := strconv.ParseFloat(s, 64)
*f = intValue(v)
if err == nil {
*f.v = (int)(v)
}
return err
}
func (f *intValue) Get() interface{} { return int(*f) }
func (f *intValue) Get() interface{} { return (int)(*f.v) }
func (f *intValue) String() string { return fmt.Sprintf("%v", *f) }
@@ -318,23 +350,27 @@ func (p *parserMixin) Ints() (target *[]int) {
}
func (p *parserMixin) IntsVar(target *[]int) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newIntValue(v.(*int)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newIntValue(v.(*int))
}))
}
// -- int8 Value
type int8Value int8
type int8Value struct{ v *int8 }
func newInt8Value(p *int8) *int8Value {
return (*int8Value)(p)
return &int8Value{p}
}
func (f *int8Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 8)
*f = int8Value(v)
if err == nil {
*f.v = (int8)(v)
}
return err
}
func (f *int8Value) Get() interface{} { return int8(*f) }
func (f *int8Value) Get() interface{} { return (int8)(*f.v) }
func (f *int8Value) String() string { return fmt.Sprintf("%v", *f) }
@@ -357,23 +393,27 @@ func (p *parserMixin) Int8List() (target *[]int8) {
}
func (p *parserMixin) Int8ListVar(target *[]int8) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newInt8Value(v.(*int8)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newInt8Value(v.(*int8))
}))
}
// -- int16 Value
type int16Value int16
type int16Value struct{ v *int16 }
func newInt16Value(p *int16) *int16Value {
return (*int16Value)(p)
return &int16Value{p}
}
func (f *int16Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 16)
*f = int16Value(v)
if err == nil {
*f.v = (int16)(v)
}
return err
}
func (f *int16Value) Get() interface{} { return int16(*f) }
func (f *int16Value) Get() interface{} { return (int16)(*f.v) }
func (f *int16Value) String() string { return fmt.Sprintf("%v", *f) }
@@ -396,23 +436,27 @@ func (p *parserMixin) Int16List() (target *[]int16) {
}
func (p *parserMixin) Int16ListVar(target *[]int16) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newInt16Value(v.(*int16)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newInt16Value(v.(*int16))
}))
}
// -- int32 Value
type int32Value int32
type int32Value struct{ v *int32 }
func newInt32Value(p *int32) *int32Value {
return (*int32Value)(p)
return &int32Value{p}
}
func (f *int32Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 32)
*f = int32Value(v)
if err == nil {
*f.v = (int32)(v)
}
return err
}
func (f *int32Value) Get() interface{} { return int32(*f) }
func (f *int32Value) Get() interface{} { return (int32)(*f.v) }
func (f *int32Value) String() string { return fmt.Sprintf("%v", *f) }
@@ -435,23 +479,27 @@ func (p *parserMixin) Int32List() (target *[]int32) {
}
func (p *parserMixin) Int32ListVar(target *[]int32) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newInt32Value(v.(*int32)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newInt32Value(v.(*int32))
}))
}
// -- int64 Value
type int64Value int64
type int64Value struct{ v *int64 }
func newInt64Value(p *int64) *int64Value {
return (*int64Value)(p)
return &int64Value{p}
}
func (f *int64Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 64)
*f = int64Value(v)
if err == nil {
*f.v = (int64)(v)
}
return err
}
func (f *int64Value) Get() interface{} { return int64(*f) }
func (f *int64Value) Get() interface{} { return (int64)(*f.v) }
func (f *int64Value) String() string { return fmt.Sprintf("%v", *f) }
@@ -474,23 +522,27 @@ func (p *parserMixin) Int64List() (target *[]int64) {
}
func (p *parserMixin) Int64ListVar(target *[]int64) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newInt64Value(v.(*int64)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newInt64Value(v.(*int64))
}))
}
// -- float64 Value
type float64Value float64
type float64Value struct{ v *float64 }
func newFloat64Value(p *float64) *float64Value {
return (*float64Value)(p)
return &float64Value{p}
}
func (f *float64Value) Set(s string) error {
v, err := strconv.ParseFloat(s, 64)
*f = float64Value(v)
if err == nil {
*f.v = (float64)(v)
}
return err
}
func (f *float64Value) Get() interface{} { return float64(*f) }
func (f *float64Value) Get() interface{} { return (float64)(*f.v) }
func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
@@ -513,23 +565,27 @@ func (p *parserMixin) Float64List() (target *[]float64) {
}
func (p *parserMixin) Float64ListVar(target *[]float64) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newFloat64Value(v.(*float64)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newFloat64Value(v.(*float64))
}))
}
// -- float32 Value
type float32Value float32
type float32Value struct{ v *float32 }
func newFloat32Value(p *float32) *float32Value {
return (*float32Value)(p)
return &float32Value{p}
}
func (f *float32Value) Set(s string) error {
v, err := strconv.ParseFloat(s, 32)
*f = float32Value(v)
if err == nil {
*f.v = (float32)(v)
}
return err
}
func (f *float32Value) Get() interface{} { return float32(*f) }
func (f *float32Value) Get() interface{} { return (float32)(*f.v) }
func (f *float32Value) String() string { return fmt.Sprintf("%v", *f) }
@@ -552,7 +608,9 @@ func (p *parserMixin) Float32List() (target *[]float32) {
}
func (p *parserMixin) Float32ListVar(target *[]float32) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newFloat32Value(v.(*float32)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newFloat32Value(v.(*float32))
}))
}
// DurationList accumulates time.Duration values into a slice.
@@ -563,7 +621,9 @@ func (p *parserMixin) DurationList() (target *[]time.Duration) {
}
func (p *parserMixin) DurationListVar(target *[]time.Duration) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newDurationValue(v.(*time.Duration)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newDurationValue(v.(*time.Duration))
}))
}
// IPList accumulates net.IP values into a slice.
@@ -574,7 +634,9 @@ func (p *parserMixin) IPList() (target *[]net.IP) {
}
func (p *parserMixin) IPListVar(target *[]net.IP) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newIPValue(v.(*net.IP)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newIPValue(v.(*net.IP))
}))
}
// TCPList accumulates *net.TCPAddr values into a slice.
@@ -585,7 +647,9 @@ func (p *parserMixin) TCPList() (target *[]*net.TCPAddr) {
}
func (p *parserMixin) TCPListVar(target *[]*net.TCPAddr) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newTCPAddrValue(v.(**net.TCPAddr)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newTCPAddrValue(v.(**net.TCPAddr))
}))
}
// ExistingFiles accumulates string values into a slice.
@@ -596,7 +660,9 @@ func (p *parserMixin) ExistingFiles() (target *[]string) {
}
func (p *parserMixin) ExistingFilesVar(target *[]string) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newExistingFileValue(v.(*string)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newExistingFileValue(v.(*string))
}))
}
// ExistingDirs accumulates string values into a slice.
@@ -607,7 +673,9 @@ func (p *parserMixin) ExistingDirs() (target *[]string) {
}
func (p *parserMixin) ExistingDirsVar(target *[]string) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newExistingDirValue(v.(*string)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newExistingDirValue(v.(*string))
}))
}
// ExistingFilesOrDirs accumulates string values into a slice.
@@ -618,5 +686,136 @@ func (p *parserMixin) ExistingFilesOrDirs() (target *[]string) {
}
func (p *parserMixin) ExistingFilesOrDirsVar(target *[]string) {
p.SetValue(newAccumulator(target, func(v interface{}) Value { return newExistingFileOrDirValue(v.(*string)) }))
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newExistingFileOrDirValue(v.(*string))
}))
}
// -- *regexp.Regexp Value
type regexpValue struct{ v **regexp.Regexp }
func newRegexpValue(p **regexp.Regexp) *regexpValue {
return &regexpValue{p}
}
func (f *regexpValue) Set(s string) error {
v, err := regexp.Compile(s)
if err == nil {
*f.v = (*regexp.Regexp)(v)
}
return err
}
func (f *regexpValue) Get() interface{} { return (*regexp.Regexp)(*f.v) }
func (f *regexpValue) String() string { return fmt.Sprintf("%v", *f) }
// Regexp parses the next command-line value as *regexp.Regexp.
func (p *parserMixin) Regexp() (target **regexp.Regexp) {
target = new(*regexp.Regexp)
p.RegexpVar(target)
return
}
func (p *parserMixin) RegexpVar(target **regexp.Regexp) {
p.SetValue(newRegexpValue(target))
}
// RegexpList accumulates *regexp.Regexp values into a slice.
func (p *parserMixin) RegexpList() (target *[]*regexp.Regexp) {
target = new([]*regexp.Regexp)
p.RegexpListVar(target)
return
}
func (p *parserMixin) RegexpListVar(target *[]*regexp.Regexp) {
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newRegexpValue(v.(**regexp.Regexp))
}))
}
// -- net.IP Value
type resolvedIPValue struct{ v *net.IP }
func newResolvedIPValue(p *net.IP) *resolvedIPValue {
return &resolvedIPValue{p}
}
func (f *resolvedIPValue) Set(s string) error {
v, err := resolveHost(s)
if err == nil {
*f.v = (net.IP)(v)
}
return err
}
func (f *resolvedIPValue) Get() interface{} { return (net.IP)(*f.v) }
func (f *resolvedIPValue) String() string { return fmt.Sprintf("%v", *f) }
// Resolve a hostname or IP to an IP.
func (p *parserMixin) ResolvedIP() (target *net.IP) {
target = new(net.IP)
p.ResolvedIPVar(target)
return
}
func (p *parserMixin) ResolvedIPVar(target *net.IP) {
p.SetValue(newResolvedIPValue(target))
}
// ResolvedIPList accumulates net.IP values into a slice.
func (p *parserMixin) ResolvedIPList() (target *[]net.IP) {
target = new([]net.IP)
p.ResolvedIPListVar(target)
return
}
func (p *parserMixin) ResolvedIPListVar(target *[]net.IP) {
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newResolvedIPValue(v.(*net.IP))
}))
}
// -- []byte Value
type hexBytesValue struct{ v *[]byte }
func newHexBytesValue(p *[]byte) *hexBytesValue {
return &hexBytesValue{p}
}
func (f *hexBytesValue) Set(s string) error {
v, err := hex.DecodeString(s)
if err == nil {
*f.v = ([]byte)(v)
}
return err
}
func (f *hexBytesValue) Get() interface{} { return ([]byte)(*f.v) }
func (f *hexBytesValue) String() string { return fmt.Sprintf("%v", *f) }
// Bytes as a hex string.
func (p *parserMixin) HexBytes() (target *[]byte) {
target = new([]byte)
p.HexBytesVar(target)
return
}
func (p *parserMixin) HexBytesVar(target *[]byte) {
p.SetValue(newHexBytesValue(target))
}
// HexBytesList accumulates []byte values into a slice.
func (p *parserMixin) HexBytesList() (target *[][]byte) {
target = new([][]byte)
p.HexBytesListVar(target)
return
}
func (p *parserMixin) HexBytesListVar(target *[][]byte) {
p.SetValue(newAccumulator(target, func(v interface{}) Value {
return newHexBytesValue(v.(*[]byte))
}))
}

View File

@@ -1,4 +1,4 @@
Copyright (c) 2013 Google. All rights reserved.
Copyright (c) 2012 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are

View File

@@ -12,6 +12,7 @@ import (
"runtime"
"sort"
"strings"
"github.com/alecthomas/template/parse"
)

View File

@@ -7,6 +7,7 @@ package template
import (
"fmt"
"reflect"
"github.com/alecthomas/template/parse"
)

14
vendor/github.com/codeskyblue/openid-go/.travis.yml generated vendored Normal file
View File

@@ -0,0 +1,14 @@
sudo: false
language: go
go:
- 1.3.3
- 1.4.2
- 1.5.2
- 1.6beta2
# Get deps, build, test, and ensure the code is gofmt'ed.
script:
- go test -v ./...
- diff <(gofmt -d .) <("")

13
vendor/github.com/codeskyblue/openid-go/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,13 @@
Copyright 2015 Yohann Coppel
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

38
vendor/github.com/codeskyblue/openid-go/README.md generated vendored Normal file
View File

@@ -0,0 +1,38 @@
# openid.go
This is a consumer (Relying party) implementation of OpenId 2.0,
written in Go.
go get -u github.com/yohcop/openid-go
[![Build Status](https://travis-ci.org/yohcop/openid-go.svg?branch=master)](https://travis-ci.org/yohcop/openid-go)
## Github
Be awesome! Feel free to clone and use according to the licence.
If you make a useful change that can benefit others, send a
pull request! This ensures that one version has all the good stuff
and doesn't fall behind.
## Code example
See `_example/` for a simple webserver using the openID
implementation. Also, read the comment about the NonceStore towards
the top of that file. The example must be run for the openid-go
directory, like so:
go run _example/server.go
## App Engine
In order to use this on Google App Engine, you need to create an instance with a custom `*http.Client` provided by [urlfetch](https://cloud.google.com/appengine/docs/go/urlfetch/).
```go
oid := openid.NewOpenID(urlfetch.Client(appengine.NewContext(r)))
oid.RedirectURL(...)
oid.Verify(...)
```
## License
Distributed under the [Apache v2.0 license](http://www.apache.org/licenses/LICENSE-2.0.html).

57
vendor/github.com/codeskyblue/openid-go/discover.go generated vendored Normal file
View File

@@ -0,0 +1,57 @@
package openid
// 7.3.1. Discovered Information
// Upon successful completion of discovery, the Relying Party will
// have one or more sets of the following information (see the
// Terminology section for definitions). If more than one set of the
// following information has been discovered, the precedence rules
// defined in [XRI_Resolution_2.0] are to be applied.
// - OP Endpoint URL
// - Protocol Version
// If the end user did not enter an OP Identifier, the following
// information will also be present:
// - Claimed Identifier
// - OP-Local Identifier
// If the end user entered an OP Identifier, there is no Claimed
// Identifier. For the purposes of making OpenID Authentication
// requests, the value
// "http://specs.openid.net/auth/2.0/identifier_select" MUST be
// used as both the Claimed Identifier and the OP-Local Identifier
// when an OP Identifier is entered.
func Discover(id string) (opEndpoint, opLocalID, claimedID string, err error) {
return defaultInstance.Discover(id)
}
func (oid *OpenID) Discover(id string) (opEndpoint, opLocalID, claimedID string, err error) {
// From OpenID specs, 7.2: Normalization
if id, err = Normalize(id); err != nil {
return
}
// From OpenID specs, 7.3: Discovery.
// If the identifier is an XRI, [XRI_Resolution_2.0] will yield an
// XRDS document that contains the necessary information. It
// should also be noted that Relying Parties can take advantage of
// XRI Proxy Resolvers, such as the one provided by XDI.org at
// http://www.xri.net. This will remove the need for the RPs to
// perform XRI Resolution locally.
// XRI not supported.
// If it is a URL, the Yadis protocol [Yadis] SHALL be first
// attempted. If it succeeds, the result is again an XRDS
// document.
if opEndpoint, opLocalID, err = yadisDiscovery(id, oid.urlGetter); err != nil {
// If the Yadis protocol fails and no valid XRDS document is
// retrieved, or no Service Elements are found in the XRDS
// document, the URL is retrieved and HTML-Based discovery SHALL be
// attempted.
opEndpoint, opLocalID, claimedID, err = htmlDiscovery(id, oid.urlGetter)
}
if err != nil {
return "", "", "", err
}
return
}

View File

@@ -0,0 +1,69 @@
package openid
import (
"sync"
)
type DiscoveredInfo interface {
OpEndpoint() string
OpLocalID() string
ClaimedID() string
// ProtocolVersion: it's always openId 2.
}
type DiscoveryCache interface {
Put(id string, info DiscoveredInfo)
// Return a discovered info, or nil.
Get(id string) DiscoveredInfo
}
type SimpleDiscoveredInfo struct {
opEndpoint string
opLocalID string
claimedID string
}
func (s *SimpleDiscoveredInfo) OpEndpoint() string {
return s.opEndpoint
}
func (s *SimpleDiscoveredInfo) OpLocalID() string {
return s.opLocalID
}
func (s *SimpleDiscoveredInfo) ClaimedID() string {
return s.claimedID
}
type SimpleDiscoveryCache struct {
cache map[string]DiscoveredInfo
mutex *sync.Mutex
}
func NewSimpleDiscoveryCache() *SimpleDiscoveryCache {
return &SimpleDiscoveryCache{cache: map[string]DiscoveredInfo{}, mutex: &sync.Mutex{}}
}
func (s *SimpleDiscoveryCache) Put(id string, info DiscoveredInfo) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.cache[id] = info
}
func (s *SimpleDiscoveryCache) Get(id string) DiscoveredInfo {
s.mutex.Lock()
defer s.mutex.Unlock()
if info, has := s.cache[id]; has {
return info
}
return nil
}
func compareDiscoveredInfo(a DiscoveredInfo, opEndpoint, opLocalID, claimedID string) bool {
return a != nil &&
a.OpEndpoint() == opEndpoint &&
a.OpLocalID() == opLocalID &&
a.ClaimedID() == claimedID
}

31
vendor/github.com/codeskyblue/openid-go/getter.go generated vendored Normal file
View File

@@ -0,0 +1,31 @@
package openid
import (
"net/http"
"net/url"
)
// Interface that simplifies testing.
type httpGetter interface {
Get(uri string, headers map[string]string) (resp *http.Response, err error)
Post(uri string, form url.Values) (resp *http.Response, err error)
}
type defaultGetter struct {
client *http.Client
}
func (dg *defaultGetter) Get(uri string, headers map[string]string) (resp *http.Response, err error) {
request, err := http.NewRequest("GET", uri, nil)
if err != nil {
return
}
for h, v := range headers {
request.Header.Add(h, v)
}
return dg.client.Do(request)
}
func (dg *defaultGetter) Post(uri string, form url.Values) (resp *http.Response, err error) {
return dg.client.PostForm(uri, form)
}

View File

@@ -0,0 +1,75 @@
package openid
import (
"errors"
"io"
"golang.org/x/net/html"
)
func htmlDiscovery(id string, getter httpGetter) (opEndpoint, opLocalID, claimedID string, err error) {
resp, err := getter.Get(id, nil)
if err != nil {
return "", "", "", err
}
opEndpoint, opLocalID, err = findProviderFromHeadLink(resp.Body)
return opEndpoint, opLocalID, resp.Request.URL.String(), err
}
func findProviderFromHeadLink(input io.Reader) (opEndpoint, opLocalID string, err error) {
tokenizer := html.NewTokenizer(input)
inHead := false
for {
tt := tokenizer.Next()
switch tt {
case html.ErrorToken:
// Even if the document is malformed after we found a
// valid <link> tag, ignore and let's be happy with our
// openid2.provider and potentially openid2.local_id as well.
if len(opEndpoint) > 0 {
return
}
return "", "", tokenizer.Err()
case html.StartTagToken, html.EndTagToken, html.SelfClosingTagToken:
tk := tokenizer.Token()
if tk.Data == "head" {
if tt == html.StartTagToken {
inHead = true
} else {
if len(opEndpoint) > 0 {
return
}
return "", "", errors.New(
"LINK with rel=openid2.provider not found")
}
} else if inHead && tk.Data == "link" {
provider := false
localID := false
href := ""
for _, attr := range tk.Attr {
if attr.Key == "rel" {
if attr.Val == "openid2.provider" {
provider = true
} else if attr.Val == "openid2.local_id" {
localID = true
}
} else if attr.Key == "href" {
href = attr.Val
}
}
if provider && !localID && len(href) > 0 {
opEndpoint = href
} else if !provider && localID && len(href) > 0 {
opLocalID = href
}
}
}
}
// At this point we should probably have returned either from
// a closing </head> or a tokenizer error (no </head> found).
// But just in case.
if len(opEndpoint) > 0 {
return
}
return "", "", errors.New("LINK rel=openid2.provider not found")
}

87
vendor/github.com/codeskyblue/openid-go/nonce_store.go generated vendored Normal file
View File

@@ -0,0 +1,87 @@
package openid
import (
"errors"
"flag"
"fmt"
"sync"
"time"
)
var maxNonceAge = flag.Duration("openid-max-nonce-age",
60*time.Second,
"Maximum accepted age for openid nonces. The bigger, the more"+
"memory is needed to store used nonces.")
type NonceStore interface {
// Returns nil if accepted, an error otherwise.
Accept(endpoint, nonce string) error
}
type Nonce struct {
T time.Time
S string
}
type SimpleNonceStore struct {
store map[string][]*Nonce
mutex *sync.Mutex
}
func NewSimpleNonceStore() *SimpleNonceStore {
return &SimpleNonceStore{store: map[string][]*Nonce{}, mutex: &sync.Mutex{}}
}
func (d *SimpleNonceStore) Accept(endpoint, nonce string) error {
// Value: A string 255 characters or less in length, that MUST be
// unique to this particular successful authentication response.
if len(nonce) < 20 || len(nonce) > 256 {
return errors.New("Invalid nonce")
}
// The nonce MUST start with the current time on the server, and MAY
// contain additional ASCII characters in the range 33-126 inclusive
// (printable non-whitespace characters), as necessary to make each
// response unique. The date and time MUST be formatted as specified in
// section 5.6 of [RFC3339], with the following restrictions:
// All times must be in the UTC timezone, indicated with a "Z". No
// fractional seconds are allowed For example:
// 2005-05-15T17:11:51ZUNIQUE
ts, err := time.Parse(time.RFC3339, nonce[0:20])
if err != nil {
return err
}
now := time.Now()
diff := now.Sub(ts)
if diff > *maxNonceAge {
return fmt.Errorf("Nonce too old: %ds", diff.Seconds())
}
s := nonce[20:]
// Meh.. now we have to use a mutex, to protect that map from
// concurrent access. Could put a go routine in charge of it
// though.
d.mutex.Lock()
defer d.mutex.Unlock()
if nonces, hasOp := d.store[endpoint]; hasOp {
// Delete old nonces while we are at it.
newNonces := []*Nonce{{ts, s}}
for _, n := range nonces {
if n.T == ts && n.S == s {
// If return early, just ignore the filtered list
// we have been building so far...
return errors.New("Nonce already used")
}
if now.Sub(n.T) < *maxNonceAge {
newNonces = append(newNonces, n)
}
}
d.store[endpoint] = newNonces
} else {
d.store[endpoint] = []*Nonce{{ts, s}}
}
return nil
}

64
vendor/github.com/codeskyblue/openid-go/normalizer.go generated vendored Normal file
View File

@@ -0,0 +1,64 @@
package openid
import (
"errors"
"net/url"
"strings"
)
func Normalize(id string) (string, error) {
id = strings.TrimSpace(id)
if len(id) == 0 {
return "", errors.New("No id provided")
}
// 7.2 from openID 2.0 spec.
//If the user's input starts with the "xri://" prefix, it MUST be
//stripped off, so that XRIs are used in the canonical form.
if strings.HasPrefix(id, "xri://") {
id = id[6:]
return id, errors.New("XRI identifiers not supported")
}
// If the first character of the resulting string is an XRI
// Global Context Symbol ("=", "@", "+", "$", "!") or "(", as
// defined in Section 2.2.1 of [XRI_Syntax_2.0], then the input
// SHOULD be treated as an XRI.
if b := id[0]; b == '=' || b == '@' || b == '+' || b == '$' || b == '!' {
return id, errors.New("XRI identifiers not supported")
}
// Otherwise, the input SHOULD be treated as an http URL; if it
// does not include a "http" or "https" scheme, the Identifier
// MUST be prefixed with the string "http://". If the URL
// contains a fragment part, it MUST be stripped off together
// with the fragment delimiter character "#". See Section 11.5.2 for
// more information.
if !strings.HasPrefix(id, "http://") && !strings.HasPrefix(id,
"https://") {
id = "http://" + id
}
if fragmentIndex := strings.Index(id, "#"); fragmentIndex != -1 {
id = id[0:fragmentIndex]
}
if u, err := url.ParseRequestURI(id); err != nil {
return "", err
} else {
if u.Host == "" {
return "", errors.New("Invalid address provided as id")
}
if u.Path == "" {
u.Path = "/"
}
id = u.String()
}
// URL Identifiers MUST then be further normalized by both
// following redirects when retrieving their content and finally
// applying the rules in Section 6 of [RFC3986] to the final
// destination URL. This final URL MUST be noted by the Relying
// Party as the Claimed Identifier and be used when requesting
// authentication.
return id, nil
}

15
vendor/github.com/codeskyblue/openid-go/openid.go generated vendored Normal file
View File

@@ -0,0 +1,15 @@
package openid
import (
"net/http"
)
type OpenID struct {
urlGetter httpGetter
}
func NewOpenID(client *http.Client) *OpenID {
return &OpenID{urlGetter: &defaultGetter{client: client}}
}
var defaultInstance = NewOpenID(http.DefaultClient)

59
vendor/github.com/codeskyblue/openid-go/redirect.go generated vendored Normal file
View File

@@ -0,0 +1,59 @@
package openid
import (
"net/url"
"strings"
)
func RedirectURL(id, callbackURL, realm string) (string, error) {
return defaultInstance.RedirectURL(id, callbackURL, realm)
}
func (oid *OpenID) RedirectURL(id, callbackURL, realm string) (string, error) {
opEndpoint, opLocalID, claimedID, err := oid.Discover(id)
if err != nil {
return "", err
}
return BuildRedirectURL(opEndpoint, opLocalID, claimedID, callbackURL, realm)
}
func BuildRedirectURL(opEndpoint, opLocalID, claimedID, returnTo, realm string) (string, error) {
values := make(url.Values)
values.Add("openid.ns", "http://specs.openid.net/auth/2.0")
values.Add("openid.mode", "checkid_setup")
values.Add("openid.return_to", returnTo)
// 9.1. Request Parameters
// "openid.claimed_id" and "openid.identity" SHALL be either both present or both absent.
if len(claimedID) > 0 {
values.Add("openid.claimed_id", claimedID)
if len(opLocalID) > 0 {
values.Add("openid.identity", opLocalID)
} else {
// If a different OP-Local Identifier is not specified,
// the claimed identifier MUST be used as the value for openid.identity.
values.Add("openid.identity", claimedID)
}
} else {
// 7.3.1. Discovered Information
// If the end user entered an OP Identifier, there is no Claimed Identifier.
// For the purposes of making OpenID Authentication requests, the value
// "http://specs.openid.net/auth/2.0/identifier_select" MUST be used as both the
// Claimed Identifier and the OP-Local Identifier when an OP Identifier is entered.
values.Add("openid.claimed_id", "http://specs.openid.net/auth/2.0/identifier_select")
values.Add("openid.identity", "http://specs.openid.net/auth/2.0/identifier_select")
}
if len(realm) > 0 {
values.Add("openid.realm", realm)
}
// ssx: quick dirty patch
values.Add("openid.ns.sreg", "http://openid.net/extensions/sreg/1.1")
values.Add("openid.sreg.required", "nickname,email,fullname")
if strings.Contains(opEndpoint, "?") {
return opEndpoint + "&" + values.Encode(), nil
}
return opEndpoint + "?" + values.Encode(), nil
}

250
vendor/github.com/codeskyblue/openid-go/verify.go generated vendored Normal file
View File

@@ -0,0 +1,250 @@
package openid
import (
"errors"
"fmt"
"io/ioutil"
"net/url"
"strings"
)
func Verify(uri string, cache DiscoveryCache, nonceStore NonceStore) (id string, err error) {
return defaultInstance.Verify(uri, cache, nonceStore)
}
func (oid *OpenID) Verify(uri string, cache DiscoveryCache, nonceStore NonceStore) (id string, err error) {
parsedURL, err := url.Parse(uri)
if err != nil {
return "", err
}
values, err := url.ParseQuery(parsedURL.RawQuery)
if err != nil {
return "", err
}
// 11. Verifying Assertions
// When the Relying Party receives a positive assertion, it MUST
// verify the following before accepting the assertion:
// - The value of "openid.signed" contains all the required fields.
// (Section 10.1)
if err = verifySignedFields(values); err != nil {
return "", err
}
// - The signature on the assertion is valid (Section 11.4)
if err = verifySignature(uri, values, oid.urlGetter); err != nil {
return "", err
}
// - The value of "openid.return_to" matches the URL of the current
// request (Section 11.1)
if err = verifyReturnTo(parsedURL, values); err != nil {
return "", err
}
// - Discovered information matches the information in the assertion
// (Section 11.2)
if err = oid.verifyDiscovered(parsedURL, values, cache); err != nil {
return "", err
}
// - An assertion has not yet been accepted from this OP with the
// same value for "openid.response_nonce" (Section 11.3)
if err = verifyNonce(values, nonceStore); err != nil {
return "", err
}
// If all four of these conditions are met, assertion is now
// verified. If the assertion contained a Claimed Identifier, the
// user is now authenticated with that identifier.
return values.Get("openid.claimed_id"), nil
}
// 10.1. Positive Assertions
// openid.signed - Comma-separated list of signed fields.
// This entry consists of the fields without the "openid." prefix that the signature covers.
// This list MUST contain at least "op_endpoint", "return_to" "response_nonce" and "assoc_handle",
// and if present in the response, "claimed_id" and "identity".
func verifySignedFields(vals url.Values) error {
ok := map[string]bool{
"op_endpoint": false,
"return_to": false,
"response_nonce": false,
"assoc_handle": false,
"claimed_id": vals.Get("openid.claimed_id") == "",
"identity": vals.Get("openid.identity") == "",
}
signed := strings.Split(vals.Get("openid.signed"), ",")
for _, sf := range signed {
ok[sf] = true
}
for k, v := range ok {
if !v {
return fmt.Errorf("%v must be signed but isn't", k)
}
}
return nil
}
// 11.1. Verifying the Return URL
// To verify that the "openid.return_to" URL matches the URL that is processing this assertion:
// - The URL scheme, authority, and path MUST be the same between the two
// URLs.
// - Any query parameters that are present in the "openid.return_to" URL
// MUST also be present with the same values in the URL of the HTTP
// request the RP received.
func verifyReturnTo(uri *url.URL, vals url.Values) error {
returnTo := vals.Get("openid.return_to")
rp, err := url.Parse(returnTo)
if err != nil {
return err
}
if uri.Scheme != rp.Scheme ||
uri.Host != rp.Host ||
uri.Path != rp.Path {
return errors.New(
"Scheme, host or path don't match in return_to URL")
}
qp, err := url.ParseQuery(rp.RawQuery)
if err != nil {
return err
}
return compareQueryParams(qp, vals)
}
// Any parameter in q1 must also be present in q2, and values must match.
func compareQueryParams(q1, q2 url.Values) error {
for k := range q1 {
v1 := q1.Get(k)
v2 := q2.Get(k)
if v1 != v2 {
return fmt.Errorf(
"URLs query params don't match: Param %s different: %s vs %s",
k, v1, v2)
}
}
return nil
}
func (oid *OpenID) verifyDiscovered(uri *url.URL, vals url.Values, cache DiscoveryCache) error {
version := vals.Get("openid.ns")
if version != "http://specs.openid.net/auth/2.0" {
return errors.New("Bad protocol version")
}
endpoint := vals.Get("openid.op_endpoint")
if len(endpoint) == 0 {
return errors.New("missing openid.op_endpoint url param")
}
localID := vals.Get("openid.identity")
if len(localID) == 0 {
return errors.New("no localId to verify")
}
claimedID := vals.Get("openid.claimed_id")
if len(claimedID) == 0 {
// If no Claimed Identifier is present in the response, the
// assertion is not about an identifier and the RP MUST NOT use the
// User-supplied Identifier associated with the current OpenID
// authentication transaction to identify the user. Extension
// information in the assertion MAY still be used.
// --- This library does not support this case. So claimed
// identifier must be present.
return errors.New("no claimed_id to verify")
}
// 11.2. Verifying Discovered Information
// If the Claimed Identifier in the assertion is a URL and contains a
// fragment, the fragment part and the fragment delimiter character "#"
// MUST NOT be used for the purposes of verifying the discovered
// information.
claimedIDVerify := claimedID
if fragmentIndex := strings.Index(claimedID, "#"); fragmentIndex != -1 {
claimedIDVerify = claimedID[0:fragmentIndex]
}
// If the Claimed Identifier is included in the assertion, it
// MUST have been discovered by the Relying Party and the
// information in the assertion MUST be present in the
// discovered information. The Claimed Identifier MUST NOT be an
// OP Identifier.
if discovered := cache.Get(claimedIDVerify); discovered != nil &&
discovered.OpEndpoint() == endpoint &&
discovered.OpLocalID() == localID &&
discovered.ClaimedID() == claimedIDVerify {
return nil
}
// If the Claimed Identifier was not previously discovered by the
// Relying Party (the "openid.identity" in the request was
// "http://specs.openid.net/auth/2.0/identifier_select" or a different
// Identifier, or if the OP is sending an unsolicited positive
// assertion), the Relying Party MUST perform discovery on the Claimed
// Identifier in the response to make sure that the OP is authorized to
// make assertions about the Claimed Identifier.
if ep, _, _, err := oid.Discover(claimedID); err == nil {
if ep == endpoint {
// This claimed ID points to the same endpoint, therefore this
// endpoint is authorized to make assertions about that claimed ID.
// TODO: There may be multiple endpoints found during discovery.
// They should all be checked.
cache.Put(claimedIDVerify, &SimpleDiscoveredInfo{opEndpoint: endpoint, opLocalID: localID, claimedID: claimedIDVerify})
return nil
}
}
return errors.New("Could not verify the claimed ID")
}
func verifyNonce(vals url.Values, store NonceStore) error {
nonce := vals.Get("openid.response_nonce")
endpoint := vals.Get("openid.op_endpoint")
return store.Accept(endpoint, nonce)
}
func verifySignature(uri string, vals url.Values, getter httpGetter) error {
// To have the signature verification performed by the OP, the
// Relying Party sends a direct request to the OP. To verify the
// signature, the OP uses a private association that was generated
// when it issued the positive assertion.
// 11.4.2.1. Request Parameters
params := make(url.Values)
// openid.mode: Value: "check_authentication"
params.Add("openid.mode", "check_authentication")
// Exact copies of all fields from the authentication response,
// except for "openid.mode".
for k, vs := range vals {
if k == "openid.mode" {
continue
}
for _, v := range vs {
params.Add(k, v)
}
}
resp, err := getter.Post(vals.Get("openid.op_endpoint"), params)
if err != nil {
return err
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
response := string(content)
lines := strings.Split(response, "\n")
isValid := false
nsValid := false
for _, l := range lines {
if l == "is_valid:true" {
isValid = true
} else if l == "ns:http://specs.openid.net/auth/2.0" {
nsValid = true
}
}
if isValid && nsValid {
// Yay !
return nil
}
return errors.New("Could not verify assertion with provider")
}

83
vendor/github.com/codeskyblue/openid-go/xrds.go generated vendored Normal file
View File

@@ -0,0 +1,83 @@
package openid
import (
"encoding/xml"
"errors"
"strings"
)
// TODO: As per 11.2 in openid 2 specs, a service may have multiple
// URIs. We don't care for discovery really, but we do care for
// verification though.
type XrdsIdentifier struct {
Type []string `xml:"Type"`
URI string `xml:"URI"`
LocalID string `xml:"LocalID"`
Priority int `xml:"priority,attr"`
}
type Xrd struct {
Service []*XrdsIdentifier `xml:"Service"`
}
type XrdsDocument struct {
XMLName xml.Name `xml:"XRDS"`
Xrd *Xrd `xml:"XRD"`
}
func parseXrds(input []byte) (opEndpoint, opLocalID string, err error) {
xrdsDoc := &XrdsDocument{}
err = xml.Unmarshal(input, xrdsDoc)
if err != nil {
return
}
if xrdsDoc.Xrd == nil {
return "", "", errors.New("XRDS document missing XRD tag")
}
// 7.3.2.2. Extracting Authentication Data
// Once the Relying Party has obtained an XRDS document, it
// MUST first search the document (following the rules
// described in [XRI_Resolution_2.0]) for an OP Identifier
// Element. If none is found, the RP will search for a Claimed
// Identifier Element.
for _, service := range xrdsDoc.Xrd.Service {
// 7.3.2.1.1. OP Identifier Element
// An OP Identifier Element is an <xrd:Service> element with the
// following information:
// An <xrd:Type> tag whose text content is
// "http://specs.openid.net/auth/2.0/server".
// An <xrd:URI> tag whose text content is the OP Endpoint URL
if service.hasType("http://specs.openid.net/auth/2.0/server") {
opEndpoint = strings.TrimSpace(service.URI)
return
}
}
for _, service := range xrdsDoc.Xrd.Service {
// 7.3.2.1.2. Claimed Identifier Element
// A Claimed Identifier Element is an <xrd:Service> element
// with the following information:
// An <xrd:Type> tag whose text content is
// "http://specs.openid.net/auth/2.0/signon".
// An <xrd:URI> tag whose text content is the OP Endpoint
// URL.
// An <xrd:LocalID> tag (optional) whose text content is the
// OP-Local Identifier.
if service.hasType("http://specs.openid.net/auth/2.0/signon") {
opEndpoint = strings.TrimSpace(service.URI)
opLocalID = strings.TrimSpace(service.LocalID)
return
}
}
return "", "", errors.New("Could not find a compatible service")
}
func (xrdsi *XrdsIdentifier) hasType(tpe string) bool {
for _, t := range xrdsi.Type {
if t == tpe {
return true
}
}
return false
}

View File

@@ -0,0 +1,119 @@
package openid
import (
"errors"
"io"
"io/ioutil"
"strings"
"golang.org/x/net/html"
)
var yadisHeaders = map[string]string{
"Accept": "application/xrds+xml"}
func yadisDiscovery(id string, getter httpGetter) (opEndpoint string, opLocalID string, err error) {
// Section 6.2.4 of Yadis 1.0 specifications.
// The Yadis Protocol is initiated by the Relying Party Agent
// with an initial HTTP request using the Yadis URL.
// This request MUST be either a GET or a HEAD request.
// A GET or HEAD request MAY include an HTTP Accept
// request-header (HTTP 14.1) specifying MIME media type,
// application/xrds+xml.
resp, err := getter.Get(id, yadisHeaders)
if err != nil {
return "", "", err
}
defer resp.Body.Close()
// Section 6.2.5 from Yadis 1.0 spec: Response
contentType := resp.Header.Get("Content-Type")
// The response MUST be one of:
// (see 6.2.6 for precedence)
if l := resp.Header.Get("X-XRDS-Location"); l != "" {
// 2. HTTP response-headers that include an X-XRDS-Location
// response-header, together with a document
return getYadisResourceDescriptor(l, getter)
} else if strings.Contains(contentType, "text/html") {
// 1. An HTML document with a <head> element that includes a
// <meta> element with http-equiv attribute, X-XRDS-Location,
metaContent, err := findMetaXrdsLocation(resp.Body)
if err == nil {
return getYadisResourceDescriptor(metaContent, getter)
}
return "", "", err
} else if strings.Contains(contentType, "application/xrds+xml") {
// 4. A document of MIME media type, application/xrds+xml.
body, err := ioutil.ReadAll(resp.Body)
if err == nil {
return parseXrds(body)
}
return "", "", err
}
// 3. HTTP response-headers only, which MAY include an
// X-XRDS-Location response-header, a content-type
// response-header specifying MIME media type,
// application/xrds+xml, or both.
// (this is handled by one of the 2 previous if statements)
return "", "", errors.New("No expected header, or content type")
}
// Similar as above, but we expect an absolute Yadis document URL.
func getYadisResourceDescriptor(id string, getter httpGetter) (opEndpoint string, opLocalID string, err error) {
resp, err := getter.Get(id, yadisHeaders)
if err != nil {
return "", "", err
}
defer resp.Body.Close()
// 4. A document of MIME media type, application/xrds+xml.
body, err := ioutil.ReadAll(resp.Body)
if err == nil {
return parseXrds(body)
}
return "", "", err
}
// Search for
// <head>
// <meta http-equiv="X-XRDS-Location" content="....">
func findMetaXrdsLocation(input io.Reader) (location string, err error) {
tokenizer := html.NewTokenizer(input)
inHead := false
for {
tt := tokenizer.Next()
switch tt {
case html.ErrorToken:
return "", tokenizer.Err()
case html.StartTagToken, html.EndTagToken:
tk := tokenizer.Token()
if tk.Data == "head" {
if tt == html.StartTagToken {
inHead = true
} else {
return "", errors.New("Meta X-XRDS-Location not found")
}
} else if inHead && tk.Data == "meta" {
ok := false
content := ""
for _, attr := range tk.Attr {
if attr.Key == "http-equiv" &&
strings.ToLower(attr.Val) == "x-xrds-location" {
ok = true
} else if attr.Key == "content" {
content = attr.Val
}
}
if ok && len(content) > 0 {
return content, nil
}
}
}
}
return "", errors.New("Meta X-XRDS-Location not found")
}

View File

@@ -1,13 +0,0 @@
Copyright (c) 2012-2013 Dave Collins <dave@davec.name>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

9
vendor/github.com/go-yaml/yaml/.travis.yml generated vendored Normal file
View File

@@ -0,0 +1,9 @@
language: go
go:
- 1.4
- 1.5
- 1.6
- tip
go_import_path: gopkg.in/yaml.v2

13
vendor/github.com/go-yaml/yaml/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,13 @@
Copyright 2011-2016 Canonical Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,14 +1,23 @@
The MIT License (MIT)
The following files were ported to Go from C files of libyaml, and thus
are still covered by their original copyright and license:
Copyright (c) 2015 Klaus Post
Copyright (c) 2012 The Go Authors. All rights reserved
apic.go
emitterc.go
parserc.go
readerc.go
scannerc.go
writerc.go
yamlh.go
yamlprivateh.go
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:
Copyright (c) 2006 Kirill Simonov
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.
@@ -20,4 +29,3 @@ 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.

131
vendor/github.com/go-yaml/yaml/README.md generated vendored Normal file
View File

@@ -0,0 +1,131 @@
# YAML support for the Go language
Introduction
------------
The yaml package enables Go programs to comfortably encode and decode YAML
values. It was developed within [Canonical](https://www.canonical.com) as
part of the [juju](https://juju.ubuntu.com) project, and is based on a
pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML)
C library to parse and generate YAML data quickly and reliably.
Compatibility
-------------
The yaml package supports most of YAML 1.1 and 1.2, including support for
anchors, tags, map merging, etc. Multi-document unmarshalling is not yet
implemented, and base-60 floats from YAML 1.1 are purposefully not
supported since they're a poor design and are gone in YAML 1.2.
Installation and usage
----------------------
The import path for the package is *gopkg.in/yaml.v2*.
To install it, run:
go get gopkg.in/yaml.v2
API documentation
-----------------
If opened in a browser, the import path itself leads to the API documentation:
* [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2)
API stability
-------------
The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in).
License
-------
The yaml package is licensed under the LGPL with an exception that allows it to be linked statically. Please see the LICENSE file for details.
Example
-------
```Go
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
var data = `
a: Easy!
b:
c: 2
d: [3, 4]
`
type T struct {
A string
B struct {
RenamedC int `yaml:"c"`
D []int `yaml:",flow"`
}
}
func main() {
t := T{}
err := yaml.Unmarshal([]byte(data), &t)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- t:\n%v\n\n", t)
d, err := yaml.Marshal(&t)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- t dump:\n%s\n\n", string(d))
m := make(map[interface{}]interface{})
err = yaml.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m:\n%v\n\n", m)
d, err = yaml.Marshal(&m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m dump:\n%s\n\n", string(d))
}
```
This example will generate the following output:
```
--- t:
{Easy! {2 [3 4]}}
--- t dump:
a: Easy!
b:
c: 2
d: [3, 4]
--- m:
map[a:Easy! b:map[c:2 d:[3 4]]]
--- m dump:
a: Easy!
b:
c: 2
d:
- 3
- 4
```

742
vendor/github.com/go-yaml/yaml/apic.go generated vendored Normal file
View File

@@ -0,0 +1,742 @@
package yaml
import (
"io"
"os"
)
func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) {
//fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens))
// Check if we can move the queue at the beginning of the buffer.
if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) {
if parser.tokens_head != len(parser.tokens) {
copy(parser.tokens, parser.tokens[parser.tokens_head:])
}
parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head]
parser.tokens_head = 0
}
parser.tokens = append(parser.tokens, *token)
if pos < 0 {
return
}
copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:])
parser.tokens[parser.tokens_head+pos] = *token
}
// Create a new parser object.
func yaml_parser_initialize(parser *yaml_parser_t) bool {
*parser = yaml_parser_t{
raw_buffer: make([]byte, 0, input_raw_buffer_size),
buffer: make([]byte, 0, input_buffer_size),
}
return true
}
// Destroy a parser object.
func yaml_parser_delete(parser *yaml_parser_t) {
*parser = yaml_parser_t{}
}
// String read handler.
func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) {
if parser.input_pos == len(parser.input) {
return 0, io.EOF
}
n = copy(buffer, parser.input[parser.input_pos:])
parser.input_pos += n
return n, nil
}
// File read handler.
func yaml_file_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) {
return parser.input_file.Read(buffer)
}
// Set a string input.
func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) {
if parser.read_handler != nil {
panic("must set the input source only once")
}
parser.read_handler = yaml_string_read_handler
parser.input = input
parser.input_pos = 0
}
// Set a file input.
func yaml_parser_set_input_file(parser *yaml_parser_t, file *os.File) {
if parser.read_handler != nil {
panic("must set the input source only once")
}
parser.read_handler = yaml_file_read_handler
parser.input_file = file
}
// Set the source encoding.
func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) {
if parser.encoding != yaml_ANY_ENCODING {
panic("must set the encoding only once")
}
parser.encoding = encoding
}
// Create a new emitter object.
func yaml_emitter_initialize(emitter *yaml_emitter_t) bool {
*emitter = yaml_emitter_t{
buffer: make([]byte, output_buffer_size),
raw_buffer: make([]byte, 0, output_raw_buffer_size),
states: make([]yaml_emitter_state_t, 0, initial_stack_size),
events: make([]yaml_event_t, 0, initial_queue_size),
}
return true
}
// Destroy an emitter object.
func yaml_emitter_delete(emitter *yaml_emitter_t) {
*emitter = yaml_emitter_t{}
}
// String write handler.
func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error {
*emitter.output_buffer = append(*emitter.output_buffer, buffer...)
return nil
}
// File write handler.
func yaml_file_write_handler(emitter *yaml_emitter_t, buffer []byte) error {
_, err := emitter.output_file.Write(buffer)
return err
}
// Set a string output.
func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) {
if emitter.write_handler != nil {
panic("must set the output target only once")
}
emitter.write_handler = yaml_string_write_handler
emitter.output_buffer = output_buffer
}
// Set a file output.
func yaml_emitter_set_output_file(emitter *yaml_emitter_t, file io.Writer) {
if emitter.write_handler != nil {
panic("must set the output target only once")
}
emitter.write_handler = yaml_file_write_handler
emitter.output_file = file
}
// Set the output encoding.
func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) {
if emitter.encoding != yaml_ANY_ENCODING {
panic("must set the output encoding only once")
}
emitter.encoding = encoding
}
// Set the canonical output style.
func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) {
emitter.canonical = canonical
}
//// Set the indentation increment.
func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) {
if indent < 2 || indent > 9 {
indent = 2
}
emitter.best_indent = indent
}
// Set the preferred line width.
func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) {
if width < 0 {
width = -1
}
emitter.best_width = width
}
// Set if unescaped non-ASCII characters are allowed.
func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) {
emitter.unicode = unicode
}
// Set the preferred line break character.
func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) {
emitter.line_break = line_break
}
///*
// * Destroy a token object.
// */
//
//YAML_DECLARE(void)
//yaml_token_delete(yaml_token_t *token)
//{
// assert(token); // Non-NULL token object expected.
//
// switch (token.type)
// {
// case YAML_TAG_DIRECTIVE_TOKEN:
// yaml_free(token.data.tag_directive.handle);
// yaml_free(token.data.tag_directive.prefix);
// break;
//
// case YAML_ALIAS_TOKEN:
// yaml_free(token.data.alias.value);
// break;
//
// case YAML_ANCHOR_TOKEN:
// yaml_free(token.data.anchor.value);
// break;
//
// case YAML_TAG_TOKEN:
// yaml_free(token.data.tag.handle);
// yaml_free(token.data.tag.suffix);
// break;
//
// case YAML_SCALAR_TOKEN:
// yaml_free(token.data.scalar.value);
// break;
//
// default:
// break;
// }
//
// memset(token, 0, sizeof(yaml_token_t));
//}
//
///*
// * Check if a string is a valid UTF-8 sequence.
// *
// * Check 'reader.c' for more details on UTF-8 encoding.
// */
//
//static int
//yaml_check_utf8(yaml_char_t *start, size_t length)
//{
// yaml_char_t *end = start+length;
// yaml_char_t *pointer = start;
//
// while (pointer < end) {
// unsigned char octet;
// unsigned int width;
// unsigned int value;
// size_t k;
//
// octet = pointer[0];
// width = (octet & 0x80) == 0x00 ? 1 :
// (octet & 0xE0) == 0xC0 ? 2 :
// (octet & 0xF0) == 0xE0 ? 3 :
// (octet & 0xF8) == 0xF0 ? 4 : 0;
// value = (octet & 0x80) == 0x00 ? octet & 0x7F :
// (octet & 0xE0) == 0xC0 ? octet & 0x1F :
// (octet & 0xF0) == 0xE0 ? octet & 0x0F :
// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
// if (!width) return 0;
// if (pointer+width > end) return 0;
// for (k = 1; k < width; k ++) {
// octet = pointer[k];
// if ((octet & 0xC0) != 0x80) return 0;
// value = (value << 6) + (octet & 0x3F);
// }
// if (!((width == 1) ||
// (width == 2 && value >= 0x80) ||
// (width == 3 && value >= 0x800) ||
// (width == 4 && value >= 0x10000))) return 0;
//
// pointer += width;
// }
//
// return 1;
//}
//
// Create STREAM-START.
func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) bool {
*event = yaml_event_t{
typ: yaml_STREAM_START_EVENT,
encoding: encoding,
}
return true
}
// Create STREAM-END.
func yaml_stream_end_event_initialize(event *yaml_event_t) bool {
*event = yaml_event_t{
typ: yaml_STREAM_END_EVENT,
}
return true
}
// Create DOCUMENT-START.
func yaml_document_start_event_initialize(event *yaml_event_t, version_directive *yaml_version_directive_t,
tag_directives []yaml_tag_directive_t, implicit bool) bool {
*event = yaml_event_t{
typ: yaml_DOCUMENT_START_EVENT,
version_directive: version_directive,
tag_directives: tag_directives,
implicit: implicit,
}
return true
}
// Create DOCUMENT-END.
func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) bool {
*event = yaml_event_t{
typ: yaml_DOCUMENT_END_EVENT,
implicit: implicit,
}
return true
}
///*
// * Create ALIAS.
// */
//
//YAML_DECLARE(int)
//yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t)
//{
// mark yaml_mark_t = { 0, 0, 0 }
// anchor_copy *yaml_char_t = NULL
//
// assert(event) // Non-NULL event object is expected.
// assert(anchor) // Non-NULL anchor is expected.
//
// if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0
//
// anchor_copy = yaml_strdup(anchor)
// if (!anchor_copy)
// return 0
//
// ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark)
//
// return 1
//}
// Create SCALAR.
func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool {
*event = yaml_event_t{
typ: yaml_SCALAR_EVENT,
anchor: anchor,
tag: tag,
value: value,
implicit: plain_implicit,
quoted_implicit: quoted_implicit,
style: yaml_style_t(style),
}
return true
}
// Create SEQUENCE-START.
func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool {
*event = yaml_event_t{
typ: yaml_SEQUENCE_START_EVENT,
anchor: anchor,
tag: tag,
implicit: implicit,
style: yaml_style_t(style),
}
return true
}
// Create SEQUENCE-END.
func yaml_sequence_end_event_initialize(event *yaml_event_t) bool {
*event = yaml_event_t{
typ: yaml_SEQUENCE_END_EVENT,
}
return true
}
// Create MAPPING-START.
func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) bool {
*event = yaml_event_t{
typ: yaml_MAPPING_START_EVENT,
anchor: anchor,
tag: tag,
implicit: implicit,
style: yaml_style_t(style),
}
return true
}
// Create MAPPING-END.
func yaml_mapping_end_event_initialize(event *yaml_event_t) bool {
*event = yaml_event_t{
typ: yaml_MAPPING_END_EVENT,
}
return true
}
// Destroy an event object.
func yaml_event_delete(event *yaml_event_t) {
*event = yaml_event_t{}
}
///*
// * Create a document object.
// */
//
//YAML_DECLARE(int)
//yaml_document_initialize(document *yaml_document_t,
// version_directive *yaml_version_directive_t,
// tag_directives_start *yaml_tag_directive_t,
// tag_directives_end *yaml_tag_directive_t,
// start_implicit int, end_implicit int)
//{
// struct {
// error yaml_error_type_t
// } context
// struct {
// start *yaml_node_t
// end *yaml_node_t
// top *yaml_node_t
// } nodes = { NULL, NULL, NULL }
// version_directive_copy *yaml_version_directive_t = NULL
// struct {
// start *yaml_tag_directive_t
// end *yaml_tag_directive_t
// top *yaml_tag_directive_t
// } tag_directives_copy = { NULL, NULL, NULL }
// value yaml_tag_directive_t = { NULL, NULL }
// mark yaml_mark_t = { 0, 0, 0 }
//
// assert(document) // Non-NULL document object is expected.
// assert((tag_directives_start && tag_directives_end) ||
// (tag_directives_start == tag_directives_end))
// // Valid tag directives are expected.
//
// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error
//
// if (version_directive) {
// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t))
// if (!version_directive_copy) goto error
// version_directive_copy.major = version_directive.major
// version_directive_copy.minor = version_directive.minor
// }
//
// if (tag_directives_start != tag_directives_end) {
// tag_directive *yaml_tag_directive_t
// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE))
// goto error
// for (tag_directive = tag_directives_start
// tag_directive != tag_directives_end; tag_directive ++) {
// assert(tag_directive.handle)
// assert(tag_directive.prefix)
// if (!yaml_check_utf8(tag_directive.handle,
// strlen((char *)tag_directive.handle)))
// goto error
// if (!yaml_check_utf8(tag_directive.prefix,
// strlen((char *)tag_directive.prefix)))
// goto error
// value.handle = yaml_strdup(tag_directive.handle)
// value.prefix = yaml_strdup(tag_directive.prefix)
// if (!value.handle || !value.prefix) goto error
// if (!PUSH(&context, tag_directives_copy, value))
// goto error
// value.handle = NULL
// value.prefix = NULL
// }
// }
//
// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy,
// tag_directives_copy.start, tag_directives_copy.top,
// start_implicit, end_implicit, mark, mark)
//
// return 1
//
//error:
// STACK_DEL(&context, nodes)
// yaml_free(version_directive_copy)
// while (!STACK_EMPTY(&context, tag_directives_copy)) {
// value yaml_tag_directive_t = POP(&context, tag_directives_copy)
// yaml_free(value.handle)
// yaml_free(value.prefix)
// }
// STACK_DEL(&context, tag_directives_copy)
// yaml_free(value.handle)
// yaml_free(value.prefix)
//
// return 0
//}
//
///*
// * Destroy a document object.
// */
//
//YAML_DECLARE(void)
//yaml_document_delete(document *yaml_document_t)
//{
// struct {
// error yaml_error_type_t
// } context
// tag_directive *yaml_tag_directive_t
//
// context.error = YAML_NO_ERROR // Eliminate a compliler warning.
//
// assert(document) // Non-NULL document object is expected.
//
// while (!STACK_EMPTY(&context, document.nodes)) {
// node yaml_node_t = POP(&context, document.nodes)
// yaml_free(node.tag)
// switch (node.type) {
// case YAML_SCALAR_NODE:
// yaml_free(node.data.scalar.value)
// break
// case YAML_SEQUENCE_NODE:
// STACK_DEL(&context, node.data.sequence.items)
// break
// case YAML_MAPPING_NODE:
// STACK_DEL(&context, node.data.mapping.pairs)
// break
// default:
// assert(0) // Should not happen.
// }
// }
// STACK_DEL(&context, document.nodes)
//
// yaml_free(document.version_directive)
// for (tag_directive = document.tag_directives.start
// tag_directive != document.tag_directives.end
// tag_directive++) {
// yaml_free(tag_directive.handle)
// yaml_free(tag_directive.prefix)
// }
// yaml_free(document.tag_directives.start)
//
// memset(document, 0, sizeof(yaml_document_t))
//}
//
///**
// * Get a document node.
// */
//
//YAML_DECLARE(yaml_node_t *)
//yaml_document_get_node(document *yaml_document_t, index int)
//{
// assert(document) // Non-NULL document object is expected.
//
// if (index > 0 && document.nodes.start + index <= document.nodes.top) {
// return document.nodes.start + index - 1
// }
// return NULL
//}
//
///**
// * Get the root object.
// */
//
//YAML_DECLARE(yaml_node_t *)
//yaml_document_get_root_node(document *yaml_document_t)
//{
// assert(document) // Non-NULL document object is expected.
//
// if (document.nodes.top != document.nodes.start) {
// return document.nodes.start
// }
// return NULL
//}
//
///*
// * Add a scalar node to a document.
// */
//
//YAML_DECLARE(int)
//yaml_document_add_scalar(document *yaml_document_t,
// tag *yaml_char_t, value *yaml_char_t, length int,
// style yaml_scalar_style_t)
//{
// struct {
// error yaml_error_type_t
// } context
// mark yaml_mark_t = { 0, 0, 0 }
// tag_copy *yaml_char_t = NULL
// value_copy *yaml_char_t = NULL
// node yaml_node_t
//
// assert(document) // Non-NULL document object is expected.
// assert(value) // Non-NULL value is expected.
//
// if (!tag) {
// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG
// }
//
// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error
// tag_copy = yaml_strdup(tag)
// if (!tag_copy) goto error
//
// if (length < 0) {
// length = strlen((char *)value)
// }
//
// if (!yaml_check_utf8(value, length)) goto error
// value_copy = yaml_malloc(length+1)
// if (!value_copy) goto error
// memcpy(value_copy, value, length)
// value_copy[length] = '\0'
//
// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark)
// if (!PUSH(&context, document.nodes, node)) goto error
//
// return document.nodes.top - document.nodes.start
//
//error:
// yaml_free(tag_copy)
// yaml_free(value_copy)
//
// return 0
//}
//
///*
// * Add a sequence node to a document.
// */
//
//YAML_DECLARE(int)
//yaml_document_add_sequence(document *yaml_document_t,
// tag *yaml_char_t, style yaml_sequence_style_t)
//{
// struct {
// error yaml_error_type_t
// } context
// mark yaml_mark_t = { 0, 0, 0 }
// tag_copy *yaml_char_t = NULL
// struct {
// start *yaml_node_item_t
// end *yaml_node_item_t
// top *yaml_node_item_t
// } items = { NULL, NULL, NULL }
// node yaml_node_t
//
// assert(document) // Non-NULL document object is expected.
//
// if (!tag) {
// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG
// }
//
// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error
// tag_copy = yaml_strdup(tag)
// if (!tag_copy) goto error
//
// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error
//
// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end,
// style, mark, mark)
// if (!PUSH(&context, document.nodes, node)) goto error
//
// return document.nodes.top - document.nodes.start
//
//error:
// STACK_DEL(&context, items)
// yaml_free(tag_copy)
//
// return 0
//}
//
///*
// * Add a mapping node to a document.
// */
//
//YAML_DECLARE(int)
//yaml_document_add_mapping(document *yaml_document_t,
// tag *yaml_char_t, style yaml_mapping_style_t)
//{
// struct {
// error yaml_error_type_t
// } context
// mark yaml_mark_t = { 0, 0, 0 }
// tag_copy *yaml_char_t = NULL
// struct {
// start *yaml_node_pair_t
// end *yaml_node_pair_t
// top *yaml_node_pair_t
// } pairs = { NULL, NULL, NULL }
// node yaml_node_t
//
// assert(document) // Non-NULL document object is expected.
//
// if (!tag) {
// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG
// }
//
// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error
// tag_copy = yaml_strdup(tag)
// if (!tag_copy) goto error
//
// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error
//
// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end,
// style, mark, mark)
// if (!PUSH(&context, document.nodes, node)) goto error
//
// return document.nodes.top - document.nodes.start
//
//error:
// STACK_DEL(&context, pairs)
// yaml_free(tag_copy)
//
// return 0
//}
//
///*
// * Append an item to a sequence node.
// */
//
//YAML_DECLARE(int)
//yaml_document_append_sequence_item(document *yaml_document_t,
// sequence int, item int)
//{
// struct {
// error yaml_error_type_t
// } context
//
// assert(document) // Non-NULL document is required.
// assert(sequence > 0
// && document.nodes.start + sequence <= document.nodes.top)
// // Valid sequence id is required.
// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE)
// // A sequence node is required.
// assert(item > 0 && document.nodes.start + item <= document.nodes.top)
// // Valid item id is required.
//
// if (!PUSH(&context,
// document.nodes.start[sequence-1].data.sequence.items, item))
// return 0
//
// return 1
//}
//
///*
// * Append a pair of a key and a value to a mapping node.
// */
//
//YAML_DECLARE(int)
//yaml_document_append_mapping_pair(document *yaml_document_t,
// mapping int, key int, value int)
//{
// struct {
// error yaml_error_type_t
// } context
//
// pair yaml_node_pair_t
//
// assert(document) // Non-NULL document is required.
// assert(mapping > 0
// && document.nodes.start + mapping <= document.nodes.top)
// // Valid mapping id is required.
// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE)
// // A mapping node is required.
// assert(key > 0 && document.nodes.start + key <= document.nodes.top)
// // Valid key id is required.
// assert(value > 0 && document.nodes.start + value <= document.nodes.top)
// // Valid value id is required.
//
// pair.key = key
// pair.value = value
//
// if (!PUSH(&context,
// document.nodes.start[mapping-1].data.mapping.pairs, pair))
// return 0
//
// return 1
//}
//
//

683
vendor/github.com/go-yaml/yaml/decode.go generated vendored Normal file
View File

@@ -0,0 +1,683 @@
package yaml
import (
"encoding"
"encoding/base64"
"fmt"
"math"
"reflect"
"strconv"
"time"
)
const (
documentNode = 1 << iota
mappingNode
sequenceNode
scalarNode
aliasNode
)
type node struct {
kind int
line, column int
tag string
value string
implicit bool
children []*node
anchors map[string]*node
}
// ----------------------------------------------------------------------------
// Parser, produces a node tree out of a libyaml event stream.
type parser struct {
parser yaml_parser_t
event yaml_event_t
doc *node
}
func newParser(b []byte) *parser {
p := parser{}
if !yaml_parser_initialize(&p.parser) {
panic("failed to initialize YAML emitter")
}
if len(b) == 0 {
b = []byte{'\n'}
}
yaml_parser_set_input_string(&p.parser, b)
p.skip()
if p.event.typ != yaml_STREAM_START_EVENT {
panic("expected stream start event, got " + strconv.Itoa(int(p.event.typ)))
}
p.skip()
return &p
}
func (p *parser) destroy() {
if p.event.typ != yaml_NO_EVENT {
yaml_event_delete(&p.event)
}
yaml_parser_delete(&p.parser)
}
func (p *parser) skip() {
if p.event.typ != yaml_NO_EVENT {
if p.event.typ == yaml_STREAM_END_EVENT {
failf("attempted to go past the end of stream; corrupted value?")
}
yaml_event_delete(&p.event)
}
if !yaml_parser_parse(&p.parser, &p.event) {
p.fail()
}
}
func (p *parser) fail() {
var where string
var line int
if p.parser.problem_mark.line != 0 {
line = p.parser.problem_mark.line
} else if p.parser.context_mark.line != 0 {
line = p.parser.context_mark.line
}
if line != 0 {
where = "line " + strconv.Itoa(line) + ": "
}
var msg string
if len(p.parser.problem) > 0 {
msg = p.parser.problem
} else {
msg = "unknown problem parsing YAML content"
}
failf("%s%s", where, msg)
}
func (p *parser) anchor(n *node, anchor []byte) {
if anchor != nil {
p.doc.anchors[string(anchor)] = n
}
}
func (p *parser) parse() *node {
switch p.event.typ {
case yaml_SCALAR_EVENT:
return p.scalar()
case yaml_ALIAS_EVENT:
return p.alias()
case yaml_MAPPING_START_EVENT:
return p.mapping()
case yaml_SEQUENCE_START_EVENT:
return p.sequence()
case yaml_DOCUMENT_START_EVENT:
return p.document()
case yaml_STREAM_END_EVENT:
// Happens when attempting to decode an empty buffer.
return nil
default:
panic("attempted to parse unknown event: " + strconv.Itoa(int(p.event.typ)))
}
panic("unreachable")
}
func (p *parser) node(kind int) *node {
return &node{
kind: kind,
line: p.event.start_mark.line,
column: p.event.start_mark.column,
}
}
func (p *parser) document() *node {
n := p.node(documentNode)
n.anchors = make(map[string]*node)
p.doc = n
p.skip()
n.children = append(n.children, p.parse())
if p.event.typ != yaml_DOCUMENT_END_EVENT {
panic("expected end of document event but got " + strconv.Itoa(int(p.event.typ)))
}
p.skip()
return n
}
func (p *parser) alias() *node {
n := p.node(aliasNode)
n.value = string(p.event.anchor)
p.skip()
return n
}
func (p *parser) scalar() *node {
n := p.node(scalarNode)
n.value = string(p.event.value)
n.tag = string(p.event.tag)
n.implicit = p.event.implicit
p.anchor(n, p.event.anchor)
p.skip()
return n
}
func (p *parser) sequence() *node {
n := p.node(sequenceNode)
p.anchor(n, p.event.anchor)
p.skip()
for p.event.typ != yaml_SEQUENCE_END_EVENT {
n.children = append(n.children, p.parse())
}
p.skip()
return n
}
func (p *parser) mapping() *node {
n := p.node(mappingNode)
p.anchor(n, p.event.anchor)
p.skip()
for p.event.typ != yaml_MAPPING_END_EVENT {
n.children = append(n.children, p.parse(), p.parse())
}
p.skip()
return n
}
// ----------------------------------------------------------------------------
// Decoder, unmarshals a node into a provided value.
type decoder struct {
doc *node
aliases map[string]bool
mapType reflect.Type
terrors []string
}
var (
mapItemType = reflect.TypeOf(MapItem{})
durationType = reflect.TypeOf(time.Duration(0))
defaultMapType = reflect.TypeOf(map[interface{}]interface{}{})
ifaceType = defaultMapType.Elem()
)
func newDecoder() *decoder {
d := &decoder{mapType: defaultMapType}
d.aliases = make(map[string]bool)
return d
}
func (d *decoder) terror(n *node, tag string, out reflect.Value) {
if n.tag != "" {
tag = n.tag
}
value := n.value
if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG {
if len(value) > 10 {
value = " `" + value[:7] + "...`"
} else {
value = " `" + value + "`"
}
}
d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type()))
}
func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) {
terrlen := len(d.terrors)
err := u.UnmarshalYAML(func(v interface{}) (err error) {
defer handleErr(&err)
d.unmarshal(n, reflect.ValueOf(v))
if len(d.terrors) > terrlen {
issues := d.terrors[terrlen:]
d.terrors = d.terrors[:terrlen]
return &TypeError{issues}
}
return nil
})
if e, ok := err.(*TypeError); ok {
d.terrors = append(d.terrors, e.Errors...)
return false
}
if err != nil {
fail(err)
}
return true
}
// d.prepare initializes and dereferences pointers and calls UnmarshalYAML
// if a value is found to implement it.
// It returns the initialized and dereferenced out value, whether
// unmarshalling was already done by UnmarshalYAML, and if so whether
// its types unmarshalled appropriately.
//
// If n holds a null value, prepare returns before doing anything.
func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) {
if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "") {
return out, false, false
}
again := true
for again {
again = false
if out.Kind() == reflect.Ptr {
if out.IsNil() {
out.Set(reflect.New(out.Type().Elem()))
}
out = out.Elem()
again = true
}
if out.CanAddr() {
if u, ok := out.Addr().Interface().(Unmarshaler); ok {
good = d.callUnmarshaler(n, u)
return out, true, good
}
}
}
return out, false, false
}
func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) {
switch n.kind {
case documentNode:
return d.document(n, out)
case aliasNode:
return d.alias(n, out)
}
out, unmarshaled, good := d.prepare(n, out)
if unmarshaled {
return good
}
switch n.kind {
case scalarNode:
good = d.scalar(n, out)
case mappingNode:
good = d.mapping(n, out)
case sequenceNode:
good = d.sequence(n, out)
default:
panic("internal error: unknown node kind: " + strconv.Itoa(n.kind))
}
return good
}
func (d *decoder) document(n *node, out reflect.Value) (good bool) {
if len(n.children) == 1 {
d.doc = n
d.unmarshal(n.children[0], out)
return true
}
return false
}
func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
an, ok := d.doc.anchors[n.value]
if !ok {
failf("unknown anchor '%s' referenced", n.value)
}
if d.aliases[n.value] {
failf("anchor '%s' value contains itself", n.value)
}
d.aliases[n.value] = true
good = d.unmarshal(an, out)
delete(d.aliases, n.value)
return good
}
var zeroValue reflect.Value
func resetMap(out reflect.Value) {
for _, k := range out.MapKeys() {
out.SetMapIndex(k, zeroValue)
}
}
func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
var tag string
var resolved interface{}
if n.tag == "" && !n.implicit {
tag = yaml_STR_TAG
resolved = n.value
} else {
tag, resolved = resolve(n.tag, n.value)
if tag == yaml_BINARY_TAG {
data, err := base64.StdEncoding.DecodeString(resolved.(string))
if err != nil {
failf("!!binary value contains invalid base64 data")
}
resolved = string(data)
}
}
if resolved == nil {
if out.Kind() == reflect.Map && !out.CanAddr() {
resetMap(out)
} else {
out.Set(reflect.Zero(out.Type()))
}
return true
}
if s, ok := resolved.(string); ok && out.CanAddr() {
if u, ok := out.Addr().Interface().(encoding.TextUnmarshaler); ok {
err := u.UnmarshalText([]byte(s))
if err != nil {
fail(err)
}
return true
}
}
switch out.Kind() {
case reflect.String:
if tag == yaml_BINARY_TAG {
out.SetString(resolved.(string))
good = true
} else if resolved != nil {
out.SetString(n.value)
good = true
}
case reflect.Interface:
if resolved == nil {
out.Set(reflect.Zero(out.Type()))
} else {
out.Set(reflect.ValueOf(resolved))
}
good = true
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
switch resolved := resolved.(type) {
case int:
if !out.OverflowInt(int64(resolved)) {
out.SetInt(int64(resolved))
good = true
}
case int64:
if !out.OverflowInt(resolved) {
out.SetInt(resolved)
good = true
}
case uint64:
if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
out.SetInt(int64(resolved))
good = true
}
case float64:
if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
out.SetInt(int64(resolved))
good = true
}
case string:
if out.Type() == durationType {
d, err := time.ParseDuration(resolved)
if err == nil {
out.SetInt(int64(d))
good = true
}
}
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
switch resolved := resolved.(type) {
case int:
if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved))
good = true
}
case int64:
if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved))
good = true
}
case uint64:
if !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved))
good = true
}
case float64:
if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved))
good = true
}
}
case reflect.Bool:
switch resolved := resolved.(type) {
case bool:
out.SetBool(resolved)
good = true
}
case reflect.Float32, reflect.Float64:
switch resolved := resolved.(type) {
case int:
out.SetFloat(float64(resolved))
good = true
case int64:
out.SetFloat(float64(resolved))
good = true
case uint64:
out.SetFloat(float64(resolved))
good = true
case float64:
out.SetFloat(resolved)
good = true
}
case reflect.Ptr:
if out.Type().Elem() == reflect.TypeOf(resolved) {
// TODO DOes this make sense? When is out a Ptr except when decoding a nil value?
elem := reflect.New(out.Type().Elem())
elem.Elem().Set(reflect.ValueOf(resolved))
out.Set(elem)
good = true
}
}
if !good {
d.terror(n, tag, out)
}
return good
}
func settableValueOf(i interface{}) reflect.Value {
v := reflect.ValueOf(i)
sv := reflect.New(v.Type()).Elem()
sv.Set(v)
return sv
}
func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
l := len(n.children)
var iface reflect.Value
switch out.Kind() {
case reflect.Slice:
out.Set(reflect.MakeSlice(out.Type(), l, l))
case reflect.Interface:
// No type hints. Will have to use a generic sequence.
iface = out
out = settableValueOf(make([]interface{}, l))
default:
d.terror(n, yaml_SEQ_TAG, out)
return false
}
et := out.Type().Elem()
j := 0
for i := 0; i < l; i++ {
e := reflect.New(et).Elem()
if ok := d.unmarshal(n.children[i], e); ok {
out.Index(j).Set(e)
j++
}
}
out.Set(out.Slice(0, j))
if iface.IsValid() {
iface.Set(out)
}
return true
}
func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
switch out.Kind() {
case reflect.Struct:
return d.mappingStruct(n, out)
case reflect.Slice:
return d.mappingSlice(n, out)
case reflect.Map:
// okay
case reflect.Interface:
if d.mapType.Kind() == reflect.Map {
iface := out
out = reflect.MakeMap(d.mapType)
iface.Set(out)
} else {
slicev := reflect.New(d.mapType).Elem()
if !d.mappingSlice(n, slicev) {
return false
}
out.Set(slicev)
return true
}
default:
d.terror(n, yaml_MAP_TAG, out)
return false
}
outt := out.Type()
kt := outt.Key()
et := outt.Elem()
mapType := d.mapType
if outt.Key() == ifaceType && outt.Elem() == ifaceType {
d.mapType = outt
}
if out.IsNil() {
out.Set(reflect.MakeMap(outt))
}
l := len(n.children)
for i := 0; i < l; i += 2 {
if isMerge(n.children[i]) {
d.merge(n.children[i+1], out)
continue
}
k := reflect.New(kt).Elem()
if d.unmarshal(n.children[i], k) {
kkind := k.Kind()
if kkind == reflect.Interface {
kkind = k.Elem().Kind()
}
if kkind == reflect.Map || kkind == reflect.Slice {
failf("invalid map key: %#v", k.Interface())
}
e := reflect.New(et).Elem()
if d.unmarshal(n.children[i+1], e) {
out.SetMapIndex(k, e)
}
}
}
d.mapType = mapType
return true
}
func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) {
outt := out.Type()
if outt.Elem() != mapItemType {
d.terror(n, yaml_MAP_TAG, out)
return false
}
mapType := d.mapType
d.mapType = outt
var slice []MapItem
var l = len(n.children)
for i := 0; i < l; i += 2 {
if isMerge(n.children[i]) {
d.merge(n.children[i+1], out)
continue
}
item := MapItem{}
k := reflect.ValueOf(&item.Key).Elem()
if d.unmarshal(n.children[i], k) {
v := reflect.ValueOf(&item.Value).Elem()
if d.unmarshal(n.children[i+1], v) {
slice = append(slice, item)
}
}
}
out.Set(reflect.ValueOf(slice))
d.mapType = mapType
return true
}
func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
sinfo, err := getStructInfo(out.Type())
if err != nil {
panic(err)
}
name := settableValueOf("")
l := len(n.children)
var inlineMap reflect.Value
var elemType reflect.Type
if sinfo.InlineMap != -1 {
inlineMap = out.Field(sinfo.InlineMap)
inlineMap.Set(reflect.New(inlineMap.Type()).Elem())
elemType = inlineMap.Type().Elem()
}
for i := 0; i < l; i += 2 {
ni := n.children[i]
if isMerge(ni) {
d.merge(n.children[i+1], out)
continue
}
if !d.unmarshal(ni, name) {
continue
}
if info, ok := sinfo.FieldsMap[name.String()]; ok {
var field reflect.Value
if info.Inline == nil {
field = out.Field(info.Num)
} else {
field = out.FieldByIndex(info.Inline)
}
d.unmarshal(n.children[i+1], field)
} else if sinfo.InlineMap != -1 {
if inlineMap.IsNil() {
inlineMap.Set(reflect.MakeMap(inlineMap.Type()))
}
value := reflect.New(elemType).Elem()
d.unmarshal(n.children[i+1], value)
inlineMap.SetMapIndex(name, value)
}
}
return true
}
func failWantMap() {
failf("map merge requires map or sequence of maps as the value")
}
func (d *decoder) merge(n *node, out reflect.Value) {
switch n.kind {
case mappingNode:
d.unmarshal(n, out)
case aliasNode:
an, ok := d.doc.anchors[n.value]
if ok && an.kind != mappingNode {
failWantMap()
}
d.unmarshal(n, out)
case sequenceNode:
// Step backwards as earlier nodes take precedence.
for i := len(n.children) - 1; i >= 0; i-- {
ni := n.children[i]
if ni.kind == aliasNode {
an, ok := d.doc.anchors[ni.value]
if ok && an.kind != mappingNode {
failWantMap()
}
} else if ni.kind != mappingNode {
failWantMap()
}
d.unmarshal(ni, out)
}
default:
failWantMap()
}
}
func isMerge(n *node) bool {
return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG)
}

1685
vendor/github.com/go-yaml/yaml/emitterc.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

306
vendor/github.com/go-yaml/yaml/encode.go generated vendored Normal file
View File

@@ -0,0 +1,306 @@
package yaml
import (
"encoding"
"fmt"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
type encoder struct {
emitter yaml_emitter_t
event yaml_event_t
out []byte
flow bool
}
func newEncoder() (e *encoder) {
e = &encoder{}
e.must(yaml_emitter_initialize(&e.emitter))
yaml_emitter_set_output_string(&e.emitter, &e.out)
yaml_emitter_set_unicode(&e.emitter, true)
e.must(yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING))
e.emit()
e.must(yaml_document_start_event_initialize(&e.event, nil, nil, true))
e.emit()
return e
}
func (e *encoder) finish() {
e.must(yaml_document_end_event_initialize(&e.event, true))
e.emit()
e.emitter.open_ended = false
e.must(yaml_stream_end_event_initialize(&e.event))
e.emit()
}
func (e *encoder) destroy() {
yaml_emitter_delete(&e.emitter)
}
func (e *encoder) emit() {
// This will internally delete the e.event value.
if !yaml_emitter_emit(&e.emitter, &e.event) && e.event.typ != yaml_DOCUMENT_END_EVENT && e.event.typ != yaml_STREAM_END_EVENT {
e.must(false)
}
}
func (e *encoder) must(ok bool) {
if !ok {
msg := e.emitter.problem
if msg == "" {
msg = "unknown problem generating YAML content"
}
failf("%s", msg)
}
}
func (e *encoder) marshal(tag string, in reflect.Value) {
if !in.IsValid() {
e.nilv()
return
}
iface := in.Interface()
if m, ok := iface.(Marshaler); ok {
v, err := m.MarshalYAML()
if err != nil {
fail(err)
}
if v == nil {
e.nilv()
return
}
in = reflect.ValueOf(v)
} else if m, ok := iface.(encoding.TextMarshaler); ok {
text, err := m.MarshalText()
if err != nil {
fail(err)
}
in = reflect.ValueOf(string(text))
}
switch in.Kind() {
case reflect.Interface:
if in.IsNil() {
e.nilv()
} else {
e.marshal(tag, in.Elem())
}
case reflect.Map:
e.mapv(tag, in)
case reflect.Ptr:
if in.IsNil() {
e.nilv()
} else {
e.marshal(tag, in.Elem())
}
case reflect.Struct:
e.structv(tag, in)
case reflect.Slice:
if in.Type().Elem() == mapItemType {
e.itemsv(tag, in)
} else {
e.slicev(tag, in)
}
case reflect.String:
e.stringv(tag, in)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if in.Type() == durationType {
e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String()))
} else {
e.intv(tag, in)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
e.uintv(tag, in)
case reflect.Float32, reflect.Float64:
e.floatv(tag, in)
case reflect.Bool:
e.boolv(tag, in)
default:
panic("cannot marshal type: " + in.Type().String())
}
}
func (e *encoder) mapv(tag string, in reflect.Value) {
e.mappingv(tag, func() {
keys := keyList(in.MapKeys())
sort.Sort(keys)
for _, k := range keys {
e.marshal("", k)
e.marshal("", in.MapIndex(k))
}
})
}
func (e *encoder) itemsv(tag string, in reflect.Value) {
e.mappingv(tag, func() {
slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem)
for _, item := range slice {
e.marshal("", reflect.ValueOf(item.Key))
e.marshal("", reflect.ValueOf(item.Value))
}
})
}
func (e *encoder) structv(tag string, in reflect.Value) {
sinfo, err := getStructInfo(in.Type())
if err != nil {
panic(err)
}
e.mappingv(tag, func() {
for _, info := range sinfo.FieldsList {
var value reflect.Value
if info.Inline == nil {
value = in.Field(info.Num)
} else {
value = in.FieldByIndex(info.Inline)
}
if info.OmitEmpty && isZero(value) {
continue
}
e.marshal("", reflect.ValueOf(info.Key))
e.flow = info.Flow
e.marshal("", value)
}
if sinfo.InlineMap >= 0 {
m := in.Field(sinfo.InlineMap)
if m.Len() > 0 {
e.flow = false
keys := keyList(m.MapKeys())
sort.Sort(keys)
for _, k := range keys {
if _, found := sinfo.FieldsMap[k.String()]; found {
panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String()))
}
e.marshal("", k)
e.flow = false
e.marshal("", m.MapIndex(k))
}
}
}
})
}
func (e *encoder) mappingv(tag string, f func()) {
implicit := tag == ""
style := yaml_BLOCK_MAPPING_STYLE
if e.flow {
e.flow = false
style = yaml_FLOW_MAPPING_STYLE
}
e.must(yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style))
e.emit()
f()
e.must(yaml_mapping_end_event_initialize(&e.event))
e.emit()
}
func (e *encoder) slicev(tag string, in reflect.Value) {
implicit := tag == ""
style := yaml_BLOCK_SEQUENCE_STYLE
if e.flow {
e.flow = false
style = yaml_FLOW_SEQUENCE_STYLE
}
e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style))
e.emit()
n := in.Len()
for i := 0; i < n; i++ {
e.marshal("", in.Index(i))
}
e.must(yaml_sequence_end_event_initialize(&e.event))
e.emit()
}
// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1.
//
// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported
// in YAML 1.2 and by this package, but these should be marshalled quoted for
// the time being for compatibility with other parsers.
func isBase60Float(s string) (result bool) {
// Fast path.
if s == "" {
return false
}
c := s[0]
if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 {
return false
}
// Do the full match.
return base60float.MatchString(s)
}
// From http://yaml.org/type/float.html, except the regular expression there
// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix.
var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`)
func (e *encoder) stringv(tag string, in reflect.Value) {
var style yaml_scalar_style_t
s := in.String()
rtag, rs := resolve("", s)
if rtag == yaml_BINARY_TAG {
if tag == "" || tag == yaml_STR_TAG {
tag = rtag
s = rs.(string)
} else if tag == yaml_BINARY_TAG {
failf("explicitly tagged !!binary data must be base64-encoded")
} else {
failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag))
}
}
if tag == "" && (rtag != yaml_STR_TAG || isBase60Float(s)) {
style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
} else if strings.Contains(s, "\n") {
style = yaml_LITERAL_SCALAR_STYLE
} else {
style = yaml_PLAIN_SCALAR_STYLE
}
e.emitScalar(s, "", tag, style)
}
func (e *encoder) boolv(tag string, in reflect.Value) {
var s string
if in.Bool() {
s = "true"
} else {
s = "false"
}
e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
}
func (e *encoder) intv(tag string, in reflect.Value) {
s := strconv.FormatInt(in.Int(), 10)
e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
}
func (e *encoder) uintv(tag string, in reflect.Value) {
s := strconv.FormatUint(in.Uint(), 10)
e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
}
func (e *encoder) floatv(tag string, in reflect.Value) {
// FIXME: Handle 64 bits here.
s := strconv.FormatFloat(float64(in.Float()), 'g', -1, 32)
switch s {
case "+Inf":
s = ".inf"
case "-Inf":
s = "-.inf"
case "NaN":
s = ".nan"
}
e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
}
func (e *encoder) nilv() {
e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE)
}
func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) {
implicit := tag == ""
e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style))
e.emit()
}

1096
vendor/github.com/go-yaml/yaml/parserc.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

394
vendor/github.com/go-yaml/yaml/readerc.go generated vendored Normal file
View File

@@ -0,0 +1,394 @@
package yaml
import (
"io"
)
// Set the reader error and return 0.
func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool {
parser.error = yaml_READER_ERROR
parser.problem = problem
parser.problem_offset = offset
parser.problem_value = value
return false
}
// Byte order marks.
const (
bom_UTF8 = "\xef\xbb\xbf"
bom_UTF16LE = "\xff\xfe"
bom_UTF16BE = "\xfe\xff"
)
// Determine the input stream encoding by checking the BOM symbol. If no BOM is
// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure.
func yaml_parser_determine_encoding(parser *yaml_parser_t) bool {
// Ensure that we had enough bytes in the raw buffer.
for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 {
if !yaml_parser_update_raw_buffer(parser) {
return false
}
}
// Determine the encoding.
buf := parser.raw_buffer
pos := parser.raw_buffer_pos
avail := len(buf) - pos
if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] {
parser.encoding = yaml_UTF16LE_ENCODING
parser.raw_buffer_pos += 2
parser.offset += 2
} else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] {
parser.encoding = yaml_UTF16BE_ENCODING
parser.raw_buffer_pos += 2
parser.offset += 2
} else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] {
parser.encoding = yaml_UTF8_ENCODING
parser.raw_buffer_pos += 3
parser.offset += 3
} else {
parser.encoding = yaml_UTF8_ENCODING
}
return true
}
// Update the raw buffer.
func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool {
size_read := 0
// Return if the raw buffer is full.
if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) {
return true
}
// Return on EOF.
if parser.eof {
return true
}
// Move the remaining bytes in the raw buffer to the beginning.
if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) {
copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:])
}
parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos]
parser.raw_buffer_pos = 0
// Call the read handler to fill the buffer.
size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)])
parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read]
if err == io.EOF {
parser.eof = true
} else if err != nil {
return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1)
}
return true
}
// Ensure that the buffer contains at least `length` characters.
// Return true on success, false on failure.
//
// The length is supposed to be significantly less that the buffer size.
func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool {
if parser.read_handler == nil {
panic("read handler must be set")
}
// If the EOF flag is set and the raw buffer is empty, do nothing.
if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) {
return true
}
// Return if the buffer contains enough characters.
if parser.unread >= length {
return true
}
// Determine the input encoding if it is not known yet.
if parser.encoding == yaml_ANY_ENCODING {
if !yaml_parser_determine_encoding(parser) {
return false
}
}
// Move the unread characters to the beginning of the buffer.
buffer_len := len(parser.buffer)
if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len {
copy(parser.buffer, parser.buffer[parser.buffer_pos:])
buffer_len -= parser.buffer_pos
parser.buffer_pos = 0
} else if parser.buffer_pos == buffer_len {
buffer_len = 0
parser.buffer_pos = 0
}
// Open the whole buffer for writing, and cut it before returning.
parser.buffer = parser.buffer[:cap(parser.buffer)]
// Fill the buffer until it has enough characters.
first := true
for parser.unread < length {
// Fill the raw buffer if necessary.
if !first || parser.raw_buffer_pos == len(parser.raw_buffer) {
if !yaml_parser_update_raw_buffer(parser) {
parser.buffer = parser.buffer[:buffer_len]
return false
}
}
first = false
// Decode the raw buffer.
inner:
for parser.raw_buffer_pos != len(parser.raw_buffer) {
var value rune
var width int
raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos
// Decode the next character.
switch parser.encoding {
case yaml_UTF8_ENCODING:
// Decode a UTF-8 character. Check RFC 3629
// (http://www.ietf.org/rfc/rfc3629.txt) for more details.
//
// The following table (taken from the RFC) is used for
// decoding.
//
// Char. number range | UTF-8 octet sequence
// (hexadecimal) | (binary)
// --------------------+------------------------------------
// 0000 0000-0000 007F | 0xxxxxxx
// 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
// 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
// 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
//
// Additionally, the characters in the range 0xD800-0xDFFF
// are prohibited as they are reserved for use with UTF-16
// surrogate pairs.
// Determine the length of the UTF-8 sequence.
octet := parser.raw_buffer[parser.raw_buffer_pos]
switch {
case octet&0x80 == 0x00:
width = 1
case octet&0xE0 == 0xC0:
width = 2
case octet&0xF0 == 0xE0:
width = 3
case octet&0xF8 == 0xF0:
width = 4
default:
// The leading octet is invalid.
return yaml_parser_set_reader_error(parser,
"invalid leading UTF-8 octet",
parser.offset, int(octet))
}
// Check if the raw buffer contains an incomplete character.
if width > raw_unread {
if parser.eof {
return yaml_parser_set_reader_error(parser,
"incomplete UTF-8 octet sequence",
parser.offset, -1)
}
break inner
}
// Decode the leading octet.
switch {
case octet&0x80 == 0x00:
value = rune(octet & 0x7F)
case octet&0xE0 == 0xC0:
value = rune(octet & 0x1F)
case octet&0xF0 == 0xE0:
value = rune(octet & 0x0F)
case octet&0xF8 == 0xF0:
value = rune(octet & 0x07)
default:
value = 0
}
// Check and decode the trailing octets.
for k := 1; k < width; k++ {
octet = parser.raw_buffer[parser.raw_buffer_pos+k]
// Check if the octet is valid.
if (octet & 0xC0) != 0x80 {
return yaml_parser_set_reader_error(parser,
"invalid trailing UTF-8 octet",
parser.offset+k, int(octet))
}
// Decode the octet.
value = (value << 6) + rune(octet&0x3F)
}
// Check the length of the sequence against the value.
switch {
case width == 1:
case width == 2 && value >= 0x80:
case width == 3 && value >= 0x800:
case width == 4 && value >= 0x10000:
default:
return yaml_parser_set_reader_error(parser,
"invalid length of a UTF-8 sequence",
parser.offset, -1)
}
// Check the range of the value.
if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF {
return yaml_parser_set_reader_error(parser,
"invalid Unicode character",
parser.offset, int(value))
}
case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING:
var low, high int
if parser.encoding == yaml_UTF16LE_ENCODING {
low, high = 0, 1
} else {
low, high = 1, 0
}
// The UTF-16 encoding is not as simple as one might
// naively think. Check RFC 2781
// (http://www.ietf.org/rfc/rfc2781.txt).
//
// Normally, two subsequent bytes describe a Unicode
// character. However a special technique (called a
// surrogate pair) is used for specifying character
// values larger than 0xFFFF.
//
// A surrogate pair consists of two pseudo-characters:
// high surrogate area (0xD800-0xDBFF)
// low surrogate area (0xDC00-0xDFFF)
//
// The following formulas are used for decoding
// and encoding characters using surrogate pairs:
//
// U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF)
// U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF)
// W1 = 110110yyyyyyyyyy
// W2 = 110111xxxxxxxxxx
//
// where U is the character value, W1 is the high surrogate
// area, W2 is the low surrogate area.
// Check for incomplete UTF-16 character.
if raw_unread < 2 {
if parser.eof {
return yaml_parser_set_reader_error(parser,
"incomplete UTF-16 character",
parser.offset, -1)
}
break inner
}
// Get the character.
value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) +
(rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8)
// Check for unexpected low surrogate area.
if value&0xFC00 == 0xDC00 {
return yaml_parser_set_reader_error(parser,
"unexpected low surrogate area",
parser.offset, int(value))
}
// Check for a high surrogate area.
if value&0xFC00 == 0xD800 {
width = 4
// Check for incomplete surrogate pair.
if raw_unread < 4 {
if parser.eof {
return yaml_parser_set_reader_error(parser,
"incomplete UTF-16 surrogate pair",
parser.offset, -1)
}
break inner
}
// Get the next character.
value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) +
(rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8)
// Check for a low surrogate area.
if value2&0xFC00 != 0xDC00 {
return yaml_parser_set_reader_error(parser,
"expected low surrogate area",
parser.offset+2, int(value2))
}
// Generate the value of the surrogate pair.
value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF)
} else {
width = 2
}
default:
panic("impossible")
}
// Check if the character is in the allowed range:
// #x9 | #xA | #xD | [#x20-#x7E] (8 bit)
// | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit)
// | [#x10000-#x10FFFF] (32 bit)
switch {
case value == 0x09:
case value == 0x0A:
case value == 0x0D:
case value >= 0x20 && value <= 0x7E:
case value == 0x85:
case value >= 0xA0 && value <= 0xD7FF:
case value >= 0xE000 && value <= 0xFFFD:
case value >= 0x10000 && value <= 0x10FFFF:
default:
return yaml_parser_set_reader_error(parser,
"control characters are not allowed",
parser.offset, int(value))
}
// Move the raw pointers.
parser.raw_buffer_pos += width
parser.offset += width
// Finally put the character into the buffer.
if value <= 0x7F {
// 0000 0000-0000 007F . 0xxxxxxx
parser.buffer[buffer_len+0] = byte(value)
buffer_len += 1
} else if value <= 0x7FF {
// 0000 0080-0000 07FF . 110xxxxx 10xxxxxx
parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6))
parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F))
buffer_len += 2
} else if value <= 0xFFFF {
// 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx
parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12))
parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F))
parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F))
buffer_len += 3
} else {
// 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18))
parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F))
parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F))
parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F))
buffer_len += 4
}
parser.unread++
}
// On EOF, put NUL into the buffer and return.
if parser.eof {
parser.buffer[buffer_len] = 0
buffer_len++
parser.unread++
break
}
}
parser.buffer = parser.buffer[:buffer_len]
return true
}

203
vendor/github.com/go-yaml/yaml/resolve.go generated vendored Normal file
View File

@@ -0,0 +1,203 @@
package yaml
import (
"encoding/base64"
"math"
"strconv"
"strings"
"unicode/utf8"
)
type resolveMapItem struct {
value interface{}
tag string
}
var resolveTable = make([]byte, 256)
var resolveMap = make(map[string]resolveMapItem)
func init() {
t := resolveTable
t[int('+')] = 'S' // Sign
t[int('-')] = 'S'
for _, c := range "0123456789" {
t[int(c)] = 'D' // Digit
}
for _, c := range "yYnNtTfFoO~" {
t[int(c)] = 'M' // In map
}
t[int('.')] = '.' // Float (potentially in map)
var resolveMapList = []struct {
v interface{}
tag string
l []string
}{
{true, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}},
{true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}},
{true, yaml_BOOL_TAG, []string{"on", "On", "ON"}},
{false, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}},
{false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}},
{false, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}},
{nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}},
{math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}},
{math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}},
{math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}},
{math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}},
{"<<", yaml_MERGE_TAG, []string{"<<"}},
}
m := resolveMap
for _, item := range resolveMapList {
for _, s := range item.l {
m[s] = resolveMapItem{item.v, item.tag}
}
}
}
const longTagPrefix = "tag:yaml.org,2002:"
func shortTag(tag string) string {
// TODO This can easily be made faster and produce less garbage.
if strings.HasPrefix(tag, longTagPrefix) {
return "!!" + tag[len(longTagPrefix):]
}
return tag
}
func longTag(tag string) string {
if strings.HasPrefix(tag, "!!") {
return longTagPrefix + tag[2:]
}
return tag
}
func resolvableTag(tag string) bool {
switch tag {
case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG:
return true
}
return false
}
func resolve(tag string, in string) (rtag string, out interface{}) {
if !resolvableTag(tag) {
return tag, in
}
defer func() {
switch tag {
case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG:
return
}
failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag))
}()
// Any data is accepted as a !!str or !!binary.
// Otherwise, the prefix is enough of a hint about what it might be.
hint := byte('N')
if in != "" {
hint = resolveTable[in[0]]
}
if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG {
// Handle things we can lookup in a map.
if item, ok := resolveMap[in]; ok {
return item.tag, item.value
}
// Base 60 floats are a bad idea, were dropped in YAML 1.2, and
// are purposefully unsupported here. They're still quoted on
// the way out for compatibility with other parser, though.
switch hint {
case 'M':
// We've already checked the map above.
case '.':
// Not in the map, so maybe a normal float.
floatv, err := strconv.ParseFloat(in, 64)
if err == nil {
return yaml_FLOAT_TAG, floatv
}
case 'D', 'S':
// Int, float, or timestamp.
plain := strings.Replace(in, "_", "", -1)
intv, err := strconv.ParseInt(plain, 0, 64)
if err == nil {
if intv == int64(int(intv)) {
return yaml_INT_TAG, int(intv)
} else {
return yaml_INT_TAG, intv
}
}
uintv, err := strconv.ParseUint(plain, 0, 64)
if err == nil {
return yaml_INT_TAG, uintv
}
floatv, err := strconv.ParseFloat(plain, 64)
if err == nil {
return yaml_FLOAT_TAG, floatv
}
if strings.HasPrefix(plain, "0b") {
intv, err := strconv.ParseInt(plain[2:], 2, 64)
if err == nil {
if intv == int64(int(intv)) {
return yaml_INT_TAG, int(intv)
} else {
return yaml_INT_TAG, intv
}
}
uintv, err := strconv.ParseUint(plain[2:], 2, 64)
if err == nil {
return yaml_INT_TAG, uintv
}
} else if strings.HasPrefix(plain, "-0b") {
intv, err := strconv.ParseInt(plain[3:], 2, 64)
if err == nil {
if intv == int64(int(intv)) {
return yaml_INT_TAG, -int(intv)
} else {
return yaml_INT_TAG, -intv
}
}
}
// XXX Handle timestamps here.
default:
panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")")
}
}
if tag == yaml_BINARY_TAG {
return yaml_BINARY_TAG, in
}
if utf8.ValidString(in) {
return yaml_STR_TAG, in
}
return yaml_BINARY_TAG, encodeBase64(in)
}
// encodeBase64 encodes s as base64 that is broken up into multiple lines
// as appropriate for the resulting length.
func encodeBase64(s string) string {
const lineLen = 70
encLen := base64.StdEncoding.EncodedLen(len(s))
lines := encLen/lineLen + 1
buf := make([]byte, encLen*2+lines)
in := buf[0:encLen]
out := buf[encLen:]
base64.StdEncoding.Encode(in, []byte(s))
k := 0
for i := 0; i < len(in); i += lineLen {
j := i + lineLen
if j > len(in) {
j = len(in)
}
k += copy(out[k:], in[i:j])
if lines > 1 {
out[k] = '\n'
k++
}
}
return string(out[:k])
}

2710
vendor/github.com/go-yaml/yaml/scannerc.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

104
vendor/github.com/go-yaml/yaml/sorter.go generated vendored Normal file
View File

@@ -0,0 +1,104 @@
package yaml
import (
"reflect"
"unicode"
)
type keyList []reflect.Value
func (l keyList) Len() int { return len(l) }
func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func (l keyList) Less(i, j int) bool {
a := l[i]
b := l[j]
ak := a.Kind()
bk := b.Kind()
for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() {
a = a.Elem()
ak = a.Kind()
}
for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() {
b = b.Elem()
bk = b.Kind()
}
af, aok := keyFloat(a)
bf, bok := keyFloat(b)
if aok && bok {
if af != bf {
return af < bf
}
if ak != bk {
return ak < bk
}
return numLess(a, b)
}
if ak != reflect.String || bk != reflect.String {
return ak < bk
}
ar, br := []rune(a.String()), []rune(b.String())
for i := 0; i < len(ar) && i < len(br); i++ {
if ar[i] == br[i] {
continue
}
al := unicode.IsLetter(ar[i])
bl := unicode.IsLetter(br[i])
if al && bl {
return ar[i] < br[i]
}
if al || bl {
return bl
}
var ai, bi int
var an, bn int64
for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ {
an = an*10 + int64(ar[ai]-'0')
}
for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ {
bn = bn*10 + int64(br[bi]-'0')
}
if an != bn {
return an < bn
}
if ai != bi {
return ai < bi
}
return ar[i] < br[i]
}
return len(ar) < len(br)
}
// keyFloat returns a float value for v if it is a number/bool
// and whether it is a number/bool or not.
func keyFloat(v reflect.Value) (f float64, ok bool) {
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return float64(v.Int()), true
case reflect.Float32, reflect.Float64:
return v.Float(), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return float64(v.Uint()), true
case reflect.Bool:
if v.Bool() {
return 1, true
}
return 0, true
}
return 0, false
}
// numLess returns whether a < b.
// a and b must necessarily have the same kind.
func numLess(a, b reflect.Value) bool {
switch a.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return a.Int() < b.Int()
case reflect.Float32, reflect.Float64:
return a.Float() < b.Float()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return a.Uint() < b.Uint()
case reflect.Bool:
return !a.Bool() && b.Bool()
}
panic("not a number")
}

89
vendor/github.com/go-yaml/yaml/writerc.go generated vendored Normal file
View File

@@ -0,0 +1,89 @@
package yaml
// Set the writer error and return false.
func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool {
emitter.error = yaml_WRITER_ERROR
emitter.problem = problem
return false
}
// Flush the output buffer.
func yaml_emitter_flush(emitter *yaml_emitter_t) bool {
if emitter.write_handler == nil {
panic("write handler not set")
}
// Check if the buffer is empty.
if emitter.buffer_pos == 0 {
return true
}
// If the output encoding is UTF-8, we don't need to recode the buffer.
if emitter.encoding == yaml_UTF8_ENCODING {
if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil {
return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
}
emitter.buffer_pos = 0
return true
}
// Recode the buffer into the raw buffer.
var low, high int
if emitter.encoding == yaml_UTF16LE_ENCODING {
low, high = 0, 1
} else {
high, low = 1, 0
}
pos := 0
for pos < emitter.buffer_pos {
// See the "reader.c" code for more details on UTF-8 encoding. Note
// that we assume that the buffer contains a valid UTF-8 sequence.
// Read the next UTF-8 character.
octet := emitter.buffer[pos]
var w int
var value rune
switch {
case octet&0x80 == 0x00:
w, value = 1, rune(octet&0x7F)
case octet&0xE0 == 0xC0:
w, value = 2, rune(octet&0x1F)
case octet&0xF0 == 0xE0:
w, value = 3, rune(octet&0x0F)
case octet&0xF8 == 0xF0:
w, value = 4, rune(octet&0x07)
}
for k := 1; k < w; k++ {
octet = emitter.buffer[pos+k]
value = (value << 6) + (rune(octet) & 0x3F)
}
pos += w
// Write the character.
if value < 0x10000 {
var b [2]byte
b[high] = byte(value >> 8)
b[low] = byte(value & 0xFF)
emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1])
} else {
// Write the character using a surrogate pair (check "reader.c").
var b [4]byte
value -= 0x10000
b[high] = byte(0xD8 + (value >> 18))
b[low] = byte((value >> 10) & 0xFF)
b[high+2] = byte(0xDC + ((value >> 8) & 0xFF))
b[low+2] = byte(value & 0xFF)
emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1], b[2], b[3])
}
}
// Write the raw buffer.
if err := emitter.write_handler(emitter, emitter.raw_buffer); err != nil {
return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
}
emitter.buffer_pos = 0
emitter.raw_buffer = emitter.raw_buffer[:0]
return true
}

346
vendor/github.com/go-yaml/yaml/yaml.go generated vendored Normal file
View File

@@ -0,0 +1,346 @@
// Package yaml implements YAML support for the Go language.
//
// Source code and other details for the project are available at GitHub:
//
// https://github.com/go-yaml/yaml
//
package yaml
import (
"errors"
"fmt"
"reflect"
"strings"
"sync"
)
// MapSlice encodes and decodes as a YAML map.
// The order of keys is preserved when encoding and decoding.
type MapSlice []MapItem
// MapItem is an item in a MapSlice.
type MapItem struct {
Key, Value interface{}
}
// The Unmarshaler interface may be implemented by types to customize their
// behavior when being unmarshaled from a YAML document. The UnmarshalYAML
// method receives a function that may be called to unmarshal the original
// YAML value into a field or variable. It is safe to call the unmarshal
// function parameter more than once if necessary.
type Unmarshaler interface {
UnmarshalYAML(unmarshal func(interface{}) error) error
}
// The Marshaler interface may be implemented by types to customize their
// behavior when being marshaled into a YAML document. The returned value
// is marshaled in place of the original value implementing Marshaler.
//
// If an error is returned by MarshalYAML, the marshaling procedure stops
// and returns with the provided error.
type Marshaler interface {
MarshalYAML() (interface{}, error)
}
// Unmarshal decodes the first document found within the in byte slice
// and assigns decoded values into the out value.
//
// Maps and pointers (to a struct, string, int, etc) are accepted as out
// values. If an internal pointer within a struct is not initialized,
// the yaml package will initialize it if necessary for unmarshalling
// the provided data. The out parameter must not be nil.
//
// The type of the decoded values should be compatible with the respective
// values in out. If one or more values cannot be decoded due to a type
// mismatches, decoding continues partially until the end of the YAML
// content, and a *yaml.TypeError is returned with details for all
// missed values.
//
// Struct fields are only unmarshalled if they are exported (have an
// upper case first letter), and are unmarshalled using the field name
// lowercased as the default key. Custom keys may be defined via the
// "yaml" name in the field tag: the content preceding the first comma
// is used as the key, and the following comma-separated options are
// used to tweak the marshalling process (see Marshal).
// Conflicting names result in a runtime error.
//
// For example:
//
// type T struct {
// F int `yaml:"a,omitempty"`
// B int
// }
// var t T
// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t)
//
// See the documentation of Marshal for the format of tags and a list of
// supported tag options.
//
func Unmarshal(in []byte, out interface{}) (err error) {
defer handleErr(&err)
d := newDecoder()
p := newParser(in)
defer p.destroy()
node := p.parse()
if node != nil {
v := reflect.ValueOf(out)
if v.Kind() == reflect.Ptr && !v.IsNil() {
v = v.Elem()
}
d.unmarshal(node, v)
}
if len(d.terrors) > 0 {
return &TypeError{d.terrors}
}
return nil
}
// Marshal serializes the value provided into a YAML document. The structure
// of the generated document will reflect the structure of the value itself.
// Maps and pointers (to struct, string, int, etc) are accepted as the in value.
//
// Struct fields are only unmarshalled if they are exported (have an upper case
// first letter), and are unmarshalled using the field name lowercased as the
// default key. Custom keys may be defined via the "yaml" name in the field
// tag: the content preceding the first comma is used as the key, and the
// following comma-separated options are used to tweak the marshalling process.
// Conflicting names result in a runtime error.
//
// The field tag format accepted is:
//
// `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
//
// The following flags are currently supported:
//
// omitempty Only include the field if it's not set to the zero
// value for the type or to empty slices or maps.
// Does not apply to zero valued structs.
//
// flow Marshal using a flow style (useful for structs,
// sequences and maps).
//
// inline Inline the field, which must be a struct or a map,
// causing all of its fields or keys to be processed as if
// they were part of the outer struct. For maps, keys must
// not conflict with the yaml keys of other struct fields.
//
// In addition, if the key is "-", the field is ignored.
//
// For example:
//
// type T struct {
// F int "a,omitempty"
// B int
// }
// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n"
//
func Marshal(in interface{}) (out []byte, err error) {
defer handleErr(&err)
e := newEncoder()
defer e.destroy()
e.marshal("", reflect.ValueOf(in))
e.finish()
out = e.out
return
}
func handleErr(err *error) {
if v := recover(); v != nil {
if e, ok := v.(yamlError); ok {
*err = e.err
} else {
panic(v)
}
}
}
type yamlError struct {
err error
}
func fail(err error) {
panic(yamlError{err})
}
func failf(format string, args ...interface{}) {
panic(yamlError{fmt.Errorf("yaml: "+format, args...)})
}
// A TypeError is returned by Unmarshal when one or more fields in
// the YAML document cannot be properly decoded into the requested
// types. When this error is returned, the value is still
// unmarshaled partially.
type TypeError struct {
Errors []string
}
func (e *TypeError) Error() string {
return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n "))
}
// --------------------------------------------------------------------------
// Maintain a mapping of keys to structure field indexes
// The code in this section was copied from mgo/bson.
// structInfo holds details for the serialization of fields of
// a given struct.
type structInfo struct {
FieldsMap map[string]fieldInfo
FieldsList []fieldInfo
// InlineMap is the number of the field in the struct that
// contains an ,inline map, or -1 if there's none.
InlineMap int
}
type fieldInfo struct {
Key string
Num int
OmitEmpty bool
Flow bool
// Inline holds the field index if the field is part of an inlined struct.
Inline []int
}
var structMap = make(map[reflect.Type]*structInfo)
var fieldMapMutex sync.RWMutex
func getStructInfo(st reflect.Type) (*structInfo, error) {
fieldMapMutex.RLock()
sinfo, found := structMap[st]
fieldMapMutex.RUnlock()
if found {
return sinfo, nil
}
n := st.NumField()
fieldsMap := make(map[string]fieldInfo)
fieldsList := make([]fieldInfo, 0, n)
inlineMap := -1
for i := 0; i != n; i++ {
field := st.Field(i)
if field.PkgPath != "" && !field.Anonymous {
continue // Private field
}
info := fieldInfo{Num: i}
tag := field.Tag.Get("yaml")
if tag == "" && strings.Index(string(field.Tag), ":") < 0 {
tag = string(field.Tag)
}
if tag == "-" {
continue
}
inline := false
fields := strings.Split(tag, ",")
if len(fields) > 1 {
for _, flag := range fields[1:] {
switch flag {
case "omitempty":
info.OmitEmpty = true
case "flow":
info.Flow = true
case "inline":
inline = true
default:
return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st))
}
}
tag = fields[0]
}
if inline {
switch field.Type.Kind() {
case reflect.Map:
if inlineMap >= 0 {
return nil, errors.New("Multiple ,inline maps in struct " + st.String())
}
if field.Type.Key() != reflect.TypeOf("") {
return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String())
}
inlineMap = info.Num
case reflect.Struct:
sinfo, err := getStructInfo(field.Type)
if err != nil {
return nil, err
}
for _, finfo := range sinfo.FieldsList {
if _, found := fieldsMap[finfo.Key]; found {
msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String()
return nil, errors.New(msg)
}
if finfo.Inline == nil {
finfo.Inline = []int{i, finfo.Num}
} else {
finfo.Inline = append([]int{i}, finfo.Inline...)
}
fieldsMap[finfo.Key] = finfo
fieldsList = append(fieldsList, finfo)
}
default:
//return nil, errors.New("Option ,inline needs a struct value or map field")
return nil, errors.New("Option ,inline needs a struct value field")
}
continue
}
if tag != "" {
info.Key = tag
} else {
info.Key = strings.ToLower(field.Name)
}
if _, found = fieldsMap[info.Key]; found {
msg := "Duplicated key '" + info.Key + "' in struct " + st.String()
return nil, errors.New(msg)
}
fieldsList = append(fieldsList, info)
fieldsMap[info.Key] = info
}
sinfo = &structInfo{fieldsMap, fieldsList, inlineMap}
fieldMapMutex.Lock()
structMap[st] = sinfo
fieldMapMutex.Unlock()
return sinfo, nil
}
func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.String:
return len(v.String()) == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
case reflect.Slice:
return v.Len() == 0
case reflect.Map:
return v.Len() == 0
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Struct:
vt := v.Type()
for i := v.NumField() - 1; i >= 0; i-- {
if vt.Field(i).PkgPath != "" {
continue // Private field
}
if !isZero(v.Field(i)) {
return false
}
}
return true
}
return false
}

716
vendor/github.com/go-yaml/yaml/yamlh.go generated vendored Normal file
View File

@@ -0,0 +1,716 @@
package yaml
import (
"io"
)
// The version directive data.
type yaml_version_directive_t struct {
major int8 // The major version number.
minor int8 // The minor version number.
}
// The tag directive data.
type yaml_tag_directive_t struct {
handle []byte // The tag handle.
prefix []byte // The tag prefix.
}
type yaml_encoding_t int
// The stream encoding.
const (
// Let the parser choose the encoding.
yaml_ANY_ENCODING yaml_encoding_t = iota
yaml_UTF8_ENCODING // The default UTF-8 encoding.
yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM.
yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM.
)
type yaml_break_t int
// Line break types.
const (
// Let the parser choose the break type.
yaml_ANY_BREAK yaml_break_t = iota
yaml_CR_BREAK // Use CR for line breaks (Mac style).
yaml_LN_BREAK // Use LN for line breaks (Unix style).
yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style).
)
type yaml_error_type_t int
// Many bad things could happen with the parser and emitter.
const (
// No error is produced.
yaml_NO_ERROR yaml_error_type_t = iota
yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory.
yaml_READER_ERROR // Cannot read or decode the input stream.
yaml_SCANNER_ERROR // Cannot scan the input stream.
yaml_PARSER_ERROR // Cannot parse the input stream.
yaml_COMPOSER_ERROR // Cannot compose a YAML document.
yaml_WRITER_ERROR // Cannot write to the output stream.
yaml_EMITTER_ERROR // Cannot emit a YAML stream.
)
// The pointer position.
type yaml_mark_t struct {
index int // The position index.
line int // The position line.
column int // The position column.
}
// Node Styles
type yaml_style_t int8
type yaml_scalar_style_t yaml_style_t
// Scalar styles.
const (
// Let the emitter choose the style.
yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota
yaml_PLAIN_SCALAR_STYLE // The plain scalar style.
yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style.
yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style.
yaml_LITERAL_SCALAR_STYLE // The literal scalar style.
yaml_FOLDED_SCALAR_STYLE // The folded scalar style.
)
type yaml_sequence_style_t yaml_style_t
// Sequence styles.
const (
// Let the emitter choose the style.
yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota
yaml_BLOCK_SEQUENCE_STYLE // The block sequence style.
yaml_FLOW_SEQUENCE_STYLE // The flow sequence style.
)
type yaml_mapping_style_t yaml_style_t
// Mapping styles.
const (
// Let the emitter choose the style.
yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota
yaml_BLOCK_MAPPING_STYLE // The block mapping style.
yaml_FLOW_MAPPING_STYLE // The flow mapping style.
)
// Tokens
type yaml_token_type_t int
// Token types.
const (
// An empty token.
yaml_NO_TOKEN yaml_token_type_t = iota
yaml_STREAM_START_TOKEN // A STREAM-START token.
yaml_STREAM_END_TOKEN // A STREAM-END token.
yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token.
yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token.
yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token.
yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token.
yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token.
yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token.
yaml_BLOCK_END_TOKEN // A BLOCK-END token.
yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token.
yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token.
yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token.
yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token.
yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token.
yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token.
yaml_KEY_TOKEN // A KEY token.
yaml_VALUE_TOKEN // A VALUE token.
yaml_ALIAS_TOKEN // An ALIAS token.
yaml_ANCHOR_TOKEN // An ANCHOR token.
yaml_TAG_TOKEN // A TAG token.
yaml_SCALAR_TOKEN // A SCALAR token.
)
func (tt yaml_token_type_t) String() string {
switch tt {
case yaml_NO_TOKEN:
return "yaml_NO_TOKEN"
case yaml_STREAM_START_TOKEN:
return "yaml_STREAM_START_TOKEN"
case yaml_STREAM_END_TOKEN:
return "yaml_STREAM_END_TOKEN"
case yaml_VERSION_DIRECTIVE_TOKEN:
return "yaml_VERSION_DIRECTIVE_TOKEN"
case yaml_TAG_DIRECTIVE_TOKEN:
return "yaml_TAG_DIRECTIVE_TOKEN"
case yaml_DOCUMENT_START_TOKEN:
return "yaml_DOCUMENT_START_TOKEN"
case yaml_DOCUMENT_END_TOKEN:
return "yaml_DOCUMENT_END_TOKEN"
case yaml_BLOCK_SEQUENCE_START_TOKEN:
return "yaml_BLOCK_SEQUENCE_START_TOKEN"
case yaml_BLOCK_MAPPING_START_TOKEN:
return "yaml_BLOCK_MAPPING_START_TOKEN"
case yaml_BLOCK_END_TOKEN:
return "yaml_BLOCK_END_TOKEN"
case yaml_FLOW_SEQUENCE_START_TOKEN:
return "yaml_FLOW_SEQUENCE_START_TOKEN"
case yaml_FLOW_SEQUENCE_END_TOKEN:
return "yaml_FLOW_SEQUENCE_END_TOKEN"
case yaml_FLOW_MAPPING_START_TOKEN:
return "yaml_FLOW_MAPPING_START_TOKEN"
case yaml_FLOW_MAPPING_END_TOKEN:
return "yaml_FLOW_MAPPING_END_TOKEN"
case yaml_BLOCK_ENTRY_TOKEN:
return "yaml_BLOCK_ENTRY_TOKEN"
case yaml_FLOW_ENTRY_TOKEN:
return "yaml_FLOW_ENTRY_TOKEN"
case yaml_KEY_TOKEN:
return "yaml_KEY_TOKEN"
case yaml_VALUE_TOKEN:
return "yaml_VALUE_TOKEN"
case yaml_ALIAS_TOKEN:
return "yaml_ALIAS_TOKEN"
case yaml_ANCHOR_TOKEN:
return "yaml_ANCHOR_TOKEN"
case yaml_TAG_TOKEN:
return "yaml_TAG_TOKEN"
case yaml_SCALAR_TOKEN:
return "yaml_SCALAR_TOKEN"
}
return "<unknown token>"
}
// The token structure.
type yaml_token_t struct {
// The token type.
typ yaml_token_type_t
// The start/end of the token.
start_mark, end_mark yaml_mark_t
// The stream encoding (for yaml_STREAM_START_TOKEN).
encoding yaml_encoding_t
// The alias/anchor/scalar value or tag/tag directive handle
// (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN).
value []byte
// The tag suffix (for yaml_TAG_TOKEN).
suffix []byte
// The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN).
prefix []byte
// The scalar style (for yaml_SCALAR_TOKEN).
style yaml_scalar_style_t
// The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN).
major, minor int8
}
// Events
type yaml_event_type_t int8
// Event types.
const (
// An empty event.
yaml_NO_EVENT yaml_event_type_t = iota
yaml_STREAM_START_EVENT // A STREAM-START event.
yaml_STREAM_END_EVENT // A STREAM-END event.
yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event.
yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event.
yaml_ALIAS_EVENT // An ALIAS event.
yaml_SCALAR_EVENT // A SCALAR event.
yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event.
yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event.
yaml_MAPPING_START_EVENT // A MAPPING-START event.
yaml_MAPPING_END_EVENT // A MAPPING-END event.
)
// The event structure.
type yaml_event_t struct {
// The event type.
typ yaml_event_type_t
// The start and end of the event.
start_mark, end_mark yaml_mark_t
// The document encoding (for yaml_STREAM_START_EVENT).
encoding yaml_encoding_t
// The version directive (for yaml_DOCUMENT_START_EVENT).
version_directive *yaml_version_directive_t
// The list of tag directives (for yaml_DOCUMENT_START_EVENT).
tag_directives []yaml_tag_directive_t
// The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT).
anchor []byte
// The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT).
tag []byte
// The scalar value (for yaml_SCALAR_EVENT).
value []byte
// Is the document start/end indicator implicit, or the tag optional?
// (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT).
implicit bool
// Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT).
quoted_implicit bool
// The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT).
style yaml_style_t
}
func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) }
func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) }
func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) }
// Nodes
const (
yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null.
yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false.
yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values.
yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values.
yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values.
yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values.
yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences.
yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping.
// Not in original libyaml.
yaml_BINARY_TAG = "tag:yaml.org,2002:binary"
yaml_MERGE_TAG = "tag:yaml.org,2002:merge"
yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str.
yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq.
yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map.
)
type yaml_node_type_t int
// Node types.
const (
// An empty node.
yaml_NO_NODE yaml_node_type_t = iota
yaml_SCALAR_NODE // A scalar node.
yaml_SEQUENCE_NODE // A sequence node.
yaml_MAPPING_NODE // A mapping node.
)
// An element of a sequence node.
type yaml_node_item_t int
// An element of a mapping node.
type yaml_node_pair_t struct {
key int // The key of the element.
value int // The value of the element.
}
// The node structure.
type yaml_node_t struct {
typ yaml_node_type_t // The node type.
tag []byte // The node tag.
// The node data.
// The scalar parameters (for yaml_SCALAR_NODE).
scalar struct {
value []byte // The scalar value.
length int // The length of the scalar value.
style yaml_scalar_style_t // The scalar style.
}
// The sequence parameters (for YAML_SEQUENCE_NODE).
sequence struct {
items_data []yaml_node_item_t // The stack of sequence items.
style yaml_sequence_style_t // The sequence style.
}
// The mapping parameters (for yaml_MAPPING_NODE).
mapping struct {
pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value).
pairs_start *yaml_node_pair_t // The beginning of the stack.
pairs_end *yaml_node_pair_t // The end of the stack.
pairs_top *yaml_node_pair_t // The top of the stack.
style yaml_mapping_style_t // The mapping style.
}
start_mark yaml_mark_t // The beginning of the node.
end_mark yaml_mark_t // The end of the node.
}
// The document structure.
type yaml_document_t struct {
// The document nodes.
nodes []yaml_node_t
// The version directive.
version_directive *yaml_version_directive_t
// The list of tag directives.
tag_directives_data []yaml_tag_directive_t
tag_directives_start int // The beginning of the tag directives list.
tag_directives_end int // The end of the tag directives list.
start_implicit int // Is the document start indicator implicit?
end_implicit int // Is the document end indicator implicit?
// The start/end of the document.
start_mark, end_mark yaml_mark_t
}
// The prototype of a read handler.
//
// The read handler is called when the parser needs to read more bytes from the
// source. The handler should write not more than size bytes to the buffer.
// The number of written bytes should be set to the size_read variable.
//
// [in,out] data A pointer to an application data specified by
// yaml_parser_set_input().
// [out] buffer The buffer to write the data from the source.
// [in] size The size of the buffer.
// [out] size_read The actual number of bytes read from the source.
//
// On success, the handler should return 1. If the handler failed,
// the returned value should be 0. On EOF, the handler should set the
// size_read to 0 and return 1.
type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error)
// This structure holds information about a potential simple key.
type yaml_simple_key_t struct {
possible bool // Is a simple key possible?
required bool // Is a simple key required?
token_number int // The number of the token.
mark yaml_mark_t // The position mark.
}
// The states of the parser.
type yaml_parser_state_t int
const (
yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota
yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document.
yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START.
yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document.
yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END.
yaml_PARSE_BLOCK_NODE_STATE // Expect a block node.
yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence.
yaml_PARSE_FLOW_NODE_STATE // Expect a flow node.
yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence.
yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence.
yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence.
yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping.
yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key.
yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value.
yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence.
yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence.
yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping.
yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping.
yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry.
yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping.
yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping.
yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping.
yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping.
yaml_PARSE_END_STATE // Expect nothing.
)
func (ps yaml_parser_state_t) String() string {
switch ps {
case yaml_PARSE_STREAM_START_STATE:
return "yaml_PARSE_STREAM_START_STATE"
case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE:
return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE"
case yaml_PARSE_DOCUMENT_START_STATE:
return "yaml_PARSE_DOCUMENT_START_STATE"
case yaml_PARSE_DOCUMENT_CONTENT_STATE:
return "yaml_PARSE_DOCUMENT_CONTENT_STATE"
case yaml_PARSE_DOCUMENT_END_STATE:
return "yaml_PARSE_DOCUMENT_END_STATE"
case yaml_PARSE_BLOCK_NODE_STATE:
return "yaml_PARSE_BLOCK_NODE_STATE"
case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE:
return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE"
case yaml_PARSE_FLOW_NODE_STATE:
return "yaml_PARSE_FLOW_NODE_STATE"
case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE:
return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE"
case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE:
return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE"
case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE:
return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE"
case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE:
return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE"
case yaml_PARSE_BLOCK_MAPPING_KEY_STATE:
return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE"
case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE:
return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE"
case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE:
return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE"
case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE:
return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE"
case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE:
return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE"
case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE:
return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE"
case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE:
return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE"
case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE:
return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE"
case yaml_PARSE_FLOW_MAPPING_KEY_STATE:
return "yaml_PARSE_FLOW_MAPPING_KEY_STATE"
case yaml_PARSE_FLOW_MAPPING_VALUE_STATE:
return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE"
case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE:
return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE"
case yaml_PARSE_END_STATE:
return "yaml_PARSE_END_STATE"
}
return "<unknown parser state>"
}
// This structure holds aliases data.
type yaml_alias_data_t struct {
anchor []byte // The anchor.
index int // The node id.
mark yaml_mark_t // The anchor mark.
}
// The parser structure.
//
// All members are internal. Manage the structure using the
// yaml_parser_ family of functions.
type yaml_parser_t struct {
// Error handling
error yaml_error_type_t // Error type.
problem string // Error description.
// The byte about which the problem occured.
problem_offset int
problem_value int
problem_mark yaml_mark_t
// The error context.
context string
context_mark yaml_mark_t
// Reader stuff
read_handler yaml_read_handler_t // Read handler.
input_file io.Reader // File input data.
input []byte // String input data.
input_pos int
eof bool // EOF flag
buffer []byte // The working buffer.
buffer_pos int // The current position of the buffer.
unread int // The number of unread characters in the buffer.
raw_buffer []byte // The raw buffer.
raw_buffer_pos int // The current position of the buffer.
encoding yaml_encoding_t // The input encoding.
offset int // The offset of the current position (in bytes).
mark yaml_mark_t // The mark of the current position.
// Scanner stuff
stream_start_produced bool // Have we started to scan the input stream?
stream_end_produced bool // Have we reached the end of the input stream?
flow_level int // The number of unclosed '[' and '{' indicators.
tokens []yaml_token_t // The tokens queue.
tokens_head int // The head of the tokens queue.
tokens_parsed int // The number of tokens fetched from the queue.
token_available bool // Does the tokens queue contain a token ready for dequeueing.
indent int // The current indentation level.
indents []int // The indentation levels stack.
simple_key_allowed bool // May a simple key occur at the current position?
simple_keys []yaml_simple_key_t // The stack of simple keys.
// Parser stuff
state yaml_parser_state_t // The current parser state.
states []yaml_parser_state_t // The parser states stack.
marks []yaml_mark_t // The stack of marks.
tag_directives []yaml_tag_directive_t // The list of TAG directives.
// Dumper stuff
aliases []yaml_alias_data_t // The alias data.
document *yaml_document_t // The currently parsed document.
}
// Emitter Definitions
// The prototype of a write handler.
//
// The write handler is called when the emitter needs to flush the accumulated
// characters to the output. The handler should write @a size bytes of the
// @a buffer to the output.
//
// @param[in,out] data A pointer to an application data specified by
// yaml_emitter_set_output().
// @param[in] buffer The buffer with bytes to be written.
// @param[in] size The size of the buffer.
//
// @returns On success, the handler should return @c 1. If the handler failed,
// the returned value should be @c 0.
//
type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error
type yaml_emitter_state_t int
// The emitter states.
const (
// Expect STREAM-START.
yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota
yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END.
yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END.
yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document.
yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END.
yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence.
yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence.
yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping.
yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping.
yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping.
yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping.
yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence.
yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence.
yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping.
yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping.
yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping.
yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping.
yaml_EMIT_END_STATE // Expect nothing.
)
// The emitter structure.
//
// All members are internal. Manage the structure using the @c yaml_emitter_
// family of functions.
type yaml_emitter_t struct {
// Error handling
error yaml_error_type_t // Error type.
problem string // Error description.
// Writer stuff
write_handler yaml_write_handler_t // Write handler.
output_buffer *[]byte // String output data.
output_file io.Writer // File output data.
buffer []byte // The working buffer.
buffer_pos int // The current position of the buffer.
raw_buffer []byte // The raw buffer.
raw_buffer_pos int // The current position of the buffer.
encoding yaml_encoding_t // The stream encoding.
// Emitter stuff
canonical bool // If the output is in the canonical style?
best_indent int // The number of indentation spaces.
best_width int // The preferred width of the output lines.
unicode bool // Allow unescaped non-ASCII characters?
line_break yaml_break_t // The preferred line break.
state yaml_emitter_state_t // The current emitter state.
states []yaml_emitter_state_t // The stack of states.
events []yaml_event_t // The event queue.
events_head int // The head of the event queue.
indents []int // The stack of indentation levels.
tag_directives []yaml_tag_directive_t // The list of tag directives.
indent int // The current indentation level.
flow_level int // The current flow level.
root_context bool // Is it the document root context?
sequence_context bool // Is it a sequence context?
mapping_context bool // Is it a mapping context?
simple_key_context bool // Is it a simple mapping key context?
line int // The current line.
column int // The current column.
whitespace bool // If the last character was a whitespace?
indention bool // If the last character was an indentation character (' ', '-', '?', ':')?
open_ended bool // If an explicit document end is required?
// Anchor analysis.
anchor_data struct {
anchor []byte // The anchor value.
alias bool // Is it an alias?
}
// Tag analysis.
tag_data struct {
handle []byte // The tag handle.
suffix []byte // The tag suffix.
}
// Scalar analysis.
scalar_data struct {
value []byte // The scalar value.
multiline bool // Does the scalar contain line breaks?
flow_plain_allowed bool // Can the scalar be expessed in the flow plain style?
block_plain_allowed bool // Can the scalar be expressed in the block plain style?
single_quoted_allowed bool // Can the scalar be expressed in the single quoted style?
block_allowed bool // Can the scalar be expressed in the literal or folded styles?
style yaml_scalar_style_t // The output style.
}
// Dumper stuff
opened bool // If the stream was already opened?
closed bool // If the stream was already closed?
// The information associated with the document nodes.
anchors *struct {
references int // The number of references.
anchor int // The anchor id.
serialized bool // If the node has been emitted?
}
last_anchor_id int // The last assigned anchor id.
document *yaml_document_t // The currently emitted document.
}

173
vendor/github.com/go-yaml/yaml/yamlprivateh.go generated vendored Normal file
View File

@@ -0,0 +1,173 @@
package yaml
const (
// The size of the input raw buffer.
input_raw_buffer_size = 512
// The size of the input buffer.
// It should be possible to decode the whole raw buffer.
input_buffer_size = input_raw_buffer_size * 3
// The size of the output buffer.
output_buffer_size = 128
// The size of the output raw buffer.
// It should be possible to encode the whole output buffer.
output_raw_buffer_size = (output_buffer_size*2 + 2)
// The size of other stacks and queues.
initial_stack_size = 16
initial_queue_size = 16
initial_string_size = 16
)
// Check if the character at the specified position is an alphabetical
// character, a digit, '_', or '-'.
func is_alpha(b []byte, i int) bool {
return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-'
}
// Check if the character at the specified position is a digit.
func is_digit(b []byte, i int) bool {
return b[i] >= '0' && b[i] <= '9'
}
// Get the value of a digit.
func as_digit(b []byte, i int) int {
return int(b[i]) - '0'
}
// Check if the character at the specified position is a hex-digit.
func is_hex(b []byte, i int) bool {
return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f'
}
// Get the value of a hex-digit.
func as_hex(b []byte, i int) int {
bi := b[i]
if bi >= 'A' && bi <= 'F' {
return int(bi) - 'A' + 10
}
if bi >= 'a' && bi <= 'f' {
return int(bi) - 'a' + 10
}
return int(bi) - '0'
}
// Check if the character is ASCII.
func is_ascii(b []byte, i int) bool {
return b[i] <= 0x7F
}
// Check if the character at the start of the buffer can be printed unescaped.
func is_printable(b []byte, i int) bool {
return ((b[i] == 0x0A) || // . == #x0A
(b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E
(b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF
(b[i] > 0xC2 && b[i] < 0xED) ||
(b[i] == 0xED && b[i+1] < 0xA0) ||
(b[i] == 0xEE) ||
(b[i] == 0xEF && // #xE000 <= . <= #xFFFD
!(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF
!(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF))))
}
// Check if the character at the specified position is NUL.
func is_z(b []byte, i int) bool {
return b[i] == 0x00
}
// Check if the beginning of the buffer is a BOM.
func is_bom(b []byte, i int) bool {
return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF
}
// Check if the character at the specified position is space.
func is_space(b []byte, i int) bool {
return b[i] == ' '
}
// Check if the character at the specified position is tab.
func is_tab(b []byte, i int) bool {
return b[i] == '\t'
}
// Check if the character at the specified position is blank (space or tab).
func is_blank(b []byte, i int) bool {
//return is_space(b, i) || is_tab(b, i)
return b[i] == ' ' || b[i] == '\t'
}
// Check if the character at the specified position is a line break.
func is_break(b []byte, i int) bool {
return (b[i] == '\r' || // CR (#xD)
b[i] == '\n' || // LF (#xA)
b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029)
}
func is_crlf(b []byte, i int) bool {
return b[i] == '\r' && b[i+1] == '\n'
}
// Check if the character is a line break or NUL.
func is_breakz(b []byte, i int) bool {
//return is_break(b, i) || is_z(b, i)
return ( // is_break:
b[i] == '\r' || // CR (#xD)
b[i] == '\n' || // LF (#xA)
b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
// is_z:
b[i] == 0)
}
// Check if the character is a line break, space, or NUL.
func is_spacez(b []byte, i int) bool {
//return is_space(b, i) || is_breakz(b, i)
return ( // is_space:
b[i] == ' ' ||
// is_breakz:
b[i] == '\r' || // CR (#xD)
b[i] == '\n' || // LF (#xA)
b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
b[i] == 0)
}
// Check if the character is a line break, space, tab, or NUL.
func is_blankz(b []byte, i int) bool {
//return is_blank(b, i) || is_breakz(b, i)
return ( // is_blank:
b[i] == ' ' || b[i] == '\t' ||
// is_breakz:
b[i] == '\r' || // CR (#xD)
b[i] == '\n' || // LF (#xA)
b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
b[i] == 0)
}
// Determine the width of the character.
func width(b byte) int {
// Don't replace these by a switch without first
// confirming that it is being inlined.
if b&0x80 == 0x00 {
return 1
}
if b&0xE0 == 0xC0 {
return 2
}
if b&0xF0 == 0xE0 {
return 3
}
if b&0xF8 == 0xF0 {
return 4
}
return 0
}

View File

@@ -7,6 +7,7 @@ matrix:
- go: 1.4
- go: 1.5
- go: 1.6
- go: 1.7
- go: tip
allow_failures:
- go: tip

View File

@@ -4,4 +4,7 @@ context
gorilla/context is a general purpose registry for global request variables.
> Note: gorilla/context, having been born well before `context.Context` existed, does not play well
> with the shallow copying of the request that [`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext) (added to net/http Go 1.7 onwards) performs. You should either use *just* gorilla/context, or moving forward, the new `http.Request.Context()`.
Read the full documentation here: http://www.gorillatoolkit.org/pkg/context

View File

@@ -6,31 +6,32 @@ package context
import (
"net/http"
"net/url"
"sync"
"time"
)
var (
mutex sync.RWMutex
data = make(map[*http.Request]map[interface{}]interface{})
datat = make(map[*http.Request]int64)
data = make(map[*url.URL]map[interface{}]interface{})
datat = make(map[*url.URL]int64)
)
// Set stores a value for a given key in a given request.
func Set(r *http.Request, key, val interface{}) {
mutex.Lock()
if data[r] == nil {
data[r] = make(map[interface{}]interface{})
datat[r] = time.Now().Unix()
if data[r.URL] == nil {
data[r.URL] = make(map[interface{}]interface{})
datat[r.URL] = time.Now().Unix()
}
data[r][key] = val
data[r.URL][key] = val
mutex.Unlock()
}
// Get returns a value stored for a given key in a given request.
func Get(r *http.Request, key interface{}) interface{} {
mutex.RLock()
if ctx := data[r]; ctx != nil {
if ctx := data[r.URL]; ctx != nil {
value := ctx[key]
mutex.RUnlock()
return value
@@ -42,8 +43,8 @@ func Get(r *http.Request, key interface{}) interface{} {
// GetOk returns stored value and presence state like multi-value return of map access.
func GetOk(r *http.Request, key interface{}) (interface{}, bool) {
mutex.RLock()
if _, ok := data[r]; ok {
value, ok := data[r][key]
if _, ok := data[r.URL]; ok {
value, ok := data[r.URL][key]
mutex.RUnlock()
return value, ok
}
@@ -54,7 +55,7 @@ func GetOk(r *http.Request, key interface{}) (interface{}, bool) {
// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests.
func GetAll(r *http.Request) map[interface{}]interface{} {
mutex.RLock()
if context, ok := data[r]; ok {
if context, ok := data[r.URL]; ok {
result := make(map[interface{}]interface{}, len(context))
for k, v := range context {
result[k] = v
@@ -70,7 +71,7 @@ func GetAll(r *http.Request) map[interface{}]interface{} {
// the request was registered.
func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) {
mutex.RLock()
context, ok := data[r]
context, ok := data[r.URL]
result := make(map[interface{}]interface{}, len(context))
for k, v := range context {
result[k] = v
@@ -82,8 +83,8 @@ func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) {
// Delete removes a value stored for a given key in a given request.
func Delete(r *http.Request, key interface{}) {
mutex.Lock()
if data[r] != nil {
delete(data[r], key)
if data[r.URL] != nil {
delete(data[r.URL], key)
}
mutex.Unlock()
}
@@ -94,14 +95,14 @@ func Delete(r *http.Request, key interface{}) {
// variables at the end of a request lifetime. See ClearHandler().
func Clear(r *http.Request) {
mutex.Lock()
clear(r)
clear(r.URL)
mutex.Unlock()
}
// clear is Clear without the lock.
func clear(r *http.Request) {
delete(data, r)
delete(datat, r)
func clear(u *url.URL) {
delete(data, u)
delete(datat, u)
}
// Purge removes request data stored for longer than maxAge, in seconds.
@@ -118,13 +119,13 @@ func Purge(maxAge int) int {
count := 0
if maxAge <= 0 {
count = len(data)
data = make(map[*http.Request]map[interface{}]interface{})
datat = make(map[*http.Request]int64)
data = make(map[*url.URL]map[interface{}]interface{})
datat = make(map[*url.URL]int64)
} else {
min := time.Now().Unix() - int64(maxAge)
for r := range data {
if datat[r] < min {
clear(r)
for u := range data {
if datat[u] < min {
clear(u)
count++
}
}

View File

@@ -5,6 +5,12 @@
/*
Package context stores values shared during a request lifetime.
Note: gorilla/context, having been born well before `context.Context` existed,
does not play well > with the shallow copying of the request that
[`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext)
(added to net/http Go 1.7 onwards) performs. You should either use *just*
gorilla/context, or moving forward, the new `http.Request.Context()`.
For example, a router can set variables extracted from the URL and later
application handlers can access those values, or it can be used to store
sessions values to be saved at the end of a request. There are several

View File

@@ -6,6 +6,7 @@ matrix:
- go: 1.4
- go: 1.5
- go: 1.6
- go: 1.7
- go: tip
allow_failures:
- go: tip

Some files were not shown because too many files have changed in this diff Show More