summaryrefslogtreecommitdiffstats
path: root/vendor/github.com
diff options
context:
space:
mode:
authorCorey Hulen <corey@hulen.com>2017-03-24 23:31:34 -0700
committerenahum <nahumhbl@gmail.com>2017-03-25 03:31:34 -0300
commit54d3d47daf9190275bbdaf8703b84969a4593451 (patch)
tree05899b296d0186c1a0da8a540bc486e34ad8eec9 /vendor/github.com
parent7460302dec7796e01c98264e84bece8169cb6ed9 (diff)
downloadchat-54d3d47daf9190275bbdaf8703b84969a4593451.tar.gz
chat-54d3d47daf9190275bbdaf8703b84969a4593451.tar.bz2
chat-54d3d47daf9190275bbdaf8703b84969a4593451.zip
PLT-6076 Adding viper libs for config file changes (#5871)
* Adding viper libs for config file changes * Removing the old fsnotify lib * updating some missing libs
Diffstat (limited to 'vendor/github.com')
-rw-r--r--vendor/github.com/NYTimes/gziphandler/gzip.go1
-rw-r--r--vendor/github.com/NYTimes/gziphandler/gzip_test.go25
-rw-r--r--vendor/github.com/fsnotify/fsnotify/.editorconfig5
-rw-r--r--vendor/github.com/fsnotify/fsnotify/.github/ISSUE_TEMPLATE.md11
-rw-r--r--vendor/github.com/fsnotify/fsnotify/.github/PULL_REQUEST_TEMPLATE.md8
-rw-r--r--vendor/github.com/fsnotify/fsnotify/.gitignore6
-rw-r--r--vendor/github.com/fsnotify/fsnotify/.travis.yml28
-rw-r--r--vendor/github.com/fsnotify/fsnotify/AUTHORS46
-rw-r--r--vendor/github.com/fsnotify/fsnotify/CHANGELOG.md307
-rw-r--r--vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md77
-rw-r--r--vendor/github.com/fsnotify/fsnotify/LICENSE28
-rw-r--r--vendor/github.com/fsnotify/fsnotify/README.md50
-rw-r--r--vendor/github.com/fsnotify/fsnotify/example_test.go42
-rw-r--r--vendor/github.com/fsnotify/fsnotify/fen.go37
-rw-r--r--vendor/github.com/fsnotify/fsnotify/fsnotify.go62
-rw-r--r--vendor/github.com/fsnotify/fsnotify/fsnotify_test.go40
-rw-r--r--vendor/github.com/fsnotify/fsnotify/inotify.go325
-rw-r--r--vendor/github.com/fsnotify/fsnotify/inotify_poller.go187
-rw-r--r--vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go229
-rw-r--r--vendor/github.com/fsnotify/fsnotify/inotify_test.go360
-rw-r--r--vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go147
-rw-r--r--vendor/github.com/fsnotify/fsnotify/integration_test.go1237
-rw-r--r--vendor/github.com/fsnotify/fsnotify/kqueue.go503
-rw-r--r--vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go11
-rw-r--r--vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go12
-rw-r--r--vendor/github.com/fsnotify/fsnotify/windows.go561
-rw-r--r--vendor/github.com/hashicorp/hcl/.github/ISSUE_TEMPLATE.md21
-rw-r--r--vendor/github.com/hashicorp/hcl/.gitignore9
-rw-r--r--vendor/github.com/hashicorp/hcl/.travis.yml12
-rw-r--r--vendor/github.com/hashicorp/hcl/LICENSE354
-rw-r--r--vendor/github.com/hashicorp/hcl/Makefile18
-rw-r--r--vendor/github.com/hashicorp/hcl/README.md125
-rw-r--r--vendor/github.com/hashicorp/hcl/appveyor.yml19
-rw-r--r--vendor/github.com/hashicorp/hcl/decoder.go724
-rw-r--r--vendor/github.com/hashicorp/hcl/decoder_test.go1165
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl.go11
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/ast/ast.go219
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/ast/ast_test.go200
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/ast/walk.go52
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/fmtcmd/fmtcmd.go162
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/fmtcmd/fmtcmd_test.go440
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/.hidden.ignore1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/dir.ignore0
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/file.ignore1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/good.hcl0
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/error.go17
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/error_test.go9
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/parser.go514
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/parser_test.go566
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/array_comment.hcl4
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/array_comment_2.hcl6
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/assign_colon.hcl6
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/assign_deep.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment.hcl15
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment_lastline.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment_single.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/complex.hcl42
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/complex_key.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/empty.hcl0
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/git_crypt.hclbin0 -> 10 bytes
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/key_without_value.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/list.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/list_comma.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/missing_braces.hcl4
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/multiple.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value.hcl3
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value2.hcl4
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value3.hcl4
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_without_value.hcl3
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_list_comma.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/old.hcl3
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure_basic.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure_empty.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/types.hcl7
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/unterminated_object.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/unterminated_object_2.hcl6
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go779
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/printer.go67
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/printer_test.go153
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment.golden36
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment.input37
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_aligned.golden32
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_aligned.input28
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_array.golden13
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_array.input13
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_end_file.golden6
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_end_file.input5
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_indent.golden12
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_indent.input13
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_no_stanza.golden7
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_no_stanza.input6
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_stanza.golden10
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_stanza.input10
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_newline.golden3
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_newline.input2
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_object_multi.golden9
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_object_multi.input9
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_standalone.golden17
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_standalone.input16
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/complexhcl.golden54
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/complexhcl.input53
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/empty_block.golden12
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/empty_block.input14
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list.golden43
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list.input37
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_comment.golden7
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_comment.input6
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_of_objects.golden10
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_of_objects.input10
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/multiline_string.golden7
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/multiline_string.input7
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_singleline.golden26
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_singleline.input19
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_with_heredoc.golden6
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_with_heredoc.input6
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go651
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/scanner/scanner_test.go591
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go241
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/strconv/quote_test.go96
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/array_comment.hcl4
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/assign_colon.hcl6
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/comment.hcl15
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/comment_single.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/complex.hcl42
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/complex_key.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/empty.hcl0
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/list.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/list_comma.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/multiple.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/old.hcl3
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure_basic.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure_empty.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/test-fixtures/types.hcl7
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/token/position.go46
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/token/token.go219
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl/token/token_test.go69
-rw-r--r--vendor/github.com/hashicorp/hcl/hcl_test.go19
-rw-r--r--vendor/github.com/hashicorp/hcl/json/parser/flatten.go117
-rw-r--r--vendor/github.com/hashicorp/hcl/json/parser/parser.go313
-rw-r--r--vendor/github.com/hashicorp/hcl/json/parser/parser_test.go384
-rw-r--r--vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/array.json4
-rw-r--r--vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/bad_input_128.json1
-rw-r--r--vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/bad_input_tf_8110.json7
-rw-r--r--vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/basic.json3
-rw-r--r--vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/good_input_tf_8110.json7
-rw-r--r--vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/object.json5
-rw-r--r--vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/types.json10
-rw-r--r--vendor/github.com/hashicorp/hcl/json/scanner/scanner.go451
-rw-r--r--vendor/github.com/hashicorp/hcl/json/scanner/scanner_test.go362
-rw-r--r--vendor/github.com/hashicorp/hcl/json/test-fixtures/array.json4
-rw-r--r--vendor/github.com/hashicorp/hcl/json/test-fixtures/basic.json3
-rw-r--r--vendor/github.com/hashicorp/hcl/json/test-fixtures/object.json5
-rw-r--r--vendor/github.com/hashicorp/hcl/json/test-fixtures/types.json10
-rw-r--r--vendor/github.com/hashicorp/hcl/json/token/position.go46
-rw-r--r--vendor/github.com/hashicorp/hcl/json/token/token.go118
-rw-r--r--vendor/github.com/hashicorp/hcl/json/token/token_test.go34
-rw-r--r--vendor/github.com/hashicorp/hcl/lex.go38
-rw-r--r--vendor/github.com/hashicorp/hcl/lex_test.go37
-rw-r--r--vendor/github.com/hashicorp/hcl/parse.go39
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/assign_deep.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/basic.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/basic.json4
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/basic_int_string.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/basic_squish.hcl3
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/block_assign.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/decode_policy.hcl15
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/decode_policy.json19
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/decode_tf_variable.hcl10
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/decode_tf_variable.json14
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/empty.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/escape.hcl6
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/escape_backslash.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/flat.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/float.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/float.json3
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/git_crypt.hclbin0 -> 10 bytes
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/interpolate.json3
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/list_of_lists.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/list_of_maps.hcl4
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/multiline.hcl4
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/multiline.json3
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/multiline_bad.hcl4
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/multiline_indented.hcl4
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/multiline_literal.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/multiline_literal_with_hil.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_eof.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_hanging_indent.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_marker.hcl1
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/nested_block_comment.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/nested_provider_bad.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/null_strings.json7
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/object_list.json15
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/object_with_bool.hcl6
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/scientific.hcl6
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/scientific.json8
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/slice_expand.hcl7
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure.json8
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure2.hcl9
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure2.json10
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure_flat.json8
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure_flatmap.hcl7
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure_list.hcl6
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure_list.json7
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure_list_deep.json16
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure_list_empty.json3
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure_multi.hcl7
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/structure_multi.json11
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/terraform_heroku.hcl5
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/terraform_heroku.json6
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/terraform_variable_invalid.json5
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/tfvars.hcl3
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/unterminated_block_comment.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/test-fixtures/unterminated_brace.hcl2
-rw-r--r--vendor/github.com/hashicorp/hcl/testhelper/unix2dos.go15
-rw-r--r--vendor/github.com/lib/pq/conn.go32
-rw-r--r--vendor/github.com/lib/pq/conn_go18.go64
-rw-r--r--vendor/github.com/lib/pq/go18_test.go54
-rw-r--r--vendor/github.com/magiconair/properties/.gitignore6
-rw-r--r--vendor/github.com/magiconair/properties/.travis.yml8
-rw-r--r--vendor/github.com/magiconair/properties/CHANGELOG.md96
-rw-r--r--vendor/github.com/magiconair/properties/LICENSE25
-rw-r--r--vendor/github.com/magiconair/properties/README.md100
-rw-r--r--vendor/github.com/magiconair/properties/assert/assert.go90
-rw-r--r--vendor/github.com/magiconair/properties/assert/assert_test.go55
-rw-r--r--vendor/github.com/magiconair/properties/benchmark_test.go24
-rw-r--r--vendor/github.com/magiconair/properties/decode.go289
-rw-r--r--vendor/github.com/magiconair/properties/decode_test.go299
-rw-r--r--vendor/github.com/magiconair/properties/doc.go156
-rw-r--r--vendor/github.com/magiconair/properties/example_test.go93
-rw-r--r--vendor/github.com/magiconair/properties/integrate.go34
-rw-r--r--vendor/github.com/magiconair/properties/integrate_test.go76
-rw-r--r--vendor/github.com/magiconair/properties/lex.go408
-rw-r--r--vendor/github.com/magiconair/properties/load.go241
-rw-r--r--vendor/github.com/magiconair/properties/load_test.go231
-rw-r--r--vendor/github.com/magiconair/properties/parser.go95
-rw-r--r--vendor/github.com/magiconair/properties/properties.go808
-rw-r--r--vendor/github.com/magiconair/properties/properties_test.go934
-rw-r--r--vendor/github.com/magiconair/properties/rangecheck.go31
-rw-r--r--vendor/github.com/miekg/dns/README.md1
-rw-r--r--vendor/github.com/miekg/dns/client.go2
-rw-r--r--vendor/github.com/miekg/dns/issue_test.go47
-rw-r--r--vendor/github.com/miekg/dns/msg.go13
-rw-r--r--vendor/github.com/miekg/dns/msg_generate.go13
-rw-r--r--vendor/github.com/miekg/dns/msg_helpers.go5
-rw-r--r--vendor/github.com/miekg/dns/zmsg.go20
-rw-r--r--vendor/github.com/mitchellh/mapstructure/.travis.yml7
-rw-r--r--vendor/github.com/mitchellh/mapstructure/LICENSE21
-rw-r--r--vendor/github.com/mitchellh/mapstructure/README.md46
-rw-r--r--vendor/github.com/mitchellh/mapstructure/decode_hooks.go154
-rw-r--r--vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go229
-rw-r--r--vendor/github.com/mitchellh/mapstructure/error.go50
-rw-r--r--vendor/github.com/mitchellh/mapstructure/mapstructure.go823
-rw-r--r--vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go279
-rw-r--r--vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go260
-rw-r--r--vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go203
-rw-r--r--vendor/github.com/mitchellh/mapstructure/mapstructure_test.go1193
-rw-r--r--vendor/github.com/pelletier/go-buffruneio/.gitignore1
-rw-r--r--vendor/github.com/pelletier/go-buffruneio/.travis.yml7
-rw-r--r--vendor/github.com/pelletier/go-buffruneio/README.md62
-rw-r--r--vendor/github.com/pelletier/go-buffruneio/buffruneio.go117
-rw-r--r--vendor/github.com/pelletier/go-buffruneio/buffruneio_test.go145
-rw-r--r--vendor/github.com/pelletier/go-toml/.gitignore1
-rw-r--r--vendor/github.com/pelletier/go-toml/.travis.yml21
-rw-r--r--vendor/github.com/pelletier/go-toml/LICENSE21
-rw-r--r--vendor/github.com/pelletier/go-toml/README.md120
-rwxr-xr-xvendor/github.com/pelletier/go-toml/clean.sh6
-rw-r--r--vendor/github.com/pelletier/go-toml/cmd/test_program.go91
-rw-r--r--vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go67
-rw-r--r--vendor/github.com/pelletier/go-toml/cmd/tomljson/main_test.go82
-rw-r--r--vendor/github.com/pelletier/go-toml/cmd/tomll/main.go61
-rw-r--r--vendor/github.com/pelletier/go-toml/doc.go250
-rw-r--r--vendor/github.com/pelletier/go-toml/doc_test.go81
-rw-r--r--vendor/github.com/pelletier/go-toml/example-crlf.toml29
-rw-r--r--vendor/github.com/pelletier/go-toml/example.toml29
-rw-r--r--vendor/github.com/pelletier/go-toml/keysparsing.go94
-rw-r--r--vendor/github.com/pelletier/go-toml/keysparsing_test.go56
-rw-r--r--vendor/github.com/pelletier/go-toml/lexer.go657
-rw-r--r--vendor/github.com/pelletier/go-toml/lexer_test.go750
-rw-r--r--vendor/github.com/pelletier/go-toml/match.go234
-rw-r--r--vendor/github.com/pelletier/go-toml/match_test.go201
-rw-r--r--vendor/github.com/pelletier/go-toml/parser.go393
-rw-r--r--vendor/github.com/pelletier/go-toml/parser_test.go785
-rw-r--r--vendor/github.com/pelletier/go-toml/position.go29
-rw-r--r--vendor/github.com/pelletier/go-toml/position_test.go29
-rw-r--r--vendor/github.com/pelletier/go-toml/query.go153
-rw-r--r--vendor/github.com/pelletier/go-toml/query_test.go70
-rw-r--r--vendor/github.com/pelletier/go-toml/querylexer.go356
-rw-r--r--vendor/github.com/pelletier/go-toml/querylexer_test.go178
-rw-r--r--vendor/github.com/pelletier/go-toml/queryparser.go275
-rw-r--r--vendor/github.com/pelletier/go-toml/queryparser_test.go483
-rwxr-xr-xvendor/github.com/pelletier/go-toml/test.sh82
-rw-r--r--vendor/github.com/pelletier/go-toml/token.go140
-rw-r--r--vendor/github.com/pelletier/go-toml/token_test.go67
-rw-r--r--vendor/github.com/pelletier/go-toml/toml.go284
-rw-r--r--vendor/github.com/pelletier/go-toml/toml_test.go131
-rw-r--r--vendor/github.com/pelletier/go-toml/tomltree_create.go135
-rw-r--r--vendor/github.com/pelletier/go-toml/tomltree_create_test.go126
-rw-r--r--vendor/github.com/pelletier/go-toml/tomltree_write.go214
-rw-r--r--vendor/github.com/pelletier/go-toml/tomltree_write_test.go271
-rw-r--r--vendor/github.com/spf13/afero/.travis.yml20
-rw-r--r--vendor/github.com/spf13/afero/LICENSE.txt174
-rw-r--r--vendor/github.com/spf13/afero/README.md449
-rw-r--r--vendor/github.com/spf13/afero/afero.go108
-rw-r--r--vendor/github.com/spf13/afero/afero_test.go699
-rw-r--r--vendor/github.com/spf13/afero/appveyor.yml15
-rw-r--r--vendor/github.com/spf13/afero/basepath.go145
-rw-r--r--vendor/github.com/spf13/afero/basepath_test.go142
-rw-r--r--vendor/github.com/spf13/afero/cacheOnReadFs.go295
-rw-r--r--vendor/github.com/spf13/afero/composite_test.go368
-rw-r--r--vendor/github.com/spf13/afero/const_bsds.go22
-rw-r--r--vendor/github.com/spf13/afero/const_win_unix.go25
-rw-r--r--vendor/github.com/spf13/afero/copyOnWriteFs.go253
-rw-r--r--vendor/github.com/spf13/afero/copyOnWriteFs_test.go23
-rw-r--r--vendor/github.com/spf13/afero/httpFs.go110
-rw-r--r--vendor/github.com/spf13/afero/ioutil.go230
-rw-r--r--vendor/github.com/spf13/afero/ioutil_test.go112
-rw-r--r--vendor/github.com/spf13/afero/mem/dir.go37
-rw-r--r--vendor/github.com/spf13/afero/mem/dirmap.go43
-rw-r--r--vendor/github.com/spf13/afero/mem/file.go285
-rw-r--r--vendor/github.com/spf13/afero/memmap.go361
-rw-r--r--vendor/github.com/spf13/afero/memmap_test.go345
-rw-r--r--vendor/github.com/spf13/afero/memradix.go14
-rw-r--r--vendor/github.com/spf13/afero/os.go94
-rw-r--r--vendor/github.com/spf13/afero/path.go108
-rw-r--r--vendor/github.com/spf13/afero/path_test.go69
-rw-r--r--vendor/github.com/spf13/afero/readonlyfs.go70
-rw-r--r--vendor/github.com/spf13/afero/regexpfs.go214
-rw-r--r--vendor/github.com/spf13/afero/ro_regexp_test.go96
-rw-r--r--vendor/github.com/spf13/afero/sftpfs/file.go95
-rw-r--r--vendor/github.com/spf13/afero/sftpfs/sftp.go129
-rw-r--r--vendor/github.com/spf13/afero/sftpfs/sftp_test_go286
-rw-r--r--vendor/github.com/spf13/afero/unionFile.go274
-rw-r--r--vendor/github.com/spf13/afero/util.go331
-rw-r--r--vendor/github.com/spf13/afero/util_test.go450
-rw-r--r--vendor/github.com/spf13/cast/.gitignore25
-rw-r--r--vendor/github.com/spf13/cast/.travis.yml14
-rw-r--r--vendor/github.com/spf13/cast/LICENSE21
-rw-r--r--vendor/github.com/spf13/cast/Makefile38
-rw-r--r--vendor/github.com/spf13/cast/README.md75
-rw-r--r--vendor/github.com/spf13/cast/cast.go153
-rw-r--r--vendor/github.com/spf13/cast/cast_test.go1151
-rw-r--r--vendor/github.com/spf13/cast/caste.go1117
-rw-r--r--vendor/github.com/spf13/cobra/command.go1
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/.gitignore22
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/LICENSE21
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/README.md148
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/default_notepad.go113
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go102
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/log_counter.go56
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/notepad.go195
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/notepad_test.go41
-rw-r--r--vendor/github.com/spf13/viper/.gitignore24
-rw-r--r--vendor/github.com/spf13/viper/.travis.yml26
-rw-r--r--vendor/github.com/spf13/viper/LICENSE21
-rw-r--r--vendor/github.com/spf13/viper/README.md621
-rw-r--r--vendor/github.com/spf13/viper/flags.go57
-rw-r--r--vendor/github.com/spf13/viper/flags_test.go66
-rw-r--r--vendor/github.com/spf13/viper/nohup.out1
-rw-r--r--vendor/github.com/spf13/viper/overrides_test.go173
-rw-r--r--vendor/github.com/spf13/viper/remote/remote.go107
-rw-r--r--vendor/github.com/spf13/viper/util.go282
-rw-r--r--vendor/github.com/spf13/viper/util_test.go55
-rw-r--r--vendor/github.com/spf13/viper/viper.go1550
-rw-r--r--vendor/github.com/spf13/viper/viper_test.go1154
-rw-r--r--vendor/github.com/xenolf/lego/acme/client.go18
-rw-r--r--vendor/github.com/xenolf/lego/acme/jws.go5
-rw-r--r--vendor/github.com/xenolf/lego/providers/dns/dnsimple/dnsimple.go117
-rw-r--r--vendor/github.com/xenolf/lego/providers/dns/dnsimple/dnsimple_test.go113
371 files changed, 44107 insertions, 134 deletions
diff --git a/vendor/github.com/NYTimes/gziphandler/gzip.go b/vendor/github.com/NYTimes/gziphandler/gzip.go
index fbc99396d..23efacc45 100644
--- a/vendor/github.com/NYTimes/gziphandler/gzip.go
+++ b/vendor/github.com/NYTimes/gziphandler/gzip.go
@@ -117,6 +117,7 @@ func (w *GzipResponseWriter) Close() error {
err := w.gw.Close()
gzipWriterPools[w.index].Put(w.gw)
+ w.gw = nil
return err
}
diff --git a/vendor/github.com/NYTimes/gziphandler/gzip_test.go b/vendor/github.com/NYTimes/gziphandler/gzip_test.go
index f2d44e04f..80f54c77d 100644
--- a/vendor/github.com/NYTimes/gziphandler/gzip_test.go
+++ b/vendor/github.com/NYTimes/gziphandler/gzip_test.go
@@ -215,6 +215,31 @@ func TestGzipHandlerContentLength(t *testing.T) {
assert.NotEqual(t, b, body)
}
+func TestGzipDoubleClose(t *testing.T) {
+ // reset the pool for the default compression so we can make sure duplicates
+ // aren't added back by double close
+ addLevelPool(gzip.DefaultCompression)
+
+ handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // call close here and it'll get called again interally by
+ // NewGzipLevelHandler's handler defer
+ w.Write([]byte("test"))
+ w.(io.Closer).Close()
+ }))
+
+ r := httptest.NewRequest("GET", "/", nil)
+ r.Header.Set("Accept-Encoding", "gzip")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, r)
+
+ // the second close shouldn't have added the same writer
+ // so we pull out 2 writers from the pool and make sure they're different
+ w1 := gzipWriterPools[poolIndex(gzip.DefaultCompression)].Get()
+ w2 := gzipWriterPools[poolIndex(gzip.DefaultCompression)].Get()
+ // assert.NotEqual looks at the value and not the address, so we use regular ==
+ assert.False(t, w1 == w2)
+}
+
// --------------------------------------------------------------------
func BenchmarkGzipHandler_S2k(b *testing.B) { benchmark(b, false, 2048) }
diff --git a/vendor/github.com/fsnotify/fsnotify/.editorconfig b/vendor/github.com/fsnotify/fsnotify/.editorconfig
new file mode 100644
index 000000000..ba49e3c23
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/.editorconfig
@@ -0,0 +1,5 @@
+root = true
+
+[*]
+indent_style = tab
+indent_size = 4
diff --git a/vendor/github.com/fsnotify/fsnotify/.github/ISSUE_TEMPLATE.md b/vendor/github.com/fsnotify/fsnotify/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 000000000..4ad1aed8f
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,11 @@
+Before reporting an issue, please ensure you are using the latest release of fsnotify.
+
+### Which operating system (GOOS) and version are you using?
+
+Linux: lsb_release -a
+macOS: sw_vers
+Windows: systeminfo | findstr /B /C:OS
+
+### Please describe the issue that occurred.
+
+### Are you able to reproduce the issue? Please provide steps to reproduce and a code sample if possible.
diff --git a/vendor/github.com/fsnotify/fsnotify/.github/PULL_REQUEST_TEMPLATE.md b/vendor/github.com/fsnotify/fsnotify/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 000000000..64ddf7cef
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,8 @@
+#### What does this pull request do?
+
+
+#### Where should the reviewer start?
+
+
+#### How should this be manually tested?
+
diff --git a/vendor/github.com/fsnotify/fsnotify/.gitignore b/vendor/github.com/fsnotify/fsnotify/.gitignore
new file mode 100644
index 000000000..4cd0cbaf4
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/.gitignore
@@ -0,0 +1,6 @@
+# Setup a Global .gitignore for OS and editor generated files:
+# https://help.github.com/articles/ignoring-files
+# git config --global core.excludesfile ~/.gitignore_global
+
+.vagrant
+*.sublime-project
diff --git a/vendor/github.com/fsnotify/fsnotify/.travis.yml b/vendor/github.com/fsnotify/fsnotify/.travis.yml
new file mode 100644
index 000000000..3a5c933bc
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/.travis.yml
@@ -0,0 +1,28 @@
+sudo: false
+language: go
+
+go:
+ - 1.6.3
+ - tip
+
+matrix:
+ allow_failures:
+ - go: tip
+
+before_script:
+ - go get -u github.com/golang/lint/golint
+
+script:
+ - go test -v --race ./...
+
+after_script:
+ - test -z "$(gofmt -s -l -w . | tee /dev/stderr)"
+ - test -z "$(golint ./... | tee /dev/stderr)"
+ - go vet ./...
+
+os:
+ - linux
+ - osx
+
+notifications:
+ email: false
diff --git a/vendor/github.com/fsnotify/fsnotify/AUTHORS b/vendor/github.com/fsnotify/fsnotify/AUTHORS
new file mode 100644
index 000000000..0a5bf8f61
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/AUTHORS
@@ -0,0 +1,46 @@
+# Names should be added to this file as
+# Name or Organization <email address>
+# The email address is not required for organizations.
+
+# You can update this list using the following command:
+#
+# $ git shortlog -se | awk '{print $2 " " $3 " " $4}'
+
+# Please keep the list sorted.
+
+Adrien Bustany <adrien@bustany.org>
+Amit Krishnan <amit.krishnan@oracle.com>
+Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
+Bruno Bigras <bigras.bruno@gmail.com>
+Caleb Spare <cespare@gmail.com>
+Case Nelson <case@teammating.com>
+Chris Howey <chris@howey.me> <howeyc@gmail.com>
+Christoffer Buchholz <christoffer.buchholz@gmail.com>
+Daniel Wagner-Hall <dawagner@gmail.com>
+Dave Cheney <dave@cheney.net>
+Evan Phoenix <evan@fallingsnow.net>
+Francisco Souza <f@souza.cc>
+Hari haran <hariharan.uno@gmail.com>
+John C Barstow
+Kelvin Fo <vmirage@gmail.com>
+Ken-ichirou MATSUZAWA <chamas@h4.dion.ne.jp>
+Matt Layher <mdlayher@gmail.com>
+Nathan Youngman <git@nathany.com>
+Patrick <patrick@dropbox.com>
+Paul Hammond <paul@paulhammond.org>
+Pawel Knap <pawelknap88@gmail.com>
+Pieter Droogendijk <pieter@binky.org.uk>
+Pursuit92 <JoshChase@techpursuit.net>
+Riku Voipio <riku.voipio@linaro.org>
+Rob Figueiredo <robfig@gmail.com>
+Slawek Ligus <root@ooz.ie>
+Soge Zhang <zhssoge@gmail.com>
+Tiffany Jernigan <tiffany.jernigan@intel.com>
+Tilak Sharma <tilaks@google.com>
+Travis Cline <travis.cline@gmail.com>
+Tudor Golubenco <tudor.g@gmail.com>
+Yukang <moorekang@gmail.com>
+bronze1man <bronze1man@gmail.com>
+debrando <denis.brandolini@gmail.com>
+henrikedwards <henrik.edwards@gmail.com>
+铁哥 <guotie.9@gmail.com>
diff --git a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md
new file mode 100644
index 000000000..40d7660d5
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md
@@ -0,0 +1,307 @@
+# Changelog
+
+## v1.4.2 / 2016-10-10
+
+* Linux: use InotifyInit1 with IN_CLOEXEC to stop leaking a file descriptor to a child process when using fork/exec [#178](https://github.com/fsnotify/fsnotify/pull/178) (thanks @pattyshack)
+
+## v1.4.1 / 2016-10-04
+
+* Fix flaky inotify stress test on Linux [#177](https://github.com/fsnotify/fsnotify/pull/177) (thanks @pattyshack)
+
+## v1.4.0 / 2016-10-01
+
+* add a String() method to Event.Op [#165](https://github.com/fsnotify/fsnotify/pull/165) (thanks @oozie)
+
+## v1.3.1 / 2016-06-28
+
+* Windows: fix for double backslash when watching the root of a drive [#151](https://github.com/fsnotify/fsnotify/issues/151) (thanks @brunoqc)
+
+## v1.3.0 / 2016-04-19
+
+* Support linux/arm64 by [patching](https://go-review.googlesource.com/#/c/21971/) x/sys/unix and switching to to it from syscall (thanks @suihkulokki) [#135](https://github.com/fsnotify/fsnotify/pull/135)
+
+## v1.2.10 / 2016-03-02
+
+* Fix golint errors in windows.go [#121](https://github.com/fsnotify/fsnotify/pull/121) (thanks @tiffanyfj)
+
+## v1.2.9 / 2016-01-13
+
+kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsnotify/pull/111) (thanks @bep)
+
+## v1.2.8 / 2015-12-17
+
+* kqueue: fix race condition in Close [#105](https://github.com/fsnotify/fsnotify/pull/105) (thanks @djui for reporting the issue and @ppknap for writing a failing test)
+* inotify: fix race in test
+* enable race detection for continuous integration (Linux, Mac, Windows)
+
+## v1.2.5 / 2015-10-17
+
+* inotify: use epoll_create1 for arm64 support (requires Linux 2.6.27 or later) [#100](https://github.com/fsnotify/fsnotify/pull/100) (thanks @suihkulokki)
+* inotify: fix path leaks [#73](https://github.com/fsnotify/fsnotify/pull/73) (thanks @chamaken)
+* kqueue: watch for rename events on subdirectories [#83](https://github.com/fsnotify/fsnotify/pull/83) (thanks @guotie)
+* kqueue: avoid infinite loops from symlinks cycles [#101](https://github.com/fsnotify/fsnotify/pull/101) (thanks @illicitonion)
+
+## v1.2.1 / 2015-10-14
+
+* kqueue: don't watch named pipes [#98](https://github.com/fsnotify/fsnotify/pull/98) (thanks @evanphx)
+
+## v1.2.0 / 2015-02-08
+
+* inotify: use epoll to wake up readEvents [#66](https://github.com/fsnotify/fsnotify/pull/66) (thanks @PieterD)
+* inotify: closing watcher should now always shut down goroutine [#63](https://github.com/fsnotify/fsnotify/pull/63) (thanks @PieterD)
+* kqueue: close kqueue after removing watches, fixes [#59](https://github.com/fsnotify/fsnotify/issues/59)
+
+## v1.1.1 / 2015-02-05
+
+* inotify: Retry read on EINTR [#61](https://github.com/fsnotify/fsnotify/issues/61) (thanks @PieterD)
+
+## v1.1.0 / 2014-12-12
+
+* kqueue: rework internals [#43](https://github.com/fsnotify/fsnotify/pull/43)
+ * add low-level functions
+ * only need to store flags on directories
+ * less mutexes [#13](https://github.com/fsnotify/fsnotify/issues/13)
+ * done can be an unbuffered channel
+ * remove calls to os.NewSyscallError
+* More efficient string concatenation for Event.String() [#52](https://github.com/fsnotify/fsnotify/pull/52) (thanks @mdlayher)
+* kqueue: fix regression in rework causing subdirectories to be watched [#48](https://github.com/fsnotify/fsnotify/issues/48)
+* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51)
+
+## v1.0.4 / 2014-09-07
+
+* kqueue: add dragonfly to the build tags.
+* Rename source code files, rearrange code so exported APIs are at the top.
+* Add done channel to example code. [#37](https://github.com/fsnotify/fsnotify/pull/37) (thanks @chenyukang)
+
+## v1.0.3 / 2014-08-19
+
+* [Fix] Windows MOVED_TO now translates to Create like on BSD and Linux. [#36](https://github.com/fsnotify/fsnotify/issues/36)
+
+## v1.0.2 / 2014-08-17
+
+* [Fix] Missing create events on OS X. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso)
+* [Fix] Make ./path and path equivalent. (thanks @zhsso)
+
+## v1.0.0 / 2014-08-15
+
+* [API] Remove AddWatch on Windows, use Add.
+* Improve documentation for exported identifiers. [#30](https://github.com/fsnotify/fsnotify/issues/30)
+* Minor updates based on feedback from golint.
+
+## dev / 2014-07-09
+
+* Moved to [github.com/fsnotify/fsnotify](https://github.com/fsnotify/fsnotify).
+* Use os.NewSyscallError instead of returning errno (thanks @hariharan-uno)
+
+## dev / 2014-07-04
+
+* kqueue: fix incorrect mutex used in Close()
+* Update example to demonstrate usage of Op.
+
+## dev / 2014-06-28
+
+* [API] Don't set the Write Op for attribute notifications [#4](https://github.com/fsnotify/fsnotify/issues/4)
+* Fix for String() method on Event (thanks Alex Brainman)
+* Don't build on Plan 9 or Solaris (thanks @4ad)
+
+## dev / 2014-06-21
+
+* Events channel of type Event rather than *Event.
+* [internal] use syscall constants directly for inotify and kqueue.
+* [internal] kqueue: rename events to kevents and fileEvent to event.
+
+## dev / 2014-06-19
+
+* Go 1.3+ required on Windows (uses syscall.ERROR_MORE_DATA internally).
+* [internal] remove cookie from Event struct (unused).
+* [internal] Event struct has the same definition across every OS.
+* [internal] remove internal watch and removeWatch methods.
+
+## dev / 2014-06-12
+
+* [API] Renamed Watch() to Add() and RemoveWatch() to Remove().
+* [API] Pluralized channel names: Events and Errors.
+* [API] Renamed FileEvent struct to Event.
+* [API] Op constants replace methods like IsCreate().
+
+## dev / 2014-06-12
+
+* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98)
+
+## dev / 2014-05-23
+
+* [API] Remove current implementation of WatchFlags.
+ * current implementation doesn't take advantage of OS for efficiency
+ * provides little benefit over filtering events as they are received, but has extra bookkeeping and mutexes
+ * no tests for the current implementation
+ * not fully implemented on Windows [#93](https://github.com/howeyc/fsnotify/issues/93#issuecomment-39285195)
+
+## v0.9.3 / 2014-12-31
+
+* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51)
+
+## v0.9.2 / 2014-08-17
+
+* [Backport] Fix missing create events on OS X. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso)
+
+## v0.9.1 / 2014-06-12
+
+* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98)
+
+## v0.9.0 / 2014-01-17
+
+* IsAttrib() for events that only concern a file's metadata [#79][] (thanks @abustany)
+* [Fix] kqueue: fix deadlock [#77][] (thanks @cespare)
+* [NOTICE] Development has moved to `code.google.com/p/go.exp/fsnotify` in preparation for inclusion in the Go standard library.
+
+## v0.8.12 / 2013-11-13
+
+* [API] Remove FD_SET and friends from Linux adapter
+
+## v0.8.11 / 2013-11-02
+
+* [Doc] Add Changelog [#72][] (thanks @nathany)
+* [Doc] Spotlight and double modify events on OS X [#62][] (reported by @paulhammond)
+
+## v0.8.10 / 2013-10-19
+
+* [Fix] kqueue: remove file watches when parent directory is removed [#71][] (reported by @mdwhatcott)
+* [Fix] kqueue: race between Close and readEvents [#70][] (reported by @bernerdschaefer)
+* [Doc] specify OS-specific limits in README (thanks @debrando)
+
+## v0.8.9 / 2013-09-08
+
+* [Doc] Contributing (thanks @nathany)
+* [Doc] update package path in example code [#63][] (thanks @paulhammond)
+* [Doc] GoCI badge in README (Linux only) [#60][]
+* [Doc] Cross-platform testing with Vagrant [#59][] (thanks @nathany)
+
+## v0.8.8 / 2013-06-17
+
+* [Fix] Windows: handle `ERROR_MORE_DATA` on Windows [#49][] (thanks @jbowtie)
+
+## v0.8.7 / 2013-06-03
+
+* [API] Make syscall flags internal
+* [Fix] inotify: ignore event changes
+* [Fix] race in symlink test [#45][] (reported by @srid)
+* [Fix] tests on Windows
+* lower case error messages
+
+## v0.8.6 / 2013-05-23
+
+* kqueue: Use EVT_ONLY flag on Darwin
+* [Doc] Update README with full example
+
+## v0.8.5 / 2013-05-09
+
+* [Fix] inotify: allow monitoring of "broken" symlinks (thanks @tsg)
+
+## v0.8.4 / 2013-04-07
+
+* [Fix] kqueue: watch all file events [#40][] (thanks @ChrisBuchholz)
+
+## v0.8.3 / 2013-03-13
+
+* [Fix] inoitfy/kqueue memory leak [#36][] (reported by @nbkolchin)
+* [Fix] kqueue: use fsnFlags for watching a directory [#33][] (reported by @nbkolchin)
+
+## v0.8.2 / 2013-02-07
+
+* [Doc] add Authors
+* [Fix] fix data races for map access [#29][] (thanks @fsouza)
+
+## v0.8.1 / 2013-01-09
+
+* [Fix] Windows path separators
+* [Doc] BSD License
+
+## v0.8.0 / 2012-11-09
+
+* kqueue: directory watching improvements (thanks @vmirage)
+* inotify: add `IN_MOVED_TO` [#25][] (requested by @cpisto)
+* [Fix] kqueue: deleting watched directory [#24][] (reported by @jakerr)
+
+## v0.7.4 / 2012-10-09
+
+* [Fix] inotify: fixes from https://codereview.appspot.com/5418045/ (ugorji)
+* [Fix] kqueue: preserve watch flags when watching for delete [#21][] (reported by @robfig)
+* [Fix] kqueue: watch the directory even if it isn't a new watch (thanks @robfig)
+* [Fix] kqueue: modify after recreation of file
+
+## v0.7.3 / 2012-09-27
+
+* [Fix] kqueue: watch with an existing folder inside the watched folder (thanks @vmirage)
+* [Fix] kqueue: no longer get duplicate CREATE events
+
+## v0.7.2 / 2012-09-01
+
+* kqueue: events for created directories
+
+## v0.7.1 / 2012-07-14
+
+* [Fix] for renaming files
+
+## v0.7.0 / 2012-07-02
+
+* [Feature] FSNotify flags
+* [Fix] inotify: Added file name back to event path
+
+## v0.6.0 / 2012-06-06
+
+* kqueue: watch files after directory created (thanks @tmc)
+
+## v0.5.1 / 2012-05-22
+
+* [Fix] inotify: remove all watches before Close()
+
+## v0.5.0 / 2012-05-03
+
+* [API] kqueue: return errors during watch instead of sending over channel
+* kqueue: match symlink behavior on Linux
+* inotify: add `DELETE_SELF` (requested by @taralx)
+* [Fix] kqueue: handle EINTR (reported by @robfig)
+* [Doc] Godoc example [#1][] (thanks @davecheney)
+
+## v0.4.0 / 2012-03-30
+
+* Go 1 released: build with go tool
+* [Feature] Windows support using winfsnotify
+* Windows does not have attribute change notifications
+* Roll attribute notifications into IsModify
+
+## v0.3.0 / 2012-02-19
+
+* kqueue: add files when watch directory
+
+## v0.2.0 / 2011-12-30
+
+* update to latest Go weekly code
+
+## v0.1.0 / 2011-10-19
+
+* kqueue: add watch on file creation to match inotify
+* kqueue: create file event
+* inotify: ignore `IN_IGNORED` events
+* event String()
+* linux: common FileEvent functions
+* initial commit
+
+[#79]: https://github.com/howeyc/fsnotify/pull/79
+[#77]: https://github.com/howeyc/fsnotify/pull/77
+[#72]: https://github.com/howeyc/fsnotify/issues/72
+[#71]: https://github.com/howeyc/fsnotify/issues/71
+[#70]: https://github.com/howeyc/fsnotify/issues/70
+[#63]: https://github.com/howeyc/fsnotify/issues/63
+[#62]: https://github.com/howeyc/fsnotify/issues/62
+[#60]: https://github.com/howeyc/fsnotify/issues/60
+[#59]: https://github.com/howeyc/fsnotify/issues/59
+[#49]: https://github.com/howeyc/fsnotify/issues/49
+[#45]: https://github.com/howeyc/fsnotify/issues/45
+[#40]: https://github.com/howeyc/fsnotify/issues/40
+[#36]: https://github.com/howeyc/fsnotify/issues/36
+[#33]: https://github.com/howeyc/fsnotify/issues/33
+[#29]: https://github.com/howeyc/fsnotify/issues/29
+[#25]: https://github.com/howeyc/fsnotify/issues/25
+[#24]: https://github.com/howeyc/fsnotify/issues/24
+[#21]: https://github.com/howeyc/fsnotify/issues/21
diff --git a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md
new file mode 100644
index 000000000..6a81ba489
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md
@@ -0,0 +1,77 @@
+# Contributing
+
+## Issues
+
+* Request features and report bugs using the [GitHub Issue Tracker](https://github.com/fsnotify/fsnotify/issues).
+* Please indicate the platform you are using fsnotify on.
+* A code example to reproduce the problem is appreciated.
+
+## Pull Requests
+
+### Contributor License Agreement
+
+fsnotify is derived from code in the [golang.org/x/exp](https://godoc.org/golang.org/x/exp) package and it may be included [in the standard library](https://github.com/fsnotify/fsnotify/issues/1) in the future. Therefore fsnotify carries the same [LICENSE](https://github.com/fsnotify/fsnotify/blob/master/LICENSE) as Go. Contributors retain their copyright, so you need to fill out a short form before we can accept your contribution: [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual).
+
+Please indicate that you have signed the CLA in your pull request.
+
+### How fsnotify is Developed
+
+* Development is done on feature branches.
+* Tests are run on BSD, Linux, OS X and Windows.
+* Pull requests are reviewed and [applied to master][am] using [hub][].
+ * Maintainers may modify or squash commits rather than asking contributors to.
+* To issue a new release, the maintainers will:
+ * Update the CHANGELOG
+ * Tag a version, which will become available through gopkg.in.
+
+### How to Fork
+
+For smooth sailing, always use the original import path. Installing with `go get` makes this easy.
+
+1. Install from GitHub (`go get -u github.com/fsnotify/fsnotify`)
+2. Create your feature branch (`git checkout -b my-new-feature`)
+3. Ensure everything works and the tests pass (see below)
+4. Commit your changes (`git commit -am 'Add some feature'`)
+
+Contribute upstream:
+
+1. Fork fsnotify on GitHub
+2. Add your remote (`git remote add fork git@github.com:mycompany/repo.git`)
+3. Push to the branch (`git push fork my-new-feature`)
+4. Create a new Pull Request on GitHub
+
+This workflow is [thoroughly explained by Katrina Owen](https://splice.com/blog/contributing-open-source-git-repositories-go/).
+
+### Testing
+
+fsnotify uses build tags to compile different code on Linux, BSD, OS X, and Windows.
+
+Before doing a pull request, please do your best to test your changes on multiple platforms, and list which platforms you were able/unable to test on.
+
+To aid in cross-platform testing there is a Vagrantfile for Linux and BSD.
+
+* Install [Vagrant](http://www.vagrantup.com/) and [VirtualBox](https://www.virtualbox.org/)
+* Setup [Vagrant Gopher](https://github.com/nathany/vagrant-gopher) in your `src` folder.
+* Run `vagrant up` from the project folder. You can also setup just one box with `vagrant up linux` or `vagrant up bsd` (note: the BSD box doesn't support Windows hosts at this time, and NFS may prompt for your host OS password)
+* Once setup, you can run the test suite on a given OS with a single command `vagrant ssh linux -c 'cd fsnotify/fsnotify; go test'`.
+* When you're done, you will want to halt or destroy the Vagrant boxes.
+
+Notice: fsnotify file system events won't trigger in shared folders. The tests get around this limitation by using the /tmp directory.
+
+Right now there is no equivalent solution for Windows and OS X, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads).
+
+### Maintainers
+
+Help maintaining fsnotify is welcome. To be a maintainer:
+
+* Submit a pull request and sign the CLA as above.
+* You must be able to run the test suite on Mac, Windows, Linux and BSD.
+
+To keep master clean, the fsnotify project uses the "apply mail" workflow outlined in Nathaniel Talbott's post ["Merge pull request" Considered Harmful][am]. This requires installing [hub][].
+
+All code changes should be internal pull requests.
+
+Releases are tagged using [Semantic Versioning](http://semver.org/).
+
+[hub]: https://github.com/github/hub
+[am]: http://blog.spreedly.com/2014/06/24/merge-pull-request-considered-harmful/#.VGa5yZPF_Zs
diff --git a/vendor/github.com/fsnotify/fsnotify/LICENSE b/vendor/github.com/fsnotify/fsnotify/LICENSE
new file mode 100644
index 000000000..f21e54080
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/LICENSE
@@ -0,0 +1,28 @@
+Copyright (c) 2012 The Go Authors. All rights reserved.
+Copyright (c) 2012 fsnotify Authors. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md
new file mode 100644
index 000000000..3c891e349
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/README.md
@@ -0,0 +1,50 @@
+# File system notifications for Go
+
+[![GoDoc](https://godoc.org/github.com/fsnotify/fsnotify?status.svg)](https://godoc.org/github.com/fsnotify/fsnotify) [![Go Report Card](https://goreportcard.com/badge/github.com/fsnotify/fsnotify)](https://goreportcard.com/report/github.com/fsnotify/fsnotify)
+
+fsnotify utilizes [golang.org/x/sys](https://godoc.org/golang.org/x/sys) rather than `syscall` from the standard library. Ensure you have the latest version installed by running:
+
+```console
+go get -u golang.org/x/sys/...
+```
+
+Cross platform: Windows, Linux, BSD and OS X.
+
+|Adapter |OS |Status |
+|----------|----------|----------|
+|inotify |Linux 2.6.27 or later, Android\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)|
+|kqueue |BSD, OS X, iOS\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)|
+|ReadDirectoryChangesW|Windows|Supported [![Build status](https://ci.appveyor.com/api/projects/status/ivwjubaih4r0udeh/branch/master?svg=true)](https://ci.appveyor.com/project/NathanYoungman/fsnotify/branch/master)|
+|FSEvents |OS X |[Planned](https://github.com/fsnotify/fsnotify/issues/11)|
+|FEN |Solaris 11 |[In Progress](https://github.com/fsnotify/fsnotify/issues/12)|
+|fanotify |Linux 2.6.37+ | |
+|USN Journals |Windows |[Maybe](https://github.com/fsnotify/fsnotify/issues/53)|
+|Polling |*All* |[Maybe](https://github.com/fsnotify/fsnotify/issues/9)|
+
+\* Android and iOS are untested.
+
+Please see [the documentation](https://godoc.org/github.com/fsnotify/fsnotify) for usage. Consult the [Wiki](https://github.com/fsnotify/fsnotify/wiki) for the FAQ and further information.
+
+## API stability
+
+fsnotify is a fork of [howeyc/fsnotify](https://godoc.org/github.com/howeyc/fsnotify) with a new API as of v1.0. The API is based on [this design document](http://goo.gl/MrYxyA).
+
+All [releases](https://github.com/fsnotify/fsnotify/releases) are tagged based on [Semantic Versioning](http://semver.org/). Further API changes are [planned](https://github.com/fsnotify/fsnotify/milestones), and will be tagged with a new major revision number.
+
+Go 1.6 supports dependencies located in the `vendor/` folder. Unless you are creating a library, it is recommended that you copy fsnotify into `vendor/github.com/fsnotify/fsnotify` within your project, and likewise for `golang.org/x/sys`.
+
+## Contributing
+
+Please refer to [CONTRIBUTING][] before opening an issue or pull request.
+
+## Example
+
+See [example_test.go](https://github.com/fsnotify/fsnotify/blob/master/example_test.go).
+
+[contributing]: https://github.com/fsnotify/fsnotify/blob/master/CONTRIBUTING.md
+
+## Related Projects
+
+* [notify](https://github.com/rjeczalik/notify)
+* [fsevents](https://github.com/fsnotify/fsevents)
+
diff --git a/vendor/github.com/fsnotify/fsnotify/example_test.go b/vendor/github.com/fsnotify/fsnotify/example_test.go
new file mode 100644
index 000000000..700502cb3
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/example_test.go
@@ -0,0 +1,42 @@
+// Copyright 2012 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !plan9
+
+package fsnotify_test
+
+import (
+ "log"
+
+ "github.com/fsnotify/fsnotify"
+)
+
+func ExampleNewWatcher() {
+ watcher, err := fsnotify.NewWatcher()
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer watcher.Close()
+
+ done := make(chan bool)
+ go func() {
+ for {
+ select {
+ case event := <-watcher.Events:
+ log.Println("event:", event)
+ if event.Op&fsnotify.Write == fsnotify.Write {
+ log.Println("modified file:", event.Name)
+ }
+ case err := <-watcher.Errors:
+ log.Println("error:", err)
+ }
+ }
+ }()
+
+ err = watcher.Add("/tmp/foo")
+ if err != nil {
+ log.Fatal(err)
+ }
+ <-done
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/fen.go b/vendor/github.com/fsnotify/fsnotify/fen.go
new file mode 100644
index 000000000..ced39cb88
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/fen.go
@@ -0,0 +1,37 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build solaris
+
+package fsnotify
+
+import (
+ "errors"
+)
+
+// Watcher watches a set of files, delivering events to a channel.
+type Watcher struct {
+ Events chan Event
+ Errors chan error
+}
+
+// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
+func NewWatcher() (*Watcher, error) {
+ return nil, errors.New("FEN based watcher not yet supported for fsnotify\n")
+}
+
+// Close removes all watches and closes the events channel.
+func (w *Watcher) Close() error {
+ return nil
+}
+
+// Add starts watching the named file or directory (non-recursively).
+func (w *Watcher) Add(name string) error {
+ return nil
+}
+
+// Remove stops watching the the named file or directory (non-recursively).
+func (w *Watcher) Remove(name string) error {
+ return nil
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go
new file mode 100644
index 000000000..e7f55fee7
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go
@@ -0,0 +1,62 @@
+// Copyright 2012 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !plan9
+
+// Package fsnotify provides a platform-independent interface for file system notifications.
+package fsnotify
+
+import (
+ "bytes"
+ "fmt"
+)
+
+// Event represents a single file system notification.
+type Event struct {
+ Name string // Relative path to the file or directory.
+ Op Op // File operation that triggered the event.
+}
+
+// Op describes a set of file operations.
+type Op uint32
+
+// These are the generalized file operations that can trigger a notification.
+const (
+ Create Op = 1 << iota
+ Write
+ Remove
+ Rename
+ Chmod
+)
+
+func (op Op) String() string {
+ // Use a buffer for efficient string concatenation
+ var buffer bytes.Buffer
+
+ if op&Create == Create {
+ buffer.WriteString("|CREATE")
+ }
+ if op&Remove == Remove {
+ buffer.WriteString("|REMOVE")
+ }
+ if op&Write == Write {
+ buffer.WriteString("|WRITE")
+ }
+ if op&Rename == Rename {
+ buffer.WriteString("|RENAME")
+ }
+ if op&Chmod == Chmod {
+ buffer.WriteString("|CHMOD")
+ }
+ if buffer.Len() == 0 {
+ return ""
+ }
+ return buffer.String()[1:] // Strip leading pipe
+}
+
+// String returns a string representation of the event in the form
+// "file: REMOVE|WRITE|..."
+func (e Event) String() string {
+ return fmt.Sprintf("%q: %s", e.Name, e.Op.String())
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go b/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go
new file mode 100644
index 000000000..9d6d72afc
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go
@@ -0,0 +1,40 @@
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !plan9
+
+package fsnotify
+
+import "testing"
+
+func TestEventStringWithValue(t *testing.T) {
+ for opMask, expectedString := range map[Op]string{
+ Chmod | Create: `"/usr/someFile": CREATE|CHMOD`,
+ Rename: `"/usr/someFile": RENAME`,
+ Remove: `"/usr/someFile": REMOVE`,
+ Write | Chmod: `"/usr/someFile": WRITE|CHMOD`,
+ } {
+ event := Event{Name: "/usr/someFile", Op: opMask}
+ if event.String() != expectedString {
+ t.Fatalf("Expected %s, got: %v", expectedString, event.String())
+ }
+
+ }
+}
+
+func TestEventOpStringWithValue(t *testing.T) {
+ expectedOpString := "WRITE|CHMOD"
+ event := Event{Name: "someFile", Op: Write | Chmod}
+ if event.Op.String() != expectedOpString {
+ t.Fatalf("Expected %s, got: %v", expectedOpString, event.Op.String())
+ }
+}
+
+func TestEventOpStringWithNoValue(t *testing.T) {
+ expectedOpString := ""
+ event := Event{Name: "testFile", Op: 0}
+ if event.Op.String() != expectedOpString {
+ t.Fatalf("Expected %s, got: %v", expectedOpString, event.Op.String())
+ }
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify.go b/vendor/github.com/fsnotify/fsnotify/inotify.go
new file mode 100644
index 000000000..f3b74c51f
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/inotify.go
@@ -0,0 +1,325 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build linux
+
+package fsnotify
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+// Watcher watches a set of files, delivering events to a channel.
+type Watcher struct {
+ Events chan Event
+ Errors chan error
+ mu sync.Mutex // Map access
+ cv *sync.Cond // sync removing on rm_watch with IN_IGNORE
+ fd int
+ poller *fdPoller
+ watches map[string]*watch // Map of inotify watches (key: path)
+ paths map[int]string // Map of watched paths (key: watch descriptor)
+ done chan struct{} // Channel for sending a "quit message" to the reader goroutine
+ doneResp chan struct{} // Channel to respond to Close
+}
+
+// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
+func NewWatcher() (*Watcher, error) {
+ // Create inotify fd
+ fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC)
+ if fd == -1 {
+ return nil, errno
+ }
+ // Create epoll
+ poller, err := newFdPoller(fd)
+ if err != nil {
+ unix.Close(fd)
+ return nil, err
+ }
+ w := &Watcher{
+ fd: fd,
+ poller: poller,
+ watches: make(map[string]*watch),
+ paths: make(map[int]string),
+ Events: make(chan Event),
+ Errors: make(chan error),
+ done: make(chan struct{}),
+ doneResp: make(chan struct{}),
+ }
+ w.cv = sync.NewCond(&w.mu)
+
+ go w.readEvents()
+ return w, nil
+}
+
+func (w *Watcher) isClosed() bool {
+ select {
+ case <-w.done:
+ return true
+ default:
+ return false
+ }
+}
+
+// Close removes all watches and closes the events channel.
+func (w *Watcher) Close() error {
+ if w.isClosed() {
+ return nil
+ }
+
+ // Send 'close' signal to goroutine, and set the Watcher to closed.
+ close(w.done)
+
+ // Wake up goroutine
+ w.poller.wake()
+
+ // Wait for goroutine to close
+ <-w.doneResp
+
+ return nil
+}
+
+// Add starts watching the named file or directory (non-recursively).
+func (w *Watcher) Add(name string) error {
+ name = filepath.Clean(name)
+ if w.isClosed() {
+ return errors.New("inotify instance already closed")
+ }
+
+ const agnosticEvents = unix.IN_MOVED_TO | unix.IN_MOVED_FROM |
+ unix.IN_CREATE | unix.IN_ATTRIB | unix.IN_MODIFY |
+ unix.IN_MOVE_SELF | unix.IN_DELETE | unix.IN_DELETE_SELF
+
+ var flags uint32 = agnosticEvents
+
+ w.mu.Lock()
+ watchEntry, found := w.watches[name]
+ w.mu.Unlock()
+ if found {
+ watchEntry.flags |= flags
+ flags |= unix.IN_MASK_ADD
+ }
+ wd, errno := unix.InotifyAddWatch(w.fd, name, flags)
+ if wd == -1 {
+ return errno
+ }
+
+ w.mu.Lock()
+ w.watches[name] = &watch{wd: uint32(wd), flags: flags}
+ w.paths[wd] = name
+ w.mu.Unlock()
+
+ return nil
+}
+
+// Remove stops watching the named file or directory (non-recursively).
+func (w *Watcher) Remove(name string) error {
+ name = filepath.Clean(name)
+
+ // Fetch the watch.
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ watch, ok := w.watches[name]
+
+ // Remove it from inotify.
+ if !ok {
+ return fmt.Errorf("can't remove non-existent inotify watch for: %s", name)
+ }
+ // inotify_rm_watch will return EINVAL if the file has been deleted;
+ // the inotify will already have been removed.
+ // watches and pathes are deleted in ignoreLinux() implicitly and asynchronously
+ // by calling inotify_rm_watch() below. e.g. readEvents() goroutine receives IN_IGNORE
+ // so that EINVAL means that the wd is being rm_watch()ed or its file removed
+ // by another thread and we have not received IN_IGNORE event.
+ success, errno := unix.InotifyRmWatch(w.fd, watch.wd)
+ if success == -1 {
+ // TODO: Perhaps it's not helpful to return an error here in every case.
+ // the only two possible errors are:
+ // EBADF, which happens when w.fd is not a valid file descriptor of any kind.
+ // EINVAL, which is when fd is not an inotify descriptor or wd is not a valid watch descriptor.
+ // Watch descriptors are invalidated when they are removed explicitly or implicitly;
+ // explicitly by inotify_rm_watch, implicitly when the file they are watching is deleted.
+ return errno
+ }
+
+ // wait until ignoreLinux() deleting maps
+ exists := true
+ for exists {
+ w.cv.Wait()
+ _, exists = w.watches[name]
+ }
+
+ return nil
+}
+
+type watch struct {
+ wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall)
+ flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags)
+}
+
+// readEvents reads from the inotify file descriptor, converts the
+// received events into Event objects and sends them via the Events channel
+func (w *Watcher) readEvents() {
+ var (
+ buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events
+ n int // Number of bytes read with read()
+ errno error // Syscall errno
+ ok bool // For poller.wait
+ )
+
+ defer close(w.doneResp)
+ defer close(w.Errors)
+ defer close(w.Events)
+ defer unix.Close(w.fd)
+ defer w.poller.close()
+
+ for {
+ // See if we have been closed.
+ if w.isClosed() {
+ return
+ }
+
+ ok, errno = w.poller.wait()
+ if errno != nil {
+ select {
+ case w.Errors <- errno:
+ case <-w.done:
+ return
+ }
+ continue
+ }
+
+ if !ok {
+ continue
+ }
+
+ n, errno = unix.Read(w.fd, buf[:])
+ // If a signal interrupted execution, see if we've been asked to close, and try again.
+ // http://man7.org/linux/man-pages/man7/signal.7.html :
+ // "Before Linux 3.8, reads from an inotify(7) file descriptor were not restartable"
+ if errno == unix.EINTR {
+ continue
+ }
+
+ // unix.Read might have been woken up by Close. If so, we're done.
+ if w.isClosed() {
+ return
+ }
+
+ if n < unix.SizeofInotifyEvent {
+ var err error
+ if n == 0 {
+ // If EOF is received. This should really never happen.
+ err = io.EOF
+ } else if n < 0 {
+ // If an error occurred while reading.
+ err = errno
+ } else {
+ // Read was too short.
+ err = errors.New("notify: short read in readEvents()")
+ }
+ select {
+ case w.Errors <- err:
+ case <-w.done:
+ return
+ }
+ continue
+ }
+
+ var offset uint32
+ // We don't know how many events we just read into the buffer
+ // While the offset points to at least one whole event...
+ for offset <= uint32(n-unix.SizeofInotifyEvent) {
+ // Point "raw" to the event in the buffer
+ raw := (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset]))
+
+ mask := uint32(raw.Mask)
+ nameLen := uint32(raw.Len)
+ // If the event happened to the watched directory or the watched file, the kernel
+ // doesn't append the filename to the event, but we would like to always fill the
+ // the "Name" field with a valid filename. We retrieve the path of the watch from
+ // the "paths" map.
+ w.mu.Lock()
+ name := w.paths[int(raw.Wd)]
+ w.mu.Unlock()
+ if nameLen > 0 {
+ // Point "bytes" at the first byte of the filename
+ bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))
+ // The filename is padded with NULL bytes. TrimRight() gets rid of those.
+ name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000")
+ }
+
+ event := newEvent(name, mask)
+
+ // Send the events that are not ignored on the events channel
+ if !event.ignoreLinux(w, raw.Wd, mask) {
+ select {
+ case w.Events <- event:
+ case <-w.done:
+ return
+ }
+ }
+
+ // Move to the next event in the buffer
+ offset += unix.SizeofInotifyEvent + nameLen
+ }
+ }
+}
+
+// Certain types of events can be "ignored" and not sent over the Events
+// channel. Such as events marked ignore by the kernel, or MODIFY events
+// against files that do not exist.
+func (e *Event) ignoreLinux(w *Watcher, wd int32, mask uint32) bool {
+ // Ignore anything the inotify API says to ignore
+ if mask&unix.IN_IGNORED == unix.IN_IGNORED {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ name := w.paths[int(wd)]
+ delete(w.paths, int(wd))
+ delete(w.watches, name)
+ w.cv.Broadcast()
+ return true
+ }
+
+ // If the event is not a DELETE or RENAME, the file must exist.
+ // Otherwise the event is ignored.
+ // *Note*: this was put in place because it was seen that a MODIFY
+ // event was sent after the DELETE. This ignores that MODIFY and
+ // assumes a DELETE will come or has come if the file doesn't exist.
+ if !(e.Op&Remove == Remove || e.Op&Rename == Rename) {
+ _, statErr := os.Lstat(e.Name)
+ return os.IsNotExist(statErr)
+ }
+ return false
+}
+
+// newEvent returns an platform-independent Event based on an inotify mask.
+func newEvent(name string, mask uint32) Event {
+ e := Event{Name: name}
+ if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO {
+ e.Op |= Create
+ }
+ if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE {
+ e.Op |= Remove
+ }
+ if mask&unix.IN_MODIFY == unix.IN_MODIFY {
+ e.Op |= Write
+ }
+ if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM {
+ e.Op |= Rename
+ }
+ if mask&unix.IN_ATTRIB == unix.IN_ATTRIB {
+ e.Op |= Chmod
+ }
+ return e
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_poller.go b/vendor/github.com/fsnotify/fsnotify/inotify_poller.go
new file mode 100644
index 000000000..cc7db4b22
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/inotify_poller.go
@@ -0,0 +1,187 @@
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build linux
+
+package fsnotify
+
+import (
+ "errors"
+
+ "golang.org/x/sys/unix"
+)
+
+type fdPoller struct {
+ fd int // File descriptor (as returned by the inotify_init() syscall)
+ epfd int // Epoll file descriptor
+ pipe [2]int // Pipe for waking up
+}
+
+func emptyPoller(fd int) *fdPoller {
+ poller := new(fdPoller)
+ poller.fd = fd
+ poller.epfd = -1
+ poller.pipe[0] = -1
+ poller.pipe[1] = -1
+ return poller
+}
+
+// Create a new inotify poller.
+// This creates an inotify handler, and an epoll handler.
+func newFdPoller(fd int) (*fdPoller, error) {
+ var errno error
+ poller := emptyPoller(fd)
+ defer func() {
+ if errno != nil {
+ poller.close()
+ }
+ }()
+ poller.fd = fd
+
+ // Create epoll fd
+ poller.epfd, errno = unix.EpollCreate1(0)
+ if poller.epfd == -1 {
+ return nil, errno
+ }
+ // Create pipe; pipe[0] is the read end, pipe[1] the write end.
+ errno = unix.Pipe2(poller.pipe[:], unix.O_NONBLOCK)
+ if errno != nil {
+ return nil, errno
+ }
+
+ // Register inotify fd with epoll
+ event := unix.EpollEvent{
+ Fd: int32(poller.fd),
+ Events: unix.EPOLLIN,
+ }
+ errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.fd, &event)
+ if errno != nil {
+ return nil, errno
+ }
+
+ // Register pipe fd with epoll
+ event = unix.EpollEvent{
+ Fd: int32(poller.pipe[0]),
+ Events: unix.EPOLLIN,
+ }
+ errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.pipe[0], &event)
+ if errno != nil {
+ return nil, errno
+ }
+
+ return poller, nil
+}
+
+// Wait using epoll.
+// Returns true if something is ready to be read,
+// false if there is not.
+func (poller *fdPoller) wait() (bool, error) {
+ // 3 possible events per fd, and 2 fds, makes a maximum of 6 events.
+ // I don't know whether epoll_wait returns the number of events returned,
+ // or the total number of events ready.
+ // I decided to catch both by making the buffer one larger than the maximum.
+ events := make([]unix.EpollEvent, 7)
+ for {
+ n, errno := unix.EpollWait(poller.epfd, events, -1)
+ if n == -1 {
+ if errno == unix.EINTR {
+ continue
+ }
+ return false, errno
+ }
+ if n == 0 {
+ // If there are no events, try again.
+ continue
+ }
+ if n > 6 {
+ // This should never happen. More events were returned than should be possible.
+ return false, errors.New("epoll_wait returned more events than I know what to do with")
+ }
+ ready := events[:n]
+ epollhup := false
+ epollerr := false
+ epollin := false
+ for _, event := range ready {
+ if event.Fd == int32(poller.fd) {
+ if event.Events&unix.EPOLLHUP != 0 {
+ // This should not happen, but if it does, treat it as a wakeup.
+ epollhup = true
+ }
+ if event.Events&unix.EPOLLERR != 0 {
+ // If an error is waiting on the file descriptor, we should pretend
+ // something is ready to read, and let unix.Read pick up the error.
+ epollerr = true
+ }
+ if event.Events&unix.EPOLLIN != 0 {
+ // There is data to read.
+ epollin = true
+ }
+ }
+ if event.Fd == int32(poller.pipe[0]) {
+ if event.Events&unix.EPOLLHUP != 0 {
+ // Write pipe descriptor was closed, by us. This means we're closing down the
+ // watcher, and we should wake up.
+ }
+ if event.Events&unix.EPOLLERR != 0 {
+ // If an error is waiting on the pipe file descriptor.
+ // This is an absolute mystery, and should never ever happen.
+ return false, errors.New("Error on the pipe descriptor.")
+ }
+ if event.Events&unix.EPOLLIN != 0 {
+ // This is a regular wakeup, so we have to clear the buffer.
+ err := poller.clearWake()
+ if err != nil {
+ return false, err
+ }
+ }
+ }
+ }
+
+ if epollhup || epollerr || epollin {
+ return true, nil
+ }
+ return false, nil
+ }
+}
+
+// Close the write end of the poller.
+func (poller *fdPoller) wake() error {
+ buf := make([]byte, 1)
+ n, errno := unix.Write(poller.pipe[1], buf)
+ if n == -1 {
+ if errno == unix.EAGAIN {
+ // Buffer is full, poller will wake.
+ return nil
+ }
+ return errno
+ }
+ return nil
+}
+
+func (poller *fdPoller) clearWake() error {
+ // You have to be woken up a LOT in order to get to 100!
+ buf := make([]byte, 100)
+ n, errno := unix.Read(poller.pipe[0], buf)
+ if n == -1 {
+ if errno == unix.EAGAIN {
+ // Buffer is empty, someone else cleared our wake.
+ return nil
+ }
+ return errno
+ }
+ return nil
+}
+
+// Close all poller file descriptors, but not the one passed to it.
+func (poller *fdPoller) close() {
+ if poller.pipe[1] != -1 {
+ unix.Close(poller.pipe[1])
+ }
+ if poller.pipe[0] != -1 {
+ unix.Close(poller.pipe[0])
+ }
+ if poller.epfd != -1 {
+ unix.Close(poller.epfd)
+ }
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go b/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go
new file mode 100644
index 000000000..26623efef
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go
@@ -0,0 +1,229 @@
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build linux
+
+package fsnotify
+
+import (
+ "testing"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+type testFd [2]int
+
+func makeTestFd(t *testing.T) testFd {
+ var tfd testFd
+ errno := unix.Pipe(tfd[:])
+ if errno != nil {
+ t.Fatalf("Failed to create pipe: %v", errno)
+ }
+ return tfd
+}
+
+func (tfd testFd) fd() int {
+ return tfd[0]
+}
+
+func (tfd testFd) closeWrite(t *testing.T) {
+ errno := unix.Close(tfd[1])
+ if errno != nil {
+ t.Fatalf("Failed to close write end of pipe: %v", errno)
+ }
+}
+
+func (tfd testFd) put(t *testing.T) {
+ buf := make([]byte, 10)
+ _, errno := unix.Write(tfd[1], buf)
+ if errno != nil {
+ t.Fatalf("Failed to write to pipe: %v", errno)
+ }
+}
+
+func (tfd testFd) get(t *testing.T) {
+ buf := make([]byte, 10)
+ _, errno := unix.Read(tfd[0], buf)
+ if errno != nil {
+ t.Fatalf("Failed to read from pipe: %v", errno)
+ }
+}
+
+func (tfd testFd) close() {
+ unix.Close(tfd[1])
+ unix.Close(tfd[0])
+}
+
+func makePoller(t *testing.T) (testFd, *fdPoller) {
+ tfd := makeTestFd(t)
+ poller, err := newFdPoller(tfd.fd())
+ if err != nil {
+ t.Fatalf("Failed to create poller: %v", err)
+ }
+ return tfd, poller
+}
+
+func TestPollerWithBadFd(t *testing.T) {
+ _, err := newFdPoller(-1)
+ if err != unix.EBADF {
+ t.Fatalf("Expected EBADF, got: %v", err)
+ }
+}
+
+func TestPollerWithData(t *testing.T) {
+ tfd, poller := makePoller(t)
+ defer tfd.close()
+ defer poller.close()
+
+ tfd.put(t)
+ ok, err := poller.wait()
+ if err != nil {
+ t.Fatalf("poller failed: %v", err)
+ }
+ if !ok {
+ t.Fatalf("expected poller to return true")
+ }
+ tfd.get(t)
+}
+
+func TestPollerWithWakeup(t *testing.T) {
+ tfd, poller := makePoller(t)
+ defer tfd.close()
+ defer poller.close()
+
+ err := poller.wake()
+ if err != nil {
+ t.Fatalf("wake failed: %v", err)
+ }
+ ok, err := poller.wait()
+ if err != nil {
+ t.Fatalf("poller failed: %v", err)
+ }
+ if ok {
+ t.Fatalf("expected poller to return false")
+ }
+}
+
+func TestPollerWithClose(t *testing.T) {
+ tfd, poller := makePoller(t)
+ defer tfd.close()
+ defer poller.close()
+
+ tfd.closeWrite(t)
+ ok, err := poller.wait()
+ if err != nil {
+ t.Fatalf("poller failed: %v", err)
+ }
+ if !ok {
+ t.Fatalf("expected poller to return true")
+ }
+}
+
+func TestPollerWithWakeupAndData(t *testing.T) {
+ tfd, poller := makePoller(t)
+ defer tfd.close()
+ defer poller.close()
+
+ tfd.put(t)
+ err := poller.wake()
+ if err != nil {
+ t.Fatalf("wake failed: %v", err)
+ }
+
+ // both data and wakeup
+ ok, err := poller.wait()
+ if err != nil {
+ t.Fatalf("poller failed: %v", err)
+ }
+ if !ok {
+ t.Fatalf("expected poller to return true")
+ }
+
+ // data is still in the buffer, wakeup is cleared
+ ok, err = poller.wait()
+ if err != nil {
+ t.Fatalf("poller failed: %v", err)
+ }
+ if !ok {
+ t.Fatalf("expected poller to return true")
+ }
+
+ tfd.get(t)
+ // data is gone, only wakeup now
+ err = poller.wake()
+ if err != nil {
+ t.Fatalf("wake failed: %v", err)
+ }
+ ok, err = poller.wait()
+ if err != nil {
+ t.Fatalf("poller failed: %v", err)
+ }
+ if ok {
+ t.Fatalf("expected poller to return false")
+ }
+}
+
+func TestPollerConcurrent(t *testing.T) {
+ tfd, poller := makePoller(t)
+ defer tfd.close()
+ defer poller.close()
+
+ oks := make(chan bool)
+ live := make(chan bool)
+ defer close(live)
+ go func() {
+ defer close(oks)
+ for {
+ ok, err := poller.wait()
+ if err != nil {
+ t.Fatalf("poller failed: %v", err)
+ }
+ oks <- ok
+ if !<-live {
+ return
+ }
+ }
+ }()
+
+ // Try a write
+ select {
+ case <-time.After(50 * time.Millisecond):
+ case <-oks:
+ t.Fatalf("poller did not wait")
+ }
+ tfd.put(t)
+ if !<-oks {
+ t.Fatalf("expected true")
+ }
+ tfd.get(t)
+ live <- true
+
+ // Try a wakeup
+ select {
+ case <-time.After(50 * time.Millisecond):
+ case <-oks:
+ t.Fatalf("poller did not wait")
+ }
+ err := poller.wake()
+ if err != nil {
+ t.Fatalf("wake failed: %v", err)
+ }
+ if <-oks {
+ t.Fatalf("expected false")
+ }
+ live <- true
+
+ // Try a close
+ select {
+ case <-time.After(50 * time.Millisecond):
+ case <-oks:
+ t.Fatalf("poller did not wait")
+ }
+ tfd.closeWrite(t)
+ if !<-oks {
+ t.Fatalf("expected true")
+ }
+ tfd.get(t)
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_test.go b/vendor/github.com/fsnotify/fsnotify/inotify_test.go
new file mode 100644
index 000000000..a4bb202d1
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/inotify_test.go
@@ -0,0 +1,360 @@
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build linux
+
+package fsnotify
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestInotifyCloseRightAway(t *testing.T) {
+ w, err := NewWatcher()
+ if err != nil {
+ t.Fatalf("Failed to create watcher")
+ }
+
+ // Close immediately; it won't even reach the first unix.Read.
+ w.Close()
+
+ // Wait for the close to complete.
+ <-time.After(50 * time.Millisecond)
+ isWatcherReallyClosed(t, w)
+}
+
+func TestInotifyCloseSlightlyLater(t *testing.T) {
+ w, err := NewWatcher()
+ if err != nil {
+ t.Fatalf("Failed to create watcher")
+ }
+
+ // Wait until readEvents has reached unix.Read, and Close.
+ <-time.After(50 * time.Millisecond)
+ w.Close()
+
+ // Wait for the close to complete.
+ <-time.After(50 * time.Millisecond)
+ isWatcherReallyClosed(t, w)
+}
+
+func TestInotifyCloseSlightlyLaterWithWatch(t *testing.T) {
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ w, err := NewWatcher()
+ if err != nil {
+ t.Fatalf("Failed to create watcher")
+ }
+ w.Add(testDir)
+
+ // Wait until readEvents has reached unix.Read, and Close.
+ <-time.After(50 * time.Millisecond)
+ w.Close()
+
+ // Wait for the close to complete.
+ <-time.After(50 * time.Millisecond)
+ isWatcherReallyClosed(t, w)
+}
+
+func TestInotifyCloseAfterRead(t *testing.T) {
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ w, err := NewWatcher()
+ if err != nil {
+ t.Fatalf("Failed to create watcher")
+ }
+
+ err = w.Add(testDir)
+ if err != nil {
+ t.Fatalf("Failed to add .")
+ }
+
+ // Generate an event.
+ os.Create(filepath.Join(testDir, "somethingSOMETHINGsomethingSOMETHING"))
+
+ // Wait for readEvents to read the event, then close the watcher.
+ <-time.After(50 * time.Millisecond)
+ w.Close()
+
+ // Wait for the close to complete.
+ <-time.After(50 * time.Millisecond)
+ isWatcherReallyClosed(t, w)
+}
+
+func isWatcherReallyClosed(t *testing.T, w *Watcher) {
+ select {
+ case err, ok := <-w.Errors:
+ if ok {
+ t.Fatalf("w.Errors is not closed; readEvents is still alive after closing (error: %v)", err)
+ }
+ default:
+ t.Fatalf("w.Errors would have blocked; readEvents is still alive!")
+ }
+
+ select {
+ case _, ok := <-w.Events:
+ if ok {
+ t.Fatalf("w.Events is not closed; readEvents is still alive after closing")
+ }
+ default:
+ t.Fatalf("w.Events would have blocked; readEvents is still alive!")
+ }
+}
+
+func TestInotifyCloseCreate(t *testing.T) {
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ w, err := NewWatcher()
+ if err != nil {
+ t.Fatalf("Failed to create watcher: %v", err)
+ }
+ defer w.Close()
+
+ err = w.Add(testDir)
+ if err != nil {
+ t.Fatalf("Failed to add testDir: %v", err)
+ }
+ h, err := os.Create(filepath.Join(testDir, "testfile"))
+ if err != nil {
+ t.Fatalf("Failed to create file in testdir: %v", err)
+ }
+ h.Close()
+ select {
+ case _ = <-w.Events:
+ case err := <-w.Errors:
+ t.Fatalf("Error from watcher: %v", err)
+ case <-time.After(50 * time.Millisecond):
+ t.Fatalf("Took too long to wait for event")
+ }
+
+ // At this point, we've received one event, so the goroutine is ready.
+ // It's also blocking on unix.Read.
+ // Now we try to swap the file descriptor under its nose.
+ w.Close()
+ w, err = NewWatcher()
+ defer w.Close()
+ if err != nil {
+ t.Fatalf("Failed to create second watcher: %v", err)
+ }
+
+ <-time.After(50 * time.Millisecond)
+ err = w.Add(testDir)
+ if err != nil {
+ t.Fatalf("Error adding testDir again: %v", err)
+ }
+}
+
+// This test verifies the watcher can keep up with file creations/deletions
+// when under load.
+func TestInotifyStress(t *testing.T) {
+ maxNumToCreate := 1000
+
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+ testFilePrefix := filepath.Join(testDir, "testfile")
+
+ w, err := NewWatcher()
+ if err != nil {
+ t.Fatalf("Failed to create watcher: %v", err)
+ }
+ defer w.Close()
+
+ err = w.Add(testDir)
+ if err != nil {
+ t.Fatalf("Failed to add testDir: %v", err)
+ }
+
+ doneChan := make(chan struct{})
+ // The buffer ensures that the file generation goroutine is never blocked.
+ errChan := make(chan error, 2*maxNumToCreate)
+
+ go func() {
+ for i := 0; i < maxNumToCreate; i++ {
+ testFile := fmt.Sprintf("%s%d", testFilePrefix, i)
+
+ handle, err := os.Create(testFile)
+ if err != nil {
+ errChan <- fmt.Errorf("Create failed: %v", err)
+ continue
+ }
+
+ err = handle.Close()
+ if err != nil {
+ errChan <- fmt.Errorf("Close failed: %v", err)
+ continue
+ }
+ }
+
+ // If we delete a newly created file too quickly, inotify will skip the
+ // create event and only send the delete event.
+ time.Sleep(100 * time.Millisecond)
+
+ for i := 0; i < maxNumToCreate; i++ {
+ testFile := fmt.Sprintf("%s%d", testFilePrefix, i)
+ err = os.Remove(testFile)
+ if err != nil {
+ errChan <- fmt.Errorf("Remove failed: %v", err)
+ }
+ }
+
+ close(doneChan)
+ }()
+
+ creates := 0
+ removes := 0
+
+ finished := false
+ after := time.After(10 * time.Second)
+ for !finished {
+ select {
+ case <-after:
+ t.Fatalf("Not done")
+ case <-doneChan:
+ finished = true
+ case err := <-errChan:
+ t.Fatalf("Got an error from file creator goroutine: %v", err)
+ case err := <-w.Errors:
+ t.Fatalf("Got an error from watcher: %v", err)
+ case evt := <-w.Events:
+ if !strings.HasPrefix(evt.Name, testFilePrefix) {
+ t.Fatalf("Got an event for an unknown file: %s", evt.Name)
+ }
+ if evt.Op == Create {
+ creates++
+ }
+ if evt.Op == Remove {
+ removes++
+ }
+ }
+ }
+
+ // Drain remaining events from channels
+ count := 0
+ for count < 10 {
+ select {
+ case err := <-errChan:
+ t.Fatalf("Got an error from file creator goroutine: %v", err)
+ case err := <-w.Errors:
+ t.Fatalf("Got an error from watcher: %v", err)
+ case evt := <-w.Events:
+ if !strings.HasPrefix(evt.Name, testFilePrefix) {
+ t.Fatalf("Got an event for an unknown file: %s", evt.Name)
+ }
+ if evt.Op == Create {
+ creates++
+ }
+ if evt.Op == Remove {
+ removes++
+ }
+ count = 0
+ default:
+ count++
+ // Give the watcher chances to fill the channels.
+ time.Sleep(time.Millisecond)
+ }
+ }
+
+ if creates-removes > 1 || creates-removes < -1 {
+ t.Fatalf("Creates and removes should not be off by more than one: %d creates, %d removes", creates, removes)
+ }
+ if creates < 50 {
+ t.Fatalf("Expected at least 50 creates, got %d", creates)
+ }
+}
+
+func TestInotifyRemoveTwice(t *testing.T) {
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+ testFile := filepath.Join(testDir, "testfile")
+
+ handle, err := os.Create(testFile)
+ if err != nil {
+ t.Fatalf("Create failed: %v", err)
+ }
+ handle.Close()
+
+ w, err := NewWatcher()
+ if err != nil {
+ t.Fatalf("Failed to create watcher: %v", err)
+ }
+ defer w.Close()
+
+ err = w.Add(testFile)
+ if err != nil {
+ t.Fatalf("Failed to add testFile: %v", err)
+ }
+
+ err = os.Remove(testFile)
+ if err != nil {
+ t.Fatalf("Failed to remove testFile: %v", err)
+ }
+
+ err = w.Remove(testFile)
+ if err == nil {
+ t.Fatalf("no error on removing invalid file")
+ }
+ s1 := fmt.Sprintf("%s", err)
+
+ err = w.Remove(testFile)
+ if err == nil {
+ t.Fatalf("no error on removing invalid file")
+ }
+ s2 := fmt.Sprintf("%s", err)
+
+ if s1 != s2 {
+ t.Fatalf("receive different error - %s / %s", s1, s2)
+ }
+}
+
+func TestInotifyInnerMapLength(t *testing.T) {
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+ testFile := filepath.Join(testDir, "testfile")
+
+ handle, err := os.Create(testFile)
+ if err != nil {
+ t.Fatalf("Create failed: %v", err)
+ }
+ handle.Close()
+
+ w, err := NewWatcher()
+ if err != nil {
+ t.Fatalf("Failed to create watcher: %v", err)
+ }
+ defer w.Close()
+
+ err = w.Add(testFile)
+ if err != nil {
+ t.Fatalf("Failed to add testFile: %v", err)
+ }
+ go func() {
+ for err := range w.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ err = os.Remove(testFile)
+ if err != nil {
+ t.Fatalf("Failed to remove testFile: %v", err)
+ }
+ _ = <-w.Events // consume Remove event
+ <-time.After(50 * time.Millisecond) // wait IN_IGNORE propagated
+
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if len(w.watches) != 0 {
+ t.Fatalf("Expected watches len is 0, but got: %d, %v", len(w.watches), w.watches)
+ }
+ if len(w.paths) != 0 {
+ t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths)
+ }
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go b/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go
new file mode 100644
index 000000000..5564554f7
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go
@@ -0,0 +1,147 @@
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fsnotify
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+// testExchangedataForWatcher tests the watcher with the exchangedata operation on OS X.
+//
+// This is widely used for atomic saves on OS X, e.g. TextMate and in Apple's NSDocument.
+//
+// See https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/exchangedata.2.html
+// Also see: https://github.com/textmate/textmate/blob/cd016be29489eba5f3c09b7b70b06da134dda550/Frameworks/io/src/swap_file_data.cc#L20
+func testExchangedataForWatcher(t *testing.T, watchDir bool) {
+ // Create directory to watch
+ testDir1 := tempMkdir(t)
+
+ // For the intermediate file
+ testDir2 := tempMkdir(t)
+
+ defer os.RemoveAll(testDir1)
+ defer os.RemoveAll(testDir2)
+
+ resolvedFilename := "TestFsnotifyEvents.file"
+
+ // TextMate does:
+ //
+ // 1. exchangedata (intermediate, resolved)
+ // 2. unlink intermediate
+ //
+ // Let's try to simulate that:
+ resolved := filepath.Join(testDir1, resolvedFilename)
+ intermediate := filepath.Join(testDir2, resolvedFilename+"~")
+
+ // Make sure we create the file before we start watching
+ createAndSyncFile(t, resolved)
+
+ watcher := newWatcher(t)
+
+ // Test both variants in isolation
+ if watchDir {
+ addWatch(t, watcher, testDir1)
+ } else {
+ addWatch(t, watcher, resolved)
+ }
+
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for err := range watcher.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ // Receive events on the event channel on a separate goroutine
+ eventstream := watcher.Events
+ var removeReceived counter
+ var createReceived counter
+
+ done := make(chan bool)
+
+ go func() {
+ for event := range eventstream {
+ // Only count relevant events
+ if event.Name == filepath.Clean(resolved) {
+ if event.Op&Remove == Remove {
+ removeReceived.increment()
+ }
+ if event.Op&Create == Create {
+ createReceived.increment()
+ }
+ }
+ t.Logf("event received: %s", event)
+ }
+ done <- true
+ }()
+
+ // Repeat to make sure the watched file/directory "survives" the REMOVE/CREATE loop.
+ for i := 1; i <= 3; i++ {
+ // The intermediate file is created in a folder outside the watcher
+ createAndSyncFile(t, intermediate)
+
+ // 1. Swap
+ if err := unix.Exchangedata(intermediate, resolved, 0); err != nil {
+ t.Fatalf("[%d] exchangedata failed: %s", i, err)
+ }
+
+ time.Sleep(50 * time.Millisecond)
+
+ // 2. Delete the intermediate file
+ err := os.Remove(intermediate)
+
+ if err != nil {
+ t.Fatalf("[%d] remove %s failed: %s", i, intermediate, err)
+ }
+
+ time.Sleep(50 * time.Millisecond)
+
+ }
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+
+ // The events will be (CHMOD + REMOVE + CREATE) X 2. Let's focus on the last two:
+ if removeReceived.value() < 3 {
+ t.Fatal("fsnotify remove events have not been received after 500 ms")
+ }
+
+ if createReceived.value() < 3 {
+ t.Fatal("fsnotify create events have not been received after 500 ms")
+ }
+
+ watcher.Close()
+ t.Log("waiting for the event channel to become closed...")
+ select {
+ case <-done:
+ t.Log("event channel closed")
+ case <-time.After(2 * time.Second):
+ t.Fatal("event stream was not closed after 2 seconds")
+ }
+}
+
+// TestExchangedataInWatchedDir test exchangedata operation on file in watched dir.
+func TestExchangedataInWatchedDir(t *testing.T) {
+ testExchangedataForWatcher(t, true)
+}
+
+// TestExchangedataInWatchedDir test exchangedata operation on watched file.
+func TestExchangedataInWatchedFile(t *testing.T) {
+ testExchangedataForWatcher(t, false)
+}
+
+func createAndSyncFile(t *testing.T, filepath string) {
+ f1, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating %s failed: %s", filepath, err)
+ }
+ f1.Sync()
+ f1.Close()
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/integration_test.go b/vendor/github.com/fsnotify/fsnotify/integration_test.go
new file mode 100644
index 000000000..8b7e9d3ec
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/integration_test.go
@@ -0,0 +1,1237 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !plan9,!solaris
+
+package fsnotify
+
+import (
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path"
+ "path/filepath"
+ "runtime"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// An atomic counter
+type counter struct {
+ val int32
+}
+
+func (c *counter) increment() {
+ atomic.AddInt32(&c.val, 1)
+}
+
+func (c *counter) value() int32 {
+ return atomic.LoadInt32(&c.val)
+}
+
+func (c *counter) reset() {
+ atomic.StoreInt32(&c.val, 0)
+}
+
+// tempMkdir makes a temporary directory
+func tempMkdir(t *testing.T) string {
+ dir, err := ioutil.TempDir("", "fsnotify")
+ if err != nil {
+ t.Fatalf("failed to create test directory: %s", err)
+ }
+ return dir
+}
+
+// tempMkFile makes a temporary file.
+func tempMkFile(t *testing.T, dir string) string {
+ f, err := ioutil.TempFile(dir, "fsnotify")
+ if err != nil {
+ t.Fatalf("failed to create test file: %v", err)
+ }
+ defer f.Close()
+ return f.Name()
+}
+
+// newWatcher initializes an fsnotify Watcher instance.
+func newWatcher(t *testing.T) *Watcher {
+ watcher, err := NewWatcher()
+ if err != nil {
+ t.Fatalf("NewWatcher() failed: %s", err)
+ }
+ return watcher
+}
+
+// addWatch adds a watch for a directory
+func addWatch(t *testing.T, watcher *Watcher, dir string) {
+ if err := watcher.Add(dir); err != nil {
+ t.Fatalf("watcher.Add(%q) failed: %s", dir, err)
+ }
+}
+
+func TestFsnotifyMultipleOperations(t *testing.T) {
+ watcher := newWatcher(t)
+
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for err := range watcher.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ // Create directory that's not watched
+ testDirToMoveFiles := tempMkdir(t)
+ defer os.RemoveAll(testDirToMoveFiles)
+
+ testFile := filepath.Join(testDir, "TestFsnotifySeq.testfile")
+ testFileRenamed := filepath.Join(testDirToMoveFiles, "TestFsnotifySeqRename.testfile")
+
+ addWatch(t, watcher, testDir)
+
+ // Receive events on the event channel on a separate goroutine
+ eventstream := watcher.Events
+ var createReceived, modifyReceived, deleteReceived, renameReceived counter
+ done := make(chan bool)
+ go func() {
+ for event := range eventstream {
+ // Only count relevant events
+ if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) {
+ t.Logf("event received: %s", event)
+ if event.Op&Remove == Remove {
+ deleteReceived.increment()
+ }
+ if event.Op&Write == Write {
+ modifyReceived.increment()
+ }
+ if event.Op&Create == Create {
+ createReceived.increment()
+ }
+ if event.Op&Rename == Rename {
+ renameReceived.increment()
+ }
+ } else {
+ t.Logf("unexpected event received: %s", event)
+ }
+ }
+ done <- true
+ }()
+
+ // Create a file
+ // This should add at least one event to the fsnotify event queue
+ var f *os.File
+ f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+
+ time.Sleep(time.Millisecond)
+ f.WriteString("data")
+ f.Sync()
+ f.Close()
+
+ time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
+
+ if err := testRename(testFile, testFileRenamed); err != nil {
+ t.Fatalf("rename failed: %s", err)
+ }
+
+ // Modify the file outside of the watched dir
+ f, err = os.Open(testFileRenamed)
+ if err != nil {
+ t.Fatalf("open test renamed file failed: %s", err)
+ }
+ f.WriteString("data")
+ f.Sync()
+ f.Close()
+
+ time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
+
+ // Recreate the file that was moved
+ f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Close()
+ time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+ cReceived := createReceived.value()
+ if cReceived != 2 {
+ t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2)
+ }
+ mReceived := modifyReceived.value()
+ if mReceived != 1 {
+ t.Fatalf("incorrect number of modify events received after 500 ms (%d vs %d)", mReceived, 1)
+ }
+ dReceived := deleteReceived.value()
+ rReceived := renameReceived.value()
+ if dReceived+rReceived != 1 {
+ t.Fatalf("incorrect number of rename+delete events received after 500 ms (%d vs %d)", rReceived+dReceived, 1)
+ }
+
+ // Try closing the fsnotify instance
+ t.Log("calling Close()")
+ watcher.Close()
+ t.Log("waiting for the event channel to become closed...")
+ select {
+ case <-done:
+ t.Log("event channel closed")
+ case <-time.After(2 * time.Second):
+ t.Fatal("event stream was not closed after 2 seconds")
+ }
+}
+
+func TestFsnotifyMultipleCreates(t *testing.T) {
+ watcher := newWatcher(t)
+
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for err := range watcher.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ testFile := filepath.Join(testDir, "TestFsnotifySeq.testfile")
+
+ addWatch(t, watcher, testDir)
+
+ // Receive events on the event channel on a separate goroutine
+ eventstream := watcher.Events
+ var createReceived, modifyReceived, deleteReceived counter
+ done := make(chan bool)
+ go func() {
+ for event := range eventstream {
+ // Only count relevant events
+ if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) {
+ t.Logf("event received: %s", event)
+ if event.Op&Remove == Remove {
+ deleteReceived.increment()
+ }
+ if event.Op&Create == Create {
+ createReceived.increment()
+ }
+ if event.Op&Write == Write {
+ modifyReceived.increment()
+ }
+ } else {
+ t.Logf("unexpected event received: %s", event)
+ }
+ }
+ done <- true
+ }()
+
+ // Create a file
+ // This should add at least one event to the fsnotify event queue
+ var f *os.File
+ f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+
+ time.Sleep(time.Millisecond)
+ f.WriteString("data")
+ f.Sync()
+ f.Close()
+
+ time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
+
+ os.Remove(testFile)
+
+ time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
+
+ // Recreate the file
+ f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Close()
+ time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
+
+ // Modify
+ f, err = os.OpenFile(testFile, os.O_WRONLY, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+
+ time.Sleep(time.Millisecond)
+ f.WriteString("data")
+ f.Sync()
+ f.Close()
+
+ time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
+
+ // Modify
+ f, err = os.OpenFile(testFile, os.O_WRONLY, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+
+ time.Sleep(time.Millisecond)
+ f.WriteString("data")
+ f.Sync()
+ f.Close()
+
+ time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+ cReceived := createReceived.value()
+ if cReceived != 2 {
+ t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2)
+ }
+ mReceived := modifyReceived.value()
+ if mReceived < 3 {
+ t.Fatalf("incorrect number of modify events received after 500 ms (%d vs atleast %d)", mReceived, 3)
+ }
+ dReceived := deleteReceived.value()
+ if dReceived != 1 {
+ t.Fatalf("incorrect number of rename+delete events received after 500 ms (%d vs %d)", dReceived, 1)
+ }
+
+ // Try closing the fsnotify instance
+ t.Log("calling Close()")
+ watcher.Close()
+ t.Log("waiting for the event channel to become closed...")
+ select {
+ case <-done:
+ t.Log("event channel closed")
+ case <-time.After(2 * time.Second):
+ t.Fatal("event stream was not closed after 2 seconds")
+ }
+}
+
+func TestFsnotifyDirOnly(t *testing.T) {
+ watcher := newWatcher(t)
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ // Create a file before watching directory
+ // This should NOT add any events to the fsnotify event queue
+ testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile")
+ {
+ var f *os.File
+ f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+ f.Close()
+ }
+
+ addWatch(t, watcher, testDir)
+
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for err := range watcher.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ testFile := filepath.Join(testDir, "TestFsnotifyDirOnly.testfile")
+
+ // Receive events on the event channel on a separate goroutine
+ eventstream := watcher.Events
+ var createReceived, modifyReceived, deleteReceived counter
+ done := make(chan bool)
+ go func() {
+ for event := range eventstream {
+ // Only count relevant events
+ if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileAlreadyExists) {
+ t.Logf("event received: %s", event)
+ if event.Op&Remove == Remove {
+ deleteReceived.increment()
+ }
+ if event.Op&Write == Write {
+ modifyReceived.increment()
+ }
+ if event.Op&Create == Create {
+ createReceived.increment()
+ }
+ } else {
+ t.Logf("unexpected event received: %s", event)
+ }
+ }
+ done <- true
+ }()
+
+ // Create a file
+ // This should add at least one event to the fsnotify event queue
+ var f *os.File
+ f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+
+ time.Sleep(time.Millisecond)
+ f.WriteString("data")
+ f.Sync()
+ f.Close()
+
+ time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
+
+ os.Remove(testFile)
+ os.Remove(testFileAlreadyExists)
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+ cReceived := createReceived.value()
+ if cReceived != 1 {
+ t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 1)
+ }
+ mReceived := modifyReceived.value()
+ if mReceived != 1 {
+ t.Fatalf("incorrect number of modify events received after 500 ms (%d vs %d)", mReceived, 1)
+ }
+ dReceived := deleteReceived.value()
+ if dReceived != 2 {
+ t.Fatalf("incorrect number of delete events received after 500 ms (%d vs %d)", dReceived, 2)
+ }
+
+ // Try closing the fsnotify instance
+ t.Log("calling Close()")
+ watcher.Close()
+ t.Log("waiting for the event channel to become closed...")
+ select {
+ case <-done:
+ t.Log("event channel closed")
+ case <-time.After(2 * time.Second):
+ t.Fatal("event stream was not closed after 2 seconds")
+ }
+}
+
+func TestFsnotifyDeleteWatchedDir(t *testing.T) {
+ watcher := newWatcher(t)
+ defer watcher.Close()
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ // Create a file before watching directory
+ testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile")
+ {
+ var f *os.File
+ f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+ f.Close()
+ }
+
+ addWatch(t, watcher, testDir)
+
+ // Add a watch for testFile
+ addWatch(t, watcher, testFileAlreadyExists)
+
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for err := range watcher.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ // Receive events on the event channel on a separate goroutine
+ eventstream := watcher.Events
+ var deleteReceived counter
+ go func() {
+ for event := range eventstream {
+ // Only count relevant events
+ if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFileAlreadyExists) {
+ t.Logf("event received: %s", event)
+ if event.Op&Remove == Remove {
+ deleteReceived.increment()
+ }
+ } else {
+ t.Logf("unexpected event received: %s", event)
+ }
+ }
+ }()
+
+ os.RemoveAll(testDir)
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+ dReceived := deleteReceived.value()
+ if dReceived < 2 {
+ t.Fatalf("did not receive at least %d delete events, received %d after 500 ms", 2, dReceived)
+ }
+}
+
+func TestFsnotifySubDir(t *testing.T) {
+ watcher := newWatcher(t)
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ testFile1 := filepath.Join(testDir, "TestFsnotifyFile1.testfile")
+ testSubDir := filepath.Join(testDir, "sub")
+ testSubDirFile := filepath.Join(testDir, "sub/TestFsnotifyFile1.testfile")
+
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for err := range watcher.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ // Receive events on the event channel on a separate goroutine
+ eventstream := watcher.Events
+ var createReceived, deleteReceived counter
+ done := make(chan bool)
+ go func() {
+ for event := range eventstream {
+ // Only count relevant events
+ if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testSubDir) || event.Name == filepath.Clean(testFile1) {
+ t.Logf("event received: %s", event)
+ if event.Op&Create == Create {
+ createReceived.increment()
+ }
+ if event.Op&Remove == Remove {
+ deleteReceived.increment()
+ }
+ } else {
+ t.Logf("unexpected event received: %s", event)
+ }
+ }
+ done <- true
+ }()
+
+ addWatch(t, watcher, testDir)
+
+ // Create sub-directory
+ if err := os.Mkdir(testSubDir, 0777); err != nil {
+ t.Fatalf("failed to create test sub-directory: %s", err)
+ }
+
+ // Create a file
+ var f *os.File
+ f, err := os.OpenFile(testFile1, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+ f.Close()
+
+ // Create a file (Should not see this! we are not watching subdir)
+ var fs *os.File
+ fs, err = os.OpenFile(testSubDirFile, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ fs.Sync()
+ fs.Close()
+
+ time.Sleep(200 * time.Millisecond)
+
+ // Make sure receive deletes for both file and sub-directory
+ os.RemoveAll(testSubDir)
+ os.Remove(testFile1)
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+ cReceived := createReceived.value()
+ if cReceived != 2 {
+ t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2)
+ }
+ dReceived := deleteReceived.value()
+ if dReceived != 2 {
+ t.Fatalf("incorrect number of delete events received after 500 ms (%d vs %d)", dReceived, 2)
+ }
+
+ // Try closing the fsnotify instance
+ t.Log("calling Close()")
+ watcher.Close()
+ t.Log("waiting for the event channel to become closed...")
+ select {
+ case <-done:
+ t.Log("event channel closed")
+ case <-time.After(2 * time.Second):
+ t.Fatal("event stream was not closed after 2 seconds")
+ }
+}
+
+func TestFsnotifyRename(t *testing.T) {
+ watcher := newWatcher(t)
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ addWatch(t, watcher, testDir)
+
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for err := range watcher.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ testFile := filepath.Join(testDir, "TestFsnotifyEvents.testfile")
+ testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed")
+
+ // Receive events on the event channel on a separate goroutine
+ eventstream := watcher.Events
+ var renameReceived counter
+ done := make(chan bool)
+ go func() {
+ for event := range eventstream {
+ // Only count relevant events
+ if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileRenamed) {
+ if event.Op&Rename == Rename {
+ renameReceived.increment()
+ }
+ t.Logf("event received: %s", event)
+ } else {
+ t.Logf("unexpected event received: %s", event)
+ }
+ }
+ done <- true
+ }()
+
+ // Create a file
+ // This should add at least one event to the fsnotify event queue
+ var f *os.File
+ f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+
+ f.WriteString("data")
+ f.Sync()
+ f.Close()
+
+ // Add a watch for testFile
+ addWatch(t, watcher, testFile)
+
+ if err := testRename(testFile, testFileRenamed); err != nil {
+ t.Fatalf("rename failed: %s", err)
+ }
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+ if renameReceived.value() == 0 {
+ t.Fatal("fsnotify rename events have not been received after 500 ms")
+ }
+
+ // Try closing the fsnotify instance
+ t.Log("calling Close()")
+ watcher.Close()
+ t.Log("waiting for the event channel to become closed...")
+ select {
+ case <-done:
+ t.Log("event channel closed")
+ case <-time.After(2 * time.Second):
+ t.Fatal("event stream was not closed after 2 seconds")
+ }
+
+ os.Remove(testFileRenamed)
+}
+
+func TestFsnotifyRenameToCreate(t *testing.T) {
+ watcher := newWatcher(t)
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ // Create directory to get file
+ testDirFrom := tempMkdir(t)
+ defer os.RemoveAll(testDirFrom)
+
+ addWatch(t, watcher, testDir)
+
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for err := range watcher.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ testFile := filepath.Join(testDirFrom, "TestFsnotifyEvents.testfile")
+ testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed")
+
+ // Receive events on the event channel on a separate goroutine
+ eventstream := watcher.Events
+ var createReceived counter
+ done := make(chan bool)
+ go func() {
+ for event := range eventstream {
+ // Only count relevant events
+ if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileRenamed) {
+ if event.Op&Create == Create {
+ createReceived.increment()
+ }
+ t.Logf("event received: %s", event)
+ } else {
+ t.Logf("unexpected event received: %s", event)
+ }
+ }
+ done <- true
+ }()
+
+ // Create a file
+ // This should add at least one event to the fsnotify event queue
+ var f *os.File
+ f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+ f.Close()
+
+ if err := testRename(testFile, testFileRenamed); err != nil {
+ t.Fatalf("rename failed: %s", err)
+ }
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+ if createReceived.value() == 0 {
+ t.Fatal("fsnotify create events have not been received after 500 ms")
+ }
+
+ // Try closing the fsnotify instance
+ t.Log("calling Close()")
+ watcher.Close()
+ t.Log("waiting for the event channel to become closed...")
+ select {
+ case <-done:
+ t.Log("event channel closed")
+ case <-time.After(2 * time.Second):
+ t.Fatal("event stream was not closed after 2 seconds")
+ }
+
+ os.Remove(testFileRenamed)
+}
+
+func TestFsnotifyRenameToOverwrite(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9", "windows":
+ t.Skipf("skipping test on %q (os.Rename over existing file does not create event).", runtime.GOOS)
+ }
+
+ watcher := newWatcher(t)
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ // Create directory to get file
+ testDirFrom := tempMkdir(t)
+ defer os.RemoveAll(testDirFrom)
+
+ testFile := filepath.Join(testDirFrom, "TestFsnotifyEvents.testfile")
+ testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed")
+
+ // Create a file
+ var fr *os.File
+ fr, err := os.OpenFile(testFileRenamed, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ fr.Sync()
+ fr.Close()
+
+ addWatch(t, watcher, testDir)
+
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for err := range watcher.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ // Receive events on the event channel on a separate goroutine
+ eventstream := watcher.Events
+ var eventReceived counter
+ done := make(chan bool)
+ go func() {
+ for event := range eventstream {
+ // Only count relevant events
+ if event.Name == filepath.Clean(testFileRenamed) {
+ eventReceived.increment()
+ t.Logf("event received: %s", event)
+ } else {
+ t.Logf("unexpected event received: %s", event)
+ }
+ }
+ done <- true
+ }()
+
+ // Create a file
+ // This should add at least one event to the fsnotify event queue
+ var f *os.File
+ f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+ f.Close()
+
+ if err := testRename(testFile, testFileRenamed); err != nil {
+ t.Fatalf("rename failed: %s", err)
+ }
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+ if eventReceived.value() == 0 {
+ t.Fatal("fsnotify events have not been received after 500 ms")
+ }
+
+ // Try closing the fsnotify instance
+ t.Log("calling Close()")
+ watcher.Close()
+ t.Log("waiting for the event channel to become closed...")
+ select {
+ case <-done:
+ t.Log("event channel closed")
+ case <-time.After(2 * time.Second):
+ t.Fatal("event stream was not closed after 2 seconds")
+ }
+
+ os.Remove(testFileRenamed)
+}
+
+func TestRemovalOfWatch(t *testing.T) {
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ // Create a file before watching directory
+ testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile")
+ {
+ var f *os.File
+ f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+ f.Close()
+ }
+
+ watcher := newWatcher(t)
+ defer watcher.Close()
+
+ addWatch(t, watcher, testDir)
+ if err := watcher.Remove(testDir); err != nil {
+ t.Fatalf("Could not remove the watch: %v\n", err)
+ }
+
+ go func() {
+ select {
+ case ev := <-watcher.Events:
+ t.Fatalf("We received event: %v\n", ev)
+ case <-time.After(500 * time.Millisecond):
+ t.Log("No event received, as expected.")
+ }
+ }()
+
+ time.Sleep(200 * time.Millisecond)
+ // Modify the file outside of the watched dir
+ f, err := os.Open(testFileAlreadyExists)
+ if err != nil {
+ t.Fatalf("Open test file failed: %s", err)
+ }
+ f.WriteString("data")
+ f.Sync()
+ f.Close()
+ if err := os.Chmod(testFileAlreadyExists, 0700); err != nil {
+ t.Fatalf("chmod failed: %s", err)
+ }
+ time.Sleep(400 * time.Millisecond)
+}
+
+func TestFsnotifyAttrib(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("attributes don't work on Windows.")
+ }
+
+ watcher := newWatcher(t)
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for err := range watcher.Errors {
+ t.Fatalf("error received: %s", err)
+ }
+ }()
+
+ testFile := filepath.Join(testDir, "TestFsnotifyAttrib.testfile")
+
+ // Receive events on the event channel on a separate goroutine
+ eventstream := watcher.Events
+ // The modifyReceived counter counts IsModify events that are not IsAttrib,
+ // and the attribReceived counts IsAttrib events (which are also IsModify as
+ // a consequence).
+ var modifyReceived counter
+ var attribReceived counter
+ done := make(chan bool)
+ go func() {
+ for event := range eventstream {
+ // Only count relevant events
+ if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) {
+ if event.Op&Write == Write {
+ modifyReceived.increment()
+ }
+ if event.Op&Chmod == Chmod {
+ attribReceived.increment()
+ }
+ t.Logf("event received: %s", event)
+ } else {
+ t.Logf("unexpected event received: %s", event)
+ }
+ }
+ done <- true
+ }()
+
+ // Create a file
+ // This should add at least one event to the fsnotify event queue
+ var f *os.File
+ f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+
+ f.WriteString("data")
+ f.Sync()
+ f.Close()
+
+ // Add a watch for testFile
+ addWatch(t, watcher, testFile)
+
+ if err := os.Chmod(testFile, 0700); err != nil {
+ t.Fatalf("chmod failed: %s", err)
+ }
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ // Creating/writing a file changes also the mtime, so IsAttrib should be set to true here
+ time.Sleep(500 * time.Millisecond)
+ if modifyReceived.value() != 0 {
+ t.Fatal("received an unexpected modify event when creating a test file")
+ }
+ if attribReceived.value() == 0 {
+ t.Fatal("fsnotify attribute events have not received after 500 ms")
+ }
+
+ // Modifying the contents of the file does not set the attrib flag (although eg. the mtime
+ // might have been modified).
+ modifyReceived.reset()
+ attribReceived.reset()
+
+ f, err = os.OpenFile(testFile, os.O_WRONLY, 0)
+ if err != nil {
+ t.Fatalf("reopening test file failed: %s", err)
+ }
+
+ f.WriteString("more data")
+ f.Sync()
+ f.Close()
+
+ time.Sleep(500 * time.Millisecond)
+
+ if modifyReceived.value() != 1 {
+ t.Fatal("didn't receive a modify event after changing test file contents")
+ }
+
+ if attribReceived.value() != 0 {
+ t.Fatal("did receive an unexpected attrib event after changing test file contents")
+ }
+
+ modifyReceived.reset()
+ attribReceived.reset()
+
+ // Doing a chmod on the file should trigger an event with the "attrib" flag set (the contents
+ // of the file are not changed though)
+ if err := os.Chmod(testFile, 0600); err != nil {
+ t.Fatalf("chmod failed: %s", err)
+ }
+
+ time.Sleep(500 * time.Millisecond)
+
+ if attribReceived.value() != 1 {
+ t.Fatal("didn't receive an attribute change after 500ms")
+ }
+
+ // Try closing the fsnotify instance
+ t.Log("calling Close()")
+ watcher.Close()
+ t.Log("waiting for the event channel to become closed...")
+ select {
+ case <-done:
+ t.Log("event channel closed")
+ case <-time.After(1e9):
+ t.Fatal("event stream was not closed after 1 second")
+ }
+
+ os.Remove(testFile)
+}
+
+func TestFsnotifyClose(t *testing.T) {
+ watcher := newWatcher(t)
+ watcher.Close()
+
+ var done int32
+ go func() {
+ watcher.Close()
+ atomic.StoreInt32(&done, 1)
+ }()
+
+ time.Sleep(50e6) // 50 ms
+ if atomic.LoadInt32(&done) == 0 {
+ t.Fatal("double Close() test failed: second Close() call didn't return")
+ }
+
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ if err := watcher.Add(testDir); err == nil {
+ t.Fatal("expected error on Watch() after Close(), got nil")
+ }
+}
+
+func TestFsnotifyFakeSymlink(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("symlinks don't work on Windows.")
+ }
+
+ watcher := newWatcher(t)
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ var errorsReceived counter
+ // Receive errors on the error channel on a separate goroutine
+ go func() {
+ for errors := range watcher.Errors {
+ t.Logf("Received error: %s", errors)
+ errorsReceived.increment()
+ }
+ }()
+
+ // Count the CREATE events received
+ var createEventsReceived, otherEventsReceived counter
+ go func() {
+ for ev := range watcher.Events {
+ t.Logf("event received: %s", ev)
+ if ev.Op&Create == Create {
+ createEventsReceived.increment()
+ } else {
+ otherEventsReceived.increment()
+ }
+ }
+ }()
+
+ addWatch(t, watcher, testDir)
+
+ if err := os.Symlink(filepath.Join(testDir, "zzz"), filepath.Join(testDir, "zzznew")); err != nil {
+ t.Fatalf("Failed to create bogus symlink: %s", err)
+ }
+ t.Logf("Created bogus symlink")
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+
+ // Should not be error, just no events for broken links (watching nothing)
+ if errorsReceived.value() > 0 {
+ t.Fatal("fsnotify errors have been received.")
+ }
+ if otherEventsReceived.value() > 0 {
+ t.Fatal("fsnotify other events received on the broken link")
+ }
+
+ // Except for 1 create event (for the link itself)
+ if createEventsReceived.value() == 0 {
+ t.Fatal("fsnotify create events were not received after 500 ms")
+ }
+ if createEventsReceived.value() > 1 {
+ t.Fatal("fsnotify more create events received than expected")
+ }
+
+ // Try closing the fsnotify instance
+ t.Log("calling Close()")
+ watcher.Close()
+}
+
+func TestCyclicSymlink(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("symlinks don't work on Windows.")
+ }
+
+ watcher := newWatcher(t)
+
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ link := path.Join(testDir, "link")
+ if err := os.Symlink(".", link); err != nil {
+ t.Fatalf("could not make symlink: %v", err)
+ }
+ addWatch(t, watcher, testDir)
+
+ var createEventsReceived counter
+ go func() {
+ for ev := range watcher.Events {
+ if ev.Op&Create == Create {
+ createEventsReceived.increment()
+ }
+ }
+ }()
+
+ if err := os.Remove(link); err != nil {
+ t.Fatalf("Error removing link: %v", err)
+ }
+
+ // It would be nice to be able to expect a delete event here, but kqueue has
+ // no way for us to get events on symlinks themselves, because opening them
+ // opens an fd to the file to which they point.
+
+ if err := ioutil.WriteFile(link, []byte("foo"), 0700); err != nil {
+ t.Fatalf("could not make symlink: %v", err)
+ }
+
+ // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
+ time.Sleep(500 * time.Millisecond)
+
+ if got := createEventsReceived.value(); got == 0 {
+ t.Errorf("want at least 1 create event got %v", got)
+ }
+
+ watcher.Close()
+}
+
+// TestConcurrentRemovalOfWatch tests that concurrent calls to RemoveWatch do not race.
+// See https://codereview.appspot.com/103300045/
+// go test -test.run=TestConcurrentRemovalOfWatch -test.cpu=1,1,1,1,1 -race
+func TestConcurrentRemovalOfWatch(t *testing.T) {
+ if runtime.GOOS != "darwin" {
+ t.Skip("regression test for race only present on darwin")
+ }
+
+ // Create directory to watch
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ // Create a file before watching directory
+ testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile")
+ {
+ var f *os.File
+ f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666)
+ if err != nil {
+ t.Fatalf("creating test file failed: %s", err)
+ }
+ f.Sync()
+ f.Close()
+ }
+
+ watcher := newWatcher(t)
+ defer watcher.Close()
+
+ addWatch(t, watcher, testDir)
+
+ // Test that RemoveWatch can be invoked concurrently, with no data races.
+ removed1 := make(chan struct{})
+ go func() {
+ defer close(removed1)
+ watcher.Remove(testDir)
+ }()
+ removed2 := make(chan struct{})
+ go func() {
+ close(removed2)
+ watcher.Remove(testDir)
+ }()
+ <-removed1
+ <-removed2
+}
+
+func TestClose(t *testing.T) {
+ // Regression test for #59 bad file descriptor from Close
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ watcher := newWatcher(t)
+ if err := watcher.Add(testDir); err != nil {
+ t.Fatalf("Expected no error on Add, got %v", err)
+ }
+ err := watcher.Close()
+ if err != nil {
+ t.Fatalf("Expected no error on Close, got %v.", err)
+ }
+}
+
+// TestRemoveWithClose tests if one can handle Remove events and, at the same
+// time, close Watcher object without any data races.
+func TestRemoveWithClose(t *testing.T) {
+ testDir := tempMkdir(t)
+ defer os.RemoveAll(testDir)
+
+ const fileN = 200
+ tempFiles := make([]string, 0, fileN)
+ for i := 0; i < fileN; i++ {
+ tempFiles = append(tempFiles, tempMkFile(t, testDir))
+ }
+ watcher := newWatcher(t)
+ if err := watcher.Add(testDir); err != nil {
+ t.Fatalf("Expected no error on Add, got %v", err)
+ }
+ startC, stopC := make(chan struct{}), make(chan struct{})
+ errC := make(chan error)
+ go func() {
+ for {
+ select {
+ case <-watcher.Errors:
+ case <-watcher.Events:
+ case <-stopC:
+ return
+ }
+ }
+ }()
+ go func() {
+ <-startC
+ for _, fileName := range tempFiles {
+ os.Remove(fileName)
+ }
+ }()
+ go func() {
+ <-startC
+ errC <- watcher.Close()
+ }()
+ close(startC)
+ defer close(stopC)
+ if err := <-errC; err != nil {
+ t.Fatalf("Expected no error on Close, got %v.", err)
+ }
+}
+
+func testRename(file1, file2 string) error {
+ switch runtime.GOOS {
+ case "windows", "plan9":
+ return os.Rename(file1, file2)
+ default:
+ cmd := exec.Command("mv", file1, file2)
+ return cmd.Run()
+ }
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/kqueue.go b/vendor/github.com/fsnotify/fsnotify/kqueue.go
new file mode 100644
index 000000000..c2b4acb18
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/kqueue.go
@@ -0,0 +1,503 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build freebsd openbsd netbsd dragonfly darwin
+
+package fsnotify
+
+import (
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+// Watcher watches a set of files, delivering events to a channel.
+type Watcher struct {
+ Events chan Event
+ Errors chan error
+ done chan bool // Channel for sending a "quit message" to the reader goroutine
+
+ kq int // File descriptor (as returned by the kqueue() syscall).
+
+ mu sync.Mutex // Protects access to watcher data
+ watches map[string]int // Map of watched file descriptors (key: path).
+ externalWatches map[string]bool // Map of watches added by user of the library.
+ dirFlags map[string]uint32 // Map of watched directories to fflags used in kqueue.
+ paths map[int]pathInfo // Map file descriptors to path names for processing kqueue events.
+ fileExists map[string]bool // Keep track of if we know this file exists (to stop duplicate create events).
+ isClosed bool // Set to true when Close() is first called
+}
+
+type pathInfo struct {
+ name string
+ isDir bool
+}
+
+// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
+func NewWatcher() (*Watcher, error) {
+ kq, err := kqueue()
+ if err != nil {
+ return nil, err
+ }
+
+ w := &Watcher{
+ kq: kq,
+ watches: make(map[string]int),
+ dirFlags: make(map[string]uint32),
+ paths: make(map[int]pathInfo),
+ fileExists: make(map[string]bool),
+ externalWatches: make(map[string]bool),
+ Events: make(chan Event),
+ Errors: make(chan error),
+ done: make(chan bool),
+ }
+
+ go w.readEvents()
+ return w, nil
+}
+
+// Close removes all watches and closes the events channel.
+func (w *Watcher) Close() error {
+ w.mu.Lock()
+ if w.isClosed {
+ w.mu.Unlock()
+ return nil
+ }
+ w.isClosed = true
+ w.mu.Unlock()
+
+ // copy paths to remove while locked
+ w.mu.Lock()
+ var pathsToRemove = make([]string, 0, len(w.watches))
+ for name := range w.watches {
+ pathsToRemove = append(pathsToRemove, name)
+ }
+ w.mu.Unlock()
+ // unlock before calling Remove, which also locks
+
+ var err error
+ for _, name := range pathsToRemove {
+ if e := w.Remove(name); e != nil && err == nil {
+ err = e
+ }
+ }
+
+ // Send "quit" message to the reader goroutine:
+ w.done <- true
+
+ return nil
+}
+
+// Add starts watching the named file or directory (non-recursively).
+func (w *Watcher) Add(name string) error {
+ w.mu.Lock()
+ w.externalWatches[name] = true
+ w.mu.Unlock()
+ _, err := w.addWatch(name, noteAllEvents)
+ return err
+}
+
+// Remove stops watching the the named file or directory (non-recursively).
+func (w *Watcher) Remove(name string) error {
+ name = filepath.Clean(name)
+ w.mu.Lock()
+ watchfd, ok := w.watches[name]
+ w.mu.Unlock()
+ if !ok {
+ return fmt.Errorf("can't remove non-existent kevent watch for: %s", name)
+ }
+
+ const registerRemove = unix.EV_DELETE
+ if err := register(w.kq, []int{watchfd}, registerRemove, 0); err != nil {
+ return err
+ }
+
+ unix.Close(watchfd)
+
+ w.mu.Lock()
+ isDir := w.paths[watchfd].isDir
+ delete(w.watches, name)
+ delete(w.paths, watchfd)
+ delete(w.dirFlags, name)
+ w.mu.Unlock()
+
+ // Find all watched paths that are in this directory that are not external.
+ if isDir {
+ var pathsToRemove []string
+ w.mu.Lock()
+ for _, path := range w.paths {
+ wdir, _ := filepath.Split(path.name)
+ if filepath.Clean(wdir) == name {
+ if !w.externalWatches[path.name] {
+ pathsToRemove = append(pathsToRemove, path.name)
+ }
+ }
+ }
+ w.mu.Unlock()
+ for _, name := range pathsToRemove {
+ // Since these are internal, not much sense in propagating error
+ // to the user, as that will just confuse them with an error about
+ // a path they did not explicitly watch themselves.
+ w.Remove(name)
+ }
+ }
+
+ return nil
+}
+
+// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE)
+const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME
+
+// keventWaitTime to block on each read from kevent
+var keventWaitTime = durationToTimespec(100 * time.Millisecond)
+
+// addWatch adds name to the watched file set.
+// The flags are interpreted as described in kevent(2).
+// Returns the real path to the file which was added, if any, which may be different from the one passed in the case of symlinks.
+func (w *Watcher) addWatch(name string, flags uint32) (string, error) {
+ var isDir bool
+ // Make ./name and name equivalent
+ name = filepath.Clean(name)
+
+ w.mu.Lock()
+ if w.isClosed {
+ w.mu.Unlock()
+ return "", errors.New("kevent instance already closed")
+ }
+ watchfd, alreadyWatching := w.watches[name]
+ // We already have a watch, but we can still override flags.
+ if alreadyWatching {
+ isDir = w.paths[watchfd].isDir
+ }
+ w.mu.Unlock()
+
+ if !alreadyWatching {
+ fi, err := os.Lstat(name)
+ if err != nil {
+ return "", err
+ }
+
+ // Don't watch sockets.
+ if fi.Mode()&os.ModeSocket == os.ModeSocket {
+ return "", nil
+ }
+
+ // Don't watch named pipes.
+ if fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe {
+ return "", nil
+ }
+
+ // Follow Symlinks
+ // Unfortunately, Linux can add bogus symlinks to watch list without
+ // issue, and Windows can't do symlinks period (AFAIK). To maintain
+ // consistency, we will act like everything is fine. There will simply
+ // be no file events for broken symlinks.
+ // Hence the returns of nil on errors.
+ if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
+ name, err = filepath.EvalSymlinks(name)
+ if err != nil {
+ return "", nil
+ }
+
+ w.mu.Lock()
+ _, alreadyWatching = w.watches[name]
+ w.mu.Unlock()
+
+ if alreadyWatching {
+ return name, nil
+ }
+
+ fi, err = os.Lstat(name)
+ if err != nil {
+ return "", nil
+ }
+ }
+
+ watchfd, err = unix.Open(name, openMode, 0700)
+ if watchfd == -1 {
+ return "", err
+ }
+
+ isDir = fi.IsDir()
+ }
+
+ const registerAdd = unix.EV_ADD | unix.EV_CLEAR | unix.EV_ENABLE
+ if err := register(w.kq, []int{watchfd}, registerAdd, flags); err != nil {
+ unix.Close(watchfd)
+ return "", err
+ }
+
+ if !alreadyWatching {
+ w.mu.Lock()
+ w.watches[name] = watchfd
+ w.paths[watchfd] = pathInfo{name: name, isDir: isDir}
+ w.mu.Unlock()
+ }
+
+ if isDir {
+ // Watch the directory if it has not been watched before,
+ // or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles)
+ w.mu.Lock()
+
+ watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE &&
+ (!alreadyWatching || (w.dirFlags[name]&unix.NOTE_WRITE) != unix.NOTE_WRITE)
+ // Store flags so this watch can be updated later
+ w.dirFlags[name] = flags
+ w.mu.Unlock()
+
+ if watchDir {
+ if err := w.watchDirectoryFiles(name); err != nil {
+ return "", err
+ }
+ }
+ }
+ return name, nil
+}
+
+// readEvents reads from kqueue and converts the received kevents into
+// Event values that it sends down the Events channel.
+func (w *Watcher) readEvents() {
+ eventBuffer := make([]unix.Kevent_t, 10)
+
+ for {
+ // See if there is a message on the "done" channel
+ select {
+ case <-w.done:
+ err := unix.Close(w.kq)
+ if err != nil {
+ w.Errors <- err
+ }
+ close(w.Events)
+ close(w.Errors)
+ return
+ default:
+ }
+
+ // Get new events
+ kevents, err := read(w.kq, eventBuffer, &keventWaitTime)
+ // EINTR is okay, the syscall was interrupted before timeout expired.
+ if err != nil && err != unix.EINTR {
+ w.Errors <- err
+ continue
+ }
+
+ // Flush the events we received to the Events channel
+ for len(kevents) > 0 {
+ kevent := &kevents[0]
+ watchfd := int(kevent.Ident)
+ mask := uint32(kevent.Fflags)
+ w.mu.Lock()
+ path := w.paths[watchfd]
+ w.mu.Unlock()
+ event := newEvent(path.name, mask)
+
+ if path.isDir && !(event.Op&Remove == Remove) {
+ // Double check to make sure the directory exists. This can happen when
+ // we do a rm -fr on a recursively watched folders and we receive a
+ // modification event first but the folder has been deleted and later
+ // receive the delete event
+ if _, err := os.Lstat(event.Name); os.IsNotExist(err) {
+ // mark is as delete event
+ event.Op |= Remove
+ }
+ }
+
+ if event.Op&Rename == Rename || event.Op&Remove == Remove {
+ w.Remove(event.Name)
+ w.mu.Lock()
+ delete(w.fileExists, event.Name)
+ w.mu.Unlock()
+ }
+
+ if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) {
+ w.sendDirectoryChangeEvents(event.Name)
+ } else {
+ // Send the event on the Events channel
+ w.Events <- event
+ }
+
+ if event.Op&Remove == Remove {
+ // Look for a file that may have overwritten this.
+ // For example, mv f1 f2 will delete f2, then create f2.
+ if path.isDir {
+ fileDir := filepath.Clean(event.Name)
+ w.mu.Lock()
+ _, found := w.watches[fileDir]
+ w.mu.Unlock()
+ if found {
+ // make sure the directory exists before we watch for changes. When we
+ // do a recursive watch and perform rm -fr, the parent directory might
+ // have gone missing, ignore the missing directory and let the
+ // upcoming delete event remove the watch from the parent directory.
+ if _, err := os.Lstat(fileDir); err == nil {
+ w.sendDirectoryChangeEvents(fileDir)
+ }
+ }
+ } else {
+ filePath := filepath.Clean(event.Name)
+ if fileInfo, err := os.Lstat(filePath); err == nil {
+ w.sendFileCreatedEventIfNew(filePath, fileInfo)
+ }
+ }
+ }
+
+ // Move to next event
+ kevents = kevents[1:]
+ }
+ }
+}
+
+// newEvent returns an platform-independent Event based on kqueue Fflags.
+func newEvent(name string, mask uint32) Event {
+ e := Event{Name: name}
+ if mask&unix.NOTE_DELETE == unix.NOTE_DELETE {
+ e.Op |= Remove
+ }
+ if mask&unix.NOTE_WRITE == unix.NOTE_WRITE {
+ e.Op |= Write
+ }
+ if mask&unix.NOTE_RENAME == unix.NOTE_RENAME {
+ e.Op |= Rename
+ }
+ if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB {
+ e.Op |= Chmod
+ }
+ return e
+}
+
+func newCreateEvent(name string) Event {
+ return Event{Name: name, Op: Create}
+}
+
+// watchDirectoryFiles to mimic inotify when adding a watch on a directory
+func (w *Watcher) watchDirectoryFiles(dirPath string) error {
+ // Get all files
+ files, err := ioutil.ReadDir(dirPath)
+ if err != nil {
+ return err
+ }
+
+ for _, fileInfo := range files {
+ filePath := filepath.Join(dirPath, fileInfo.Name())
+ filePath, err = w.internalWatch(filePath, fileInfo)
+ if err != nil {
+ return err
+ }
+
+ w.mu.Lock()
+ w.fileExists[filePath] = true
+ w.mu.Unlock()
+ }
+
+ return nil
+}
+
+// sendDirectoryEvents searches the directory for newly created files
+// and sends them over the event channel. This functionality is to have
+// the BSD version of fsnotify match Linux inotify which provides a
+// create event for files created in a watched directory.
+func (w *Watcher) sendDirectoryChangeEvents(dirPath string) {
+ // Get all files
+ files, err := ioutil.ReadDir(dirPath)
+ if err != nil {
+ w.Errors <- err
+ }
+
+ // Search for new files
+ for _, fileInfo := range files {
+ filePath := filepath.Join(dirPath, fileInfo.Name())
+ err := w.sendFileCreatedEventIfNew(filePath, fileInfo)
+
+ if err != nil {
+ return
+ }
+ }
+}
+
+// sendFileCreatedEvent sends a create event if the file isn't already being tracked.
+func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) {
+ w.mu.Lock()
+ _, doesExist := w.fileExists[filePath]
+ w.mu.Unlock()
+ if !doesExist {
+ // Send create event
+ w.Events <- newCreateEvent(filePath)
+ }
+
+ // like watchDirectoryFiles (but without doing another ReadDir)
+ filePath, err = w.internalWatch(filePath, fileInfo)
+ if err != nil {
+ return err
+ }
+
+ w.mu.Lock()
+ w.fileExists[filePath] = true
+ w.mu.Unlock()
+
+ return nil
+}
+
+func (w *Watcher) internalWatch(name string, fileInfo os.FileInfo) (string, error) {
+ if fileInfo.IsDir() {
+ // mimic Linux providing delete events for subdirectories
+ // but preserve the flags used if currently watching subdirectory
+ w.mu.Lock()
+ flags := w.dirFlags[name]
+ w.mu.Unlock()
+
+ flags |= unix.NOTE_DELETE | unix.NOTE_RENAME
+ return w.addWatch(name, flags)
+ }
+
+ // watch file to mimic Linux inotify
+ return w.addWatch(name, noteAllEvents)
+}
+
+// kqueue creates a new kernel event queue and returns a descriptor.
+func kqueue() (kq int, err error) {
+ kq, err = unix.Kqueue()
+ if kq == -1 {
+ return kq, err
+ }
+ return kq, nil
+}
+
+// register events with the queue
+func register(kq int, fds []int, flags int, fflags uint32) error {
+ changes := make([]unix.Kevent_t, len(fds))
+
+ for i, fd := range fds {
+ // SetKevent converts int to the platform-specific types:
+ unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags)
+ changes[i].Fflags = fflags
+ }
+
+ // register the events
+ success, err := unix.Kevent(kq, changes, nil, nil)
+ if success == -1 {
+ return err
+ }
+ return nil
+}
+
+// read retrieves pending events, or waits until an event occurs.
+// A timeout of nil blocks indefinitely, while 0 polls the queue.
+func read(kq int, events []unix.Kevent_t, timeout *unix.Timespec) ([]unix.Kevent_t, error) {
+ n, err := unix.Kevent(kq, nil, events, timeout)
+ if err != nil {
+ return nil, err
+ }
+ return events[0:n], nil
+}
+
+// durationToTimespec prepares a timeout value
+func durationToTimespec(d time.Duration) unix.Timespec {
+ return unix.NsecToTimespec(d.Nanoseconds())
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go b/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go
new file mode 100644
index 000000000..7d8de1451
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go
@@ -0,0 +1,11 @@
+// Copyright 2013 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build freebsd openbsd netbsd dragonfly
+
+package fsnotify
+
+import "golang.org/x/sys/unix"
+
+const openMode = unix.O_NONBLOCK | unix.O_RDONLY
diff --git a/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go b/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go
new file mode 100644
index 000000000..9139e1716
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go
@@ -0,0 +1,12 @@
+// Copyright 2013 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin
+
+package fsnotify
+
+import "golang.org/x/sys/unix"
+
+// note: this constant is not defined on BSD
+const openMode = unix.O_EVTONLY
diff --git a/vendor/github.com/fsnotify/fsnotify/windows.go b/vendor/github.com/fsnotify/fsnotify/windows.go
new file mode 100644
index 000000000..09436f31d
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/windows.go
@@ -0,0 +1,561 @@
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build windows
+
+package fsnotify
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sync"
+ "syscall"
+ "unsafe"
+)
+
+// Watcher watches a set of files, delivering events to a channel.
+type Watcher struct {
+ Events chan Event
+ Errors chan error
+ isClosed bool // Set to true when Close() is first called
+ mu sync.Mutex // Map access
+ port syscall.Handle // Handle to completion port
+ watches watchMap // Map of watches (key: i-number)
+ input chan *input // Inputs to the reader are sent on this channel
+ quit chan chan<- error
+}
+
+// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
+func NewWatcher() (*Watcher, error) {
+ port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0)
+ if e != nil {
+ return nil, os.NewSyscallError("CreateIoCompletionPort", e)
+ }
+ w := &Watcher{
+ port: port,
+ watches: make(watchMap),
+ input: make(chan *input, 1),
+ Events: make(chan Event, 50),
+ Errors: make(chan error),
+ quit: make(chan chan<- error, 1),
+ }
+ go w.readEvents()
+ return w, nil
+}
+
+// Close removes all watches and closes the events channel.
+func (w *Watcher) Close() error {
+ if w.isClosed {
+ return nil
+ }
+ w.isClosed = true
+
+ // Send "quit" message to the reader goroutine
+ ch := make(chan error)
+ w.quit <- ch
+ if err := w.wakeupReader(); err != nil {
+ return err
+ }
+ return <-ch
+}
+
+// Add starts watching the named file or directory (non-recursively).
+func (w *Watcher) Add(name string) error {
+ if w.isClosed {
+ return errors.New("watcher already closed")
+ }
+ in := &input{
+ op: opAddWatch,
+ path: filepath.Clean(name),
+ flags: sysFSALLEVENTS,
+ reply: make(chan error),
+ }
+ w.input <- in
+ if err := w.wakeupReader(); err != nil {
+ return err
+ }
+ return <-in.reply
+}
+
+// Remove stops watching the the named file or directory (non-recursively).
+func (w *Watcher) Remove(name string) error {
+ in := &input{
+ op: opRemoveWatch,
+ path: filepath.Clean(name),
+ reply: make(chan error),
+ }
+ w.input <- in
+ if err := w.wakeupReader(); err != nil {
+ return err
+ }
+ return <-in.reply
+}
+
+const (
+ // Options for AddWatch
+ sysFSONESHOT = 0x80000000
+ sysFSONLYDIR = 0x1000000
+
+ // Events
+ sysFSACCESS = 0x1
+ sysFSALLEVENTS = 0xfff
+ sysFSATTRIB = 0x4
+ sysFSCLOSE = 0x18
+ sysFSCREATE = 0x100
+ sysFSDELETE = 0x200
+ sysFSDELETESELF = 0x400
+ sysFSMODIFY = 0x2
+ sysFSMOVE = 0xc0
+ sysFSMOVEDFROM = 0x40
+ sysFSMOVEDTO = 0x80
+ sysFSMOVESELF = 0x800
+
+ // Special events
+ sysFSIGNORED = 0x8000
+ sysFSQOVERFLOW = 0x4000
+)
+
+func newEvent(name string, mask uint32) Event {
+ e := Event{Name: name}
+ if mask&sysFSCREATE == sysFSCREATE || mask&sysFSMOVEDTO == sysFSMOVEDTO {
+ e.Op |= Create
+ }
+ if mask&sysFSDELETE == sysFSDELETE || mask&sysFSDELETESELF == sysFSDELETESELF {
+ e.Op |= Remove
+ }
+ if mask&sysFSMODIFY == sysFSMODIFY {
+ e.Op |= Write
+ }
+ if mask&sysFSMOVE == sysFSMOVE || mask&sysFSMOVESELF == sysFSMOVESELF || mask&sysFSMOVEDFROM == sysFSMOVEDFROM {
+ e.Op |= Rename
+ }
+ if mask&sysFSATTRIB == sysFSATTRIB {
+ e.Op |= Chmod
+ }
+ return e
+}
+
+const (
+ opAddWatch = iota
+ opRemoveWatch
+)
+
+const (
+ provisional uint64 = 1 << (32 + iota)
+)
+
+type input struct {
+ op int
+ path string
+ flags uint32
+ reply chan error
+}
+
+type inode struct {
+ handle syscall.Handle
+ volume uint32
+ index uint64
+}
+
+type watch struct {
+ ov syscall.Overlapped
+ ino *inode // i-number
+ path string // Directory path
+ mask uint64 // Directory itself is being watched with these notify flags
+ names map[string]uint64 // Map of names being watched and their notify flags
+ rename string // Remembers the old name while renaming a file
+ buf [4096]byte
+}
+
+type indexMap map[uint64]*watch
+type watchMap map[uint32]indexMap
+
+func (w *Watcher) wakeupReader() error {
+ e := syscall.PostQueuedCompletionStatus(w.port, 0, 0, nil)
+ if e != nil {
+ return os.NewSyscallError("PostQueuedCompletionStatus", e)
+ }
+ return nil
+}
+
+func getDir(pathname string) (dir string, err error) {
+ attr, e := syscall.GetFileAttributes(syscall.StringToUTF16Ptr(pathname))
+ if e != nil {
+ return "", os.NewSyscallError("GetFileAttributes", e)
+ }
+ if attr&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 {
+ dir = pathname
+ } else {
+ dir, _ = filepath.Split(pathname)
+ dir = filepath.Clean(dir)
+ }
+ return
+}
+
+func getIno(path string) (ino *inode, err error) {
+ h, e := syscall.CreateFile(syscall.StringToUTF16Ptr(path),
+ syscall.FILE_LIST_DIRECTORY,
+ syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
+ nil, syscall.OPEN_EXISTING,
+ syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OVERLAPPED, 0)
+ if e != nil {
+ return nil, os.NewSyscallError("CreateFile", e)
+ }
+ var fi syscall.ByHandleFileInformation
+ if e = syscall.GetFileInformationByHandle(h, &fi); e != nil {
+ syscall.CloseHandle(h)
+ return nil, os.NewSyscallError("GetFileInformationByHandle", e)
+ }
+ ino = &inode{
+ handle: h,
+ volume: fi.VolumeSerialNumber,
+ index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow),
+ }
+ return ino, nil
+}
+
+// Must run within the I/O thread.
+func (m watchMap) get(ino *inode) *watch {
+ if i := m[ino.volume]; i != nil {
+ return i[ino.index]
+ }
+ return nil
+}
+
+// Must run within the I/O thread.
+func (m watchMap) set(ino *inode, watch *watch) {
+ i := m[ino.volume]
+ if i == nil {
+ i = make(indexMap)
+ m[ino.volume] = i
+ }
+ i[ino.index] = watch
+}
+
+// Must run within the I/O thread.
+func (w *Watcher) addWatch(pathname string, flags uint64) error {
+ dir, err := getDir(pathname)
+ if err != nil {
+ return err
+ }
+ if flags&sysFSONLYDIR != 0 && pathname != dir {
+ return nil
+ }
+ ino, err := getIno(dir)
+ if err != nil {
+ return err
+ }
+ w.mu.Lock()
+ watchEntry := w.watches.get(ino)
+ w.mu.Unlock()
+ if watchEntry == nil {
+ if _, e := syscall.CreateIoCompletionPort(ino.handle, w.port, 0, 0); e != nil {
+ syscall.CloseHandle(ino.handle)
+ return os.NewSyscallError("CreateIoCompletionPort", e)
+ }
+ watchEntry = &watch{
+ ino: ino,
+ path: dir,
+ names: make(map[string]uint64),
+ }
+ w.mu.Lock()
+ w.watches.set(ino, watchEntry)
+ w.mu.Unlock()
+ flags |= provisional
+ } else {
+ syscall.CloseHandle(ino.handle)
+ }
+ if pathname == dir {
+ watchEntry.mask |= flags
+ } else {
+ watchEntry.names[filepath.Base(pathname)] |= flags
+ }
+ if err = w.startRead(watchEntry); err != nil {
+ return err
+ }
+ if pathname == dir {
+ watchEntry.mask &= ^provisional
+ } else {
+ watchEntry.names[filepath.Base(pathname)] &= ^provisional
+ }
+ return nil
+}
+
+// Must run within the I/O thread.
+func (w *Watcher) remWatch(pathname string) error {
+ dir, err := getDir(pathname)
+ if err != nil {
+ return err
+ }
+ ino, err := getIno(dir)
+ if err != nil {
+ return err
+ }
+ w.mu.Lock()
+ watch := w.watches.get(ino)
+ w.mu.Unlock()
+ if watch == nil {
+ return fmt.Errorf("can't remove non-existent watch for: %s", pathname)
+ }
+ if pathname == dir {
+ w.sendEvent(watch.path, watch.mask&sysFSIGNORED)
+ watch.mask = 0
+ } else {
+ name := filepath.Base(pathname)
+ w.sendEvent(filepath.Join(watch.path, name), watch.names[name]&sysFSIGNORED)
+ delete(watch.names, name)
+ }
+ return w.startRead(watch)
+}
+
+// Must run within the I/O thread.
+func (w *Watcher) deleteWatch(watch *watch) {
+ for name, mask := range watch.names {
+ if mask&provisional == 0 {
+ w.sendEvent(filepath.Join(watch.path, name), mask&sysFSIGNORED)
+ }
+ delete(watch.names, name)
+ }
+ if watch.mask != 0 {
+ if watch.mask&provisional == 0 {
+ w.sendEvent(watch.path, watch.mask&sysFSIGNORED)
+ }
+ watch.mask = 0
+ }
+}
+
+// Must run within the I/O thread.
+func (w *Watcher) startRead(watch *watch) error {
+ if e := syscall.CancelIo(watch.ino.handle); e != nil {
+ w.Errors <- os.NewSyscallError("CancelIo", e)
+ w.deleteWatch(watch)
+ }
+ mask := toWindowsFlags(watch.mask)
+ for _, m := range watch.names {
+ mask |= toWindowsFlags(m)
+ }
+ if mask == 0 {
+ if e := syscall.CloseHandle(watch.ino.handle); e != nil {
+ w.Errors <- os.NewSyscallError("CloseHandle", e)
+ }
+ w.mu.Lock()
+ delete(w.watches[watch.ino.volume], watch.ino.index)
+ w.mu.Unlock()
+ return nil
+ }
+ e := syscall.ReadDirectoryChanges(watch.ino.handle, &watch.buf[0],
+ uint32(unsafe.Sizeof(watch.buf)), false, mask, nil, &watch.ov, 0)
+ if e != nil {
+ err := os.NewSyscallError("ReadDirectoryChanges", e)
+ if e == syscall.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 {
+ // Watched directory was probably removed
+ if w.sendEvent(watch.path, watch.mask&sysFSDELETESELF) {
+ if watch.mask&sysFSONESHOT != 0 {
+ watch.mask = 0
+ }
+ }
+ err = nil
+ }
+ w.deleteWatch(watch)
+ w.startRead(watch)
+ return err
+ }
+ return nil
+}
+
+// readEvents reads from the I/O completion port, converts the
+// received events into Event objects and sends them via the Events channel.
+// Entry point to the I/O thread.
+func (w *Watcher) readEvents() {
+ var (
+ n, key uint32
+ ov *syscall.Overlapped
+ )
+ runtime.LockOSThread()
+
+ for {
+ e := syscall.GetQueuedCompletionStatus(w.port, &n, &key, &ov, syscall.INFINITE)
+ watch := (*watch)(unsafe.Pointer(ov))
+
+ if watch == nil {
+ select {
+ case ch := <-w.quit:
+ w.mu.Lock()
+ var indexes []indexMap
+ for _, index := range w.watches {
+ indexes = append(indexes, index)
+ }
+ w.mu.Unlock()
+ for _, index := range indexes {
+ for _, watch := range index {
+ w.deleteWatch(watch)
+ w.startRead(watch)
+ }
+ }
+ var err error
+ if e := syscall.CloseHandle(w.port); e != nil {
+ err = os.NewSyscallError("CloseHandle", e)
+ }
+ close(w.Events)
+ close(w.Errors)
+ ch <- err
+ return
+ case in := <-w.input:
+ switch in.op {
+ case opAddWatch:
+ in.reply <- w.addWatch(in.path, uint64(in.flags))
+ case opRemoveWatch:
+ in.reply <- w.remWatch(in.path)
+ }
+ default:
+ }
+ continue
+ }
+
+ switch e {
+ case syscall.ERROR_MORE_DATA:
+ if watch == nil {
+ w.Errors <- errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer")
+ } else {
+ // The i/o succeeded but the buffer is full.
+ // In theory we should be building up a full packet.
+ // In practice we can get away with just carrying on.
+ n = uint32(unsafe.Sizeof(watch.buf))
+ }
+ case syscall.ERROR_ACCESS_DENIED:
+ // Watched directory was probably removed
+ w.sendEvent(watch.path, watch.mask&sysFSDELETESELF)
+ w.deleteWatch(watch)
+ w.startRead(watch)
+ continue
+ case syscall.ERROR_OPERATION_ABORTED:
+ // CancelIo was called on this handle
+ continue
+ default:
+ w.Errors <- os.NewSyscallError("GetQueuedCompletionPort", e)
+ continue
+ case nil:
+ }
+
+ var offset uint32
+ for {
+ if n == 0 {
+ w.Events <- newEvent("", sysFSQOVERFLOW)
+ w.Errors <- errors.New("short read in readEvents()")
+ break
+ }
+
+ // Point "raw" to the event in the buffer
+ raw := (*syscall.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset]))
+ buf := (*[syscall.MAX_PATH]uint16)(unsafe.Pointer(&raw.FileName))
+ name := syscall.UTF16ToString(buf[:raw.FileNameLength/2])
+ fullname := filepath.Join(watch.path, name)
+
+ var mask uint64
+ switch raw.Action {
+ case syscall.FILE_ACTION_REMOVED:
+ mask = sysFSDELETESELF
+ case syscall.FILE_ACTION_MODIFIED:
+ mask = sysFSMODIFY
+ case syscall.FILE_ACTION_RENAMED_OLD_NAME:
+ watch.rename = name
+ case syscall.FILE_ACTION_RENAMED_NEW_NAME:
+ if watch.names[watch.rename] != 0 {
+ watch.names[name] |= watch.names[watch.rename]
+ delete(watch.names, watch.rename)
+ mask = sysFSMOVESELF
+ }
+ }
+
+ sendNameEvent := func() {
+ if w.sendEvent(fullname, watch.names[name]&mask) {
+ if watch.names[name]&sysFSONESHOT != 0 {
+ delete(watch.names, name)
+ }
+ }
+ }
+ if raw.Action != syscall.FILE_ACTION_RENAMED_NEW_NAME {
+ sendNameEvent()
+ }
+ if raw.Action == syscall.FILE_ACTION_REMOVED {
+ w.sendEvent(fullname, watch.names[name]&sysFSIGNORED)
+ delete(watch.names, name)
+ }
+ if w.sendEvent(fullname, watch.mask&toFSnotifyFlags(raw.Action)) {
+ if watch.mask&sysFSONESHOT != 0 {
+ watch.mask = 0
+ }
+ }
+ if raw.Action == syscall.FILE_ACTION_RENAMED_NEW_NAME {
+ fullname = filepath.Join(watch.path, watch.rename)
+ sendNameEvent()
+ }
+
+ // Move to the next event in the buffer
+ if raw.NextEntryOffset == 0 {
+ break
+ }
+ offset += raw.NextEntryOffset
+
+ // Error!
+ if offset >= n {
+ w.Errors <- errors.New("Windows system assumed buffer larger than it is, events have likely been missed.")
+ break
+ }
+ }
+
+ if err := w.startRead(watch); err != nil {
+ w.Errors <- err
+ }
+ }
+}
+
+func (w *Watcher) sendEvent(name string, mask uint64) bool {
+ if mask == 0 {
+ return false
+ }
+ event := newEvent(name, uint32(mask))
+ select {
+ case ch := <-w.quit:
+ w.quit <- ch
+ case w.Events <- event:
+ }
+ return true
+}
+
+func toWindowsFlags(mask uint64) uint32 {
+ var m uint32
+ if mask&sysFSACCESS != 0 {
+ m |= syscall.FILE_NOTIFY_CHANGE_LAST_ACCESS
+ }
+ if mask&sysFSMODIFY != 0 {
+ m |= syscall.FILE_NOTIFY_CHANGE_LAST_WRITE
+ }
+ if mask&sysFSATTRIB != 0 {
+ m |= syscall.FILE_NOTIFY_CHANGE_ATTRIBUTES
+ }
+ if mask&(sysFSMOVE|sysFSCREATE|sysFSDELETE) != 0 {
+ m |= syscall.FILE_NOTIFY_CHANGE_FILE_NAME | syscall.FILE_NOTIFY_CHANGE_DIR_NAME
+ }
+ return m
+}
+
+func toFSnotifyFlags(action uint32) uint64 {
+ switch action {
+ case syscall.FILE_ACTION_ADDED:
+ return sysFSCREATE
+ case syscall.FILE_ACTION_REMOVED:
+ return sysFSDELETE
+ case syscall.FILE_ACTION_MODIFIED:
+ return sysFSMODIFY
+ case syscall.FILE_ACTION_RENAMED_OLD_NAME:
+ return sysFSMOVEDFROM
+ case syscall.FILE_ACTION_RENAMED_NEW_NAME:
+ return sysFSMOVEDTO
+ }
+ return 0
+}
diff --git a/vendor/github.com/hashicorp/hcl/.github/ISSUE_TEMPLATE.md b/vendor/github.com/hashicorp/hcl/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 000000000..2d7fc4bf6
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,21 @@
+### HCL Template
+```hcl
+# Place your HCL configuration file here
+```
+
+### Expected behavior
+What should have happened?
+
+### Actual behavior
+What actually happened?
+
+### Steps to reproduce
+1.
+2.
+3.
+
+### References
+Are there any other GitHub issues (open or closed) that should
+be linked here? For example:
+- GH-1234
+- ...
diff --git a/vendor/github.com/hashicorp/hcl/.gitignore b/vendor/github.com/hashicorp/hcl/.gitignore
new file mode 100644
index 000000000..15586a2b5
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/.gitignore
@@ -0,0 +1,9 @@
+y.output
+
+# ignore intellij files
+.idea
+*.iml
+*.ipr
+*.iws
+
+*.test
diff --git a/vendor/github.com/hashicorp/hcl/.travis.yml b/vendor/github.com/hashicorp/hcl/.travis.yml
new file mode 100644
index 000000000..3f83d9023
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/.travis.yml
@@ -0,0 +1,12 @@
+sudo: false
+
+language: go
+
+go:
+ - 1.8
+
+branches:
+ only:
+ - master
+
+script: make test
diff --git a/vendor/github.com/hashicorp/hcl/LICENSE b/vendor/github.com/hashicorp/hcl/LICENSE
new file mode 100644
index 000000000..c33dcc7c9
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/LICENSE
@@ -0,0 +1,354 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. “Contributor”
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. “Contributor Version”
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor’s Contribution.
+
+1.3. “Contribution”
+
+ means Covered Software of a particular Contributor.
+
+1.4. “Covered Software”
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. “Incompatible With Secondary Licenses”
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of version
+ 1.1 or earlier of the License, but not also under the terms of a
+ Secondary License.
+
+1.6. “Executable Form”
+
+ means any form of the work other than Source Code Form.
+
+1.7. “Larger Work”
+
+ means a work that combines Covered Software with other material, in a separate
+ file or files, that is not Covered Software.
+
+1.8. “License”
+
+ means this document.
+
+1.9. “Licensable”
+
+ means having the right to grant, to the maximum extent possible, whether at the
+ time of the initial grant or subsequently, any and all of the rights conveyed by
+ this License.
+
+1.10. “Modifications”
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to, deletion
+ from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. “Patent Claims” of a Contributor
+
+ means any patent claim(s), including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by such Contributor that
+ would be infringed, but for the grant of the License, by the making,
+ using, selling, offering for sale, having made, import, or transfer of
+ either its Contributions or its Contributor Version.
+
+1.12. “Secondary License”
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. “Source Code Form”
+
+ means the form of the work preferred for making modifications.
+
+1.14. “You” (or “Your”)
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, “You” includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, “control” means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or as
+ part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its Contributions
+ or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution become
+ effective for each Contribution on the date the Contributor first distributes
+ such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under this
+ License. No additional rights or licenses will be implied from the distribution
+ or licensing of Covered Software under this License. Notwithstanding Section
+ 2.1(b) above, no patent license is granted by a Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party’s
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of its
+ Contributions.
+
+ This License does not grant any rights in the trademarks, service marks, or
+ logos of any Contributor (except as may be necessary to comply with the
+ notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this License
+ (see Section 10.2) or under the terms of a Secondary License (if permitted
+ under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its Contributions
+ are its original creation(s) or it has sufficient rights to grant the
+ rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under applicable
+ copyright doctrines of fair use, fair dealing, or other equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under the
+ terms of this License. You must inform recipients that the Source Code Form
+ of the Covered Software is governed by the terms of this License, and how
+ they can obtain a copy of this License. You may not attempt to alter or
+ restrict the recipients’ rights in the Source Code Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this License,
+ or sublicense it under different terms, provided that the license for
+ the Executable Form does not attempt to limit or alter the recipients’
+ rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for the
+ Covered Software. If the Larger Work is a combination of Covered Software
+ with a work governed by one or more Secondary Licenses, and the Covered
+ Software is not Incompatible With Secondary Licenses, this License permits
+ You to additionally distribute such Covered Software under the terms of
+ such Secondary License(s), so that the recipient of the Larger Work may, at
+ their option, further distribute the Covered Software under the terms of
+ either this License or such Secondary License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices (including
+ copyright notices, patent notices, disclaimers of warranty, or limitations
+ of liability) contained within the Source Code Form of the Covered
+ Software, except that You may alter any license notices to the extent
+ required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on behalf
+ of any Contributor. You must make it absolutely clear that any such
+ warranty, support, indemnity, or liability obligation is offered by You
+ alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute, judicial
+ order, or regulation then You must: (a) comply with the terms of this License
+ to the maximum extent possible; and (b) describe the limitations and the code
+ they affect. Such description must be placed in a text file included with all
+ distributions of the Covered Software under this License. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing basis,
+ if such Contributor fails to notify You of the non-compliance by some
+ reasonable means prior to 60 days after You have come back into compliance.
+ Moreover, Your grants from a particular Contributor are reinstated on an
+ ongoing basis if such Contributor notifies You of the non-compliance by
+ some reasonable means, this is the first time You have received notice of
+ non-compliance with this License from such Contributor, and You become
+ compliant prior to 30 days after Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions, counter-claims,
+ and cross-claims) alleging that a Contributor Version directly or
+ indirectly infringes any patent, then the rights granted to You by any and
+ all Contributors for the Covered Software under Section 2.1 of this License
+ shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an “as is” basis, without
+ warranty of any kind, either expressed, implied, or statutory, including,
+ without limitation, warranties that the Covered Software is free of defects,
+ merchantable, fit for a particular purpose or non-infringing. The entire
+ risk as to the quality and performance of the Covered Software is with You.
+ Should any Covered Software prove defective in any respect, You (not any
+ Contributor) assume the cost of any necessary servicing, repair, or
+ correction. This disclaimer of warranty constitutes an essential part of this
+ License. No use of any Covered Software is authorized under this License
+ except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from such
+ party’s negligence to the extent applicable law prohibits such limitation.
+ Some jurisdictions do not allow the exclusion or limitation of incidental or
+ consequential damages, so this exclusion and limitation may not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts of
+ a jurisdiction where the defendant maintains its principal place of business
+ and such litigation shall be governed by laws of that jurisdiction, without
+ reference to its conflict-of-law provisions. Nothing in this Section shall
+ prevent a party’s ability to bring cross-claims or counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject matter
+ hereof. If any provision of this License is held to be unenforceable, such
+ provision shall be reformed only to the extent necessary to make it
+ enforceable. Any law or regulation which provides that the language of a
+ contract shall be construed against the drafter shall not be used to construe
+ this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version of
+ the License under which You originally received the Covered Software, or
+ under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a modified
+ version of this License if you rename the license and remove any
+ references to the name of the license steward (except to note that such
+ modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
+ If You choose to distribute Source Code Form that is Incompatible With
+ Secondary Licenses under the terms of this version of the License, the
+ notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file, then
+You may include the notice in a location (such as a LICENSE file in a relevant
+directory) where a recipient would be likely to look for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - “Incompatible With Secondary Licenses” Notice
+
+ This Source Code Form is “Incompatible
+ With Secondary Licenses”, as defined by
+ the Mozilla Public License, v. 2.0.
+
diff --git a/vendor/github.com/hashicorp/hcl/Makefile b/vendor/github.com/hashicorp/hcl/Makefile
new file mode 100644
index 000000000..84fd743f5
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/Makefile
@@ -0,0 +1,18 @@
+TEST?=./...
+
+default: test
+
+fmt: generate
+ go fmt ./...
+
+test: generate
+ go get -t ./...
+ go test $(TEST) $(TESTARGS)
+
+generate:
+ go generate ./...
+
+updatedeps:
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: default generate test updatedeps
diff --git a/vendor/github.com/hashicorp/hcl/README.md b/vendor/github.com/hashicorp/hcl/README.md
new file mode 100644
index 000000000..c8223326d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/README.md
@@ -0,0 +1,125 @@
+# HCL
+
+[![GoDoc](https://godoc.org/github.com/hashicorp/hcl?status.png)](https://godoc.org/github.com/hashicorp/hcl) [![Build Status](https://travis-ci.org/hashicorp/hcl.svg?branch=master)](https://travis-ci.org/hashicorp/hcl)
+
+HCL (HashiCorp Configuration Language) is a configuration language built
+by HashiCorp. The goal of HCL is to build a structured configuration language
+that is both human and machine friendly for use with command-line tools, but
+specifically targeted towards DevOps tools, servers, etc.
+
+HCL is also fully JSON compatible. That is, JSON can be used as completely
+valid input to a system expecting HCL. This helps makes systems
+interoperable with other systems.
+
+HCL is heavily inspired by
+[libucl](https://github.com/vstakhov/libucl),
+nginx configuration, and others similar.
+
+## Why?
+
+A common question when viewing HCL is to ask the question: why not
+JSON, YAML, etc.?
+
+Prior to HCL, the tools we built at [HashiCorp](http://www.hashicorp.com)
+used a variety of configuration languages from full programming languages
+such as Ruby to complete data structure languages such as JSON. What we
+learned is that some people wanted human-friendly configuration languages
+and some people wanted machine-friendly languages.
+
+JSON fits a nice balance in this, but is fairly verbose and most
+importantly doesn't support comments. With YAML, we found that beginners
+had a really hard time determining what the actual structure was, and
+ended up guessing more often than not whether to use a hyphen, colon, etc.
+in order to represent some configuration key.
+
+Full programming languages such as Ruby enable complex behavior
+a configuration language shouldn't usually allow, and also forces
+people to learn some set of Ruby.
+
+Because of this, we decided to create our own configuration language
+that is JSON-compatible. Our configuration language (HCL) is designed
+to be written and modified by humans. The API for HCL allows JSON
+as an input so that it is also machine-friendly (machines can generate
+JSON instead of trying to generate HCL).
+
+Our goal with HCL is not to alienate other configuration languages.
+It is instead to provide HCL as a specialized language for our tools,
+and JSON as the interoperability layer.
+
+## Syntax
+
+For a complete grammar, please see the parser itself. A high-level overview
+of the syntax and grammar is listed here.
+
+ * Single line comments start with `#` or `//`
+
+ * Multi-line comments are wrapped in `/*` and `*/`. Nested block comments
+ are not allowed. A multi-line comment (also known as a block comment)
+ terminates at the first `*/` found.
+
+ * Values are assigned with the syntax `key = value` (whitespace doesn't
+ matter). The value can be any primitive: a string, number, boolean,
+ object, or list.
+
+ * Strings are double-quoted and can contain any UTF-8 characters.
+ Example: `"Hello, World"`
+
+ * Multi-line strings start with `<<EOF` at the end of a line, and end
+ with `EOF` on its own line ([here documents](https://en.wikipedia.org/wiki/Here_document)).
+ Any text may be used in place of `EOF`. Example:
+```
+<<FOO
+hello
+world
+FOO
+```
+
+ * Numbers are assumed to be base 10. If you prefix a number with 0x,
+ it is treated as a hexadecimal. If it is prefixed with 0, it is
+ treated as an octal. Numbers can be in scientific notation: "1e10".
+
+ * Boolean values: `true`, `false`
+
+ * Arrays can be made by wrapping it in `[]`. Example:
+ `["foo", "bar", 42]`. Arrays can contain primitives,
+ other arrays, and objects. As an alternative, lists
+ of objects can be created with repeated blocks, using
+ this structure:
+
+ ```hcl
+ service {
+ key = "value"
+ }
+
+ service {
+ key = "value"
+ }
+ ```
+
+Objects and nested objects are created using the structure shown below:
+
+```
+variable "ami" {
+ description = "the AMI to use"
+}
+```
+This would be equivalent to the following json:
+``` json
+{
+ "variable": {
+ "ami": {
+ "description": "the AMI to use"
+ }
+ }
+}
+```
+
+## Thanks
+
+Thanks to:
+
+ * [@vstakhov](https://github.com/vstakhov) - The original libucl parser
+ and syntax that HCL was based off of.
+
+ * [@fatih](https://github.com/fatih) - The rewritten HCL parser
+ in pure Go (no goyacc) and support for a printer.
diff --git a/vendor/github.com/hashicorp/hcl/appveyor.yml b/vendor/github.com/hashicorp/hcl/appveyor.yml
new file mode 100644
index 000000000..3c8cdf8e9
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/appveyor.yml
@@ -0,0 +1,19 @@
+version: "build-{branch}-{build}"
+image: Visual Studio 2015
+clone_folder: c:\gopath\src\github.com\hashicorp\hcl
+environment:
+ GOPATH: c:\gopath
+init:
+ - git config --global core.autocrlf true
+install:
+- cmd: >-
+ echo %Path%
+
+ go version
+
+ go env
+
+ go get -t ./...
+
+build_script:
+- cmd: go test -v ./...
diff --git a/vendor/github.com/hashicorp/hcl/decoder.go b/vendor/github.com/hashicorp/hcl/decoder.go
new file mode 100644
index 000000000..0b39c1b95
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/decoder.go
@@ -0,0 +1,724 @@
+package hcl
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+
+ "github.com/hashicorp/hcl/hcl/ast"
+ "github.com/hashicorp/hcl/hcl/parser"
+ "github.com/hashicorp/hcl/hcl/token"
+)
+
+// This is the tag to use with structures to have settings for HCL
+const tagName = "hcl"
+
+var (
+ // nodeType holds a reference to the type of ast.Node
+ nodeType reflect.Type = findNodeType()
+)
+
+// Unmarshal accepts a byte slice as input and writes the
+// data to the value pointed to by v.
+func Unmarshal(bs []byte, v interface{}) error {
+ root, err := parse(bs)
+ if err != nil {
+ return err
+ }
+
+ return DecodeObject(v, root)
+}
+
+// Decode reads the given input and decodes it into the structure
+// given by `out`.
+func Decode(out interface{}, in string) error {
+ obj, err := Parse(in)
+ if err != nil {
+ return err
+ }
+
+ return DecodeObject(out, obj)
+}
+
+// DecodeObject is a lower-level version of Decode. It decodes a
+// raw Object into the given output.
+func DecodeObject(out interface{}, n ast.Node) error {
+ val := reflect.ValueOf(out)
+ if val.Kind() != reflect.Ptr {
+ return errors.New("result must be a pointer")
+ }
+
+ // If we have the file, we really decode the root node
+ if f, ok := n.(*ast.File); ok {
+ n = f.Node
+ }
+
+ var d decoder
+ return d.decode("root", n, val.Elem())
+}
+
+type decoder struct {
+ stack []reflect.Kind
+}
+
+func (d *decoder) decode(name string, node ast.Node, result reflect.Value) error {
+ k := result
+
+ // If we have an interface with a valid value, we use that
+ // for the check.
+ if result.Kind() == reflect.Interface {
+ elem := result.Elem()
+ if elem.IsValid() {
+ k = elem
+ }
+ }
+
+ // Push current onto stack unless it is an interface.
+ if k.Kind() != reflect.Interface {
+ d.stack = append(d.stack, k.Kind())
+
+ // Schedule a pop
+ defer func() {
+ d.stack = d.stack[:len(d.stack)-1]
+ }()
+ }
+
+ switch k.Kind() {
+ case reflect.Bool:
+ return d.decodeBool(name, node, result)
+ case reflect.Float64:
+ return d.decodeFloat(name, node, result)
+ case reflect.Int, reflect.Int32, reflect.Int64:
+ return d.decodeInt(name, node, result)
+ case reflect.Interface:
+ // When we see an interface, we make our own thing
+ return d.decodeInterface(name, node, result)
+ case reflect.Map:
+ return d.decodeMap(name, node, result)
+ case reflect.Ptr:
+ return d.decodePtr(name, node, result)
+ case reflect.Slice:
+ return d.decodeSlice(name, node, result)
+ case reflect.String:
+ return d.decodeString(name, node, result)
+ case reflect.Struct:
+ return d.decodeStruct(name, node, result)
+ default:
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: unknown kind to decode into: %s", name, k.Kind()),
+ }
+ }
+}
+
+func (d *decoder) decodeBool(name string, node ast.Node, result reflect.Value) error {
+ switch n := node.(type) {
+ case *ast.LiteralType:
+ if n.Token.Type == token.BOOL {
+ v, err := strconv.ParseBool(n.Token.Text)
+ if err != nil {
+ return err
+ }
+
+ result.Set(reflect.ValueOf(v))
+ return nil
+ }
+ }
+
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: unknown type %T", name, node),
+ }
+}
+
+func (d *decoder) decodeFloat(name string, node ast.Node, result reflect.Value) error {
+ switch n := node.(type) {
+ case *ast.LiteralType:
+ if n.Token.Type == token.FLOAT {
+ v, err := strconv.ParseFloat(n.Token.Text, 64)
+ if err != nil {
+ return err
+ }
+
+ result.Set(reflect.ValueOf(v))
+ return nil
+ }
+ }
+
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: unknown type %T", name, node),
+ }
+}
+
+func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) error {
+ switch n := node.(type) {
+ case *ast.LiteralType:
+ switch n.Token.Type {
+ case token.NUMBER:
+ v, err := strconv.ParseInt(n.Token.Text, 0, 0)
+ if err != nil {
+ return err
+ }
+
+ if result.Kind() == reflect.Interface {
+ result.Set(reflect.ValueOf(int(v)))
+ } else {
+ result.SetInt(v)
+ }
+ return nil
+ case token.STRING:
+ v, err := strconv.ParseInt(n.Token.Value().(string), 0, 0)
+ if err != nil {
+ return err
+ }
+
+ if result.Kind() == reflect.Interface {
+ result.Set(reflect.ValueOf(int(v)))
+ } else {
+ result.SetInt(v)
+ }
+ return nil
+ }
+ }
+
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: unknown type %T", name, node),
+ }
+}
+
+func (d *decoder) decodeInterface(name string, node ast.Node, result reflect.Value) error {
+ // When we see an ast.Node, we retain the value to enable deferred decoding.
+ // Very useful in situations where we want to preserve ast.Node information
+ // like Pos
+ if result.Type() == nodeType && result.CanSet() {
+ result.Set(reflect.ValueOf(node))
+ return nil
+ }
+
+ var set reflect.Value
+ redecode := true
+
+ // For testing types, ObjectType should just be treated as a list. We
+ // set this to a temporary var because we want to pass in the real node.
+ testNode := node
+ if ot, ok := node.(*ast.ObjectType); ok {
+ testNode = ot.List
+ }
+
+ switch n := testNode.(type) {
+ case *ast.ObjectList:
+ // If we're at the root or we're directly within a slice, then we
+ // decode objects into map[string]interface{}, otherwise we decode
+ // them into lists.
+ if len(d.stack) == 0 || d.stack[len(d.stack)-1] == reflect.Slice {
+ var temp map[string]interface{}
+ tempVal := reflect.ValueOf(temp)
+ result := reflect.MakeMap(
+ reflect.MapOf(
+ reflect.TypeOf(""),
+ tempVal.Type().Elem()))
+
+ set = result
+ } else {
+ var temp []map[string]interface{}
+ tempVal := reflect.ValueOf(temp)
+ result := reflect.MakeSlice(
+ reflect.SliceOf(tempVal.Type().Elem()), 0, len(n.Items))
+ set = result
+ }
+ case *ast.ObjectType:
+ // If we're at the root or we're directly within a slice, then we
+ // decode objects into map[string]interface{}, otherwise we decode
+ // them into lists.
+ if len(d.stack) == 0 || d.stack[len(d.stack)-1] == reflect.Slice {
+ var temp map[string]interface{}
+ tempVal := reflect.ValueOf(temp)
+ result := reflect.MakeMap(
+ reflect.MapOf(
+ reflect.TypeOf(""),
+ tempVal.Type().Elem()))
+
+ set = result
+ } else {
+ var temp []map[string]interface{}
+ tempVal := reflect.ValueOf(temp)
+ result := reflect.MakeSlice(
+ reflect.SliceOf(tempVal.Type().Elem()), 0, 1)
+ set = result
+ }
+ case *ast.ListType:
+ var temp []interface{}
+ tempVal := reflect.ValueOf(temp)
+ result := reflect.MakeSlice(
+ reflect.SliceOf(tempVal.Type().Elem()), 0, 0)
+ set = result
+ case *ast.LiteralType:
+ switch n.Token.Type {
+ case token.BOOL:
+ var result bool
+ set = reflect.Indirect(reflect.New(reflect.TypeOf(result)))
+ case token.FLOAT:
+ var result float64
+ set = reflect.Indirect(reflect.New(reflect.TypeOf(result)))
+ case token.NUMBER:
+ var result int
+ set = reflect.Indirect(reflect.New(reflect.TypeOf(result)))
+ case token.STRING, token.HEREDOC:
+ set = reflect.Indirect(reflect.New(reflect.TypeOf("")))
+ default:
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: cannot decode into interface: %T", name, node),
+ }
+ }
+ default:
+ return fmt.Errorf(
+ "%s: cannot decode into interface: %T",
+ name, node)
+ }
+
+ // Set the result to what its supposed to be, then reset
+ // result so we don't reflect into this method anymore.
+ result.Set(set)
+
+ if redecode {
+ // Revisit the node so that we can use the newly instantiated
+ // thing and populate it.
+ if err := d.decode(name, node, result); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (d *decoder) decodeMap(name string, node ast.Node, result reflect.Value) error {
+ if item, ok := node.(*ast.ObjectItem); ok {
+ node = &ast.ObjectList{Items: []*ast.ObjectItem{item}}
+ }
+
+ if ot, ok := node.(*ast.ObjectType); ok {
+ node = ot.List
+ }
+
+ n, ok := node.(*ast.ObjectList)
+ if !ok {
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: not an object type for map (%T)", name, node),
+ }
+ }
+
+ // If we have an interface, then we can address the interface,
+ // but not the slice itself, so get the element but set the interface
+ set := result
+ if result.Kind() == reflect.Interface {
+ result = result.Elem()
+ }
+
+ resultType := result.Type()
+ resultElemType := resultType.Elem()
+ resultKeyType := resultType.Key()
+ if resultKeyType.Kind() != reflect.String {
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: map must have string keys", name),
+ }
+ }
+
+ // Make a map if it is nil
+ resultMap := result
+ if result.IsNil() {
+ resultMap = reflect.MakeMap(
+ reflect.MapOf(resultKeyType, resultElemType))
+ }
+
+ // Go through each element and decode it.
+ done := make(map[string]struct{})
+ for _, item := range n.Items {
+ if item.Val == nil {
+ continue
+ }
+
+ // github.com/hashicorp/terraform/issue/5740
+ if len(item.Keys) == 0 {
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: map must have string keys", name),
+ }
+ }
+
+ // Get the key we're dealing with, which is the first item
+ keyStr := item.Keys[0].Token.Value().(string)
+
+ // If we've already processed this key, then ignore it
+ if _, ok := done[keyStr]; ok {
+ continue
+ }
+
+ // Determine the value. If we have more than one key, then we
+ // get the objectlist of only these keys.
+ itemVal := item.Val
+ if len(item.Keys) > 1 {
+ itemVal = n.Filter(keyStr)
+ done[keyStr] = struct{}{}
+ }
+
+ // Make the field name
+ fieldName := fmt.Sprintf("%s.%s", name, keyStr)
+
+ // Get the key/value as reflection values
+ key := reflect.ValueOf(keyStr)
+ val := reflect.Indirect(reflect.New(resultElemType))
+
+ // If we have a pre-existing value in the map, use that
+ oldVal := resultMap.MapIndex(key)
+ if oldVal.IsValid() {
+ val.Set(oldVal)
+ }
+
+ // Decode!
+ if err := d.decode(fieldName, itemVal, val); err != nil {
+ return err
+ }
+
+ // Set the value on the map
+ resultMap.SetMapIndex(key, val)
+ }
+
+ // Set the final map if we can
+ set.Set(resultMap)
+ return nil
+}
+
+func (d *decoder) decodePtr(name string, node ast.Node, result reflect.Value) error {
+ // Create an element of the concrete (non pointer) type and decode
+ // into that. Then set the value of the pointer to this type.
+ resultType := result.Type()
+ resultElemType := resultType.Elem()
+ val := reflect.New(resultElemType)
+ if err := d.decode(name, node, reflect.Indirect(val)); err != nil {
+ return err
+ }
+
+ result.Set(val)
+ return nil
+}
+
+func (d *decoder) decodeSlice(name string, node ast.Node, result reflect.Value) error {
+ // If we have an interface, then we can address the interface,
+ // but not the slice itself, so get the element but set the interface
+ set := result
+ if result.Kind() == reflect.Interface {
+ result = result.Elem()
+ }
+ // Create the slice if it isn't nil
+ resultType := result.Type()
+ resultElemType := resultType.Elem()
+ if result.IsNil() {
+ resultSliceType := reflect.SliceOf(resultElemType)
+ result = reflect.MakeSlice(
+ resultSliceType, 0, 0)
+ }
+
+ // Figure out the items we'll be copying into the slice
+ var items []ast.Node
+ switch n := node.(type) {
+ case *ast.ObjectList:
+ items = make([]ast.Node, len(n.Items))
+ for i, item := range n.Items {
+ items[i] = item
+ }
+ case *ast.ObjectType:
+ items = []ast.Node{n}
+ case *ast.ListType:
+ items = n.List
+ default:
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("unknown slice type: %T", node),
+ }
+ }
+
+ for i, item := range items {
+ fieldName := fmt.Sprintf("%s[%d]", name, i)
+
+ // Decode
+ val := reflect.Indirect(reflect.New(resultElemType))
+
+ // if item is an object that was decoded from ambiguous JSON and
+ // flattened, make sure it's expanded if it needs to decode into a
+ // defined structure.
+ item := expandObject(item, val)
+
+ if err := d.decode(fieldName, item, val); err != nil {
+ return err
+ }
+
+ // Append it onto the slice
+ result = reflect.Append(result, val)
+ }
+
+ set.Set(result)
+ return nil
+}
+
+// expandObject detects if an ambiguous JSON object was flattened to a List which
+// should be decoded into a struct, and expands the ast to properly deocode.
+func expandObject(node ast.Node, result reflect.Value) ast.Node {
+ item, ok := node.(*ast.ObjectItem)
+ if !ok {
+ return node
+ }
+
+ elemType := result.Type()
+
+ // our target type must be a struct
+ switch elemType.Kind() {
+ case reflect.Ptr:
+ switch elemType.Elem().Kind() {
+ case reflect.Struct:
+ //OK
+ default:
+ return node
+ }
+ case reflect.Struct:
+ //OK
+ default:
+ return node
+ }
+
+ // A list value will have a key and field name. If it had more fields,
+ // it wouldn't have been flattened.
+ if len(item.Keys) != 2 {
+ return node
+ }
+
+ keyToken := item.Keys[0].Token
+ item.Keys = item.Keys[1:]
+
+ // we need to un-flatten the ast enough to decode
+ newNode := &ast.ObjectItem{
+ Keys: []*ast.ObjectKey{
+ &ast.ObjectKey{
+ Token: keyToken,
+ },
+ },
+ Val: &ast.ObjectType{
+ List: &ast.ObjectList{
+ Items: []*ast.ObjectItem{item},
+ },
+ },
+ }
+
+ return newNode
+}
+
+func (d *decoder) decodeString(name string, node ast.Node, result reflect.Value) error {
+ switch n := node.(type) {
+ case *ast.LiteralType:
+ switch n.Token.Type {
+ case token.NUMBER:
+ result.Set(reflect.ValueOf(n.Token.Text).Convert(result.Type()))
+ return nil
+ case token.STRING, token.HEREDOC:
+ result.Set(reflect.ValueOf(n.Token.Value()).Convert(result.Type()))
+ return nil
+ }
+ }
+
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: unknown type for string %T", name, node),
+ }
+}
+
+func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value) error {
+ var item *ast.ObjectItem
+ if it, ok := node.(*ast.ObjectItem); ok {
+ item = it
+ node = it.Val
+ }
+
+ if ot, ok := node.(*ast.ObjectType); ok {
+ node = ot.List
+ }
+
+ // Handle the special case where the object itself is a literal. Previously
+ // the yacc parser would always ensure top-level elements were arrays. The new
+ // parser does not make the same guarantees, thus we need to convert any
+ // top-level literal elements into a list.
+ if _, ok := node.(*ast.LiteralType); ok && item != nil {
+ node = &ast.ObjectList{Items: []*ast.ObjectItem{item}}
+ }
+
+ list, ok := node.(*ast.ObjectList)
+ if !ok {
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: not an object type for struct (%T)", name, node),
+ }
+ }
+
+ // This slice will keep track of all the structs we'll be decoding.
+ // There can be more than one struct if there are embedded structs
+ // that are squashed.
+ structs := make([]reflect.Value, 1, 5)
+ structs[0] = result
+
+ // Compile the list of all the fields that we're going to be decoding
+ // from all the structs.
+ fields := make(map[*reflect.StructField]reflect.Value)
+ for len(structs) > 0 {
+ structVal := structs[0]
+ structs = structs[1:]
+
+ structType := structVal.Type()
+ for i := 0; i < structType.NumField(); i++ {
+ fieldType := structType.Field(i)
+ tagParts := strings.Split(fieldType.Tag.Get(tagName), ",")
+
+ // Ignore fields with tag name "-"
+ if tagParts[0] == "-" {
+ continue
+ }
+
+ if fieldType.Anonymous {
+ fieldKind := fieldType.Type.Kind()
+ if fieldKind != reflect.Struct {
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: unsupported type to struct: %s",
+ fieldType.Name, fieldKind),
+ }
+ }
+
+ // We have an embedded field. We "squash" the fields down
+ // if specified in the tag.
+ squash := false
+ for _, tag := range tagParts[1:] {
+ if tag == "squash" {
+ squash = true
+ break
+ }
+ }
+
+ if squash {
+ structs = append(
+ structs, result.FieldByName(fieldType.Name))
+ continue
+ }
+ }
+
+ // Normal struct field, store it away
+ fields[&fieldType] = structVal.Field(i)
+ }
+ }
+
+ usedKeys := make(map[string]struct{})
+ decodedFields := make([]string, 0, len(fields))
+ decodedFieldsVal := make([]reflect.Value, 0)
+ unusedKeysVal := make([]reflect.Value, 0)
+ for fieldType, field := range fields {
+ if !field.IsValid() {
+ // This should never happen
+ panic("field is not valid")
+ }
+
+ // If we can't set the field, then it is unexported or something,
+ // and we just continue onwards.
+ if !field.CanSet() {
+ continue
+ }
+
+ fieldName := fieldType.Name
+
+ tagValue := fieldType.Tag.Get(tagName)
+ tagParts := strings.SplitN(tagValue, ",", 2)
+ if len(tagParts) >= 2 {
+ switch tagParts[1] {
+ case "decodedFields":
+ decodedFieldsVal = append(decodedFieldsVal, field)
+ continue
+ case "key":
+ if item == nil {
+ return &parser.PosError{
+ Pos: node.Pos(),
+ Err: fmt.Errorf("%s: %s asked for 'key', impossible",
+ name, fieldName),
+ }
+ }
+
+ field.SetString(item.Keys[0].Token.Value().(string))
+ continue
+ case "unusedKeys":
+ unusedKeysVal = append(unusedKeysVal, field)
+ continue
+ }
+ }
+
+ if tagParts[0] != "" {
+ fieldName = tagParts[0]
+ }
+
+ // Determine the element we'll use to decode. If it is a single
+ // match (only object with the field), then we decode it exactly.
+ // If it is a prefix match, then we decode the matches.
+ filter := list.Filter(fieldName)
+
+ prefixMatches := filter.Children()
+ matches := filter.Elem()
+ if len(matches.Items) == 0 && len(prefixMatches.Items) == 0 {
+ continue
+ }
+
+ // Track the used key
+ usedKeys[fieldName] = struct{}{}
+
+ // Create the field name and decode. We range over the elements
+ // because we actually want the value.
+ fieldName = fmt.Sprintf("%s.%s", name, fieldName)
+ if len(prefixMatches.Items) > 0 {
+ if err := d.decode(fieldName, prefixMatches, field); err != nil {
+ return err
+ }
+ }
+ for _, match := range matches.Items {
+ var decodeNode ast.Node = match.Val
+ if ot, ok := decodeNode.(*ast.ObjectType); ok {
+ decodeNode = &ast.ObjectList{Items: ot.List.Items}
+ }
+
+ if err := d.decode(fieldName, decodeNode, field); err != nil {
+ return err
+ }
+ }
+
+ decodedFields = append(decodedFields, fieldType.Name)
+ }
+
+ if len(decodedFieldsVal) > 0 {
+ // Sort it so that it is deterministic
+ sort.Strings(decodedFields)
+
+ for _, v := range decodedFieldsVal {
+ v.Set(reflect.ValueOf(decodedFields))
+ }
+ }
+
+ return nil
+}
+
+// findNodeType returns the type of ast.Node
+func findNodeType() reflect.Type {
+ var nodeContainer struct {
+ Node ast.Node
+ }
+ value := reflect.ValueOf(nodeContainer).FieldByName("Node")
+ return value.Type()
+}
diff --git a/vendor/github.com/hashicorp/hcl/decoder_test.go b/vendor/github.com/hashicorp/hcl/decoder_test.go
new file mode 100644
index 000000000..480be4fa6
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/decoder_test.go
@@ -0,0 +1,1165 @@
+package hcl
+
+import (
+ "io/ioutil"
+ "path/filepath"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/davecgh/go-spew/spew"
+ "github.com/hashicorp/hcl/hcl/ast"
+ "github.com/hashicorp/hcl/testhelper"
+)
+
+func TestDecode_interface(t *testing.T) {
+ cases := []struct {
+ File string
+ Err bool
+ Out interface{}
+ }{
+ {
+ "basic.hcl",
+ false,
+ map[string]interface{}{
+ "foo": "bar",
+ "bar": "${file(\"bing/bong.txt\")}",
+ },
+ },
+ {
+ "basic_squish.hcl",
+ false,
+ map[string]interface{}{
+ "foo": "bar",
+ "bar": "${file(\"bing/bong.txt\")}",
+ "foo-bar": "baz",
+ },
+ },
+ {
+ "empty.hcl",
+ false,
+ map[string]interface{}{
+ "resource": []map[string]interface{}{
+ map[string]interface{}{
+ "foo": []map[string]interface{}{
+ map[string]interface{}{},
+ },
+ },
+ },
+ },
+ },
+ {
+ "tfvars.hcl",
+ false,
+ map[string]interface{}{
+ "regularvar": "Should work",
+ "map.key1": "Value",
+ "map.key2": "Other value",
+ },
+ },
+ {
+ "escape.hcl",
+ false,
+ map[string]interface{}{
+ "foo": "bar\"baz\\n",
+ "qux": "back\\slash",
+ "bar": "new\nline",
+ "qax": `slash\:colon`,
+ "nested": `${HH\\:mm\\:ss}`,
+ "nestedquotes": `${"\"stringwrappedinquotes\""}`,
+ },
+ },
+ {
+ "float.hcl",
+ false,
+ map[string]interface{}{
+ "a": 1.02,
+ },
+ },
+ {
+ "multiline_bad.hcl",
+ true,
+ nil,
+ },
+ {
+ "multiline_literal.hcl",
+ true,
+ nil,
+ },
+ {
+ "multiline_literal_with_hil.hcl",
+ false,
+ map[string]interface{}{"multiline_literal_with_hil": testhelper.Unix2dos(`${hello
+ world}`)},
+ },
+ {
+ "multiline_no_marker.hcl",
+ true,
+ nil,
+ },
+ {
+ "multiline.hcl",
+ false,
+ map[string]interface{}{"foo": testhelper.Unix2dos("bar\nbaz\n")},
+ },
+ {
+ "multiline_indented.hcl",
+ false,
+ map[string]interface{}{"foo": testhelper.Unix2dos(" bar\n baz\n")},
+ },
+ {
+ "multiline_no_hanging_indent.hcl",
+ false,
+ map[string]interface{}{"foo": testhelper.Unix2dos(" baz\n bar\n foo\n")},
+ },
+ {
+ "multiline_no_eof.hcl",
+ false,
+ map[string]interface{}{"foo": testhelper.Unix2dos("bar\nbaz\n"), "key": "value"},
+ },
+ {
+ "multiline.json",
+ false,
+ map[string]interface{}{"foo": "bar\nbaz"},
+ },
+ {
+ "null_strings.json",
+ false,
+ map[string]interface{}{
+ "module": []map[string]interface{}{
+ map[string]interface{}{
+ "app": []map[string]interface{}{
+ map[string]interface{}{"foo": ""},
+ },
+ },
+ },
+ },
+ },
+ {
+ "scientific.json",
+ false,
+ map[string]interface{}{
+ "a": 1e-10,
+ "b": 1e+10,
+ "c": 1e10,
+ "d": 1.2e-10,
+ "e": 1.2e+10,
+ "f": 1.2e10,
+ },
+ },
+ {
+ "scientific.hcl",
+ false,
+ map[string]interface{}{
+ "a": 1e-10,
+ "b": 1e+10,
+ "c": 1e10,
+ "d": 1.2e-10,
+ "e": 1.2e+10,
+ "f": 1.2e10,
+ },
+ },
+ {
+ "terraform_heroku.hcl",
+ false,
+ map[string]interface{}{
+ "name": "terraform-test-app",
+ "config_vars": []map[string]interface{}{
+ map[string]interface{}{
+ "FOO": "bar",
+ },
+ },
+ },
+ },
+ {
+ "structure_multi.hcl",
+ false,
+ map[string]interface{}{
+ "foo": []map[string]interface{}{
+ map[string]interface{}{
+ "baz": []map[string]interface{}{
+ map[string]interface{}{"key": 7},
+ },
+ },
+ map[string]interface{}{
+ "bar": []map[string]interface{}{
+ map[string]interface{}{"key": 12},
+ },
+ },
+ },
+ },
+ },
+ {
+ "structure_multi.json",
+ false,
+ map[string]interface{}{
+ "foo": []map[string]interface{}{
+ map[string]interface{}{
+ "baz": []map[string]interface{}{
+ map[string]interface{}{"key": 7},
+ },
+ },
+ map[string]interface{}{
+ "bar": []map[string]interface{}{
+ map[string]interface{}{"key": 12},
+ },
+ },
+ },
+ },
+ },
+ {
+ "list_of_lists.hcl",
+ false,
+ map[string]interface{}{
+ "foo": []interface{}{
+ []interface{}{"foo"},
+ []interface{}{"bar"},
+ },
+ },
+ },
+ {
+ "list_of_maps.hcl",
+ false,
+ map[string]interface{}{
+ "foo": []interface{}{
+ map[string]interface{}{"somekey1": "someval1"},
+ map[string]interface{}{"somekey2": "someval2", "someextrakey": "someextraval"},
+ },
+ },
+ },
+ {
+ "assign_deep.hcl",
+ false,
+ map[string]interface{}{
+ "resource": []interface{}{
+ map[string]interface{}{
+ "foo": []interface{}{
+ map[string]interface{}{
+ "bar": []map[string]interface{}{
+ map[string]interface{}{}}}}}}},
+ },
+ {
+ "structure_list.hcl",
+ false,
+ map[string]interface{}{
+ "foo": []map[string]interface{}{
+ map[string]interface{}{
+ "key": 7,
+ },
+ map[string]interface{}{
+ "key": 12,
+ },
+ },
+ },
+ },
+ {
+ "structure_list.json",
+ false,
+ map[string]interface{}{
+ "foo": []map[string]interface{}{
+ map[string]interface{}{
+ "key": 7,
+ },
+ map[string]interface{}{
+ "key": 12,
+ },
+ },
+ },
+ },
+ {
+ "structure_list_deep.json",
+ false,
+ map[string]interface{}{
+ "bar": []map[string]interface{}{
+ map[string]interface{}{
+ "foo": []map[string]interface{}{
+ map[string]interface{}{
+ "name": "terraform_example",
+ "ingress": []map[string]interface{}{
+ map[string]interface{}{
+ "from_port": 22,
+ },
+ map[string]interface{}{
+ "from_port": 80,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+
+ {
+ "structure_list_empty.json",
+ false,
+ map[string]interface{}{
+ "foo": []interface{}{},
+ },
+ },
+
+ {
+ "nested_block_comment.hcl",
+ false,
+ map[string]interface{}{
+ "bar": "value",
+ },
+ },
+
+ {
+ "unterminated_block_comment.hcl",
+ true,
+ nil,
+ },
+
+ {
+ "unterminated_brace.hcl",
+ true,
+ nil,
+ },
+
+ {
+ "nested_provider_bad.hcl",
+ true,
+ nil,
+ },
+
+ {
+ "object_list.json",
+ false,
+ map[string]interface{}{
+ "resource": []map[string]interface{}{
+ map[string]interface{}{
+ "aws_instance": []map[string]interface{}{
+ map[string]interface{}{
+ "db": []map[string]interface{}{
+ map[string]interface{}{
+ "vpc": "foo",
+ "provisioner": []map[string]interface{}{
+ map[string]interface{}{
+ "file": []map[string]interface{}{
+ map[string]interface{}{
+ "source": "foo",
+ "destination": "bar",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+
+ // Terraform GH-8295 sanity test that basic decoding into
+ // interface{} works.
+ {
+ "terraform_variable_invalid.json",
+ false,
+ map[string]interface{}{
+ "variable": []map[string]interface{}{
+ map[string]interface{}{
+ "whatever": "abc123",
+ },
+ },
+ },
+ },
+
+ {
+ "interpolate.json",
+ false,
+ map[string]interface{}{
+ "default": `${replace("europe-west", "-", " ")}`,
+ },
+ },
+
+ {
+ "block_assign.hcl",
+ true,
+ nil,
+ },
+
+ {
+ "escape_backslash.hcl",
+ false,
+ map[string]interface{}{
+ "output": []map[string]interface{}{
+ map[string]interface{}{
+ "one": `${replace(var.sub_domain, ".", "\\.")}`,
+ "two": `${replace(var.sub_domain, ".", "\\\\.")}`,
+ "many": `${replace(var.sub_domain, ".", "\\\\\\\\.")}`,
+ },
+ },
+ },
+ },
+
+ {
+ "git_crypt.hcl",
+ true,
+ nil,
+ },
+
+ {
+ "object_with_bool.hcl",
+ false,
+ map[string]interface{}{
+ "path": []map[string]interface{}{
+ map[string]interface{}{
+ "policy": "write",
+ "permissions": []map[string]interface{}{
+ map[string]interface{}{
+ "bool": []interface{}{false},
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+
+ for _, tc := range cases {
+ t.Logf("Testing: %s", tc.File)
+ d, err := ioutil.ReadFile(filepath.Join(fixtureDir, tc.File))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ var out interface{}
+ err = Decode(&out, string(d))
+ if (err != nil) != tc.Err {
+ t.Fatalf("Input: %s\n\nError: %s", tc.File, err)
+ }
+
+ if !reflect.DeepEqual(out, tc.Out) {
+ t.Fatalf("Input: %s. Actual, Expected.\n\n%#v\n\n%#v", tc.File, out, tc.Out)
+ }
+
+ var v interface{}
+ err = Unmarshal(d, &v)
+ if (err != nil) != tc.Err {
+ t.Fatalf("Input: %s\n\nError: %s", tc.File, err)
+ }
+
+ if !reflect.DeepEqual(v, tc.Out) {
+ t.Fatalf("Input: %s. Actual, Expected.\n\n%#v\n\n%#v", tc.File, out, tc.Out)
+ }
+ }
+}
+
+func TestDecode_interfaceInline(t *testing.T) {
+ cases := []struct {
+ Value string
+ Err bool
+ Out interface{}
+ }{
+ {"t t e{{}}", true, nil},
+ {"t=0t d {}", true, map[string]interface{}{"t": 0}},
+ {"v=0E0v d{}", true, map[string]interface{}{"v": float64(0)}},
+ }
+
+ for _, tc := range cases {
+ t.Logf("Testing: %q", tc.Value)
+
+ var out interface{}
+ err := Decode(&out, tc.Value)
+ if (err != nil) != tc.Err {
+ t.Fatalf("Input: %q\n\nError: %s", tc.Value, err)
+ }
+
+ if !reflect.DeepEqual(out, tc.Out) {
+ t.Fatalf("Input: %q. Actual, Expected.\n\n%#v\n\n%#v", tc.Value, out, tc.Out)
+ }
+
+ var v interface{}
+ err = Unmarshal([]byte(tc.Value), &v)
+ if (err != nil) != tc.Err {
+ t.Fatalf("Input: %q\n\nError: %s", tc.Value, err)
+ }
+
+ if !reflect.DeepEqual(v, tc.Out) {
+ t.Fatalf("Input: %q. Actual, Expected.\n\n%#v\n\n%#v", tc.Value, out, tc.Out)
+ }
+ }
+}
+
+func TestDecode_equal(t *testing.T) {
+ cases := []struct {
+ One, Two string
+ }{
+ {
+ "basic.hcl",
+ "basic.json",
+ },
+ {
+ "float.hcl",
+ "float.json",
+ },
+ /*
+ {
+ "structure.hcl",
+ "structure.json",
+ },
+ */
+ {
+ "structure.hcl",
+ "structure_flat.json",
+ },
+ {
+ "terraform_heroku.hcl",
+ "terraform_heroku.json",
+ },
+ }
+
+ for _, tc := range cases {
+ p1 := filepath.Join(fixtureDir, tc.One)
+ p2 := filepath.Join(fixtureDir, tc.Two)
+
+ d1, err := ioutil.ReadFile(p1)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ d2, err := ioutil.ReadFile(p2)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ var i1, i2 interface{}
+ err = Decode(&i1, string(d1))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ err = Decode(&i2, string(d2))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ if !reflect.DeepEqual(i1, i2) {
+ t.Fatalf(
+ "%s != %s\n\n%#v\n\n%#v",
+ tc.One, tc.Two,
+ i1, i2)
+ }
+ }
+}
+
+func TestDecode_flatMap(t *testing.T) {
+ var val map[string]map[string]string
+
+ err := Decode(&val, testReadFile(t, "structure_flatmap.hcl"))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ expected := map[string]map[string]string{
+ "foo": map[string]string{
+ "foo": "bar",
+ "key": "7",
+ },
+ }
+
+ if !reflect.DeepEqual(val, expected) {
+ t.Fatalf("Actual: %#v\n\nExpected: %#v", val, expected)
+ }
+}
+
+func TestDecode_structure(t *testing.T) {
+ type Embedded interface{}
+
+ type V struct {
+ Embedded `hcl:"-"`
+ Key int
+ Foo string
+ }
+
+ var actual V
+
+ err := Decode(&actual, testReadFile(t, "flat.hcl"))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ expected := V{
+ Key: 7,
+ Foo: "bar",
+ }
+
+ if !reflect.DeepEqual(actual, expected) {
+ t.Fatalf("Actual: %#v\n\nExpected: %#v", actual, expected)
+ }
+}
+
+func TestDecode_structurePtr(t *testing.T) {
+ type V struct {
+ Key int
+ Foo string
+ }
+
+ var actual *V
+
+ err := Decode(&actual, testReadFile(t, "flat.hcl"))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ expected := &V{
+ Key: 7,
+ Foo: "bar",
+ }
+
+ if !reflect.DeepEqual(actual, expected) {
+ t.Fatalf("Actual: %#v\n\nExpected: %#v", actual, expected)
+ }
+}
+
+func TestDecode_structureArray(t *testing.T) {
+ // This test is extracted from a failure in Consul (consul.io),
+ // hence the interesting structure naming.
+
+ type KeyPolicyType string
+
+ type KeyPolicy struct {
+ Prefix string `hcl:",key"`
+ Policy KeyPolicyType
+ }
+
+ type Policy struct {
+ Keys []KeyPolicy `hcl:"key,expand"`
+ }
+
+ expected := Policy{
+ Keys: []KeyPolicy{
+ KeyPolicy{
+ Prefix: "",
+ Policy: "read",
+ },
+ KeyPolicy{
+ Prefix: "foo/",
+ Policy: "write",
+ },
+ KeyPolicy{
+ Prefix: "foo/bar/",
+ Policy: "read",
+ },
+ KeyPolicy{
+ Prefix: "foo/bar/baz",
+ Policy: "deny",
+ },
+ },
+ }
+
+ files := []string{
+ "decode_policy.hcl",
+ "decode_policy.json",
+ }
+
+ for _, f := range files {
+ var actual Policy
+
+ err := Decode(&actual, testReadFile(t, f))
+ if err != nil {
+ t.Fatalf("Input: %s\n\nerr: %s", f, err)
+ }
+
+ if !reflect.DeepEqual(actual, expected) {
+ t.Fatalf("Input: %s\n\nActual: %#v\n\nExpected: %#v", f, actual, expected)
+ }
+ }
+}
+
+func TestDecode_sliceExpand(t *testing.T) {
+ type testInner struct {
+ Name string `hcl:",key"`
+ Key string
+ }
+
+ type testStruct struct {
+ Services []testInner `hcl:"service,expand"`
+ }
+
+ expected := testStruct{
+ Services: []testInner{
+ testInner{
+ Name: "my-service-0",
+ Key: "value",
+ },
+ testInner{
+ Name: "my-service-1",
+ Key: "value",
+ },
+ },
+ }
+
+ files := []string{
+ "slice_expand.hcl",
+ }
+
+ for _, f := range files {
+ t.Logf("Testing: %s", f)
+
+ var actual testStruct
+ err := Decode(&actual, testReadFile(t, f))
+ if err != nil {
+ t.Fatalf("Input: %s\n\nerr: %s", f, err)
+ }
+
+ if !reflect.DeepEqual(actual, expected) {
+ t.Fatalf("Input: %s\n\nActual: %#v\n\nExpected: %#v", f, actual, expected)
+ }
+ }
+}
+
+func TestDecode_structureMap(t *testing.T) {
+ // This test is extracted from a failure in Terraform (terraform.io),
+ // hence the interesting structure naming.
+
+ type hclVariable struct {
+ Default interface{}
+ Description string
+ Fields []string `hcl:",decodedFields"`
+ }
+
+ type rawConfig struct {
+ Variable map[string]hclVariable
+ }
+
+ expected := rawConfig{
+ Variable: map[string]hclVariable{
+ "foo": hclVariable{
+ Default: "bar",
+ Description: "bar",
+ Fields: []string{"Default", "Description"},
+ },
+
+ "amis": hclVariable{
+ Default: []map[string]interface{}{
+ map[string]interface{}{
+ "east": "foo",
+ },
+ },
+ Fields: []string{"Default"},
+ },
+ },
+ }
+
+ files := []string{
+ "decode_tf_variable.hcl",
+ "decode_tf_variable.json",
+ }
+
+ for _, f := range files {
+ t.Logf("Testing: %s", f)
+
+ var actual rawConfig
+ err := Decode(&actual, testReadFile(t, f))
+ if err != nil {
+ t.Fatalf("Input: %s\n\nerr: %s", f, err)
+ }
+
+ if !reflect.DeepEqual(actual, expected) {
+ t.Fatalf("Input: %s\n\nActual: %#v\n\nExpected: %#v", f, actual, expected)
+ }
+ }
+}
+
+func TestDecode_structureMapInvalid(t *testing.T) {
+ // Terraform GH-8295
+
+ type hclVariable struct {
+ Default interface{}
+ Description string
+ Fields []string `hcl:",decodedFields"`
+ }
+
+ type rawConfig struct {
+ Variable map[string]*hclVariable
+ }
+
+ var actual rawConfig
+ err := Decode(&actual, testReadFile(t, "terraform_variable_invalid.json"))
+ if err == nil {
+ t.Fatal("expected error")
+ }
+}
+
+func TestDecode_interfaceNonPointer(t *testing.T) {
+ var value interface{}
+ err := Decode(value, testReadFile(t, "basic_int_string.hcl"))
+ if err == nil {
+ t.Fatal("should error")
+ }
+}
+
+func TestDecode_intString(t *testing.T) {
+ var value struct {
+ Count int
+ }
+
+ err := Decode(&value, testReadFile(t, "basic_int_string.hcl"))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ if value.Count != 3 {
+ t.Fatalf("bad: %#v", value.Count)
+ }
+}
+
+func TestDecode_intStringAliased(t *testing.T) {
+ var value struct {
+ Count time.Duration
+ }
+
+ err := Decode(&value, testReadFile(t, "basic_int_string.hcl"))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ if value.Count != time.Duration(3) {
+ t.Fatalf("bad: %#v", value.Count)
+ }
+}
+
+func TestDecode_Node(t *testing.T) {
+ // given
+ var value struct {
+ Content ast.Node
+ Nested struct {
+ Content ast.Node
+ }
+ }
+
+ content := `
+content {
+ hello = "world"
+}
+`
+
+ // when
+ err := Decode(&value, content)
+
+ // then
+ if err != nil {
+ t.Errorf("unable to decode content, %v", err)
+ return
+ }
+
+ // verify ast.Node can be decoded later
+ var v map[string]interface{}
+ err = DecodeObject(&v, value.Content)
+ if err != nil {
+ t.Errorf("unable to decode content, %v", err)
+ return
+ }
+
+ if v["hello"] != "world" {
+ t.Errorf("expected mapping to be returned")
+ }
+}
+
+func TestDecode_NestedNode(t *testing.T) {
+ // given
+ var value struct {
+ Nested struct {
+ Content ast.Node
+ }
+ }
+
+ content := `
+nested "content" {
+ hello = "world"
+}
+`
+
+ // when
+ err := Decode(&value, content)
+
+ // then
+ if err != nil {
+ t.Errorf("unable to decode content, %v", err)
+ return
+ }
+
+ // verify ast.Node can be decoded later
+ var v map[string]interface{}
+ err = DecodeObject(&v, value.Nested.Content)
+ if err != nil {
+ t.Errorf("unable to decode content, %v", err)
+ return
+ }
+
+ if v["hello"] != "world" {
+ t.Errorf("expected mapping to be returned")
+ }
+}
+
+// https://github.com/hashicorp/hcl/issues/60
+func TestDecode_topLevelKeys(t *testing.T) {
+ type Template struct {
+ Source string
+ }
+
+ templates := struct {
+ Templates []*Template `hcl:"template"`
+ }{}
+
+ err := Decode(&templates, `
+ template {
+ source = "blah"
+ }
+
+ template {
+ source = "blahblah"
+ }`)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if templates.Templates[0].Source != "blah" {
+ t.Errorf("bad source: %s", templates.Templates[0].Source)
+ }
+
+ if templates.Templates[1].Source != "blahblah" {
+ t.Errorf("bad source: %s", templates.Templates[1].Source)
+ }
+}
+
+func TestDecode_flattenedJSON(t *testing.T) {
+ // make sure we can also correctly extract a Name key too
+ type V struct {
+ Name string `hcl:",key"`
+ Description string
+ Default map[string]string
+ }
+ type Vars struct {
+ Variable []*V
+ }
+
+ cases := []struct {
+ JSON string
+ Out interface{}
+ Expected interface{}
+ }{
+ { // Nested object, no sibling keys
+ JSON: `
+{
+ "var_name": {
+ "default": {
+ "key1": "a",
+ "key2": "b"
+ }
+ }
+}
+ `,
+ Out: &[]*V{},
+ Expected: &[]*V{
+ &V{
+ Name: "var_name",
+ Default: map[string]string{"key1": "a", "key2": "b"},
+ },
+ },
+ },
+
+ { // Nested object with a sibling key (this worked previously)
+ JSON: `
+{
+ "var_name": {
+ "description": "Described",
+ "default": {
+ "key1": "a",
+ "key2": "b"
+ }
+ }
+}
+ `,
+ Out: &[]*V{},
+ Expected: &[]*V{
+ &V{
+ Name: "var_name",
+ Description: "Described",
+ Default: map[string]string{"key1": "a", "key2": "b"},
+ },
+ },
+ },
+
+ { // Multiple nested objects, one with a sibling key
+ JSON: `
+{
+ "variable": {
+ "var_1": {
+ "default": {
+ "key1": "a",
+ "key2": "b"
+ }
+ },
+ "var_2": {
+ "description": "Described",
+ "default": {
+ "key1": "a",
+ "key2": "b"
+ }
+ }
+ }
+}
+ `,
+ Out: &Vars{},
+ Expected: &Vars{
+ Variable: []*V{
+ &V{
+ Name: "var_1",
+ Default: map[string]string{"key1": "a", "key2": "b"},
+ },
+ &V{
+ Name: "var_2",
+ Description: "Described",
+ Default: map[string]string{"key1": "a", "key2": "b"},
+ },
+ },
+ },
+ },
+
+ { // Nested object to maps
+ JSON: `
+{
+ "variable": {
+ "var_name": {
+ "description": "Described",
+ "default": {
+ "key1": "a",
+ "key2": "b"
+ }
+ }
+ }
+}
+ `,
+ Out: &[]map[string]interface{}{},
+ Expected: &[]map[string]interface{}{
+ {
+ "variable": []map[string]interface{}{
+ {
+ "var_name": []map[string]interface{}{
+ {
+ "description": "Described",
+ "default": []map[string]interface{}{
+ {
+ "key1": "a",
+ "key2": "b",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+
+ { // Nested object to maps without a sibling key should decode the same as above
+ JSON: `
+{
+ "variable": {
+ "var_name": {
+ "default": {
+ "key1": "a",
+ "key2": "b"
+ }
+ }
+ }
+}
+ `,
+ Out: &[]map[string]interface{}{},
+ Expected: &[]map[string]interface{}{
+ {
+ "variable": []map[string]interface{}{
+ {
+ "var_name": []map[string]interface{}{
+ {
+ "default": []map[string]interface{}{
+ {
+ "key1": "a",
+ "key2": "b",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+
+ { // Nested objects, one with a sibling key, and one without
+ JSON: `
+{
+ "variable": {
+ "var_1": {
+ "default": {
+ "key1": "a",
+ "key2": "b"
+ }
+ },
+ "var_2": {
+ "description": "Described",
+ "default": {
+ "key1": "a",
+ "key2": "b"
+ }
+ }
+ }
+}
+ `,
+ Out: &[]map[string]interface{}{},
+ Expected: &[]map[string]interface{}{
+ {
+ "variable": []map[string]interface{}{
+ {
+ "var_1": []map[string]interface{}{
+ {
+ "default": []map[string]interface{}{
+ {
+ "key1": "a",
+ "key2": "b",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ {
+ "variable": []map[string]interface{}{
+ {
+ "var_2": []map[string]interface{}{
+ {
+ "description": "Described",
+ "default": []map[string]interface{}{
+ {
+ "key1": "a",
+ "key2": "b",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+
+ for i, tc := range cases {
+ err := Decode(tc.Out, tc.JSON)
+ if err != nil {
+ t.Fatalf("[%d] err: %s", i, err)
+ }
+
+ if !reflect.DeepEqual(tc.Out, tc.Expected) {
+ t.Fatalf("[%d]\ngot: %s\nexpected: %s\n", i, spew.Sdump(tc.Out), spew.Sdump(tc.Expected))
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl.go b/vendor/github.com/hashicorp/hcl/hcl.go
new file mode 100644
index 000000000..575a20b50
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl.go
@@ -0,0 +1,11 @@
+// Package hcl decodes HCL into usable Go structures.
+//
+// hcl input can come in either pure HCL format or JSON format.
+// It can be parsed into an AST, and then decoded into a structure,
+// or it can be decoded directly from a string into a structure.
+//
+// If you choose to parse HCL into a raw AST, the benefit is that you
+// can write custom visitor implementations to implement custom
+// semantic checks. By default, HCL does not perform any semantic
+// checks.
+package hcl
diff --git a/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go b/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go
new file mode 100644
index 000000000..6e5ef654b
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go
@@ -0,0 +1,219 @@
+// Package ast declares the types used to represent syntax trees for HCL
+// (HashiCorp Configuration Language)
+package ast
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/hashicorp/hcl/hcl/token"
+)
+
+// Node is an element in the abstract syntax tree.
+type Node interface {
+ node()
+ Pos() token.Pos
+}
+
+func (File) node() {}
+func (ObjectList) node() {}
+func (ObjectKey) node() {}
+func (ObjectItem) node() {}
+func (Comment) node() {}
+func (CommentGroup) node() {}
+func (ObjectType) node() {}
+func (LiteralType) node() {}
+func (ListType) node() {}
+
+// File represents a single HCL file
+type File struct {
+ Node Node // usually a *ObjectList
+ Comments []*CommentGroup // list of all comments in the source
+}
+
+func (f *File) Pos() token.Pos {
+ return f.Node.Pos()
+}
+
+// ObjectList represents a list of ObjectItems. An HCL file itself is an
+// ObjectList.
+type ObjectList struct {
+ Items []*ObjectItem
+}
+
+func (o *ObjectList) Add(item *ObjectItem) {
+ o.Items = append(o.Items, item)
+}
+
+// Filter filters out the objects with the given key list as a prefix.
+//
+// The returned list of objects contain ObjectItems where the keys have
+// this prefix already stripped off. This might result in objects with
+// zero-length key lists if they have no children.
+//
+// If no matches are found, an empty ObjectList (non-nil) is returned.
+func (o *ObjectList) Filter(keys ...string) *ObjectList {
+ var result ObjectList
+ for _, item := range o.Items {
+ // If there aren't enough keys, then ignore this
+ if len(item.Keys) < len(keys) {
+ continue
+ }
+
+ match := true
+ for i, key := range item.Keys[:len(keys)] {
+ key := key.Token.Value().(string)
+ if key != keys[i] && !strings.EqualFold(key, keys[i]) {
+ match = false
+ break
+ }
+ }
+ if !match {
+ continue
+ }
+
+ // Strip off the prefix from the children
+ newItem := *item
+ newItem.Keys = newItem.Keys[len(keys):]
+ result.Add(&newItem)
+ }
+
+ return &result
+}
+
+// Children returns further nested objects (key length > 0) within this
+// ObjectList. This should be used with Filter to get at child items.
+func (o *ObjectList) Children() *ObjectList {
+ var result ObjectList
+ for _, item := range o.Items {
+ if len(item.Keys) > 0 {
+ result.Add(item)
+ }
+ }
+
+ return &result
+}
+
+// Elem returns items in the list that are direct element assignments
+// (key length == 0). This should be used with Filter to get at elements.
+func (o *ObjectList) Elem() *ObjectList {
+ var result ObjectList
+ for _, item := range o.Items {
+ if len(item.Keys) == 0 {
+ result.Add(item)
+ }
+ }
+
+ return &result
+}
+
+func (o *ObjectList) Pos() token.Pos {
+ // always returns the uninitiliazed position
+ return o.Items[0].Pos()
+}
+
+// ObjectItem represents a HCL Object Item. An item is represented with a key
+// (or keys). It can be an assignment or an object (both normal and nested)
+type ObjectItem struct {
+ // keys is only one length long if it's of type assignment. If it's a
+ // nested object it can be larger than one. In that case "assign" is
+ // invalid as there is no assignments for a nested object.
+ Keys []*ObjectKey
+
+ // assign contains the position of "=", if any
+ Assign token.Pos
+
+ // val is the item itself. It can be an object,list, number, bool or a
+ // string. If key length is larger than one, val can be only of type
+ // Object.
+ Val Node
+
+ LeadComment *CommentGroup // associated lead comment
+ LineComment *CommentGroup // associated line comment
+}
+
+func (o *ObjectItem) Pos() token.Pos {
+ // I'm not entirely sure what causes this, but removing this causes
+ // a test failure. We should investigate at some point.
+ if len(o.Keys) == 0 {
+ return token.Pos{}
+ }
+
+ return o.Keys[0].Pos()
+}
+
+// ObjectKeys are either an identifier or of type string.
+type ObjectKey struct {
+ Token token.Token
+}
+
+func (o *ObjectKey) Pos() token.Pos {
+ return o.Token.Pos
+}
+
+// LiteralType represents a literal of basic type. Valid types are:
+// token.NUMBER, token.FLOAT, token.BOOL and token.STRING
+type LiteralType struct {
+ Token token.Token
+
+ // comment types, only used when in a list
+ LeadComment *CommentGroup
+ LineComment *CommentGroup
+}
+
+func (l *LiteralType) Pos() token.Pos {
+ return l.Token.Pos
+}
+
+// ListStatement represents a HCL List type
+type ListType struct {
+ Lbrack token.Pos // position of "["
+ Rbrack token.Pos // position of "]"
+ List []Node // the elements in lexical order
+}
+
+func (l *ListType) Pos() token.Pos {
+ return l.Lbrack
+}
+
+func (l *ListType) Add(node Node) {
+ l.List = append(l.List, node)
+}
+
+// ObjectType represents a HCL Object Type
+type ObjectType struct {
+ Lbrace token.Pos // position of "{"
+ Rbrace token.Pos // position of "}"
+ List *ObjectList // the nodes in lexical order
+}
+
+func (o *ObjectType) Pos() token.Pos {
+ return o.Lbrace
+}
+
+// Comment node represents a single //, # style or /*- style commment
+type Comment struct {
+ Start token.Pos // position of / or #
+ Text string
+}
+
+func (c *Comment) Pos() token.Pos {
+ return c.Start
+}
+
+// CommentGroup node represents a sequence of comments with no other tokens and
+// no empty lines between.
+type CommentGroup struct {
+ List []*Comment // len(List) > 0
+}
+
+func (c *CommentGroup) Pos() token.Pos {
+ return c.List[0].Pos()
+}
+
+//-------------------------------------------------------------------
+// GoStringer
+//-------------------------------------------------------------------
+
+func (o *ObjectKey) GoString() string { return fmt.Sprintf("*%#v", *o) }
+func (o *ObjectList) GoString() string { return fmt.Sprintf("*%#v", *o) }
diff --git a/vendor/github.com/hashicorp/hcl/hcl/ast/ast_test.go b/vendor/github.com/hashicorp/hcl/hcl/ast/ast_test.go
new file mode 100644
index 000000000..942256cad
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/ast/ast_test.go
@@ -0,0 +1,200 @@
+package ast
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/hashicorp/hcl/hcl/token"
+)
+
+func TestObjectListFilter(t *testing.T) {
+ var cases = []struct {
+ Filter []string
+ Input []*ObjectItem
+ Output []*ObjectItem
+ }{
+ {
+ []string{"foo"},
+ []*ObjectItem{
+ &ObjectItem{
+ Keys: []*ObjectKey{
+ &ObjectKey{
+ Token: token.Token{Type: token.STRING, Text: `"foo"`},
+ },
+ },
+ },
+ },
+ []*ObjectItem{
+ &ObjectItem{
+ Keys: []*ObjectKey{},
+ },
+ },
+ },
+
+ {
+ []string{"foo"},
+ []*ObjectItem{
+ &ObjectItem{
+ Keys: []*ObjectKey{
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"foo"`}},
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"bar"`}},
+ },
+ },
+ &ObjectItem{
+ Keys: []*ObjectKey{
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"baz"`}},
+ },
+ },
+ },
+ []*ObjectItem{
+ &ObjectItem{
+ Keys: []*ObjectKey{
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"bar"`}},
+ },
+ },
+ },
+ },
+ }
+
+ for _, tc := range cases {
+ input := &ObjectList{Items: tc.Input}
+ expected := &ObjectList{Items: tc.Output}
+ if actual := input.Filter(tc.Filter...); !reflect.DeepEqual(actual, expected) {
+ t.Fatalf("in order: input, expected, actual\n\n%#v\n\n%#v\n\n%#v", input, expected, actual)
+ }
+ }
+}
+
+func TestWalk(t *testing.T) {
+ items := []*ObjectItem{
+ &ObjectItem{
+ Keys: []*ObjectKey{
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"foo"`}},
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"bar"`}},
+ },
+ Val: &LiteralType{Token: token.Token{Type: token.STRING, Text: `"example"`}},
+ },
+ &ObjectItem{
+ Keys: []*ObjectKey{
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"baz"`}},
+ },
+ },
+ }
+
+ node := &ObjectList{Items: items}
+
+ order := []string{
+ "*ast.ObjectList",
+ "*ast.ObjectItem",
+ "*ast.ObjectKey",
+ "*ast.ObjectKey",
+ "*ast.LiteralType",
+ "*ast.ObjectItem",
+ "*ast.ObjectKey",
+ }
+ count := 0
+
+ Walk(node, func(n Node) (Node, bool) {
+ if n == nil {
+ return n, false
+ }
+
+ typeName := reflect.TypeOf(n).String()
+ if order[count] != typeName {
+ t.Errorf("expected '%s' got: '%s'", order[count], typeName)
+ }
+ count++
+ return n, true
+ })
+}
+
+func TestWalkEquality(t *testing.T) {
+ items := []*ObjectItem{
+ &ObjectItem{
+ Keys: []*ObjectKey{
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"foo"`}},
+ },
+ },
+ &ObjectItem{
+ Keys: []*ObjectKey{
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"bar"`}},
+ },
+ },
+ }
+
+ node := &ObjectList{Items: items}
+
+ rewritten := Walk(node, func(n Node) (Node, bool) { return n, true })
+
+ newNode, ok := rewritten.(*ObjectList)
+ if !ok {
+ t.Fatalf("expected Objectlist, got %T", rewritten)
+ }
+
+ if !reflect.DeepEqual(node, newNode) {
+ t.Fatal("rewritten node is not equal to the given node")
+ }
+
+ if len(newNode.Items) != 2 {
+ t.Error("expected newNode length 2, got: %d", len(newNode.Items))
+ }
+
+ expected := []string{
+ `"foo"`,
+ `"bar"`,
+ }
+
+ for i, item := range newNode.Items {
+ if len(item.Keys) != 1 {
+ t.Error("expected keys newNode length 1, got: %d", len(item.Keys))
+ }
+
+ if item.Keys[0].Token.Text != expected[i] {
+ t.Errorf("expected key %s, got %s", expected[i], item.Keys[0].Token.Text)
+ }
+
+ if item.Val != nil {
+ t.Errorf("expected item value should be nil")
+ }
+ }
+}
+
+func TestWalkRewrite(t *testing.T) {
+ items := []*ObjectItem{
+ &ObjectItem{
+ Keys: []*ObjectKey{
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"foo"`}},
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"bar"`}},
+ },
+ },
+ &ObjectItem{
+ Keys: []*ObjectKey{
+ &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"baz"`}},
+ },
+ },
+ }
+
+ node := &ObjectList{Items: items}
+
+ suffix := "_example"
+ node = Walk(node, func(n Node) (Node, bool) {
+ switch i := n.(type) {
+ case *ObjectKey:
+ i.Token.Text = i.Token.Text + suffix
+ n = i
+ }
+ return n, true
+ }).(*ObjectList)
+
+ Walk(node, func(n Node) (Node, bool) {
+ switch i := n.(type) {
+ case *ObjectKey:
+ if !strings.HasSuffix(i.Token.Text, suffix) {
+ t.Errorf("Token '%s' should have suffix: %s", i.Token.Text, suffix)
+ }
+ }
+ return n, true
+ })
+
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go b/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go
new file mode 100644
index 000000000..ba07ad42b
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go
@@ -0,0 +1,52 @@
+package ast
+
+import "fmt"
+
+// WalkFunc describes a function to be called for each node during a Walk. The
+// returned node can be used to rewrite the AST. Walking stops the returned
+// bool is false.
+type WalkFunc func(Node) (Node, bool)
+
+// Walk traverses an AST in depth-first order: It starts by calling fn(node);
+// node must not be nil. If fn returns true, Walk invokes fn recursively for
+// each of the non-nil children of node, followed by a call of fn(nil). The
+// returned node of fn can be used to rewrite the passed node to fn.
+func Walk(node Node, fn WalkFunc) Node {
+ rewritten, ok := fn(node)
+ if !ok {
+ return rewritten
+ }
+
+ switch n := node.(type) {
+ case *File:
+ n.Node = Walk(n.Node, fn)
+ case *ObjectList:
+ for i, item := range n.Items {
+ n.Items[i] = Walk(item, fn).(*ObjectItem)
+ }
+ case *ObjectKey:
+ // nothing to do
+ case *ObjectItem:
+ for i, k := range n.Keys {
+ n.Keys[i] = Walk(k, fn).(*ObjectKey)
+ }
+
+ if n.Val != nil {
+ n.Val = Walk(n.Val, fn)
+ }
+ case *LiteralType:
+ // nothing to do
+ case *ListType:
+ for i, l := range n.List {
+ n.List[i] = Walk(l, fn)
+ }
+ case *ObjectType:
+ n.List = Walk(n.List, fn).(*ObjectList)
+ default:
+ // should we panic here?
+ fmt.Printf("unknown type: %T\n", n)
+ }
+
+ fn(nil)
+ return rewritten
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/fmtcmd.go b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/fmtcmd.go
new file mode 100644
index 000000000..2380d71e3
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/fmtcmd.go
@@ -0,0 +1,162 @@
+// Derivative work from:
+// - https://golang.org/src/cmd/gofmt/gofmt.go
+// - https://github.com/fatih/hclfmt
+
+package fmtcmd
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+
+ "github.com/hashicorp/hcl/hcl/printer"
+)
+
+var (
+ ErrWriteStdin = errors.New("cannot use write option with standard input")
+)
+
+type Options struct {
+ List bool // list files whose formatting differs
+ Write bool // write result to (source) file instead of stdout
+ Diff bool // display diffs of formatting changes
+}
+
+func isValidFile(f os.FileInfo, extensions []string) bool {
+ if !f.IsDir() && !strings.HasPrefix(f.Name(), ".") {
+ for _, ext := range extensions {
+ if strings.HasSuffix(f.Name(), "."+ext) {
+ return true
+ }
+ }
+ }
+
+ return false
+}
+
+// If in == nil, the source is the contents of the file with the given filename.
+func processFile(filename string, in io.Reader, out io.Writer, stdin bool, opts Options) error {
+ if in == nil {
+ f, err := os.Open(filename)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ in = f
+ }
+
+ src, err := ioutil.ReadAll(in)
+ if err != nil {
+ return err
+ }
+
+ res, err := printer.Format(src)
+ if err != nil {
+ return fmt.Errorf("In %s: %s", filename, err)
+ }
+
+ if !bytes.Equal(src, res) {
+ // formatting has changed
+ if opts.List {
+ fmt.Fprintln(out, filename)
+ }
+ if opts.Write {
+ err = ioutil.WriteFile(filename, res, 0644)
+ if err != nil {
+ return err
+ }
+ }
+ if opts.Diff {
+ data, err := diff(src, res)
+ if err != nil {
+ return fmt.Errorf("computing diff: %s", err)
+ }
+ fmt.Fprintf(out, "diff a/%s b/%s\n", filename, filename)
+ out.Write(data)
+ }
+ }
+
+ if !opts.List && !opts.Write && !opts.Diff {
+ _, err = out.Write(res)
+ }
+
+ return err
+}
+
+func walkDir(path string, extensions []string, stdout io.Writer, opts Options) error {
+ visitFile := func(path string, f os.FileInfo, err error) error {
+ if err == nil && isValidFile(f, extensions) {
+ err = processFile(path, nil, stdout, false, opts)
+ }
+ return err
+ }
+
+ return filepath.Walk(path, visitFile)
+}
+
+func Run(
+ paths, extensions []string,
+ stdin io.Reader,
+ stdout io.Writer,
+ opts Options,
+) error {
+ if len(paths) == 0 {
+ if opts.Write {
+ return ErrWriteStdin
+ }
+ if err := processFile("<standard input>", stdin, stdout, true, opts); err != nil {
+ return err
+ }
+ return nil
+ }
+
+ for _, path := range paths {
+ switch dir, err := os.Stat(path); {
+ case err != nil:
+ return err
+ case dir.IsDir():
+ if err := walkDir(path, extensions, stdout, opts); err != nil {
+ return err
+ }
+ default:
+ if err := processFile(path, nil, stdout, false, opts); err != nil {
+ return err
+ }
+ }
+ }
+
+ return nil
+}
+
+func diff(b1, b2 []byte) (data []byte, err error) {
+ f1, err := ioutil.TempFile("", "")
+ if err != nil {
+ return
+ }
+ defer os.Remove(f1.Name())
+ defer f1.Close()
+
+ f2, err := ioutil.TempFile("", "")
+ if err != nil {
+ return
+ }
+ defer os.Remove(f2.Name())
+ defer f2.Close()
+
+ f1.Write(b1)
+ f2.Write(b2)
+
+ data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput()
+ if len(data) > 0 {
+ // diff exits with a non-zero status when the files don't match.
+ // Ignore that failure as long as we get output.
+ err = nil
+ }
+ return
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/fmtcmd_test.go b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/fmtcmd_test.go
new file mode 100644
index 000000000..b952d76d8
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/fmtcmd_test.go
@@ -0,0 +1,440 @@
+// +build !windows
+// TODO(jen20): These need fixing on Windows but fmt is not used right now
+// and red CI is making it harder to process other bugs, so ignore until
+// we get around to fixing them.
+
+package fmtcmd
+
+import (
+ "bytes"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "sort"
+ "syscall"
+ "testing"
+
+ "github.com/hashicorp/hcl/testhelper"
+)
+
+var fixtureExtensions = []string{"hcl"}
+
+func init() {
+ sort.Sort(ByFilename(fixtures))
+}
+
+func TestIsValidFile(t *testing.T) {
+ const fixtureDir = "./test-fixtures"
+
+ cases := []struct {
+ Path string
+ Expected bool
+ }{
+ {"good.hcl", true},
+ {".hidden.ignore", false},
+ {"file.ignore", false},
+ {"dir.ignore", false},
+ }
+
+ for _, tc := range cases {
+ file, err := os.Stat(filepath.Join(fixtureDir, tc.Path))
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+
+ if res := isValidFile(file, fixtureExtensions); res != tc.Expected {
+ t.Errorf("want: %b, got: %b", tc.Expected, res)
+ }
+ }
+}
+
+func TestRunMultiplePaths(t *testing.T) {
+ path1, err := renderFixtures("")
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ defer os.RemoveAll(path1)
+ path2, err := renderFixtures("")
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ defer os.RemoveAll(path2)
+
+ var expectedOut bytes.Buffer
+ for _, path := range []string{path1, path2} {
+ for _, fixture := range fixtures {
+ if !bytes.Equal(fixture.golden, fixture.input) {
+ expectedOut.WriteString(filepath.Join(path, fixture.filename) + "\n")
+ }
+ }
+ }
+
+ _, stdout := mockIO()
+ err = Run(
+ []string{path1, path2},
+ fixtureExtensions,
+ nil, stdout,
+ Options{
+ List: true,
+ },
+ )
+
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ if stdout.String() != expectedOut.String() {
+ t.Errorf("stdout want:\n%s\ngot:\n%s", expectedOut, stdout)
+ }
+}
+
+func TestRunSubDirectories(t *testing.T) {
+ pathParent, err := ioutil.TempDir("", "")
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ defer os.RemoveAll(pathParent)
+
+ path1, err := renderFixtures(pathParent)
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ path2, err := renderFixtures(pathParent)
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+
+ paths := []string{path1, path2}
+ sort.Strings(paths)
+
+ var expectedOut bytes.Buffer
+ for _, path := range paths {
+ for _, fixture := range fixtures {
+ if !bytes.Equal(fixture.golden, fixture.input) {
+ expectedOut.WriteString(filepath.Join(path, fixture.filename) + "\n")
+ }
+ }
+ }
+
+ _, stdout := mockIO()
+ err = Run(
+ []string{pathParent},
+ fixtureExtensions,
+ nil, stdout,
+ Options{
+ List: true,
+ },
+ )
+
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ if stdout.String() != expectedOut.String() {
+ t.Errorf("stdout want:\n%s\ngot:\n%s", expectedOut, stdout)
+ }
+}
+
+func TestRunStdin(t *testing.T) {
+ var expectedOut bytes.Buffer
+ for i, fixture := range fixtures {
+ if i != 0 {
+ expectedOut.WriteString("\n")
+ }
+ expectedOut.Write(fixture.golden)
+ }
+
+ stdin, stdout := mockIO()
+ for _, fixture := range fixtures {
+ stdin.Write(fixture.input)
+ }
+
+ err := Run(
+ []string{},
+ fixtureExtensions,
+ stdin, stdout,
+ Options{},
+ )
+
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ if !bytes.Equal(stdout.Bytes(), expectedOut.Bytes()) {
+ t.Errorf("stdout want:\n%s\ngot:\n%s", expectedOut, stdout)
+ }
+}
+
+func TestRunStdinAndWrite(t *testing.T) {
+ var expectedOut = []byte{}
+
+ stdin, stdout := mockIO()
+ stdin.WriteString("")
+ err := Run(
+ []string{}, []string{},
+ stdin, stdout,
+ Options{
+ Write: true,
+ },
+ )
+
+ if err != ErrWriteStdin {
+ t.Errorf("error want:\n%s\ngot:\n%s", ErrWriteStdin, err)
+ }
+ if !bytes.Equal(stdout.Bytes(), expectedOut) {
+ t.Errorf("stdout want:\n%s\ngot:\n%s", expectedOut, stdout)
+ }
+}
+
+func TestRunFileError(t *testing.T) {
+ path, err := ioutil.TempDir("", "")
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ defer os.RemoveAll(path)
+ filename := filepath.Join(path, "unreadable.hcl")
+
+ var expectedError = &os.PathError{
+ Op: "open",
+ Path: filename,
+ Err: syscall.EACCES,
+ }
+
+ err = ioutil.WriteFile(filename, []byte{}, 0000)
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+
+ _, stdout := mockIO()
+ err = Run(
+ []string{path},
+ fixtureExtensions,
+ nil, stdout,
+ Options{},
+ )
+
+ if !reflect.DeepEqual(err, expectedError) {
+ t.Errorf("error want: %#v, got: %#v", expectedError, err)
+ }
+}
+
+func TestRunNoOptions(t *testing.T) {
+ path, err := renderFixtures("")
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ defer os.RemoveAll(path)
+
+ var expectedOut bytes.Buffer
+ for _, fixture := range fixtures {
+ expectedOut.Write(fixture.golden)
+ }
+
+ _, stdout := mockIO()
+ err = Run(
+ []string{path},
+ fixtureExtensions,
+ nil, stdout,
+ Options{},
+ )
+
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ if stdout.String() != expectedOut.String() {
+ t.Errorf("stdout want:\n%s\ngot:\n%s", expectedOut, stdout)
+ }
+}
+
+func TestRunList(t *testing.T) {
+ path, err := renderFixtures("")
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ defer os.RemoveAll(path)
+
+ var expectedOut bytes.Buffer
+ for _, fixture := range fixtures {
+ if !bytes.Equal(fixture.golden, fixture.input) {
+ expectedOut.WriteString(fmt.Sprintln(filepath.Join(path, fixture.filename)))
+ }
+ }
+
+ _, stdout := mockIO()
+ err = Run(
+ []string{path},
+ fixtureExtensions,
+ nil, stdout,
+ Options{
+ List: true,
+ },
+ )
+
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ if stdout.String() != expectedOut.String() {
+ t.Errorf("stdout want:\n%s\ngot:\n%s", expectedOut, stdout)
+ }
+}
+
+func TestRunWrite(t *testing.T) {
+ path, err := renderFixtures("")
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ defer os.RemoveAll(path)
+
+ _, stdout := mockIO()
+ err = Run(
+ []string{path},
+ fixtureExtensions,
+ nil, stdout,
+ Options{
+ Write: true,
+ },
+ )
+
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ for _, fixture := range fixtures {
+ res, err := ioutil.ReadFile(filepath.Join(path, fixture.filename))
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ if !bytes.Equal(res, fixture.golden) {
+ t.Errorf("file %q contents want:\n%s\ngot:\n%s", fixture.filename, fixture.golden, res)
+ }
+ }
+}
+
+func TestRunDiff(t *testing.T) {
+ path, err := renderFixtures("")
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ defer os.RemoveAll(path)
+
+ var expectedOut bytes.Buffer
+ for _, fixture := range fixtures {
+ if len(fixture.diff) > 0 {
+ expectedOut.WriteString(
+ regexp.QuoteMeta(
+ fmt.Sprintf("diff a/%s/%s b/%s/%s\n", path, fixture.filename, path, fixture.filename),
+ ),
+ )
+ // Need to use regex to ignore datetimes in diff.
+ expectedOut.WriteString(`--- .+?\n`)
+ expectedOut.WriteString(`\+\+\+ .+?\n`)
+ expectedOut.WriteString(regexp.QuoteMeta(string(fixture.diff)))
+ }
+ }
+
+ expectedOutString := testhelper.Unix2dos(expectedOut.String())
+
+ _, stdout := mockIO()
+ err = Run(
+ []string{path},
+ fixtureExtensions,
+ nil, stdout,
+ Options{
+ Diff: true,
+ },
+ )
+
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ }
+ if !regexp.MustCompile(expectedOutString).Match(stdout.Bytes()) {
+ t.Errorf("stdout want match:\n%s\ngot:\n%q", expectedOutString, stdout)
+ }
+}
+
+func mockIO() (stdin, stdout *bytes.Buffer) {
+ return new(bytes.Buffer), new(bytes.Buffer)
+}
+
+type fixture struct {
+ filename string
+ input, golden, diff []byte
+}
+
+type ByFilename []fixture
+
+func (s ByFilename) Len() int { return len(s) }
+func (s ByFilename) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+func (s ByFilename) Less(i, j int) bool { return len(s[i].filename) > len(s[j].filename) }
+
+var fixtures = []fixture{
+ {
+ "noop.hcl",
+ []byte(`resource "aws_security_group" "firewall" {
+ count = 5
+}
+`),
+ []byte(`resource "aws_security_group" "firewall" {
+ count = 5
+}
+`),
+ []byte(``),
+ }, {
+ "align_equals.hcl",
+ []byte(`variable "foo" {
+ default = "bar"
+ description = "bar"
+}
+`),
+ []byte(`variable "foo" {
+ default = "bar"
+ description = "bar"
+}
+`),
+ []byte(`@@ -1,4 +1,4 @@
+ variable "foo" {
+- default = "bar"
++ default = "bar"
+ description = "bar"
+ }
+`),
+ }, {
+ "indentation.hcl",
+ []byte(`provider "aws" {
+ access_key = "foo"
+ secret_key = "bar"
+}
+`),
+ []byte(`provider "aws" {
+ access_key = "foo"
+ secret_key = "bar"
+}
+`),
+ []byte(`@@ -1,4 +1,4 @@
+ provider "aws" {
+- access_key = "foo"
+- secret_key = "bar"
++ access_key = "foo"
++ secret_key = "bar"
+ }
+`),
+ },
+}
+
+// parent can be an empty string, in which case the system's default
+// temporary directory will be used.
+func renderFixtures(parent string) (path string, err error) {
+ path, err = ioutil.TempDir(parent, "")
+ if err != nil {
+ return "", err
+ }
+
+ for _, fixture := range fixtures {
+ err = ioutil.WriteFile(filepath.Join(path, fixture.filename), []byte(fixture.input), 0644)
+ if err != nil {
+ os.RemoveAll(path)
+ return "", err
+ }
+ }
+
+ return path, nil
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/.hidden.ignore b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/.hidden.ignore
new file mode 100644
index 000000000..9977a2836
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/.hidden.ignore
@@ -0,0 +1 @@
+invalid
diff --git a/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/dir.ignore b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/dir.ignore
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/dir.ignore
diff --git a/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/file.ignore b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/file.ignore
new file mode 100644
index 000000000..9977a2836
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/file.ignore
@@ -0,0 +1 @@
+invalid
diff --git a/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/good.hcl b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/good.hcl
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/fmtcmd/test-fixtures/good.hcl
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/error.go b/vendor/github.com/hashicorp/hcl/hcl/parser/error.go
new file mode 100644
index 000000000..5c99381df
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/error.go
@@ -0,0 +1,17 @@
+package parser
+
+import (
+ "fmt"
+
+ "github.com/hashicorp/hcl/hcl/token"
+)
+
+// PosError is a parse error that contains a position.
+type PosError struct {
+ Pos token.Pos
+ Err error
+}
+
+func (e *PosError) Error() string {
+ return fmt.Sprintf("At %s: %s", e.Pos, e.Err)
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/error_test.go b/vendor/github.com/hashicorp/hcl/hcl/parser/error_test.go
new file mode 100644
index 000000000..32399fec5
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/error_test.go
@@ -0,0 +1,9 @@
+package parser
+
+import (
+ "testing"
+)
+
+func TestPosError_impl(t *testing.T) {
+ var _ error = new(PosError)
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go
new file mode 100644
index 000000000..6e54bed97
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go
@@ -0,0 +1,514 @@
+// Package parser implements a parser for HCL (HashiCorp Configuration
+// Language)
+package parser
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/hashicorp/hcl/hcl/ast"
+ "github.com/hashicorp/hcl/hcl/scanner"
+ "github.com/hashicorp/hcl/hcl/token"
+)
+
+type Parser struct {
+ sc *scanner.Scanner
+
+ // Last read token
+ tok token.Token
+ commaPrev token.Token
+
+ comments []*ast.CommentGroup
+ leadComment *ast.CommentGroup // last lead comment
+ lineComment *ast.CommentGroup // last line comment
+
+ enableTrace bool
+ indent int
+ n int // buffer size (max = 1)
+}
+
+func newParser(src []byte) *Parser {
+ return &Parser{
+ sc: scanner.New(src),
+ }
+}
+
+// Parse returns the fully parsed source and returns the abstract syntax tree.
+func Parse(src []byte) (*ast.File, error) {
+ p := newParser(src)
+ return p.Parse()
+}
+
+var errEofToken = errors.New("EOF token found")
+
+// Parse returns the fully parsed source and returns the abstract syntax tree.
+func (p *Parser) Parse() (*ast.File, error) {
+ f := &ast.File{}
+ var err, scerr error
+ p.sc.Error = func(pos token.Pos, msg string) {
+ scerr = &PosError{Pos: pos, Err: errors.New(msg)}
+ }
+
+ f.Node, err = p.objectList(false)
+ if scerr != nil {
+ return nil, scerr
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ f.Comments = p.comments
+ return f, nil
+}
+
+// objectList parses a list of items within an object (generally k/v pairs).
+// The parameter" obj" tells this whether to we are within an object (braces:
+// '{', '}') or just at the top level. If we're within an object, we end
+// at an RBRACE.
+func (p *Parser) objectList(obj bool) (*ast.ObjectList, error) {
+ defer un(trace(p, "ParseObjectList"))
+ node := &ast.ObjectList{}
+
+ for {
+ if obj {
+ tok := p.scan()
+ p.unscan()
+ if tok.Type == token.RBRACE {
+ break
+ }
+ }
+
+ n, err := p.objectItem()
+ if err == errEofToken {
+ break // we are finished
+ }
+
+ // we don't return a nil node, because might want to use already
+ // collected items.
+ if err != nil {
+ return node, err
+ }
+
+ node.Add(n)
+
+ // object lists can be optionally comma-delimited e.g. when a list of maps
+ // is being expressed, so a comma is allowed here - it's simply consumed
+ tok := p.scan()
+ if tok.Type != token.COMMA {
+ p.unscan()
+ }
+ }
+ return node, nil
+}
+
+func (p *Parser) consumeComment() (comment *ast.Comment, endline int) {
+ endline = p.tok.Pos.Line
+
+ // count the endline if it's multiline comment, ie starting with /*
+ if len(p.tok.Text) > 1 && p.tok.Text[1] == '*' {
+ // don't use range here - no need to decode Unicode code points
+ for i := 0; i < len(p.tok.Text); i++ {
+ if p.tok.Text[i] == '\n' {
+ endline++
+ }
+ }
+ }
+
+ comment = &ast.Comment{Start: p.tok.Pos, Text: p.tok.Text}
+ p.tok = p.sc.Scan()
+ return
+}
+
+func (p *Parser) consumeCommentGroup(n int) (comments *ast.CommentGroup, endline int) {
+ var list []*ast.Comment
+ endline = p.tok.Pos.Line
+
+ for p.tok.Type == token.COMMENT && p.tok.Pos.Line <= endline+n {
+ var comment *ast.Comment
+ comment, endline = p.consumeComment()
+ list = append(list, comment)
+ }
+
+ // add comment group to the comments list
+ comments = &ast.CommentGroup{List: list}
+ p.comments = append(p.comments, comments)
+
+ return
+}
+
+// objectItem parses a single object item
+func (p *Parser) objectItem() (*ast.ObjectItem, error) {
+ defer un(trace(p, "ParseObjectItem"))
+
+ keys, err := p.objectKey()
+ if len(keys) > 0 && err == errEofToken {
+ // We ignore eof token here since it is an error if we didn't
+ // receive a value (but we did receive a key) for the item.
+ err = nil
+ }
+ if len(keys) > 0 && err != nil && p.tok.Type == token.RBRACE {
+ // This is a strange boolean statement, but what it means is:
+ // We have keys with no value, and we're likely in an object
+ // (since RBrace ends an object). For this, we set err to nil so
+ // we continue and get the error below of having the wrong value
+ // type.
+ err = nil
+
+ // Reset the token type so we don't think it completed fine. See
+ // objectType which uses p.tok.Type to check if we're done with
+ // the object.
+ p.tok.Type = token.EOF
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ o := &ast.ObjectItem{
+ Keys: keys,
+ }
+
+ if p.leadComment != nil {
+ o.LeadComment = p.leadComment
+ p.leadComment = nil
+ }
+
+ switch p.tok.Type {
+ case token.ASSIGN:
+ o.Assign = p.tok.Pos
+ o.Val, err = p.object()
+ if err != nil {
+ return nil, err
+ }
+ case token.LBRACE:
+ o.Val, err = p.objectType()
+ if err != nil {
+ return nil, err
+ }
+ default:
+ keyStr := make([]string, 0, len(keys))
+ for _, k := range keys {
+ keyStr = append(keyStr, k.Token.Text)
+ }
+
+ return nil, fmt.Errorf(
+ "key '%s' expected start of object ('{') or assignment ('=')",
+ strings.Join(keyStr, " "))
+ }
+
+ // do a look-ahead for line comment
+ p.scan()
+ if len(keys) > 0 && o.Val.Pos().Line == keys[0].Pos().Line && p.lineComment != nil {
+ o.LineComment = p.lineComment
+ p.lineComment = nil
+ }
+ p.unscan()
+ return o, nil
+}
+
+// objectKey parses an object key and returns a ObjectKey AST
+func (p *Parser) objectKey() ([]*ast.ObjectKey, error) {
+ keyCount := 0
+ keys := make([]*ast.ObjectKey, 0)
+
+ for {
+ tok := p.scan()
+ switch tok.Type {
+ case token.EOF:
+ // It is very important to also return the keys here as well as
+ // the error. This is because we need to be able to tell if we
+ // did parse keys prior to finding the EOF, or if we just found
+ // a bare EOF.
+ return keys, errEofToken
+ case token.ASSIGN:
+ // assignment or object only, but not nested objects. this is not
+ // allowed: `foo bar = {}`
+ if keyCount > 1 {
+ return nil, &PosError{
+ Pos: p.tok.Pos,
+ Err: fmt.Errorf("nested object expected: LBRACE got: %s", p.tok.Type),
+ }
+ }
+
+ if keyCount == 0 {
+ return nil, &PosError{
+ Pos: p.tok.Pos,
+ Err: errors.New("no object keys found!"),
+ }
+ }
+
+ return keys, nil
+ case token.LBRACE:
+ var err error
+
+ // If we have no keys, then it is a syntax error. i.e. {{}} is not
+ // allowed.
+ if len(keys) == 0 {
+ err = &PosError{
+ Pos: p.tok.Pos,
+ Err: fmt.Errorf("expected: IDENT | STRING got: %s", p.tok.Type),
+ }
+ }
+
+ // object
+ return keys, err
+ case token.IDENT, token.STRING:
+ keyCount++
+ keys = append(keys, &ast.ObjectKey{Token: p.tok})
+ case token.ILLEGAL:
+ return keys, &PosError{
+ Pos: p.tok.Pos,
+ Err: fmt.Errorf("illegal character"),
+ }
+ default:
+ return keys, &PosError{
+ Pos: p.tok.Pos,
+ Err: fmt.Errorf("expected: IDENT | STRING | ASSIGN | LBRACE got: %s", p.tok.Type),
+ }
+ }
+ }
+}
+
+// object parses any type of object, such as number, bool, string, object or
+// list.
+func (p *Parser) object() (ast.Node, error) {
+ defer un(trace(p, "ParseType"))
+ tok := p.scan()
+
+ switch tok.Type {
+ case token.NUMBER, token.FLOAT, token.BOOL, token.STRING, token.HEREDOC:
+ return p.literalType()
+ case token.LBRACE:
+ return p.objectType()
+ case token.LBRACK:
+ return p.listType()
+ case token.COMMENT:
+ // implement comment
+ case token.EOF:
+ return nil, errEofToken
+ }
+
+ return nil, &PosError{
+ Pos: tok.Pos,
+ Err: fmt.Errorf("Unknown token: %+v", tok),
+ }
+}
+
+// objectType parses an object type and returns a ObjectType AST
+func (p *Parser) objectType() (*ast.ObjectType, error) {
+ defer un(trace(p, "ParseObjectType"))
+
+ // we assume that the currently scanned token is a LBRACE
+ o := &ast.ObjectType{
+ Lbrace: p.tok.Pos,
+ }
+
+ l, err := p.objectList(true)
+
+ // if we hit RBRACE, we are good to go (means we parsed all Items), if it's
+ // not a RBRACE, it's an syntax error and we just return it.
+ if err != nil && p.tok.Type != token.RBRACE {
+ return nil, err
+ }
+
+ // No error, scan and expect the ending to be a brace
+ if tok := p.scan(); tok.Type != token.RBRACE {
+ return nil, fmt.Errorf("object expected closing RBRACE got: %s", tok.Type)
+ }
+
+ o.List = l
+ o.Rbrace = p.tok.Pos // advanced via parseObjectList
+ return o, nil
+}
+
+// listType parses a list type and returns a ListType AST
+func (p *Parser) listType() (*ast.ListType, error) {
+ defer un(trace(p, "ParseListType"))
+
+ // we assume that the currently scanned token is a LBRACK
+ l := &ast.ListType{
+ Lbrack: p.tok.Pos,
+ }
+
+ needComma := false
+ for {
+ tok := p.scan()
+ if needComma {
+ switch tok.Type {
+ case token.COMMA, token.RBRACK:
+ default:
+ return nil, &PosError{
+ Pos: tok.Pos,
+ Err: fmt.Errorf(
+ "error parsing list, expected comma or list end, got: %s",
+ tok.Type),
+ }
+ }
+ }
+ switch tok.Type {
+ case token.BOOL, token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC:
+ node, err := p.literalType()
+ if err != nil {
+ return nil, err
+ }
+
+ // If there is a lead comment, apply it
+ if p.leadComment != nil {
+ node.LeadComment = p.leadComment
+ p.leadComment = nil
+ }
+
+ l.Add(node)
+ needComma = true
+ case token.COMMA:
+ // get next list item or we are at the end
+ // do a look-ahead for line comment
+ p.scan()
+ if p.lineComment != nil && len(l.List) > 0 {
+ lit, ok := l.List[len(l.List)-1].(*ast.LiteralType)
+ if ok {
+ lit.LineComment = p.lineComment
+ l.List[len(l.List)-1] = lit
+ p.lineComment = nil
+ }
+ }
+ p.unscan()
+
+ needComma = false
+ continue
+ case token.LBRACE:
+ // Looks like a nested object, so parse it out
+ node, err := p.objectType()
+ if err != nil {
+ return nil, &PosError{
+ Pos: tok.Pos,
+ Err: fmt.Errorf(
+ "error while trying to parse object within list: %s", err),
+ }
+ }
+ l.Add(node)
+ needComma = true
+ case token.LBRACK:
+ node, err := p.listType()
+ if err != nil {
+ return nil, &PosError{
+ Pos: tok.Pos,
+ Err: fmt.Errorf(
+ "error while trying to parse list within list: %s", err),
+ }
+ }
+ l.Add(node)
+ case token.RBRACK:
+ // finished
+ l.Rbrack = p.tok.Pos
+ return l, nil
+ default:
+ return nil, &PosError{
+ Pos: tok.Pos,
+ Err: fmt.Errorf("unexpected token while parsing list: %s", tok.Type),
+ }
+ }
+ }
+}
+
+// literalType parses a literal type and returns a LiteralType AST
+func (p *Parser) literalType() (*ast.LiteralType, error) {
+ defer un(trace(p, "ParseLiteral"))
+
+ return &ast.LiteralType{
+ Token: p.tok,
+ }, nil
+}
+
+// scan returns the next token from the underlying scanner. If a token has
+// been unscanned then read that instead. In the process, it collects any
+// comment groups encountered, and remembers the last lead and line comments.
+func (p *Parser) scan() token.Token {
+ // If we have a token on the buffer, then return it.
+ if p.n != 0 {
+ p.n = 0
+ return p.tok
+ }
+
+ // Otherwise read the next token from the scanner and Save it to the buffer
+ // in case we unscan later.
+ prev := p.tok
+ p.tok = p.sc.Scan()
+
+ if p.tok.Type == token.COMMENT {
+ var comment *ast.CommentGroup
+ var endline int
+
+ // fmt.Printf("p.tok.Pos.Line = %+v prev: %d endline %d \n",
+ // p.tok.Pos.Line, prev.Pos.Line, endline)
+ if p.tok.Pos.Line == prev.Pos.Line {
+ // The comment is on same line as the previous token; it
+ // cannot be a lead comment but may be a line comment.
+ comment, endline = p.consumeCommentGroup(0)
+ if p.tok.Pos.Line != endline {
+ // The next token is on a different line, thus
+ // the last comment group is a line comment.
+ p.lineComment = comment
+ }
+ }
+
+ // consume successor comments, if any
+ endline = -1
+ for p.tok.Type == token.COMMENT {
+ comment, endline = p.consumeCommentGroup(1)
+ }
+
+ if endline+1 == p.tok.Pos.Line && p.tok.Type != token.RBRACE {
+ switch p.tok.Type {
+ case token.RBRACE, token.RBRACK:
+ // Do not count for these cases
+ default:
+ // The next token is following on the line immediately after the
+ // comment group, thus the last comment group is a lead comment.
+ p.leadComment = comment
+ }
+ }
+
+ }
+
+ return p.tok
+}
+
+// unscan pushes the previously read token back onto the buffer.
+func (p *Parser) unscan() {
+ p.n = 1
+}
+
+// ----------------------------------------------------------------------------
+// Parsing support
+
+func (p *Parser) printTrace(a ...interface{}) {
+ if !p.enableTrace {
+ return
+ }
+
+ const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+ const n = len(dots)
+ fmt.Printf("%5d:%3d: ", p.tok.Pos.Line, p.tok.Pos.Column)
+
+ i := 2 * p.indent
+ for i > n {
+ fmt.Print(dots)
+ i -= n
+ }
+ // i <= n
+ fmt.Print(dots[0:i])
+ fmt.Println(a...)
+}
+
+func trace(p *Parser, msg string) *Parser {
+ p.printTrace(msg, "(")
+ p.indent++
+ return p
+}
+
+// Usage pattern: defer un(trace(p, "..."))
+func un(p *Parser) {
+ p.indent--
+ p.printTrace(")")
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser_test.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser_test.go
new file mode 100644
index 000000000..575865838
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/parser_test.go
@@ -0,0 +1,566 @@
+package parser
+
+import (
+ "fmt"
+ "io/ioutil"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "strings"
+ "testing"
+
+ "github.com/hashicorp/hcl/hcl/ast"
+ "github.com/hashicorp/hcl/hcl/token"
+)
+
+func TestType(t *testing.T) {
+ var literals = []struct {
+ typ token.Type
+ src string
+ }{
+ {token.STRING, `foo = "foo"`},
+ {token.NUMBER, `foo = 123`},
+ {token.NUMBER, `foo = -29`},
+ {token.FLOAT, `foo = 123.12`},
+ {token.FLOAT, `foo = -123.12`},
+ {token.BOOL, `foo = true`},
+ {token.HEREDOC, "foo = <<EOF\nHello\nWorld\nEOF"},
+ }
+
+ for _, l := range literals {
+ p := newParser([]byte(l.src))
+ item, err := p.objectItem()
+ if err != nil {
+ t.Error(err)
+ }
+
+ lit, ok := item.Val.(*ast.LiteralType)
+ if !ok {
+ t.Errorf("node should be of type LiteralType, got: %T", item.Val)
+ }
+
+ if lit.Token.Type != l.typ {
+ t.Errorf("want: %s, got: %s", l.typ, lit.Token.Type)
+ }
+ }
+}
+
+func TestListType(t *testing.T) {
+ var literals = []struct {
+ src string
+ tokens []token.Type
+ }{
+ {
+ `foo = ["123", 123]`,
+ []token.Type{token.STRING, token.NUMBER},
+ },
+ {
+ `foo = [123, "123",]`,
+ []token.Type{token.NUMBER, token.STRING},
+ },
+ {
+ `foo = [false]`,
+ []token.Type{token.BOOL},
+ },
+ {
+ `foo = []`,
+ []token.Type{},
+ },
+ {
+ `foo = [1,
+"string",
+<<EOF
+heredoc contents
+EOF
+]`,
+ []token.Type{token.NUMBER, token.STRING, token.HEREDOC},
+ },
+ }
+
+ for _, l := range literals {
+ p := newParser([]byte(l.src))
+ item, err := p.objectItem()
+ if err != nil {
+ t.Error(err)
+ }
+
+ list, ok := item.Val.(*ast.ListType)
+ if !ok {
+ t.Errorf("node should be of type LiteralType, got: %T", item.Val)
+ }
+
+ tokens := []token.Type{}
+ for _, li := range list.List {
+ if tp, ok := li.(*ast.LiteralType); ok {
+ tokens = append(tokens, tp.Token.Type)
+ }
+ }
+
+ equals(t, l.tokens, tokens)
+ }
+}
+
+func TestListOfMaps(t *testing.T) {
+ src := `foo = [
+ {key = "bar"},
+ {key = "baz", key2 = "qux"},
+ ]`
+ p := newParser([]byte(src))
+
+ file, err := p.Parse()
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ // Here we make all sorts of assumptions about the input structure w/ type
+ // assertions. The intent is only for this to be a "smoke test" ensuring
+ // parsing actually performed its duty - giving this test something a bit
+ // more robust than _just_ "no error occurred".
+ expected := []string{`"bar"`, `"baz"`, `"qux"`}
+ actual := make([]string, 0, 3)
+ ol := file.Node.(*ast.ObjectList)
+ objItem := ol.Items[0]
+ list := objItem.Val.(*ast.ListType)
+ for _, node := range list.List {
+ obj := node.(*ast.ObjectType)
+ for _, item := range obj.List.Items {
+ val := item.Val.(*ast.LiteralType)
+ actual = append(actual, val.Token.Text)
+ }
+
+ }
+ if !reflect.DeepEqual(expected, actual) {
+ t.Fatalf("Expected: %#v, got %#v", expected, actual)
+ }
+}
+
+func TestListOfMaps_requiresComma(t *testing.T) {
+ src := `foo = [
+ {key = "bar"}
+ {key = "baz"}
+ ]`
+ p := newParser([]byte(src))
+
+ _, err := p.Parse()
+ if err == nil {
+ t.Fatalf("Expected error, got none!")
+ }
+
+ expected := "error parsing list, expected comma or list end"
+ if !strings.Contains(err.Error(), expected) {
+ t.Fatalf("Expected err:\n %s\nTo contain:\n %s\n", err, expected)
+ }
+}
+
+func TestListType_leadComment(t *testing.T) {
+ var literals = []struct {
+ src string
+ comment []string
+ }{
+ {
+ `foo = [
+ 1,
+ # bar
+ 2,
+ 3,
+ ]`,
+ []string{"", "# bar", ""},
+ },
+ }
+
+ for _, l := range literals {
+ p := newParser([]byte(l.src))
+ item, err := p.objectItem()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ list, ok := item.Val.(*ast.ListType)
+ if !ok {
+ t.Fatalf("node should be of type LiteralType, got: %T", item.Val)
+ }
+
+ if len(list.List) != len(l.comment) {
+ t.Fatalf("bad: %d", len(list.List))
+ }
+
+ for i, li := range list.List {
+ lt := li.(*ast.LiteralType)
+ comment := l.comment[i]
+
+ if (lt.LeadComment == nil) != (comment == "") {
+ t.Fatalf("bad: %#v", lt)
+ }
+
+ if comment == "" {
+ continue
+ }
+
+ actual := lt.LeadComment.List[0].Text
+ if actual != comment {
+ t.Fatalf("bad: %q %q", actual, comment)
+ }
+ }
+ }
+}
+
+func TestListType_lineComment(t *testing.T) {
+ var literals = []struct {
+ src string
+ comment []string
+ }{
+ {
+ `foo = [
+ 1,
+ 2, # bar
+ 3,
+ ]`,
+ []string{"", "# bar", ""},
+ },
+ }
+
+ for _, l := range literals {
+ p := newParser([]byte(l.src))
+ item, err := p.objectItem()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ list, ok := item.Val.(*ast.ListType)
+ if !ok {
+ t.Fatalf("node should be of type LiteralType, got: %T", item.Val)
+ }
+
+ if len(list.List) != len(l.comment) {
+ t.Fatalf("bad: %d", len(list.List))
+ }
+
+ for i, li := range list.List {
+ lt := li.(*ast.LiteralType)
+ comment := l.comment[i]
+
+ if (lt.LineComment == nil) != (comment == "") {
+ t.Fatalf("bad: %s", lt)
+ }
+
+ if comment == "" {
+ continue
+ }
+
+ actual := lt.LineComment.List[0].Text
+ if actual != comment {
+ t.Fatalf("bad: %q %q", actual, comment)
+ }
+ }
+ }
+}
+
+func TestObjectType(t *testing.T) {
+ var literals = []struct {
+ src string
+ nodeType []ast.Node
+ itemLen int
+ }{
+ {
+ `foo = {}`,
+ nil,
+ 0,
+ },
+ {
+ `foo = {
+ bar = "fatih"
+ }`,
+ []ast.Node{&ast.LiteralType{}},
+ 1,
+ },
+ {
+ `foo = {
+ bar = "fatih"
+ baz = ["arslan"]
+ }`,
+ []ast.Node{
+ &ast.LiteralType{},
+ &ast.ListType{},
+ },
+ 2,
+ },
+ {
+ `foo = {
+ bar {}
+ }`,
+ []ast.Node{
+ &ast.ObjectType{},
+ },
+ 1,
+ },
+ {
+ `foo {
+ bar {}
+ foo = true
+ }`,
+ []ast.Node{
+ &ast.ObjectType{},
+ &ast.LiteralType{},
+ },
+ 2,
+ },
+ }
+
+ for _, l := range literals {
+ t.Logf("Source: %s", l.src)
+
+ p := newParser([]byte(l.src))
+ // p.enableTrace = true
+ item, err := p.objectItem()
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ // we know that the ObjectKey name is foo for all cases, what matters
+ // is the object
+ obj, ok := item.Val.(*ast.ObjectType)
+ if !ok {
+ t.Errorf("node should be of type LiteralType, got: %T", item.Val)
+ continue
+ }
+
+ // check if the total length of items are correct
+ equals(t, l.itemLen, len(obj.List.Items))
+
+ // check if the types are correct
+ for i, item := range obj.List.Items {
+ equals(t, reflect.TypeOf(l.nodeType[i]), reflect.TypeOf(item.Val))
+ }
+ }
+}
+
+func TestObjectKey(t *testing.T) {
+ keys := []struct {
+ exp []token.Type
+ src string
+ }{
+ {[]token.Type{token.IDENT}, `foo {}`},
+ {[]token.Type{token.IDENT}, `foo = {}`},
+ {[]token.Type{token.IDENT}, `foo = bar`},
+ {[]token.Type{token.IDENT}, `foo = 123`},
+ {[]token.Type{token.IDENT}, `foo = "${var.bar}`},
+ {[]token.Type{token.STRING}, `"foo" {}`},
+ {[]token.Type{token.STRING}, `"foo" = {}`},
+ {[]token.Type{token.STRING}, `"foo" = "${var.bar}`},
+ {[]token.Type{token.IDENT, token.IDENT}, `foo bar {}`},
+ {[]token.Type{token.IDENT, token.STRING}, `foo "bar" {}`},
+ {[]token.Type{token.STRING, token.IDENT}, `"foo" bar {}`},
+ {[]token.Type{token.IDENT, token.IDENT, token.IDENT}, `foo bar baz {}`},
+ }
+
+ for _, k := range keys {
+ p := newParser([]byte(k.src))
+ keys, err := p.objectKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ tokens := []token.Type{}
+ for _, o := range keys {
+ tokens = append(tokens, o.Token.Type)
+ }
+
+ equals(t, k.exp, tokens)
+ }
+
+ errKeys := []struct {
+ src string
+ }{
+ {`foo 12 {}`},
+ {`foo bar = {}`},
+ {`foo []`},
+ {`12 {}`},
+ }
+
+ for _, k := range errKeys {
+ p := newParser([]byte(k.src))
+ _, err := p.objectKey()
+ if err == nil {
+ t.Errorf("case '%s' should give an error", k.src)
+ }
+ }
+}
+
+func TestCommentGroup(t *testing.T) {
+ var cases = []struct {
+ src string
+ groups int
+ }{
+ {"# Hello\n# World", 1},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.src, func(t *testing.T) {
+ p := newParser([]byte(tc.src))
+ file, err := p.Parse()
+ if err != nil {
+ t.Fatalf("parse error: %s", err)
+ }
+
+ if len(file.Comments) != tc.groups {
+ t.Fatalf("bad: %#v", file.Comments)
+ }
+ })
+ }
+}
+
+// Official HCL tests
+func TestParse(t *testing.T) {
+ cases := []struct {
+ Name string
+ Err bool
+ }{
+ {
+ "assign_colon.hcl",
+ true,
+ },
+ {
+ "comment.hcl",
+ false,
+ },
+ {
+ "comment_lastline.hcl",
+ false,
+ },
+ {
+ "comment_single.hcl",
+ false,
+ },
+ {
+ "empty.hcl",
+ false,
+ },
+ {
+ "list_comma.hcl",
+ false,
+ },
+ {
+ "multiple.hcl",
+ false,
+ },
+ {
+ "object_list_comma.hcl",
+ false,
+ },
+ {
+ "structure.hcl",
+ false,
+ },
+ {
+ "structure_basic.hcl",
+ false,
+ },
+ {
+ "structure_empty.hcl",
+ false,
+ },
+ {
+ "complex.hcl",
+ false,
+ },
+ {
+ "types.hcl",
+ false,
+ },
+ {
+ "array_comment.hcl",
+ false,
+ },
+ {
+ "array_comment_2.hcl",
+ true,
+ },
+ {
+ "missing_braces.hcl",
+ true,
+ },
+ {
+ "unterminated_object.hcl",
+ true,
+ },
+ {
+ "unterminated_object_2.hcl",
+ true,
+ },
+ {
+ "key_without_value.hcl",
+ true,
+ },
+ {
+ "object_key_without_value.hcl",
+ true,
+ },
+ {
+ "object_key_assign_without_value.hcl",
+ true,
+ },
+ {
+ "object_key_assign_without_value2.hcl",
+ true,
+ },
+ {
+ "object_key_assign_without_value3.hcl",
+ true,
+ },
+ {
+ "git_crypt.hcl",
+ true,
+ },
+ }
+
+ const fixtureDir = "./test-fixtures"
+
+ for _, tc := range cases {
+ t.Run(tc.Name, func(t *testing.T) {
+ d, err := ioutil.ReadFile(filepath.Join(fixtureDir, tc.Name))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ v, err := Parse(d)
+ if (err != nil) != tc.Err {
+ t.Fatalf("Input: %s\n\nError: %s\n\nAST: %#v", tc.Name, err, v)
+ }
+ })
+ }
+}
+
+func TestParse_inline(t *testing.T) {
+ cases := []struct {
+ Value string
+ Err bool
+ }{
+ {"t t e{{}}", true},
+ {"o{{}}", true},
+ {"t t e d N{{}}", true},
+ {"t t e d{{}}", true},
+ {"N{}N{{}}", true},
+ {"v\nN{{}}", true},
+ {"v=/\n[,", true},
+ {"v=10kb", true},
+ {"v=/foo", true},
+ }
+
+ for _, tc := range cases {
+ t.Logf("Testing: %q", tc.Value)
+ ast, err := Parse([]byte(tc.Value))
+ if (err != nil) != tc.Err {
+ t.Fatalf("Input: %q\n\nError: %s\n\nAST: %#v", tc.Value, err, ast)
+ }
+ }
+}
+
+// equals fails the test if exp is not equal to act.
+func equals(tb testing.TB, exp, act interface{}) {
+ if !reflect.DeepEqual(exp, act) {
+ _, file, line, _ := runtime.Caller(1)
+ fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
+ tb.FailNow()
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/array_comment.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/array_comment.hcl
new file mode 100644
index 000000000..78c267582
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/array_comment.hcl
@@ -0,0 +1,4 @@
+foo = [
+ "1",
+ "2", # comment
+]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/array_comment_2.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/array_comment_2.hcl
new file mode 100644
index 000000000..f91667738
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/array_comment_2.hcl
@@ -0,0 +1,6 @@
+provisioner "remote-exec" {
+ scripts = [
+ "${path.module}/scripts/install-consul.sh" // missing comma
+ "${path.module}/scripts/install-haproxy.sh"
+ ]
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/assign_colon.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/assign_colon.hcl
new file mode 100644
index 000000000..eb5a99a69
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/assign_colon.hcl
@@ -0,0 +1,6 @@
+resource = [{
+ "foo": {
+ "bar": {},
+ "baz": [1, 2, "foo"],
+ }
+}]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/assign_deep.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/assign_deep.hcl
new file mode 100644
index 000000000..dd3151cb7
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/assign_deep.hcl
@@ -0,0 +1,5 @@
+resource = [{
+ foo = [{
+ bar = {}
+ }]
+}]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment.hcl
new file mode 100644
index 000000000..1ff7f29fd
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment.hcl
@@ -0,0 +1,15 @@
+// Foo
+
+/* Bar */
+
+/*
+/*
+Baz
+*/
+
+# Another
+
+# Multiple
+# Lines
+
+foo = "bar"
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment_lastline.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment_lastline.hcl
new file mode 100644
index 000000000..5529b9b4c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment_lastline.hcl
@@ -0,0 +1 @@
+#foo \ No newline at end of file
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment_single.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment_single.hcl
new file mode 100644
index 000000000..fec56017d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/comment_single.hcl
@@ -0,0 +1 @@
+# Hello
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/complex.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/complex.hcl
new file mode 100644
index 000000000..13b3c2726
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/complex.hcl
@@ -0,0 +1,42 @@
+variable "foo" {
+ default = "bar"
+ description = "bar"
+}
+
+variable "groups" { }
+
+provider "aws" {
+ access_key = "foo"
+ secret_key = "bar"
+}
+
+provider "do" {
+ api_key = "${var.foo}"
+}
+
+resource "aws_security_group" "firewall" {
+ count = 5
+}
+
+resource aws_instance "web" {
+ ami = "${var.foo}"
+ security_groups = [
+ "foo",
+ "${aws_security_group.firewall.foo}",
+ "${element(split(\",\", var.groups)}",
+ ]
+ network_interface = {
+ device_index = 0
+ description = "Main network interface"
+ }
+}
+
+resource "aws_instance" "db" {
+ security_groups = "${aws_security_group.firewall.*.id}"
+ VPC = "foo"
+ depends_on = ["aws_instance.web"]
+}
+
+output "web_ip" {
+ value = "${aws_instance.web.private_ip}"
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/complex_key.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/complex_key.hcl
new file mode 100644
index 000000000..0007aaf5f
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/complex_key.hcl
@@ -0,0 +1 @@
+foo.bar = "baz"
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/empty.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/empty.hcl
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/empty.hcl
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/git_crypt.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/git_crypt.hcl
new file mode 100644
index 000000000..f691948e1
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/git_crypt.hcl
Binary files differ
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/key_without_value.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/key_without_value.hcl
new file mode 100644
index 000000000..257cc5642
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/key_without_value.hcl
@@ -0,0 +1 @@
+foo
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/list.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/list.hcl
new file mode 100644
index 000000000..059d4ce65
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/list.hcl
@@ -0,0 +1 @@
+foo = [1, 2, "foo"]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/list_comma.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/list_comma.hcl
new file mode 100644
index 000000000..50f4218ac
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/list_comma.hcl
@@ -0,0 +1 @@
+foo = [1, 2, "foo",]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/missing_braces.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/missing_braces.hcl
new file mode 100644
index 000000000..68e7274e6
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/missing_braces.hcl
@@ -0,0 +1,4 @@
+# should error, but not crash
+resource "template_file" "cloud_config" {
+ template = "$file("${path.module}/some/path")"
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/multiple.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/multiple.hcl
new file mode 100644
index 000000000..029c54b0c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/multiple.hcl
@@ -0,0 +1,2 @@
+foo = "bar"
+key = 7
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value.hcl
new file mode 100644
index 000000000..37a2c7a06
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value.hcl
@@ -0,0 +1,3 @@
+foo {
+ bar =
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value2.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value2.hcl
new file mode 100644
index 000000000..83ec5e66e
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value2.hcl
@@ -0,0 +1,4 @@
+foo {
+ baz = 7
+ bar =
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value3.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value3.hcl
new file mode 100644
index 000000000..21136d1d5
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_assign_without_value3.hcl
@@ -0,0 +1,4 @@
+foo {
+ bar =
+ baz = 7
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_without_value.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_without_value.hcl
new file mode 100644
index 000000000..a9987318c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_key_without_value.hcl
@@ -0,0 +1,3 @@
+foo {
+ bar
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_list_comma.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_list_comma.hcl
new file mode 100644
index 000000000..1921ec8f2
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/object_list_comma.hcl
@@ -0,0 +1 @@
+foo = {one = 1, two = 2}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/old.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/old.hcl
new file mode 100644
index 000000000..e9f77cae9
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/old.hcl
@@ -0,0 +1,3 @@
+default = {
+ "eu-west-1": "ami-b1cf19c6",
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure.hcl
new file mode 100644
index 000000000..92592fbb3
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure.hcl
@@ -0,0 +1,5 @@
+// This is a test structure for the lexer
+foo bar "baz" {
+ key = 7
+ foo = "bar"
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure_basic.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure_basic.hcl
new file mode 100644
index 000000000..7229a1f01
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure_basic.hcl
@@ -0,0 +1,5 @@
+foo {
+ value = 7
+ "value" = 8
+ "complex::value" = 9
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure_empty.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure_empty.hcl
new file mode 100644
index 000000000..4d156ddea
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/structure_empty.hcl
@@ -0,0 +1 @@
+resource "foo" "bar" {}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/types.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/types.hcl
new file mode 100644
index 000000000..cf2747ea1
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/types.hcl
@@ -0,0 +1,7 @@
+foo = "bar"
+bar = 7
+baz = [1,2,3]
+foo = -12
+bar = 3.14159
+foo = true
+bar = false
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/unterminated_object.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/unterminated_object.hcl
new file mode 100644
index 000000000..31b37c4f9
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/unterminated_object.hcl
@@ -0,0 +1,2 @@
+foo "baz" {
+ bar = "baz"
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/unterminated_object_2.hcl b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/unterminated_object_2.hcl
new file mode 100644
index 000000000..294e36d65
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/parser/test-fixtures/unterminated_object_2.hcl
@@ -0,0 +1,6 @@
+resource "aws_eip" "EIP1" { a { a { a { a { a {
+ count = "1"
+
+resource "aws_eip" "EIP2" {
+ count = "1"
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go b/vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go
new file mode 100644
index 000000000..c896d5844
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go
@@ -0,0 +1,779 @@
+package printer
+
+import (
+ "bytes"
+ "fmt"
+ "sort"
+
+ "github.com/hashicorp/hcl/hcl/ast"
+ "github.com/hashicorp/hcl/hcl/token"
+)
+
+const (
+ blank = byte(' ')
+ newline = byte('\n')
+ tab = byte('\t')
+ infinity = 1 << 30 // offset or line
+)
+
+var (
+ unindent = []byte("\uE123") // in the private use space
+)
+
+type printer struct {
+ cfg Config
+ prev token.Pos
+
+ comments []*ast.CommentGroup // may be nil, contains all comments
+ standaloneComments []*ast.CommentGroup // contains all standalone comments (not assigned to any node)
+
+ enableTrace bool
+ indentTrace int
+}
+
+type ByPosition []*ast.CommentGroup
+
+func (b ByPosition) Len() int { return len(b) }
+func (b ByPosition) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
+func (b ByPosition) Less(i, j int) bool { return b[i].Pos().Before(b[j].Pos()) }
+
+// collectComments comments all standalone comments which are not lead or line
+// comment
+func (p *printer) collectComments(node ast.Node) {
+ // first collect all comments. This is already stored in
+ // ast.File.(comments)
+ ast.Walk(node, func(nn ast.Node) (ast.Node, bool) {
+ switch t := nn.(type) {
+ case *ast.File:
+ p.comments = t.Comments
+ return nn, false
+ }
+ return nn, true
+ })
+
+ standaloneComments := make(map[token.Pos]*ast.CommentGroup, 0)
+ for _, c := range p.comments {
+ standaloneComments[c.Pos()] = c
+ }
+
+ // next remove all lead and line comments from the overall comment map.
+ // This will give us comments which are standalone, comments which are not
+ // assigned to any kind of node.
+ ast.Walk(node, func(nn ast.Node) (ast.Node, bool) {
+ switch t := nn.(type) {
+ case *ast.LiteralType:
+ if t.LeadComment != nil {
+ for _, comment := range t.LeadComment.List {
+ if _, ok := standaloneComments[comment.Pos()]; ok {
+ delete(standaloneComments, comment.Pos())
+ }
+ }
+ }
+
+ if t.LineComment != nil {
+ for _, comment := range t.LineComment.List {
+ if _, ok := standaloneComments[comment.Pos()]; ok {
+ delete(standaloneComments, comment.Pos())
+ }
+ }
+ }
+ case *ast.ObjectItem:
+ if t.LeadComment != nil {
+ for _, comment := range t.LeadComment.List {
+ if _, ok := standaloneComments[comment.Pos()]; ok {
+ delete(standaloneComments, comment.Pos())
+ }
+ }
+ }
+
+ if t.LineComment != nil {
+ for _, comment := range t.LineComment.List {
+ if _, ok := standaloneComments[comment.Pos()]; ok {
+ delete(standaloneComments, comment.Pos())
+ }
+ }
+ }
+ }
+
+ return nn, true
+ })
+
+ for _, c := range standaloneComments {
+ p.standaloneComments = append(p.standaloneComments, c)
+ }
+
+ sort.Sort(ByPosition(p.standaloneComments))
+}
+
+// output prints creates b printable HCL output and returns it.
+func (p *printer) output(n interface{}) []byte {
+ var buf bytes.Buffer
+
+ switch t := n.(type) {
+ case *ast.File:
+ // File doesn't trace so we add the tracing here
+ defer un(trace(p, "File"))
+ return p.output(t.Node)
+ case *ast.ObjectList:
+ defer un(trace(p, "ObjectList"))
+
+ var index int
+ for {
+ // Determine the location of the next actual non-comment
+ // item. If we're at the end, the next item is at "infinity"
+ var nextItem token.Pos
+ if index != len(t.Items) {
+ nextItem = t.Items[index].Pos()
+ } else {
+ nextItem = token.Pos{Offset: infinity, Line: infinity}
+ }
+
+ // Go through the standalone comments in the file and print out
+ // the comments that we should be for this object item.
+ for _, c := range p.standaloneComments {
+ // Go through all the comments in the group. The group
+ // should be printed together, not separated by double newlines.
+ printed := false
+ newlinePrinted := false
+ for _, comment := range c.List {
+ // We only care about comments after the previous item
+ // we've printed so that comments are printed in the
+ // correct locations (between two objects for example).
+ // And before the next item.
+ if comment.Pos().After(p.prev) && comment.Pos().Before(nextItem) {
+ // if we hit the end add newlines so we can print the comment
+ // we don't do this if prev is invalid which means the
+ // beginning of the file since the first comment should
+ // be at the first line.
+ if !newlinePrinted && p.prev.IsValid() && index == len(t.Items) {
+ buf.Write([]byte{newline, newline})
+ newlinePrinted = true
+ }
+
+ // Write the actual comment.
+ buf.WriteString(comment.Text)
+ buf.WriteByte(newline)
+
+ // Set printed to true to note that we printed something
+ printed = true
+ }
+ }
+
+ // If we're not at the last item, write a new line so
+ // that there is a newline separating this comment from
+ // the next object.
+ if printed && index != len(t.Items) {
+ buf.WriteByte(newline)
+ }
+ }
+
+ if index == len(t.Items) {
+ break
+ }
+
+ buf.Write(p.output(t.Items[index]))
+ if index != len(t.Items)-1 {
+ // Always write a newline to separate us from the next item
+ buf.WriteByte(newline)
+
+ // Need to determine if we're going to separate the next item
+ // with a blank line. The logic here is simple, though there
+ // are a few conditions:
+ //
+ // 1. The next object is more than one line away anyways,
+ // so we need an empty line.
+ //
+ // 2. The next object is not a "single line" object, so
+ // we need an empty line.
+ //
+ // 3. This current object is not a single line object,
+ // so we need an empty line.
+ current := t.Items[index]
+ next := t.Items[index+1]
+ if next.Pos().Line != t.Items[index].Pos().Line+1 ||
+ !p.isSingleLineObject(next) ||
+ !p.isSingleLineObject(current) {
+ buf.WriteByte(newline)
+ }
+ }
+ index++
+ }
+ case *ast.ObjectKey:
+ buf.WriteString(t.Token.Text)
+ case *ast.ObjectItem:
+ p.prev = t.Pos()
+ buf.Write(p.objectItem(t))
+ case *ast.LiteralType:
+ buf.Write(p.literalType(t))
+ case *ast.ListType:
+ buf.Write(p.list(t))
+ case *ast.ObjectType:
+ buf.Write(p.objectType(t))
+ default:
+ fmt.Printf(" unknown type: %T\n", n)
+ }
+
+ return buf.Bytes()
+}
+
+func (p *printer) literalType(lit *ast.LiteralType) []byte {
+ result := []byte(lit.Token.Text)
+ switch lit.Token.Type {
+ case token.HEREDOC:
+ // Clear the trailing newline from heredocs
+ if result[len(result)-1] == '\n' {
+ result = result[:len(result)-1]
+ }
+
+ // Poison lines 2+ so that we don't indent them
+ result = p.heredocIndent(result)
+ case token.STRING:
+ // If this is a multiline string, poison lines 2+ so we don't
+ // indent them.
+ if bytes.IndexRune(result, '\n') >= 0 {
+ result = p.heredocIndent(result)
+ }
+ }
+
+ return result
+}
+
+// objectItem returns the printable HCL form of an object item. An object type
+// starts with one/multiple keys and has a value. The value might be of any
+// type.
+func (p *printer) objectItem(o *ast.ObjectItem) []byte {
+ defer un(trace(p, fmt.Sprintf("ObjectItem: %s", o.Keys[0].Token.Text)))
+ var buf bytes.Buffer
+
+ if o.LeadComment != nil {
+ for _, comment := range o.LeadComment.List {
+ buf.WriteString(comment.Text)
+ buf.WriteByte(newline)
+ }
+ }
+
+ for i, k := range o.Keys {
+ buf.WriteString(k.Token.Text)
+ buf.WriteByte(blank)
+
+ // reach end of key
+ if o.Assign.IsValid() && i == len(o.Keys)-1 && len(o.Keys) == 1 {
+ buf.WriteString("=")
+ buf.WriteByte(blank)
+ }
+ }
+
+ buf.Write(p.output(o.Val))
+
+ if o.Val.Pos().Line == o.Keys[0].Pos().Line && o.LineComment != nil {
+ buf.WriteByte(blank)
+ for _, comment := range o.LineComment.List {
+ buf.WriteString(comment.Text)
+ }
+ }
+
+ return buf.Bytes()
+}
+
+// objectType returns the printable HCL form of an object type. An object type
+// begins with a brace and ends with a brace.
+func (p *printer) objectType(o *ast.ObjectType) []byte {
+ defer un(trace(p, "ObjectType"))
+ var buf bytes.Buffer
+ buf.WriteString("{")
+
+ var index int
+ var nextItem token.Pos
+ var commented, newlinePrinted bool
+ for {
+ // Determine the location of the next actual non-comment
+ // item. If we're at the end, the next item is the closing brace
+ if index != len(o.List.Items) {
+ nextItem = o.List.Items[index].Pos()
+ } else {
+ nextItem = o.Rbrace
+ }
+
+ // Go through the standalone comments in the file and print out
+ // the comments that we should be for this object item.
+ for _, c := range p.standaloneComments {
+ printed := false
+ var lastCommentPos token.Pos
+ for _, comment := range c.List {
+ // We only care about comments after the previous item
+ // we've printed so that comments are printed in the
+ // correct locations (between two objects for example).
+ // And before the next item.
+ if comment.Pos().After(p.prev) && comment.Pos().Before(nextItem) {
+ // If there are standalone comments and the initial newline has not
+ // been printed yet, do it now.
+ if !newlinePrinted {
+ newlinePrinted = true
+ buf.WriteByte(newline)
+ }
+
+ // add newline if it's between other printed nodes
+ if index > 0 {
+ commented = true
+ buf.WriteByte(newline)
+ }
+
+ // Store this position
+ lastCommentPos = comment.Pos()
+
+ // output the comment itself
+ buf.Write(p.indent(p.heredocIndent([]byte(comment.Text))))
+
+ // Set printed to true to note that we printed something
+ printed = true
+
+ /*
+ if index != len(o.List.Items) {
+ buf.WriteByte(newline) // do not print on the end
+ }
+ */
+ }
+ }
+
+ // Stuff to do if we had comments
+ if printed {
+ // Always write a newline
+ buf.WriteByte(newline)
+
+ // If there is another item in the object and our comment
+ // didn't hug it directly, then make sure there is a blank
+ // line separating them.
+ if nextItem != o.Rbrace && nextItem.Line != lastCommentPos.Line+1 {
+ buf.WriteByte(newline)
+ }
+ }
+ }
+
+ if index == len(o.List.Items) {
+ p.prev = o.Rbrace
+ break
+ }
+
+ // At this point we are sure that it's not a totally empty block: print
+ // the initial newline if it hasn't been printed yet by the previous
+ // block about standalone comments.
+ if !newlinePrinted {
+ buf.WriteByte(newline)
+ newlinePrinted = true
+ }
+
+ // check if we have adjacent one liner items. If yes we'll going to align
+ // the comments.
+ var aligned []*ast.ObjectItem
+ for _, item := range o.List.Items[index:] {
+ // we don't group one line lists
+ if len(o.List.Items) == 1 {
+ break
+ }
+
+ // one means a oneliner with out any lead comment
+ // two means a oneliner with lead comment
+ // anything else might be something else
+ cur := lines(string(p.objectItem(item)))
+ if cur > 2 {
+ break
+ }
+
+ curPos := item.Pos()
+
+ nextPos := token.Pos{}
+ if index != len(o.List.Items)-1 {
+ nextPos = o.List.Items[index+1].Pos()
+ }
+
+ prevPos := token.Pos{}
+ if index != 0 {
+ prevPos = o.List.Items[index-1].Pos()
+ }
+
+ // fmt.Println("DEBUG ----------------")
+ // fmt.Printf("prev = %+v prevPos: %s\n", prev, prevPos)
+ // fmt.Printf("cur = %+v curPos: %s\n", cur, curPos)
+ // fmt.Printf("next = %+v nextPos: %s\n", next, nextPos)
+
+ if curPos.Line+1 == nextPos.Line {
+ aligned = append(aligned, item)
+ index++
+ continue
+ }
+
+ if curPos.Line-1 == prevPos.Line {
+ aligned = append(aligned, item)
+ index++
+
+ // finish if we have a new line or comment next. This happens
+ // if the next item is not adjacent
+ if curPos.Line+1 != nextPos.Line {
+ break
+ }
+ continue
+ }
+
+ break
+ }
+
+ // put newlines if the items are between other non aligned items.
+ // newlines are also added if there is a standalone comment already, so
+ // check it too
+ if !commented && index != len(aligned) {
+ buf.WriteByte(newline)
+ }
+
+ if len(aligned) >= 1 {
+ p.prev = aligned[len(aligned)-1].Pos()
+
+ items := p.alignedItems(aligned)
+ buf.Write(p.indent(items))
+ } else {
+ p.prev = o.List.Items[index].Pos()
+
+ buf.Write(p.indent(p.objectItem(o.List.Items[index])))
+ index++
+ }
+
+ buf.WriteByte(newline)
+ }
+
+ buf.WriteString("}")
+ return buf.Bytes()
+}
+
+func (p *printer) alignedItems(items []*ast.ObjectItem) []byte {
+ var buf bytes.Buffer
+
+ // find the longest key and value length, needed for alignment
+ var longestKeyLen int // longest key length
+ var longestValLen int // longest value length
+ for _, item := range items {
+ key := len(item.Keys[0].Token.Text)
+ val := len(p.output(item.Val))
+
+ if key > longestKeyLen {
+ longestKeyLen = key
+ }
+
+ if val > longestValLen {
+ longestValLen = val
+ }
+ }
+
+ for i, item := range items {
+ if item.LeadComment != nil {
+ for _, comment := range item.LeadComment.List {
+ buf.WriteString(comment.Text)
+ buf.WriteByte(newline)
+ }
+ }
+
+ for i, k := range item.Keys {
+ keyLen := len(k.Token.Text)
+ buf.WriteString(k.Token.Text)
+ for i := 0; i < longestKeyLen-keyLen+1; i++ {
+ buf.WriteByte(blank)
+ }
+
+ // reach end of key
+ if i == len(item.Keys)-1 && len(item.Keys) == 1 {
+ buf.WriteString("=")
+ buf.WriteByte(blank)
+ }
+ }
+
+ val := p.output(item.Val)
+ valLen := len(val)
+ buf.Write(val)
+
+ if item.Val.Pos().Line == item.Keys[0].Pos().Line && item.LineComment != nil {
+ for i := 0; i < longestValLen-valLen+1; i++ {
+ buf.WriteByte(blank)
+ }
+
+ for _, comment := range item.LineComment.List {
+ buf.WriteString(comment.Text)
+ }
+ }
+
+ // do not print for the last item
+ if i != len(items)-1 {
+ buf.WriteByte(newline)
+ }
+ }
+
+ return buf.Bytes()
+}
+
+// list returns the printable HCL form of an list type.
+func (p *printer) list(l *ast.ListType) []byte {
+ var buf bytes.Buffer
+ buf.WriteString("[")
+
+ var longestLine int
+ for _, item := range l.List {
+ // for now we assume that the list only contains literal types
+ if lit, ok := item.(*ast.LiteralType); ok {
+ lineLen := len(lit.Token.Text)
+ if lineLen > longestLine {
+ longestLine = lineLen
+ }
+ }
+ }
+
+ insertSpaceBeforeItem := false
+ lastHadLeadComment := false
+ for i, item := range l.List {
+ // Keep track of whether this item is a heredoc since that has
+ // unique behavior.
+ heredoc := false
+ if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC {
+ heredoc = true
+ }
+
+ if item.Pos().Line != l.Lbrack.Line {
+ // multiline list, add newline before we add each item
+ buf.WriteByte(newline)
+ insertSpaceBeforeItem = false
+
+ // If we have a lead comment, then we want to write that first
+ leadComment := false
+ if lit, ok := item.(*ast.LiteralType); ok && lit.LeadComment != nil {
+ leadComment = true
+
+ // If this isn't the first item and the previous element
+ // didn't have a lead comment, then we need to add an extra
+ // newline to properly space things out. If it did have a
+ // lead comment previously then this would be done
+ // automatically.
+ if i > 0 && !lastHadLeadComment {
+ buf.WriteByte(newline)
+ }
+
+ for _, comment := range lit.LeadComment.List {
+ buf.Write(p.indent([]byte(comment.Text)))
+ buf.WriteByte(newline)
+ }
+ }
+
+ // also indent each line
+ val := p.output(item)
+ curLen := len(val)
+ buf.Write(p.indent(val))
+
+ // if this item is a heredoc, then we output the comma on
+ // the next line. This is the only case this happens.
+ comma := []byte{','}
+ if heredoc {
+ buf.WriteByte(newline)
+ comma = p.indent(comma)
+ }
+
+ buf.Write(comma)
+
+ if lit, ok := item.(*ast.LiteralType); ok && lit.LineComment != nil {
+ // if the next item doesn't have any comments, do not align
+ buf.WriteByte(blank) // align one space
+ for i := 0; i < longestLine-curLen; i++ {
+ buf.WriteByte(blank)
+ }
+
+ for _, comment := range lit.LineComment.List {
+ buf.WriteString(comment.Text)
+ }
+ }
+
+ lastItem := i == len(l.List)-1
+ if lastItem {
+ buf.WriteByte(newline)
+ }
+
+ if leadComment && !lastItem {
+ buf.WriteByte(newline)
+ }
+
+ lastHadLeadComment = leadComment
+ } else {
+ if insertSpaceBeforeItem {
+ buf.WriteByte(blank)
+ insertSpaceBeforeItem = false
+ }
+
+ // Output the item itself
+ // also indent each line
+ val := p.output(item)
+ curLen := len(val)
+ buf.Write(val)
+
+ // If this is a heredoc item we always have to output a newline
+ // so that it parses properly.
+ if heredoc {
+ buf.WriteByte(newline)
+ }
+
+ // If this isn't the last element, write a comma.
+ if i != len(l.List)-1 {
+ buf.WriteString(",")
+ insertSpaceBeforeItem = true
+ }
+
+ if lit, ok := item.(*ast.LiteralType); ok && lit.LineComment != nil {
+ // if the next item doesn't have any comments, do not align
+ buf.WriteByte(blank) // align one space
+ for i := 0; i < longestLine-curLen; i++ {
+ buf.WriteByte(blank)
+ }
+
+ for _, comment := range lit.LineComment.List {
+ buf.WriteString(comment.Text)
+ }
+ }
+ }
+
+ }
+
+ buf.WriteString("]")
+ return buf.Bytes()
+}
+
+// indent indents the lines of the given buffer for each non-empty line
+func (p *printer) indent(buf []byte) []byte {
+ var prefix []byte
+ if p.cfg.SpacesWidth != 0 {
+ for i := 0; i < p.cfg.SpacesWidth; i++ {
+ prefix = append(prefix, blank)
+ }
+ } else {
+ prefix = []byte{tab}
+ }
+
+ var res []byte
+ bol := true
+ for _, c := range buf {
+ if bol && c != '\n' {
+ res = append(res, prefix...)
+ }
+
+ res = append(res, c)
+ bol = c == '\n'
+ }
+ return res
+}
+
+// unindent removes all the indentation from the tombstoned lines
+func (p *printer) unindent(buf []byte) []byte {
+ var res []byte
+ for i := 0; i < len(buf); i++ {
+ skip := len(buf)-i <= len(unindent)
+ if !skip {
+ skip = !bytes.Equal(unindent, buf[i:i+len(unindent)])
+ }
+ if skip {
+ res = append(res, buf[i])
+ continue
+ }
+
+ // We have a marker. we have to backtrace here and clean out
+ // any whitespace ahead of our tombstone up to a \n
+ for j := len(res) - 1; j >= 0; j-- {
+ if res[j] == '\n' {
+ break
+ }
+
+ res = res[:j]
+ }
+
+ // Skip the entire unindent marker
+ i += len(unindent) - 1
+ }
+
+ return res
+}
+
+// heredocIndent marks all the 2nd and further lines as unindentable
+func (p *printer) heredocIndent(buf []byte) []byte {
+ var res []byte
+ bol := false
+ for _, c := range buf {
+ if bol && c != '\n' {
+ res = append(res, unindent...)
+ }
+ res = append(res, c)
+ bol = c == '\n'
+ }
+ return res
+}
+
+// isSingleLineObject tells whether the given object item is a single
+// line object such as "obj {}".
+//
+// A single line object:
+//
+// * has no lead comments (hence multi-line)
+// * has no assignment
+// * has no values in the stanza (within {})
+//
+func (p *printer) isSingleLineObject(val *ast.ObjectItem) bool {
+ // If there is a lead comment, can't be one line
+ if val.LeadComment != nil {
+ return false
+ }
+
+ // If there is assignment, we always break by line
+ if val.Assign.IsValid() {
+ return false
+ }
+
+ // If it isn't an object type, then its not a single line object
+ ot, ok := val.Val.(*ast.ObjectType)
+ if !ok {
+ return false
+ }
+
+ // If the object has no items, it is single line!
+ return len(ot.List.Items) == 0
+}
+
+func lines(txt string) int {
+ endline := 1
+ for i := 0; i < len(txt); i++ {
+ if txt[i] == '\n' {
+ endline++
+ }
+ }
+ return endline
+}
+
+// ----------------------------------------------------------------------------
+// Tracing support
+
+func (p *printer) printTrace(a ...interface{}) {
+ if !p.enableTrace {
+ return
+ }
+
+ const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+ const n = len(dots)
+ i := 2 * p.indentTrace
+ for i > n {
+ fmt.Print(dots)
+ i -= n
+ }
+ // i <= n
+ fmt.Print(dots[0:i])
+ fmt.Println(a...)
+}
+
+func trace(p *printer, msg string) *printer {
+ p.printTrace(msg, "(")
+ p.indentTrace++
+ return p
+}
+
+// Usage pattern: defer un(trace(p, "..."))
+func un(p *printer) {
+ p.indentTrace--
+ p.printTrace(")")
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/printer.go b/vendor/github.com/hashicorp/hcl/hcl/printer/printer.go
new file mode 100644
index 000000000..a296fc851
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/printer.go
@@ -0,0 +1,67 @@
+// Package printer implements printing of AST nodes to HCL format.
+package printer
+
+import (
+ "bytes"
+ "io"
+ "text/tabwriter"
+
+ "github.com/hashicorp/hcl/hcl/ast"
+ "github.com/hashicorp/hcl/hcl/parser"
+)
+
+var DefaultConfig = Config{
+ SpacesWidth: 2,
+}
+
+// A Config node controls the output of Fprint.
+type Config struct {
+ SpacesWidth int // if set, it will use spaces instead of tabs for alignment
+}
+
+func (c *Config) Fprint(output io.Writer, node ast.Node) error {
+ p := &printer{
+ cfg: *c,
+ comments: make([]*ast.CommentGroup, 0),
+ standaloneComments: make([]*ast.CommentGroup, 0),
+ // enableTrace: true,
+ }
+
+ p.collectComments(node)
+
+ if _, err := output.Write(p.unindent(p.output(node))); err != nil {
+ return err
+ }
+
+ // flush tabwriter, if any
+ var err error
+ if tw, _ := output.(*tabwriter.Writer); tw != nil {
+ err = tw.Flush()
+ }
+
+ return err
+}
+
+// Fprint "pretty-prints" an HCL node to output
+// It calls Config.Fprint with default settings.
+func Fprint(output io.Writer, node ast.Node) error {
+ return DefaultConfig.Fprint(output, node)
+}
+
+// Format formats src HCL and returns the result.
+func Format(src []byte) ([]byte, error) {
+ node, err := parser.Parse(src)
+ if err != nil {
+ return nil, err
+ }
+
+ var buf bytes.Buffer
+ if err := DefaultConfig.Fprint(&buf, node); err != nil {
+ return nil, err
+ }
+
+ // Add trailing newline to result
+ buf.WriteString("\n")
+
+ return buf.Bytes(), nil
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/printer_test.go b/vendor/github.com/hashicorp/hcl/hcl/printer/printer_test.go
new file mode 100644
index 000000000..01ea3b2de
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/printer_test.go
@@ -0,0 +1,153 @@
+// +build !windows
+// TODO(jen20): These need fixing on Windows but printer is not used right now
+// and red CI is making it harder to process other bugs, so ignore until
+// we get around to fixing them.package printer
+
+package printer
+
+import (
+ "bytes"
+ "errors"
+ "flag"
+ "fmt"
+ "io/ioutil"
+ "path/filepath"
+ "testing"
+
+ "github.com/hashicorp/hcl/hcl/parser"
+)
+
+var update = flag.Bool("update", false, "update golden files")
+
+const (
+ dataDir = "testdata"
+)
+
+type entry struct {
+ source, golden string
+}
+
+// Use go test -update to create/update the respective golden files.
+var data = []entry{
+ {"complexhcl.input", "complexhcl.golden"},
+ {"list.input", "list.golden"},
+ {"list_comment.input", "list_comment.golden"},
+ {"comment.input", "comment.golden"},
+ {"comment_aligned.input", "comment_aligned.golden"},
+ {"comment_array.input", "comment_array.golden"},
+ {"comment_end_file.input", "comment_end_file.golden"},
+ {"comment_multiline_indent.input", "comment_multiline_indent.golden"},
+ {"comment_multiline_no_stanza.input", "comment_multiline_no_stanza.golden"},
+ {"comment_multiline_stanza.input", "comment_multiline_stanza.golden"},
+ {"comment_newline.input", "comment_newline.golden"},
+ {"comment_object_multi.input", "comment_object_multi.golden"},
+ {"comment_standalone.input", "comment_standalone.golden"},
+ {"empty_block.input", "empty_block.golden"},
+ {"list_of_objects.input", "list_of_objects.golden"},
+ {"multiline_string.input", "multiline_string.golden"},
+ {"object_singleline.input", "object_singleline.golden"},
+ {"object_with_heredoc.input", "object_with_heredoc.golden"},
+}
+
+func TestFiles(t *testing.T) {
+ for _, e := range data {
+ source := filepath.Join(dataDir, e.source)
+ golden := filepath.Join(dataDir, e.golden)
+ t.Run(e.source, func(t *testing.T) {
+ check(t, source, golden)
+ })
+ }
+}
+
+func check(t *testing.T, source, golden string) {
+ src, err := ioutil.ReadFile(source)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+
+ res, err := format(src)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+
+ // update golden files if necessary
+ if *update {
+ if err := ioutil.WriteFile(golden, res, 0644); err != nil {
+ t.Error(err)
+ }
+ return
+ }
+
+ // get golden
+ gld, err := ioutil.ReadFile(golden)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+
+ // formatted source and golden must be the same
+ if err := diff(source, golden, res, gld); err != nil {
+ t.Error(err)
+ return
+ }
+}
+
+// diff compares a and b.
+func diff(aname, bname string, a, b []byte) error {
+ var buf bytes.Buffer // holding long error message
+
+ // compare lengths
+ if len(a) != len(b) {
+ fmt.Fprintf(&buf, "\nlength changed: len(%s) = %d, len(%s) = %d", aname, len(a), bname, len(b))
+ }
+
+ // compare contents
+ line := 1
+ offs := 1
+ for i := 0; i < len(a) && i < len(b); i++ {
+ ch := a[i]
+ if ch != b[i] {
+ fmt.Fprintf(&buf, "\n%s:%d:%d: %s", aname, line, i-offs+1, lineAt(a, offs))
+ fmt.Fprintf(&buf, "\n%s:%d:%d: %s", bname, line, i-offs+1, lineAt(b, offs))
+ fmt.Fprintf(&buf, "\n\n")
+ break
+ }
+ if ch == '\n' {
+ line++
+ offs = i + 1
+ }
+ }
+
+ if buf.Len() > 0 {
+ return errors.New(buf.String())
+ }
+ return nil
+}
+
+// format parses src, prints the corresponding AST, verifies the resulting
+// src is syntactically correct, and returns the resulting src or an error
+// if any.
+func format(src []byte) ([]byte, error) {
+ formatted, err := Format(src)
+ if err != nil {
+ return nil, err
+ }
+
+ // make sure formatted output is syntactically correct
+ if _, err := parser.Parse(formatted); err != nil {
+ return nil, fmt.Errorf("parse: %s\n%s", err, formatted)
+ }
+
+ return formatted, nil
+}
+
+// lineAt returns the line in text starting at offset offs.
+func lineAt(text []byte, offs int) []byte {
+ i := offs
+ for i < len(text) && text[i] != '\n' {
+ i++
+ }
+ return text[offs:i]
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment.golden
new file mode 100644
index 000000000..9d4b072a0
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment.golden
@@ -0,0 +1,36 @@
+// A standalone comment is a comment which is not attached to any kind of node
+
+// This comes from Terraform, as a test
+variable "foo" {
+ # Standalone comment should be still here
+
+ default = "bar"
+ description = "bar" # yooo
+}
+
+/* This is a multi line standalone
+comment*/
+
+// fatih arslan
+/* This is a developer test
+account and a multine comment */
+developer = ["fatih", "arslan"] // fatih arslan
+
+# One line here
+numbers = [1, 2] // another line here
+
+# Another comment
+variable = {
+ description = "bar" # another yooo
+
+ foo {
+ # Nested standalone
+
+ bar = "fatih"
+ }
+}
+
+// lead comment
+foo {
+ bar = "fatih" // line comment 2
+} // line comment 3
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment.input
new file mode 100644
index 000000000..57c37ac1d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment.input
@@ -0,0 +1,37 @@
+// A standalone comment is a comment which is not attached to any kind of node
+
+ // This comes from Terraform, as a test
+variable "foo" {
+ # Standalone comment should be still here
+
+ default = "bar"
+ description = "bar" # yooo
+}
+
+/* This is a multi line standalone
+comment*/
+
+
+// fatih arslan
+/* This is a developer test
+account and a multine comment */
+developer = [ "fatih", "arslan"] // fatih arslan
+
+# One line here
+numbers = [1,2] // another line here
+
+ # Another comment
+variable = {
+ description = "bar" # another yooo
+ foo {
+ # Nested standalone
+
+ bar = "fatih"
+ }
+}
+
+ // lead comment
+foo {
+ bar = "fatih" // line comment 2
+} // line comment 3
+
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_aligned.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_aligned.golden
new file mode 100644
index 000000000..6ff21504c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_aligned.golden
@@ -0,0 +1,32 @@
+aligned {
+ # We have some aligned items below
+ foo = "fatih" # yoo1
+ default = "bar" # yoo2
+ bar = "bar and foo" # yoo3
+
+ default = {
+ bar = "example"
+ }
+
+ #deneme arslan
+ fatih = ["fatih"] # yoo4
+
+ #fatih arslan
+ fatiharslan = ["arslan"] // yoo5
+
+ default = {
+ bar = "example"
+ }
+
+ security_groups = [
+ "foo", # kenya 1
+ "${aws_security_group.firewall.foo}", # kenya 2
+ ]
+
+ security_groups2 = [
+ "foo", # kenya 1
+ "bar", # kenya 1.5
+ "${aws_security_group.firewall.foo}", # kenya 2
+ "foobar", # kenya 3
+ ]
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_aligned.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_aligned.input
new file mode 100644
index 000000000..bd43ab1ad
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_aligned.input
@@ -0,0 +1,28 @@
+aligned {
+# We have some aligned items below
+ foo = "fatih" # yoo1
+ default = "bar" # yoo2
+ bar = "bar and foo" # yoo3
+ default = {
+ bar = "example"
+ }
+ #deneme arslan
+ fatih = ["fatih"] # yoo4
+ #fatih arslan
+ fatiharslan = ["arslan"] // yoo5
+ default = {
+ bar = "example"
+ }
+
+security_groups = [
+ "foo", # kenya 1
+ "${aws_security_group.firewall.foo}", # kenya 2
+]
+
+security_groups2 = [
+ "foo", # kenya 1
+ "bar", # kenya 1.5
+ "${aws_security_group.firewall.foo}", # kenya 2
+ "foobar", # kenya 3
+]
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_array.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_array.golden
new file mode 100644
index 000000000..e778eafa3
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_array.golden
@@ -0,0 +1,13 @@
+banana = [
+ # I really want to comment this item in the array.
+ "a",
+
+ # This as well
+ "b",
+
+ "c", # And C
+ "d",
+
+ # And another
+ "e",
+]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_array.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_array.input
new file mode 100644
index 000000000..e778eafa3
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_array.input
@@ -0,0 +1,13 @@
+banana = [
+ # I really want to comment this item in the array.
+ "a",
+
+ # This as well
+ "b",
+
+ "c", # And C
+ "d",
+
+ # And another
+ "e",
+]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_end_file.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_end_file.golden
new file mode 100644
index 000000000..dbeae36a8
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_end_file.golden
@@ -0,0 +1,6 @@
+resource "blah" "blah" {}
+
+//
+//
+//
+
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_end_file.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_end_file.input
new file mode 100644
index 000000000..68c4c282e
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_end_file.input
@@ -0,0 +1,5 @@
+resource "blah" "blah" {}
+
+//
+//
+//
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_indent.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_indent.golden
new file mode 100644
index 000000000..74c4ccd89
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_indent.golden
@@ -0,0 +1,12 @@
+resource "provider" "resource" {
+ /*
+ SPACE_SENSITIVE_CODE = <<EOF
+yaml code:
+ foo: ""
+ bar: ""
+EOF
+ */
+ /*
+ OTHER
+ */
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_indent.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_indent.input
new file mode 100644
index 000000000..b07ac4d3c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_indent.input
@@ -0,0 +1,13 @@
+resource "provider" "resource" {
+ /*
+ SPACE_SENSITIVE_CODE = <<EOF
+yaml code:
+ foo: ""
+ bar: ""
+EOF
+ */
+
+ /*
+ OTHER
+ */
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_no_stanza.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_no_stanza.golden
new file mode 100644
index 000000000..7ad7ca296
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_no_stanza.golden
@@ -0,0 +1,7 @@
+# This is a multiline comment
+# That has values like this:
+#
+# ami-abcd1234
+#
+# Do not delete this comment
+
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_no_stanza.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_no_stanza.input
new file mode 100644
index 000000000..8b818e91d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_no_stanza.input
@@ -0,0 +1,6 @@
+# This is a multiline comment
+# That has values like this:
+#
+# ami-abcd1234
+#
+# Do not delete this comment
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_stanza.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_stanza.golden
new file mode 100644
index 000000000..e9db4f2ae
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_stanza.golden
@@ -0,0 +1,10 @@
+# This is a multiline comment
+# That has values like this:
+#
+# ami-abcd1234
+#
+# Do not delete this comment
+
+resource "aws_instance" "web" {
+ ami_id = "ami-abcd1234"
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_stanza.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_stanza.input
new file mode 100644
index 000000000..6a8b90230
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_multiline_stanza.input
@@ -0,0 +1,10 @@
+# This is a multiline comment
+# That has values like this:
+#
+# ami-abcd1234
+#
+# Do not delete this comment
+
+resource "aws_instance" "web" {
+ami_id = "ami-abcd1234"
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_newline.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_newline.golden
new file mode 100644
index 000000000..2162c8845
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_newline.golden
@@ -0,0 +1,3 @@
+# Hello
+# World
+
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_newline.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_newline.input
new file mode 100644
index 000000000..aa56a9880
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_newline.input
@@ -0,0 +1,2 @@
+# Hello
+# World
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_object_multi.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_object_multi.golden
new file mode 100644
index 000000000..4c0f0004a
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_object_multi.golden
@@ -0,0 +1,9 @@
+variable "environment" {
+ default = {}
+
+ # default {
+ # "region" = "us-west-2"
+ # "sg" = "playground"
+ # "env" = "prod"
+ # }
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_object_multi.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_object_multi.input
new file mode 100644
index 000000000..4c0f0004a
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_object_multi.input
@@ -0,0 +1,9 @@
+variable "environment" {
+ default = {}
+
+ # default {
+ # "region" = "us-west-2"
+ # "sg" = "playground"
+ # "env" = "prod"
+ # }
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_standalone.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_standalone.golden
new file mode 100644
index 000000000..3236d9e69
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_standalone.golden
@@ -0,0 +1,17 @@
+// A standalone comment
+
+aligned {
+ # Standalone 1
+
+ a = "bar" # yoo1
+ default = "bar" # yoo2
+
+ # Standalone 2
+}
+
+# Standalone 3
+
+numbers = [1, 2] // another line here
+
+# Standalone 4
+
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_standalone.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_standalone.input
new file mode 100644
index 000000000..4436cb16c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/comment_standalone.input
@@ -0,0 +1,16 @@
+// A standalone comment
+
+aligned {
+ # Standalone 1
+
+ a = "bar" # yoo1
+ default = "bar" # yoo2
+
+ # Standalone 2
+}
+
+ # Standalone 3
+
+numbers = [1,2] // another line here
+
+ # Standalone 4
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/complexhcl.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/complexhcl.golden
new file mode 100644
index 000000000..198c32d28
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/complexhcl.golden
@@ -0,0 +1,54 @@
+variable "foo" {
+ default = "bar"
+ description = "bar"
+}
+
+developer = ["fatih", "arslan"]
+
+provider "aws" {
+ access_key = "foo"
+ secret_key = "bar"
+}
+
+provider "do" {
+ api_key = "${var.foo}"
+}
+
+resource "aws_security_group" "firewall" {
+ count = 5
+}
+
+resource aws_instance "web" {
+ ami = "${var.foo}"
+
+ security_groups = [
+ "foo",
+ "${aws_security_group.firewall.foo}",
+ ]
+
+ network_interface {
+ device_index = 0
+ description = "Main network interface"
+ }
+
+ network_interface = {
+ device_index = 1
+
+ description = <<EOF
+ANOTHER NETWORK INTERFACE
+EOF
+ }
+}
+
+resource "aws_instance" "db" {
+ security_groups = "${aws_security_group.firewall.*.id}"
+ VPC = "foo"
+
+ depends_on = ["aws_instance.web"]
+}
+
+output "web_ip" {
+ value = <<EOF
+TUBES
+EOF
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/complexhcl.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/complexhcl.input
new file mode 100644
index 000000000..712341840
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/complexhcl.input
@@ -0,0 +1,53 @@
+variable "foo" {
+ default = "bar"
+ description = "bar"
+}
+
+developer = [ "fatih", "arslan"]
+
+provider "aws" {
+ access_key ="foo"
+ secret_key = "bar"
+}
+
+ provider "do" {
+ api_key = "${var.foo}"
+}
+
+resource "aws_security_group" "firewall" {
+ count = 5
+ }
+
+ resource aws_instance "web" {
+ ami = "${var.foo}"
+ security_groups = [
+ "foo",
+ "${aws_security_group.firewall.foo}"
+ ]
+
+ network_interface {
+ device_index = 0
+ description = "Main network interface"
+ }
+
+ network_interface = {
+ device_index = 1
+ description = <<EOF
+ANOTHER NETWORK INTERFACE
+EOF
+ }
+ }
+
+resource "aws_instance" "db" {
+ security_groups = "${aws_security_group.firewall.*.id}"
+ VPC = "foo"
+
+ depends_on = ["aws_instance.web"]
+}
+
+output "web_ip" {
+
+ value=<<EOF
+TUBES
+EOF
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/empty_block.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/empty_block.golden
new file mode 100644
index 000000000..4ff1cb3e4
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/empty_block.golden
@@ -0,0 +1,12 @@
+variable "foo" {}
+variable "foo" {}
+
+variable "foo" {
+ # Standalone comment should be still here
+}
+
+foo {}
+
+foo {
+ bar = "mssola"
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/empty_block.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/empty_block.input
new file mode 100644
index 000000000..627bf3e3f
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/empty_block.input
@@ -0,0 +1,14 @@
+variable "foo" {}
+variable "foo" {
+}
+
+variable "foo" {
+ # Standalone comment should be still here
+}
+
+foo {
+}
+
+foo {
+ bar = "mssola"
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list.golden
new file mode 100644
index 000000000..14c37ac0f
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list.golden
@@ -0,0 +1,43 @@
+foo = ["fatih", "arslan"]
+
+foo = ["bar", "qaz"]
+
+foo = ["zeynep",
+ "arslan",
+]
+
+foo = ["fatih", "zeynep",
+ "arslan",
+]
+
+foo = [
+ "vim-go",
+ "golang",
+ "hcl",
+]
+
+foo = []
+
+foo = [1, 2, 3, 4]
+
+foo = [
+ "kenya",
+ "ethiopia",
+ "columbia",
+]
+
+foo = [
+ <<EOS
+one
+EOS
+ ,
+ <<EOS
+two
+EOS
+ ,
+]
+
+foo = [<<EOS
+one
+EOS
+]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list.input
new file mode 100644
index 000000000..f55a38200
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list.input
@@ -0,0 +1,37 @@
+foo = ["fatih", "arslan" ]
+
+foo = [ "bar", "qaz", ]
+
+foo = [ "zeynep",
+"arslan", ]
+
+foo = ["fatih", "zeynep",
+"arslan", ]
+
+foo = [
+ "vim-go",
+ "golang", "hcl"]
+
+foo = []
+
+foo = [1, 2,3, 4]
+
+foo = [
+ "kenya", "ethiopia",
+ "columbia"]
+
+foo = [
+ <<EOS
+one
+EOS
+,
+ <<EOS
+two
+EOS
+,
+ ]
+
+foo = [<<EOS
+one
+EOS
+ ]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_comment.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_comment.golden
new file mode 100644
index 000000000..e5753c91a
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_comment.golden
@@ -0,0 +1,7 @@
+foo = [1, # Hello
+ 2,
+]
+
+foo = [1, # Hello
+ 2, # World
+]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_comment.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_comment.input
new file mode 100644
index 000000000..1d636c88d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_comment.input
@@ -0,0 +1,6 @@
+foo = [1, # Hello
+2]
+
+foo = [1, # Hello
+2, # World
+]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_of_objects.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_of_objects.golden
new file mode 100644
index 000000000..401ded6ef
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_of_objects.golden
@@ -0,0 +1,10 @@
+list_of_objects = [
+ {
+ key1 = "value1"
+ key2 = "value2"
+ },
+ {
+ key3 = "value3"
+ key4 = "value4"
+ },
+]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_of_objects.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_of_objects.input
new file mode 100644
index 000000000..f2adcf015
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/list_of_objects.input
@@ -0,0 +1,10 @@
+list_of_objects = [
+ {
+ key1 = "value1"
+ key2 = "value2"
+ },
+ {
+ key3 = "value3"
+ key4 = "value4"
+ }
+] \ No newline at end of file
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/multiline_string.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/multiline_string.golden
new file mode 100644
index 000000000..3d10c741d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/multiline_string.golden
@@ -0,0 +1,7 @@
+resource "null_resource" "some_command" {
+ provisioner "local-exec" {
+ command = "${echo '
+some newlines
+and additonal output'}"
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/multiline_string.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/multiline_string.input
new file mode 100644
index 000000000..3d10c741d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/multiline_string.input
@@ -0,0 +1,7 @@
+resource "null_resource" "some_command" {
+ provisioner "local-exec" {
+ command = "${echo '
+some newlines
+and additonal output'}"
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_singleline.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_singleline.golden
new file mode 100644
index 000000000..c3d914702
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_singleline.golden
@@ -0,0 +1,26 @@
+variable "foo" {}
+variable "bar" {}
+variable "baz" {}
+
+variable "qux" {}
+
+variable "foo" {
+ foo = "bar"
+}
+
+variable "foo" {}
+
+# lead comment
+variable "bar" {}
+
+variable "foo" {
+ default = "bar"
+}
+
+variable "bar" {}
+
+# Purposeful newline check below:
+
+variable "foo" {}
+
+variable "purposeful-newline" {}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_singleline.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_singleline.input
new file mode 100644
index 000000000..7b34834a4
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_singleline.input
@@ -0,0 +1,19 @@
+variable "foo" {}
+variable "bar" {}
+variable "baz" {}
+
+variable "qux" {}
+variable "foo" { foo = "bar" }
+
+variable "foo" {}
+# lead comment
+variable "bar" {}
+
+variable "foo" { default = "bar" }
+variable "bar" {}
+
+# Purposeful newline check below:
+
+variable "foo" {}
+
+variable "purposeful-newline" {}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_with_heredoc.golden b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_with_heredoc.golden
new file mode 100644
index 000000000..7e92243f6
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_with_heredoc.golden
@@ -0,0 +1,6 @@
+obj {
+ foo = [<<EOF
+ TEXT!
+EOF
+ ]
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_with_heredoc.input b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_with_heredoc.input
new file mode 100644
index 000000000..d70a05ac9
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/printer/testdata/object_with_heredoc.input
@@ -0,0 +1,6 @@
+obj {
+ foo = [<<EOF
+ TEXT!
+EOF
+ ]
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go
new file mode 100644
index 000000000..69662367f
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go
@@ -0,0 +1,651 @@
+// Package scanner implements a scanner for HCL (HashiCorp Configuration
+// Language) source text.
+package scanner
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "regexp"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/hashicorp/hcl/hcl/token"
+)
+
+// eof represents a marker rune for the end of the reader.
+const eof = rune(0)
+
+// Scanner defines a lexical scanner
+type Scanner struct {
+ buf *bytes.Buffer // Source buffer for advancing and scanning
+ src []byte // Source buffer for immutable access
+
+ // Source Position
+ srcPos token.Pos // current position
+ prevPos token.Pos // previous position, used for peek() method
+
+ lastCharLen int // length of last character in bytes
+ lastLineLen int // length of last line in characters (for correct column reporting)
+
+ tokStart int // token text start position
+ tokEnd int // token text end position
+
+ // Error is called for each error encountered. If no Error
+ // function is set, the error is reported to os.Stderr.
+ Error func(pos token.Pos, msg string)
+
+ // ErrorCount is incremented by one for each error encountered.
+ ErrorCount int
+
+ // tokPos is the start position of most recently scanned token; set by
+ // Scan. The Filename field is always left untouched by the Scanner. If
+ // an error is reported (via Error) and Position is invalid, the scanner is
+ // not inside a token.
+ tokPos token.Pos
+}
+
+// New creates and initializes a new instance of Scanner using src as
+// its source content.
+func New(src []byte) *Scanner {
+ // even though we accept a src, we read from a io.Reader compatible type
+ // (*bytes.Buffer). So in the future we might easily change it to streaming
+ // read.
+ b := bytes.NewBuffer(src)
+ s := &Scanner{
+ buf: b,
+ src: src,
+ }
+
+ // srcPosition always starts with 1
+ s.srcPos.Line = 1
+ return s
+}
+
+// next reads the next rune from the bufferred reader. Returns the rune(0) if
+// an error occurs (or io.EOF is returned).
+func (s *Scanner) next() rune {
+ ch, size, err := s.buf.ReadRune()
+ if err != nil {
+ // advance for error reporting
+ s.srcPos.Column++
+ s.srcPos.Offset += size
+ s.lastCharLen = size
+ return eof
+ }
+
+ if ch == utf8.RuneError && size == 1 {
+ s.srcPos.Column++
+ s.srcPos.Offset += size
+ s.lastCharLen = size
+ s.err("illegal UTF-8 encoding")
+ return ch
+ }
+
+ // remember last position
+ s.prevPos = s.srcPos
+
+ s.srcPos.Column++
+ s.lastCharLen = size
+ s.srcPos.Offset += size
+
+ if ch == '\n' {
+ s.srcPos.Line++
+ s.lastLineLen = s.srcPos.Column
+ s.srcPos.Column = 0
+ }
+
+ // If we see a null character with data left, then that is an error
+ if ch == '\x00' && s.buf.Len() > 0 {
+ s.err("unexpected null character (0x00)")
+ return eof
+ }
+
+ // debug
+ // fmt.Printf("ch: %q, offset:column: %d:%d\n", ch, s.srcPos.Offset, s.srcPos.Column)
+ return ch
+}
+
+// unread unreads the previous read Rune and updates the source position
+func (s *Scanner) unread() {
+ if err := s.buf.UnreadRune(); err != nil {
+ panic(err) // this is user fault, we should catch it
+ }
+ s.srcPos = s.prevPos // put back last position
+}
+
+// peek returns the next rune without advancing the reader.
+func (s *Scanner) peek() rune {
+ peek, _, err := s.buf.ReadRune()
+ if err != nil {
+ return eof
+ }
+
+ s.buf.UnreadRune()
+ return peek
+}
+
+// Scan scans the next token and returns the token.
+func (s *Scanner) Scan() token.Token {
+ ch := s.next()
+
+ // skip white space
+ for isWhitespace(ch) {
+ ch = s.next()
+ }
+
+ var tok token.Type
+
+ // token text markings
+ s.tokStart = s.srcPos.Offset - s.lastCharLen
+
+ // token position, initial next() is moving the offset by one(size of rune
+ // actually), though we are interested with the starting point
+ s.tokPos.Offset = s.srcPos.Offset - s.lastCharLen
+ if s.srcPos.Column > 0 {
+ // common case: last character was not a '\n'
+ s.tokPos.Line = s.srcPos.Line
+ s.tokPos.Column = s.srcPos.Column
+ } else {
+ // last character was a '\n'
+ // (we cannot be at the beginning of the source
+ // since we have called next() at least once)
+ s.tokPos.Line = s.srcPos.Line - 1
+ s.tokPos.Column = s.lastLineLen
+ }
+
+ switch {
+ case isLetter(ch):
+ tok = token.IDENT
+ lit := s.scanIdentifier()
+ if lit == "true" || lit == "false" {
+ tok = token.BOOL
+ }
+ case isDecimal(ch):
+ tok = s.scanNumber(ch)
+ default:
+ switch ch {
+ case eof:
+ tok = token.EOF
+ case '"':
+ tok = token.STRING
+ s.scanString()
+ case '#', '/':
+ tok = token.COMMENT
+ s.scanComment(ch)
+ case '.':
+ tok = token.PERIOD
+ ch = s.peek()
+ if isDecimal(ch) {
+ tok = token.FLOAT
+ ch = s.scanMantissa(ch)
+ ch = s.scanExponent(ch)
+ }
+ case '<':
+ tok = token.HEREDOC
+ s.scanHeredoc()
+ case '[':
+ tok = token.LBRACK
+ case ']':
+ tok = token.RBRACK
+ case '{':
+ tok = token.LBRACE
+ case '}':
+ tok = token.RBRACE
+ case ',':
+ tok = token.COMMA
+ case '=':
+ tok = token.ASSIGN
+ case '+':
+ tok = token.ADD
+ case '-':
+ if isDecimal(s.peek()) {
+ ch := s.next()
+ tok = s.scanNumber(ch)
+ } else {
+ tok = token.SUB
+ }
+ default:
+ s.err("illegal char")
+ }
+ }
+
+ // finish token ending
+ s.tokEnd = s.srcPos.Offset
+
+ // create token literal
+ var tokenText string
+ if s.tokStart >= 0 {
+ tokenText = string(s.src[s.tokStart:s.tokEnd])
+ }
+ s.tokStart = s.tokEnd // ensure idempotency of tokenText() call
+
+ return token.Token{
+ Type: tok,
+ Pos: s.tokPos,
+ Text: tokenText,
+ }
+}
+
+func (s *Scanner) scanComment(ch rune) {
+ // single line comments
+ if ch == '#' || (ch == '/' && s.peek() != '*') {
+ if ch == '/' && s.peek() != '/' {
+ s.err("expected '/' for comment")
+ return
+ }
+
+ ch = s.next()
+ for ch != '\n' && ch >= 0 && ch != eof {
+ ch = s.next()
+ }
+ if ch != eof && ch >= 0 {
+ s.unread()
+ }
+ return
+ }
+
+ // be sure we get the character after /* This allows us to find comment's
+ // that are not erminated
+ if ch == '/' {
+ s.next()
+ ch = s.next() // read character after "/*"
+ }
+
+ // look for /* - style comments
+ for {
+ if ch < 0 || ch == eof {
+ s.err("comment not terminated")
+ break
+ }
+
+ ch0 := ch
+ ch = s.next()
+ if ch0 == '*' && ch == '/' {
+ break
+ }
+ }
+}
+
+// scanNumber scans a HCL number definition starting with the given rune
+func (s *Scanner) scanNumber(ch rune) token.Type {
+ if ch == '0' {
+ // check for hexadecimal, octal or float
+ ch = s.next()
+ if ch == 'x' || ch == 'X' {
+ // hexadecimal
+ ch = s.next()
+ found := false
+ for isHexadecimal(ch) {
+ ch = s.next()
+ found = true
+ }
+
+ if !found {
+ s.err("illegal hexadecimal number")
+ }
+
+ if ch != eof {
+ s.unread()
+ }
+
+ return token.NUMBER
+ }
+
+ // now it's either something like: 0421(octal) or 0.1231(float)
+ illegalOctal := false
+ for isDecimal(ch) {
+ ch = s.next()
+ if ch == '8' || ch == '9' {
+ // this is just a possibility. For example 0159 is illegal, but
+ // 0159.23 is valid. So we mark a possible illegal octal. If
+ // the next character is not a period, we'll print the error.
+ illegalOctal = true
+ }
+ }
+
+ if ch == 'e' || ch == 'E' {
+ ch = s.scanExponent(ch)
+ return token.FLOAT
+ }
+
+ if ch == '.' {
+ ch = s.scanFraction(ch)
+
+ if ch == 'e' || ch == 'E' {
+ ch = s.next()
+ ch = s.scanExponent(ch)
+ }
+ return token.FLOAT
+ }
+
+ if illegalOctal {
+ s.err("illegal octal number")
+ }
+
+ if ch != eof {
+ s.unread()
+ }
+ return token.NUMBER
+ }
+
+ s.scanMantissa(ch)
+ ch = s.next() // seek forward
+ if ch == 'e' || ch == 'E' {
+ ch = s.scanExponent(ch)
+ return token.FLOAT
+ }
+
+ if ch == '.' {
+ ch = s.scanFraction(ch)
+ if ch == 'e' || ch == 'E' {
+ ch = s.next()
+ ch = s.scanExponent(ch)
+ }
+ return token.FLOAT
+ }
+
+ if ch != eof {
+ s.unread()
+ }
+ return token.NUMBER
+}
+
+// scanMantissa scans the mantissa begining from the rune. It returns the next
+// non decimal rune. It's used to determine wheter it's a fraction or exponent.
+func (s *Scanner) scanMantissa(ch rune) rune {
+ scanned := false
+ for isDecimal(ch) {
+ ch = s.next()
+ scanned = true
+ }
+
+ if scanned && ch != eof {
+ s.unread()
+ }
+ return ch
+}
+
+// scanFraction scans the fraction after the '.' rune
+func (s *Scanner) scanFraction(ch rune) rune {
+ if ch == '.' {
+ ch = s.peek() // we peek just to see if we can move forward
+ ch = s.scanMantissa(ch)
+ }
+ return ch
+}
+
+// scanExponent scans the remaining parts of an exponent after the 'e' or 'E'
+// rune.
+func (s *Scanner) scanExponent(ch rune) rune {
+ if ch == 'e' || ch == 'E' {
+ ch = s.next()
+ if ch == '-' || ch == '+' {
+ ch = s.next()
+ }
+ ch = s.scanMantissa(ch)
+ }
+ return ch
+}
+
+// scanHeredoc scans a heredoc string
+func (s *Scanner) scanHeredoc() {
+ // Scan the second '<' in example: '<<EOF'
+ if s.next() != '<' {
+ s.err("heredoc expected second '<', didn't see it")
+ return
+ }
+
+ // Get the original offset so we can read just the heredoc ident
+ offs := s.srcPos.Offset
+
+ // Scan the identifier
+ ch := s.next()
+
+ // Indented heredoc syntax
+ if ch == '-' {
+ ch = s.next()
+ }
+
+ for isLetter(ch) || isDigit(ch) {
+ ch = s.next()
+ }
+
+ // If we reached an EOF then that is not good
+ if ch == eof {
+ s.err("heredoc not terminated")
+ return
+ }
+
+ // Ignore the '\r' in Windows line endings
+ if ch == '\r' {
+ if s.peek() == '\n' {
+ ch = s.next()
+ }
+ }
+
+ // If we didn't reach a newline then that is also not good
+ if ch != '\n' {
+ s.err("invalid characters in heredoc anchor")
+ return
+ }
+
+ // Read the identifier
+ identBytes := s.src[offs : s.srcPos.Offset-s.lastCharLen]
+ if len(identBytes) == 0 {
+ s.err("zero-length heredoc anchor")
+ return
+ }
+
+ var identRegexp *regexp.Regexp
+ if identBytes[0] == '-' {
+ identRegexp = regexp.MustCompile(fmt.Sprintf(`[[:space:]]*%s\z`, identBytes[1:]))
+ } else {
+ identRegexp = regexp.MustCompile(fmt.Sprintf(`[[:space:]]*%s\z`, identBytes))
+ }
+
+ // Read the actual string value
+ lineStart := s.srcPos.Offset
+ for {
+ ch := s.next()
+
+ // Special newline handling.
+ if ch == '\n' {
+ // Math is fast, so we first compare the byte counts to see if we have a chance
+ // of seeing the same identifier - if the length is less than the number of bytes
+ // in the identifier, this cannot be a valid terminator.
+ lineBytesLen := s.srcPos.Offset - s.lastCharLen - lineStart
+ if lineBytesLen >= len(identBytes) && identRegexp.Match(s.src[lineStart:s.srcPos.Offset-s.lastCharLen]) {
+ break
+ }
+
+ // Not an anchor match, record the start of a new line
+ lineStart = s.srcPos.Offset
+ }
+
+ if ch == eof {
+ s.err("heredoc not terminated")
+ return
+ }
+ }
+
+ return
+}
+
+// scanString scans a quoted string
+func (s *Scanner) scanString() {
+ braces := 0
+ for {
+ // '"' opening already consumed
+ // read character after quote
+ ch := s.next()
+
+ if (ch == '\n' && braces == 0) || ch < 0 || ch == eof {
+ s.err("literal not terminated")
+ return
+ }
+
+ if ch == '"' && braces == 0 {
+ break
+ }
+
+ // If we're going into a ${} then we can ignore quotes for awhile
+ if braces == 0 && ch == '$' && s.peek() == '{' {
+ braces++
+ s.next()
+ } else if braces > 0 && ch == '{' {
+ braces++
+ }
+ if braces > 0 && ch == '}' {
+ braces--
+ }
+
+ if ch == '\\' {
+ s.scanEscape()
+ }
+ }
+
+ return
+}
+
+// scanEscape scans an escape sequence
+func (s *Scanner) scanEscape() rune {
+ // http://en.cppreference.com/w/cpp/language/escape
+ ch := s.next() // read character after '/'
+ switch ch {
+ case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"':
+ // nothing to do
+ case '0', '1', '2', '3', '4', '5', '6', '7':
+ // octal notation
+ ch = s.scanDigits(ch, 8, 3)
+ case 'x':
+ // hexademical notation
+ ch = s.scanDigits(s.next(), 16, 2)
+ case 'u':
+ // universal character name
+ ch = s.scanDigits(s.next(), 16, 4)
+ case 'U':
+ // universal character name
+ ch = s.scanDigits(s.next(), 16, 8)
+ default:
+ s.err("illegal char escape")
+ }
+ return ch
+}
+
+// scanDigits scans a rune with the given base for n times. For example an
+// octal notation \184 would yield in scanDigits(ch, 8, 3)
+func (s *Scanner) scanDigits(ch rune, base, n int) rune {
+ start := n
+ for n > 0 && digitVal(ch) < base {
+ ch = s.next()
+ if ch == eof {
+ // If we see an EOF, we halt any more scanning of digits
+ // immediately.
+ break
+ }
+
+ n--
+ }
+ if n > 0 {
+ s.err("illegal char escape")
+ }
+
+ if n != start {
+ // we scanned all digits, put the last non digit char back,
+ // only if we read anything at all
+ s.unread()
+ }
+
+ return ch
+}
+
+// scanIdentifier scans an identifier and returns the literal string
+func (s *Scanner) scanIdentifier() string {
+ offs := s.srcPos.Offset - s.lastCharLen
+ ch := s.next()
+ for isLetter(ch) || isDigit(ch) || ch == '-' || ch == '.' {
+ ch = s.next()
+ }
+
+ if ch != eof {
+ s.unread() // we got identifier, put back latest char
+ }
+
+ return string(s.src[offs:s.srcPos.Offset])
+}
+
+// recentPosition returns the position of the character immediately after the
+// character or token returned by the last call to Scan.
+func (s *Scanner) recentPosition() (pos token.Pos) {
+ pos.Offset = s.srcPos.Offset - s.lastCharLen
+ switch {
+ case s.srcPos.Column > 0:
+ // common case: last character was not a '\n'
+ pos.Line = s.srcPos.Line
+ pos.Column = s.srcPos.Column
+ case s.lastLineLen > 0:
+ // last character was a '\n'
+ // (we cannot be at the beginning of the source
+ // since we have called next() at least once)
+ pos.Line = s.srcPos.Line - 1
+ pos.Column = s.lastLineLen
+ default:
+ // at the beginning of the source
+ pos.Line = 1
+ pos.Column = 1
+ }
+ return
+}
+
+// err prints the error of any scanning to s.Error function. If the function is
+// not defined, by default it prints them to os.Stderr
+func (s *Scanner) err(msg string) {
+ s.ErrorCount++
+ pos := s.recentPosition()
+
+ if s.Error != nil {
+ s.Error(pos, msg)
+ return
+ }
+
+ fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg)
+}
+
+// isHexadecimal returns true if the given rune is a letter
+func isLetter(ch rune) bool {
+ return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
+}
+
+// isDigit returns true if the given rune is a decimal digit
+func isDigit(ch rune) bool {
+ return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch)
+}
+
+// isDecimal returns true if the given rune is a decimal number
+func isDecimal(ch rune) bool {
+ return '0' <= ch && ch <= '9'
+}
+
+// isHexadecimal returns true if the given rune is an hexadecimal number
+func isHexadecimal(ch rune) bool {
+ return '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' || 'A' <= ch && ch <= 'F'
+}
+
+// isWhitespace returns true if the rune is a space, tab, newline or carriage return
+func isWhitespace(ch rune) bool {
+ return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
+}
+
+// digitVal returns the integer value of a given octal,decimal or hexadecimal rune
+func digitVal(ch rune) int {
+ switch {
+ case '0' <= ch && ch <= '9':
+ return int(ch - '0')
+ case 'a' <= ch && ch <= 'f':
+ return int(ch - 'a' + 10)
+ case 'A' <= ch && ch <= 'F':
+ return int(ch - 'A' + 10)
+ }
+ return 16 // larger than any legal digit val
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner_test.go b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner_test.go
new file mode 100644
index 000000000..4f2c9cbe0
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner_test.go
@@ -0,0 +1,591 @@
+package scanner
+
+import (
+ "bytes"
+ "fmt"
+ "testing"
+
+ "strings"
+
+ "github.com/hashicorp/hcl/hcl/token"
+)
+
+var f100 = strings.Repeat("f", 100)
+
+type tokenPair struct {
+ tok token.Type
+ text string
+}
+
+var tokenLists = map[string][]tokenPair{
+ "comment": []tokenPair{
+ {token.COMMENT, "//"},
+ {token.COMMENT, "////"},
+ {token.COMMENT, "// comment"},
+ {token.COMMENT, "// /* comment */"},
+ {token.COMMENT, "// // comment //"},
+ {token.COMMENT, "//" + f100},
+ {token.COMMENT, "#"},
+ {token.COMMENT, "##"},
+ {token.COMMENT, "# comment"},
+ {token.COMMENT, "# /* comment */"},
+ {token.COMMENT, "# # comment #"},
+ {token.COMMENT, "#" + f100},
+ {token.COMMENT, "/**/"},
+ {token.COMMENT, "/***/"},
+ {token.COMMENT, "/* comment */"},
+ {token.COMMENT, "/* // comment */"},
+ {token.COMMENT, "/* /* comment */"},
+ {token.COMMENT, "/*\n comment\n*/"},
+ {token.COMMENT, "/*" + f100 + "*/"},
+ },
+ "operator": []tokenPair{
+ {token.LBRACK, "["},
+ {token.LBRACE, "{"},
+ {token.COMMA, ","},
+ {token.PERIOD, "."},
+ {token.RBRACK, "]"},
+ {token.RBRACE, "}"},
+ {token.ASSIGN, "="},
+ {token.ADD, "+"},
+ {token.SUB, "-"},
+ },
+ "bool": []tokenPair{
+ {token.BOOL, "true"},
+ {token.BOOL, "false"},
+ },
+ "ident": []tokenPair{
+ {token.IDENT, "a"},
+ {token.IDENT, "a0"},
+ {token.IDENT, "foobar"},
+ {token.IDENT, "foo-bar"},
+ {token.IDENT, "abc123"},
+ {token.IDENT, "LGTM"},
+ {token.IDENT, "_"},
+ {token.IDENT, "_abc123"},
+ {token.IDENT, "abc123_"},
+ {token.IDENT, "_abc_123_"},
+ {token.IDENT, "_äöü"},
+ {token.IDENT, "_本"},
+ {token.IDENT, "äöü"},
+ {token.IDENT, "本"},
+ {token.IDENT, "a۰۱۸"},
+ {token.IDENT, "foo६४"},
+ {token.IDENT, "bar9876"},
+ },
+ "heredoc": []tokenPair{
+ {token.HEREDOC, "<<EOF\nhello\nworld\nEOF"},
+ {token.HEREDOC, "<<EOF123\nhello\nworld\nEOF123"},
+ },
+ "string": []tokenPair{
+ {token.STRING, `" "`},
+ {token.STRING, `"a"`},
+ {token.STRING, `"本"`},
+ {token.STRING, `"${file("foo")}"`},
+ {token.STRING, `"${file(\"foo\")}"`},
+ {token.STRING, `"\a"`},
+ {token.STRING, `"\b"`},
+ {token.STRING, `"\f"`},
+ {token.STRING, `"\n"`},
+ {token.STRING, `"\r"`},
+ {token.STRING, `"\t"`},
+ {token.STRING, `"\v"`},
+ {token.STRING, `"\""`},
+ {token.STRING, `"\000"`},
+ {token.STRING, `"\777"`},
+ {token.STRING, `"\x00"`},
+ {token.STRING, `"\xff"`},
+ {token.STRING, `"\u0000"`},
+ {token.STRING, `"\ufA16"`},
+ {token.STRING, `"\U00000000"`},
+ {token.STRING, `"\U0000ffAB"`},
+ {token.STRING, `"` + f100 + `"`},
+ },
+ "number": []tokenPair{
+ {token.NUMBER, "0"},
+ {token.NUMBER, "1"},
+ {token.NUMBER, "9"},
+ {token.NUMBER, "42"},
+ {token.NUMBER, "1234567890"},
+ {token.NUMBER, "00"},
+ {token.NUMBER, "01"},
+ {token.NUMBER, "07"},
+ {token.NUMBER, "042"},
+ {token.NUMBER, "01234567"},
+ {token.NUMBER, "0x0"},
+ {token.NUMBER, "0x1"},
+ {token.NUMBER, "0xf"},
+ {token.NUMBER, "0x42"},
+ {token.NUMBER, "0x123456789abcDEF"},
+ {token.NUMBER, "0x" + f100},
+ {token.NUMBER, "0X0"},
+ {token.NUMBER, "0X1"},
+ {token.NUMBER, "0XF"},
+ {token.NUMBER, "0X42"},
+ {token.NUMBER, "0X123456789abcDEF"},
+ {token.NUMBER, "0X" + f100},
+ {token.NUMBER, "-0"},
+ {token.NUMBER, "-1"},
+ {token.NUMBER, "-9"},
+ {token.NUMBER, "-42"},
+ {token.NUMBER, "-1234567890"},
+ {token.NUMBER, "-00"},
+ {token.NUMBER, "-01"},
+ {token.NUMBER, "-07"},
+ {token.NUMBER, "-29"},
+ {token.NUMBER, "-042"},
+ {token.NUMBER, "-01234567"},
+ {token.NUMBER, "-0x0"},
+ {token.NUMBER, "-0x1"},
+ {token.NUMBER, "-0xf"},
+ {token.NUMBER, "-0x42"},
+ {token.NUMBER, "-0x123456789abcDEF"},
+ {token.NUMBER, "-0x" + f100},
+ {token.NUMBER, "-0X0"},
+ {token.NUMBER, "-0X1"},
+ {token.NUMBER, "-0XF"},
+ {token.NUMBER, "-0X42"},
+ {token.NUMBER, "-0X123456789abcDEF"},
+ {token.NUMBER, "-0X" + f100},
+ },
+ "float": []tokenPair{
+ {token.FLOAT, "0."},
+ {token.FLOAT, "1."},
+ {token.FLOAT, "42."},
+ {token.FLOAT, "01234567890."},
+ {token.FLOAT, ".0"},
+ {token.FLOAT, ".1"},
+ {token.FLOAT, ".42"},
+ {token.FLOAT, ".0123456789"},
+ {token.FLOAT, "0.0"},
+ {token.FLOAT, "1.0"},
+ {token.FLOAT, "42.0"},
+ {token.FLOAT, "01234567890.0"},
+ {token.FLOAT, "0e0"},
+ {token.FLOAT, "1e0"},
+ {token.FLOAT, "42e0"},
+ {token.FLOAT, "01234567890e0"},
+ {token.FLOAT, "0E0"},
+ {token.FLOAT, "1E0"},
+ {token.FLOAT, "42E0"},
+ {token.FLOAT, "01234567890E0"},
+ {token.FLOAT, "0e+10"},
+ {token.FLOAT, "1e-10"},
+ {token.FLOAT, "42e+10"},
+ {token.FLOAT, "01234567890e-10"},
+ {token.FLOAT, "0E+10"},
+ {token.FLOAT, "1E-10"},
+ {token.FLOAT, "42E+10"},
+ {token.FLOAT, "01234567890E-10"},
+ {token.FLOAT, "01.8e0"},
+ {token.FLOAT, "1.4e0"},
+ {token.FLOAT, "42.2e0"},
+ {token.FLOAT, "01234567890.12e0"},
+ {token.FLOAT, "0.E0"},
+ {token.FLOAT, "1.12E0"},
+ {token.FLOAT, "42.123E0"},
+ {token.FLOAT, "01234567890.213E0"},
+ {token.FLOAT, "0.2e+10"},
+ {token.FLOAT, "1.2e-10"},
+ {token.FLOAT, "42.54e+10"},
+ {token.FLOAT, "01234567890.98e-10"},
+ {token.FLOAT, "0.1E+10"},
+ {token.FLOAT, "1.1E-10"},
+ {token.FLOAT, "42.1E+10"},
+ {token.FLOAT, "01234567890.1E-10"},
+ {token.FLOAT, "-0.0"},
+ {token.FLOAT, "-1.0"},
+ {token.FLOAT, "-42.0"},
+ {token.FLOAT, "-01234567890.0"},
+ {token.FLOAT, "-0e0"},
+ {token.FLOAT, "-1e0"},
+ {token.FLOAT, "-42e0"},
+ {token.FLOAT, "-01234567890e0"},
+ {token.FLOAT, "-0E0"},
+ {token.FLOAT, "-1E0"},
+ {token.FLOAT, "-42E0"},
+ {token.FLOAT, "-01234567890E0"},
+ {token.FLOAT, "-0e+10"},
+ {token.FLOAT, "-1e-10"},
+ {token.FLOAT, "-42e+10"},
+ {token.FLOAT, "-01234567890e-10"},
+ {token.FLOAT, "-0E+10"},
+ {token.FLOAT, "-1E-10"},
+ {token.FLOAT, "-42E+10"},
+ {token.FLOAT, "-01234567890E-10"},
+ {token.FLOAT, "-01.8e0"},
+ {token.FLOAT, "-1.4e0"},
+ {token.FLOAT, "-42.2e0"},
+ {token.FLOAT, "-01234567890.12e0"},
+ {token.FLOAT, "-0.E0"},
+ {token.FLOAT, "-1.12E0"},
+ {token.FLOAT, "-42.123E0"},
+ {token.FLOAT, "-01234567890.213E0"},
+ {token.FLOAT, "-0.2e+10"},
+ {token.FLOAT, "-1.2e-10"},
+ {token.FLOAT, "-42.54e+10"},
+ {token.FLOAT, "-01234567890.98e-10"},
+ {token.FLOAT, "-0.1E+10"},
+ {token.FLOAT, "-1.1E-10"},
+ {token.FLOAT, "-42.1E+10"},
+ {token.FLOAT, "-01234567890.1E-10"},
+ },
+}
+
+var orderedTokenLists = []string{
+ "comment",
+ "operator",
+ "bool",
+ "ident",
+ "heredoc",
+ "string",
+ "number",
+ "float",
+}
+
+func TestPosition(t *testing.T) {
+ // create artifical source code
+ buf := new(bytes.Buffer)
+
+ for _, listName := range orderedTokenLists {
+ for _, ident := range tokenLists[listName] {
+ fmt.Fprintf(buf, "\t\t\t\t%s\n", ident.text)
+ }
+ }
+
+ s := New(buf.Bytes())
+
+ pos := token.Pos{"", 4, 1, 5}
+ s.Scan()
+ for _, listName := range orderedTokenLists {
+
+ for _, k := range tokenLists[listName] {
+ curPos := s.tokPos
+ // fmt.Printf("[%q] s = %+v:%+v\n", k.text, curPos.Offset, curPos.Column)
+
+ if curPos.Offset != pos.Offset {
+ t.Fatalf("offset = %d, want %d for %q", curPos.Offset, pos.Offset, k.text)
+ }
+ if curPos.Line != pos.Line {
+ t.Fatalf("line = %d, want %d for %q", curPos.Line, pos.Line, k.text)
+ }
+ if curPos.Column != pos.Column {
+ t.Fatalf("column = %d, want %d for %q", curPos.Column, pos.Column, k.text)
+ }
+ pos.Offset += 4 + len(k.text) + 1 // 4 tabs + token bytes + newline
+ pos.Line += countNewlines(k.text) + 1 // each token is on a new line
+ s.Scan()
+ }
+ }
+ // make sure there were no token-internal errors reported by scanner
+ if s.ErrorCount != 0 {
+ t.Errorf("%d errors", s.ErrorCount)
+ }
+}
+
+func TestNullChar(t *testing.T) {
+ s := New([]byte("\"\\0"))
+ s.Scan() // Used to panic
+}
+
+func TestComment(t *testing.T) {
+ testTokenList(t, tokenLists["comment"])
+}
+
+func TestOperator(t *testing.T) {
+ testTokenList(t, tokenLists["operator"])
+}
+
+func TestBool(t *testing.T) {
+ testTokenList(t, tokenLists["bool"])
+}
+
+func TestIdent(t *testing.T) {
+ testTokenList(t, tokenLists["ident"])
+}
+
+func TestString(t *testing.T) {
+ testTokenList(t, tokenLists["string"])
+}
+
+func TestNumber(t *testing.T) {
+ testTokenList(t, tokenLists["number"])
+}
+
+func TestFloat(t *testing.T) {
+ testTokenList(t, tokenLists["float"])
+}
+
+func TestWindowsLineEndings(t *testing.T) {
+ hcl := `// This should have Windows line endings
+resource "aws_instance" "foo" {
+ user_data=<<HEREDOC
+ test script
+HEREDOC
+}`
+ hclWindowsEndings := strings.Replace(hcl, "\n", "\r\n", -1)
+
+ literals := []struct {
+ tokenType token.Type
+ literal string
+ }{
+ {token.COMMENT, "// This should have Windows line endings\r"},
+ {token.IDENT, `resource`},
+ {token.STRING, `"aws_instance"`},
+ {token.STRING, `"foo"`},
+ {token.LBRACE, `{`},
+ {token.IDENT, `user_data`},
+ {token.ASSIGN, `=`},
+ {token.HEREDOC, "<<HEREDOC\r\n test script\r\nHEREDOC\r\n"},
+ {token.RBRACE, `}`},
+ }
+
+ s := New([]byte(hclWindowsEndings))
+ for _, l := range literals {
+ tok := s.Scan()
+
+ if l.tokenType != tok.Type {
+ t.Errorf("got: %s want %s for %s\n", tok, l.tokenType, tok.String())
+ }
+
+ if l.literal != tok.Text {
+ t.Errorf("got:\n%v\nwant:\n%v\n", []byte(tok.Text), []byte(l.literal))
+ }
+ }
+}
+
+func TestRealExample(t *testing.T) {
+ complexHCL := `// This comes from Terraform, as a test
+ variable "foo" {
+ default = "bar"
+ description = "bar"
+ }
+
+ provider "aws" {
+ access_key = "foo"
+ secret_key = "${replace(var.foo, ".", "\\.")}"
+ }
+
+ resource "aws_security_group" "firewall" {
+ count = 5
+ }
+
+ resource aws_instance "web" {
+ ami = "${var.foo}"
+ security_groups = [
+ "foo",
+ "${aws_security_group.firewall.foo}"
+ ]
+
+ network_interface {
+ device_index = 0
+ description = <<EOF
+Main interface
+EOF
+ }
+
+ network_interface {
+ device_index = 1
+ description = <<-EOF
+ Outer text
+ Indented text
+ EOF
+ }
+ }`
+
+ literals := []struct {
+ tokenType token.Type
+ literal string
+ }{
+ {token.COMMENT, `// This comes from Terraform, as a test`},
+ {token.IDENT, `variable`},
+ {token.STRING, `"foo"`},
+ {token.LBRACE, `{`},
+ {token.IDENT, `default`},
+ {token.ASSIGN, `=`},
+ {token.STRING, `"bar"`},
+ {token.IDENT, `description`},
+ {token.ASSIGN, `=`},
+ {token.STRING, `"bar"`},
+ {token.RBRACE, `}`},
+ {token.IDENT, `provider`},
+ {token.STRING, `"aws"`},
+ {token.LBRACE, `{`},
+ {token.IDENT, `access_key`},
+ {token.ASSIGN, `=`},
+ {token.STRING, `"foo"`},
+ {token.IDENT, `secret_key`},
+ {token.ASSIGN, `=`},
+ {token.STRING, `"${replace(var.foo, ".", "\\.")}"`},
+ {token.RBRACE, `}`},
+ {token.IDENT, `resource`},
+ {token.STRING, `"aws_security_group"`},
+ {token.STRING, `"firewall"`},
+ {token.LBRACE, `{`},
+ {token.IDENT, `count`},
+ {token.ASSIGN, `=`},
+ {token.NUMBER, `5`},
+ {token.RBRACE, `}`},
+ {token.IDENT, `resource`},
+ {token.IDENT, `aws_instance`},
+ {token.STRING, `"web"`},
+ {token.LBRACE, `{`},
+ {token.IDENT, `ami`},
+ {token.ASSIGN, `=`},
+ {token.STRING, `"${var.foo}"`},
+ {token.IDENT, `security_groups`},
+ {token.ASSIGN, `=`},
+ {token.LBRACK, `[`},
+ {token.STRING, `"foo"`},
+ {token.COMMA, `,`},
+ {token.STRING, `"${aws_security_group.firewall.foo}"`},
+ {token.RBRACK, `]`},
+ {token.IDENT, `network_interface`},
+ {token.LBRACE, `{`},
+ {token.IDENT, `device_index`},
+ {token.ASSIGN, `=`},
+ {token.NUMBER, `0`},
+ {token.IDENT, `description`},
+ {token.ASSIGN, `=`},
+ {token.HEREDOC, "<<EOF\nMain interface\nEOF\n"},
+ {token.RBRACE, `}`},
+ {token.IDENT, `network_interface`},
+ {token.LBRACE, `{`},
+ {token.IDENT, `device_index`},
+ {token.ASSIGN, `=`},
+ {token.NUMBER, `1`},
+ {token.IDENT, `description`},
+ {token.ASSIGN, `=`},
+ {token.HEREDOC, "<<-EOF\n\t\t\tOuter text\n\t\t\t\tIndented text\n\t\t\tEOF\n"},
+ {token.RBRACE, `}`},
+ {token.RBRACE, `}`},
+ {token.EOF, ``},
+ }
+
+ s := New([]byte(complexHCL))
+ for _, l := range literals {
+ tok := s.Scan()
+ if l.tokenType != tok.Type {
+ t.Errorf("got: %s want %s for %s\n", tok, l.tokenType, tok.String())
+ }
+
+ if l.literal != tok.Text {
+ t.Errorf("got:\n%+v\n%s\n want:\n%+v\n%s\n", []byte(tok.String()), tok, []byte(l.literal), l.literal)
+ }
+ }
+
+}
+
+func TestScan_crlf(t *testing.T) {
+ complexHCL := "foo {\r\n bar = \"baz\"\r\n}\r\n"
+
+ literals := []struct {
+ tokenType token.Type
+ literal string
+ }{
+ {token.IDENT, `foo`},
+ {token.LBRACE, `{`},
+ {token.IDENT, `bar`},
+ {token.ASSIGN, `=`},
+ {token.STRING, `"baz"`},
+ {token.RBRACE, `}`},
+ {token.EOF, ``},
+ }
+
+ s := New([]byte(complexHCL))
+ for _, l := range literals {
+ tok := s.Scan()
+ if l.tokenType != tok.Type {
+ t.Errorf("got: %s want %s for %s\n", tok, l.tokenType, tok.String())
+ }
+
+ if l.literal != tok.Text {
+ t.Errorf("got:\n%+v\n%s\n want:\n%+v\n%s\n", []byte(tok.String()), tok, []byte(l.literal), l.literal)
+ }
+ }
+
+}
+
+func TestError(t *testing.T) {
+ testError(t, "\x80", "1:1", "illegal UTF-8 encoding", token.ILLEGAL)
+ testError(t, "\xff", "1:1", "illegal UTF-8 encoding", token.ILLEGAL)
+
+ testError(t, "ab\x80", "1:3", "illegal UTF-8 encoding", token.IDENT)
+ testError(t, "abc\xff", "1:4", "illegal UTF-8 encoding", token.IDENT)
+
+ testError(t, `"ab`+"\x80", "1:4", "illegal UTF-8 encoding", token.STRING)
+ testError(t, `"abc`+"\xff", "1:5", "illegal UTF-8 encoding", token.STRING)
+
+ testError(t, `01238`, "1:6", "illegal octal number", token.NUMBER)
+ testError(t, `01238123`, "1:9", "illegal octal number", token.NUMBER)
+ testError(t, `0x`, "1:3", "illegal hexadecimal number", token.NUMBER)
+ testError(t, `0xg`, "1:3", "illegal hexadecimal number", token.NUMBER)
+ testError(t, `'aa'`, "1:1", "illegal char", token.ILLEGAL)
+
+ testError(t, `"`, "1:2", "literal not terminated", token.STRING)
+ testError(t, `"abc`, "1:5", "literal not terminated", token.STRING)
+ testError(t, `"abc`+"\n", "1:5", "literal not terminated", token.STRING)
+ testError(t, `"${abc`+"\n", "2:1", "literal not terminated", token.STRING)
+ testError(t, `/*/`, "1:4", "comment not terminated", token.COMMENT)
+ testError(t, `/foo`, "1:1", "expected '/' for comment", token.COMMENT)
+}
+
+func testError(t *testing.T, src, pos, msg string, tok token.Type) {
+ s := New([]byte(src))
+
+ errorCalled := false
+ s.Error = func(p token.Pos, m string) {
+ if !errorCalled {
+ if pos != p.String() {
+ t.Errorf("pos = %q, want %q for %q", p, pos, src)
+ }
+
+ if m != msg {
+ t.Errorf("msg = %q, want %q for %q", m, msg, src)
+ }
+ errorCalled = true
+ }
+ }
+
+ tk := s.Scan()
+ if tk.Type != tok {
+ t.Errorf("tok = %s, want %s for %q", tk, tok, src)
+ }
+ if !errorCalled {
+ t.Errorf("error handler not called for %q", src)
+ }
+ if s.ErrorCount == 0 {
+ t.Errorf("count = %d, want > 0 for %q", s.ErrorCount, src)
+ }
+}
+
+func testTokenList(t *testing.T, tokenList []tokenPair) {
+ // create artifical source code
+ buf := new(bytes.Buffer)
+ for _, ident := range tokenList {
+ fmt.Fprintf(buf, "%s\n", ident.text)
+ }
+
+ s := New(buf.Bytes())
+ for _, ident := range tokenList {
+ tok := s.Scan()
+ if tok.Type != ident.tok {
+ t.Errorf("tok = %q want %q for %q\n", tok, ident.tok, ident.text)
+ }
+
+ if tok.Text != ident.text {
+ t.Errorf("text = %q want %q", tok.String(), ident.text)
+ }
+
+ }
+}
+
+func countNewlines(s string) int {
+ n := 0
+ for _, ch := range s {
+ if ch == '\n' {
+ n++
+ }
+ }
+ return n
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go
new file mode 100644
index 000000000..5f981eaa2
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go
@@ -0,0 +1,241 @@
+package strconv
+
+import (
+ "errors"
+ "unicode/utf8"
+)
+
+// ErrSyntax indicates that a value does not have the right syntax for the target type.
+var ErrSyntax = errors.New("invalid syntax")
+
+// Unquote interprets s as a single-quoted, double-quoted,
+// or backquoted Go string literal, returning the string value
+// that s quotes. (If s is single-quoted, it would be a Go
+// character literal; Unquote returns the corresponding
+// one-character string.)
+func Unquote(s string) (t string, err error) {
+ n := len(s)
+ if n < 2 {
+ return "", ErrSyntax
+ }
+ quote := s[0]
+ if quote != s[n-1] {
+ return "", ErrSyntax
+ }
+ s = s[1 : n-1]
+
+ if quote != '"' {
+ return "", ErrSyntax
+ }
+ if !contains(s, '$') && !contains(s, '{') && contains(s, '\n') {
+ return "", ErrSyntax
+ }
+
+ // Is it trivial? Avoid allocation.
+ if !contains(s, '\\') && !contains(s, quote) && !contains(s, '$') {
+ switch quote {
+ case '"':
+ return s, nil
+ case '\'':
+ r, size := utf8.DecodeRuneInString(s)
+ if size == len(s) && (r != utf8.RuneError || size != 1) {
+ return s, nil
+ }
+ }
+ }
+
+ var runeTmp [utf8.UTFMax]byte
+ buf := make([]byte, 0, 3*len(s)/2) // Try to avoid more allocations.
+ for len(s) > 0 {
+ // If we're starting a '${}' then let it through un-unquoted.
+ // Specifically: we don't unquote any characters within the `${}`
+ // section.
+ if s[0] == '$' && len(s) > 1 && s[1] == '{' {
+ buf = append(buf, '$', '{')
+ s = s[2:]
+
+ // Continue reading until we find the closing brace, copying as-is
+ braces := 1
+ for len(s) > 0 && braces > 0 {
+ r, size := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError {
+ return "", ErrSyntax
+ }
+
+ s = s[size:]
+
+ n := utf8.EncodeRune(runeTmp[:], r)
+ buf = append(buf, runeTmp[:n]...)
+
+ switch r {
+ case '{':
+ braces++
+ case '}':
+ braces--
+ }
+ }
+ if braces != 0 {
+ return "", ErrSyntax
+ }
+ if len(s) == 0 {
+ // If there's no string left, we're done!
+ break
+ } else {
+ // If there's more left, we need to pop back up to the top of the loop
+ // in case there's another interpolation in this string.
+ continue
+ }
+ }
+
+ if s[0] == '\n' {
+ return "", ErrSyntax
+ }
+
+ c, multibyte, ss, err := unquoteChar(s, quote)
+ if err != nil {
+ return "", err
+ }
+ s = ss
+ if c < utf8.RuneSelf || !multibyte {
+ buf = append(buf, byte(c))
+ } else {
+ n := utf8.EncodeRune(runeTmp[:], c)
+ buf = append(buf, runeTmp[:n]...)
+ }
+ if quote == '\'' && len(s) != 0 {
+ // single-quoted must be single character
+ return "", ErrSyntax
+ }
+ }
+ return string(buf), nil
+}
+
+// contains reports whether the string contains the byte c.
+func contains(s string, c byte) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] == c {
+ return true
+ }
+ }
+ return false
+}
+
+func unhex(b byte) (v rune, ok bool) {
+ c := rune(b)
+ switch {
+ case '0' <= c && c <= '9':
+ return c - '0', true
+ case 'a' <= c && c <= 'f':
+ return c - 'a' + 10, true
+ case 'A' <= c && c <= 'F':
+ return c - 'A' + 10, true
+ }
+ return
+}
+
+func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error) {
+ // easy cases
+ switch c := s[0]; {
+ case c == quote && (quote == '\'' || quote == '"'):
+ err = ErrSyntax
+ return
+ case c >= utf8.RuneSelf:
+ r, size := utf8.DecodeRuneInString(s)
+ return r, true, s[size:], nil
+ case c != '\\':
+ return rune(s[0]), false, s[1:], nil
+ }
+
+ // hard case: c is backslash
+ if len(s) <= 1 {
+ err = ErrSyntax
+ return
+ }
+ c := s[1]
+ s = s[2:]
+
+ switch c {
+ case 'a':
+ value = '\a'
+ case 'b':
+ value = '\b'
+ case 'f':
+ value = '\f'
+ case 'n':
+ value = '\n'
+ case 'r':
+ value = '\r'
+ case 't':
+ value = '\t'
+ case 'v':
+ value = '\v'
+ case 'x', 'u', 'U':
+ n := 0
+ switch c {
+ case 'x':
+ n = 2
+ case 'u':
+ n = 4
+ case 'U':
+ n = 8
+ }
+ var v rune
+ if len(s) < n {
+ err = ErrSyntax
+ return
+ }
+ for j := 0; j < n; j++ {
+ x, ok := unhex(s[j])
+ if !ok {
+ err = ErrSyntax
+ return
+ }
+ v = v<<4 | x
+ }
+ s = s[n:]
+ if c == 'x' {
+ // single-byte string, possibly not UTF-8
+ value = v
+ break
+ }
+ if v > utf8.MaxRune {
+ err = ErrSyntax
+ return
+ }
+ value = v
+ multibyte = true
+ case '0', '1', '2', '3', '4', '5', '6', '7':
+ v := rune(c) - '0'
+ if len(s) < 2 {
+ err = ErrSyntax
+ return
+ }
+ for j := 0; j < 2; j++ { // one digit already; two more
+ x := rune(s[j]) - '0'
+ if x < 0 || x > 7 {
+ err = ErrSyntax
+ return
+ }
+ v = (v << 3) | x
+ }
+ s = s[2:]
+ if v > 255 {
+ err = ErrSyntax
+ return
+ }
+ value = v
+ case '\\':
+ value = '\\'
+ case '\'', '"':
+ if c != quote {
+ err = ErrSyntax
+ return
+ }
+ value = rune(c)
+ default:
+ err = ErrSyntax
+ return
+ }
+ tail = s
+ return
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote_test.go b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote_test.go
new file mode 100644
index 000000000..65be375d9
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote_test.go
@@ -0,0 +1,96 @@
+package strconv
+
+import "testing"
+
+type quoteTest struct {
+ in string
+ out string
+ ascii string
+}
+
+var quotetests = []quoteTest{
+ {"\a\b\f\r\n\t\v", `"\a\b\f\r\n\t\v"`, `"\a\b\f\r\n\t\v"`},
+ {"\\", `"\\"`, `"\\"`},
+ {"abc\xffdef", `"abc\xffdef"`, `"abc\xffdef"`},
+ {"\u263a", `"☺"`, `"\u263a"`},
+ {"\U0010ffff", `"\U0010ffff"`, `"\U0010ffff"`},
+ {"\x04", `"\x04"`, `"\x04"`},
+}
+
+type unQuoteTest struct {
+ in string
+ out string
+}
+
+var unquotetests = []unQuoteTest{
+ {`""`, ""},
+ {`"a"`, "a"},
+ {`"abc"`, "abc"},
+ {`"☺"`, "☺"},
+ {`"hello world"`, "hello world"},
+ {`"\xFF"`, "\xFF"},
+ {`"\377"`, "\377"},
+ {`"\u1234"`, "\u1234"},
+ {`"\U00010111"`, "\U00010111"},
+ {`"\U0001011111"`, "\U0001011111"},
+ {`"\a\b\f\n\r\t\v\\\""`, "\a\b\f\n\r\t\v\\\""},
+ {`"'"`, "'"},
+ {`"${file("foo")}"`, `${file("foo")}`},
+ {`"${file("\"foo\"")}"`, `${file("\"foo\"")}`},
+ {`"echo ${var.region}${element(split(",",var.zones),0)}"`,
+ `echo ${var.region}${element(split(",",var.zones),0)}`},
+ {`"${HH\\:mm\\:ss}"`, `${HH\\:mm\\:ss}`},
+ {`"${\n}"`, `${\n}`},
+}
+
+var misquoted = []string{
+ ``,
+ `"`,
+ `"a`,
+ `"'`,
+ `b"`,
+ `"\"`,
+ `"\9"`,
+ `"\19"`,
+ `"\129"`,
+ `'\'`,
+ `'\9'`,
+ `'\19'`,
+ `'\129'`,
+ `'ab'`,
+ `"\x1!"`,
+ `"\U12345678"`,
+ `"\z"`,
+ "`",
+ "`xxx",
+ "`\"",
+ `"\'"`,
+ `'\"'`,
+ "\"\n\"",
+ "\"\\n\n\"",
+ "'\n'",
+ `"${"`,
+ `"${foo{}"`,
+ "\"${foo}\n\"",
+}
+
+func TestUnquote(t *testing.T) {
+ for _, tt := range unquotetests {
+ if out, err := Unquote(tt.in); err != nil || out != tt.out {
+ t.Errorf("Unquote(%#q) = %q, %v want %q, nil", tt.in, out, err, tt.out)
+ }
+ }
+
+ // run the quote tests too, backward
+ for _, tt := range quotetests {
+ if in, err := Unquote(tt.out); in != tt.in {
+ t.Errorf("Unquote(%#q) = %q, %v, want %q, nil", tt.out, in, err, tt.in)
+ }
+ }
+
+ for _, s := range misquoted {
+ if out, err := Unquote(s); out != "" || err != ErrSyntax {
+ t.Errorf("Unquote(%#q) = %q, %v want %q, %v", s, out, err, "", ErrSyntax)
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/array_comment.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/array_comment.hcl
new file mode 100644
index 000000000..78c267582
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/array_comment.hcl
@@ -0,0 +1,4 @@
+foo = [
+ "1",
+ "2", # comment
+]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/assign_colon.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/assign_colon.hcl
new file mode 100644
index 000000000..eb5a99a69
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/assign_colon.hcl
@@ -0,0 +1,6 @@
+resource = [{
+ "foo": {
+ "bar": {},
+ "baz": [1, 2, "foo"],
+ }
+}]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/comment.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/comment.hcl
new file mode 100644
index 000000000..1ff7f29fd
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/comment.hcl
@@ -0,0 +1,15 @@
+// Foo
+
+/* Bar */
+
+/*
+/*
+Baz
+*/
+
+# Another
+
+# Multiple
+# Lines
+
+foo = "bar"
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/comment_single.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/comment_single.hcl
new file mode 100644
index 000000000..fec56017d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/comment_single.hcl
@@ -0,0 +1 @@
+# Hello
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/complex.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/complex.hcl
new file mode 100644
index 000000000..cccb5b06f
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/complex.hcl
@@ -0,0 +1,42 @@
+// This comes from Terraform, as a test
+variable "foo" {
+ default = "bar"
+ description = "bar"
+}
+
+provider "aws" {
+ access_key = "foo"
+ secret_key = "bar"
+}
+
+provider "do" {
+ api_key = "${var.foo}"
+}
+
+resource "aws_security_group" "firewall" {
+ count = 5
+}
+
+resource aws_instance "web" {
+ ami = "${var.foo}"
+ security_groups = [
+ "foo",
+ "${aws_security_group.firewall.foo}"
+ ]
+
+ network_interface {
+ device_index = 0
+ description = "Main network interface"
+ }
+}
+
+resource "aws_instance" "db" {
+ security_groups = "${aws_security_group.firewall.*.id}"
+ VPC = "foo"
+
+ depends_on = ["aws_instance.web"]
+}
+
+output "web_ip" {
+ value = "${aws_instance.web.private_ip}"
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/complex_key.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/complex_key.hcl
new file mode 100644
index 000000000..0007aaf5f
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/complex_key.hcl
@@ -0,0 +1 @@
+foo.bar = "baz"
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/empty.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/empty.hcl
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/empty.hcl
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/list.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/list.hcl
new file mode 100644
index 000000000..059d4ce65
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/list.hcl
@@ -0,0 +1 @@
+foo = [1, 2, "foo"]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/list_comma.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/list_comma.hcl
new file mode 100644
index 000000000..50f4218ac
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/list_comma.hcl
@@ -0,0 +1 @@
+foo = [1, 2, "foo",]
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/multiple.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/multiple.hcl
new file mode 100644
index 000000000..029c54b0c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/multiple.hcl
@@ -0,0 +1,2 @@
+foo = "bar"
+key = 7
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/old.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/old.hcl
new file mode 100644
index 000000000..e9f77cae9
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/old.hcl
@@ -0,0 +1,3 @@
+default = {
+ "eu-west-1": "ami-b1cf19c6",
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure.hcl
new file mode 100644
index 000000000..92592fbb3
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure.hcl
@@ -0,0 +1,5 @@
+// This is a test structure for the lexer
+foo bar "baz" {
+ key = 7
+ foo = "bar"
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure_basic.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure_basic.hcl
new file mode 100644
index 000000000..7229a1f01
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure_basic.hcl
@@ -0,0 +1,5 @@
+foo {
+ value = 7
+ "value" = 8
+ "complex::value" = 9
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure_empty.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure_empty.hcl
new file mode 100644
index 000000000..4d156ddea
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/structure_empty.hcl
@@ -0,0 +1 @@
+resource "foo" "bar" {}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/types.hcl b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/types.hcl
new file mode 100644
index 000000000..cf2747ea1
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/test-fixtures/types.hcl
@@ -0,0 +1,7 @@
+foo = "bar"
+bar = 7
+baz = [1,2,3]
+foo = -12
+bar = 3.14159
+foo = true
+bar = false
diff --git a/vendor/github.com/hashicorp/hcl/hcl/token/position.go b/vendor/github.com/hashicorp/hcl/hcl/token/position.go
new file mode 100644
index 000000000..59c1bb72d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/token/position.go
@@ -0,0 +1,46 @@
+package token
+
+import "fmt"
+
+// Pos describes an arbitrary source position
+// including the file, line, and column location.
+// A Position is valid if the line number is > 0.
+type Pos struct {
+ Filename string // filename, if any
+ Offset int // offset, starting at 0
+ Line int // line number, starting at 1
+ Column int // column number, starting at 1 (character count)
+}
+
+// IsValid returns true if the position is valid.
+func (p *Pos) IsValid() bool { return p.Line > 0 }
+
+// String returns a string in one of several forms:
+//
+// file:line:column valid position with file name
+// line:column valid position without file name
+// file invalid position with file name
+// - invalid position without file name
+func (p Pos) String() string {
+ s := p.Filename
+ if p.IsValid() {
+ if s != "" {
+ s += ":"
+ }
+ s += fmt.Sprintf("%d:%d", p.Line, p.Column)
+ }
+ if s == "" {
+ s = "-"
+ }
+ return s
+}
+
+// Before reports whether the position p is before u.
+func (p Pos) Before(u Pos) bool {
+ return u.Offset > p.Offset || u.Line > p.Line
+}
+
+// After reports whether the position p is after u.
+func (p Pos) After(u Pos) bool {
+ return u.Offset < p.Offset || u.Line < p.Line
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/token/token.go b/vendor/github.com/hashicorp/hcl/hcl/token/token.go
new file mode 100644
index 000000000..e37c0664e
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/token/token.go
@@ -0,0 +1,219 @@
+// Package token defines constants representing the lexical tokens for HCL
+// (HashiCorp Configuration Language)
+package token
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+
+ hclstrconv "github.com/hashicorp/hcl/hcl/strconv"
+)
+
+// Token defines a single HCL token which can be obtained via the Scanner
+type Token struct {
+ Type Type
+ Pos Pos
+ Text string
+ JSON bool
+}
+
+// Type is the set of lexical tokens of the HCL (HashiCorp Configuration Language)
+type Type int
+
+const (
+ // Special tokens
+ ILLEGAL Type = iota
+ EOF
+ COMMENT
+
+ identifier_beg
+ IDENT // literals
+ literal_beg
+ NUMBER // 12345
+ FLOAT // 123.45
+ BOOL // true,false
+ STRING // "abc"
+ HEREDOC // <<FOO\nbar\nFOO
+ literal_end
+ identifier_end
+
+ operator_beg
+ LBRACK // [
+ LBRACE // {
+ COMMA // ,
+ PERIOD // .
+
+ RBRACK // ]
+ RBRACE // }
+
+ ASSIGN // =
+ ADD // +
+ SUB // -
+ operator_end
+)
+
+var tokens = [...]string{
+ ILLEGAL: "ILLEGAL",
+
+ EOF: "EOF",
+ COMMENT: "COMMENT",
+
+ IDENT: "IDENT",
+ NUMBER: "NUMBER",
+ FLOAT: "FLOAT",
+ BOOL: "BOOL",
+ STRING: "STRING",
+
+ LBRACK: "LBRACK",
+ LBRACE: "LBRACE",
+ COMMA: "COMMA",
+ PERIOD: "PERIOD",
+ HEREDOC: "HEREDOC",
+
+ RBRACK: "RBRACK",
+ RBRACE: "RBRACE",
+
+ ASSIGN: "ASSIGN",
+ ADD: "ADD",
+ SUB: "SUB",
+}
+
+// String returns the string corresponding to the token tok.
+func (t Type) String() string {
+ s := ""
+ if 0 <= t && t < Type(len(tokens)) {
+ s = tokens[t]
+ }
+ if s == "" {
+ s = "token(" + strconv.Itoa(int(t)) + ")"
+ }
+ return s
+}
+
+// IsIdentifier returns true for tokens corresponding to identifiers and basic
+// type literals; it returns false otherwise.
+func (t Type) IsIdentifier() bool { return identifier_beg < t && t < identifier_end }
+
+// IsLiteral returns true for tokens corresponding to basic type literals; it
+// returns false otherwise.
+func (t Type) IsLiteral() bool { return literal_beg < t && t < literal_end }
+
+// IsOperator returns true for tokens corresponding to operators and
+// delimiters; it returns false otherwise.
+func (t Type) IsOperator() bool { return operator_beg < t && t < operator_end }
+
+// String returns the token's literal text. Note that this is only
+// applicable for certain token types, such as token.IDENT,
+// token.STRING, etc..
+func (t Token) String() string {
+ return fmt.Sprintf("%s %s %s", t.Pos.String(), t.Type.String(), t.Text)
+}
+
+// Value returns the properly typed value for this token. The type of
+// the returned interface{} is guaranteed based on the Type field.
+//
+// This can only be called for literal types. If it is called for any other
+// type, this will panic.
+func (t Token) Value() interface{} {
+ switch t.Type {
+ case BOOL:
+ if t.Text == "true" {
+ return true
+ } else if t.Text == "false" {
+ return false
+ }
+
+ panic("unknown bool value: " + t.Text)
+ case FLOAT:
+ v, err := strconv.ParseFloat(t.Text, 64)
+ if err != nil {
+ panic(err)
+ }
+
+ return float64(v)
+ case NUMBER:
+ v, err := strconv.ParseInt(t.Text, 0, 64)
+ if err != nil {
+ panic(err)
+ }
+
+ return int64(v)
+ case IDENT:
+ return t.Text
+ case HEREDOC:
+ return unindentHeredoc(t.Text)
+ case STRING:
+ // Determine the Unquote method to use. If it came from JSON,
+ // then we need to use the built-in unquote since we have to
+ // escape interpolations there.
+ f := hclstrconv.Unquote
+ if t.JSON {
+ f = strconv.Unquote
+ }
+
+ // This case occurs if json null is used
+ if t.Text == "" {
+ return ""
+ }
+
+ v, err := f(t.Text)
+ if err != nil {
+ panic(fmt.Sprintf("unquote %s err: %s", t.Text, err))
+ }
+
+ return v
+ default:
+ panic(fmt.Sprintf("unimplemented Value for type: %s", t.Type))
+ }
+}
+
+// unindentHeredoc returns the string content of a HEREDOC if it is started with <<
+// and the content of a HEREDOC with the hanging indent removed if it is started with
+// a <<-, and the terminating line is at least as indented as the least indented line.
+func unindentHeredoc(heredoc string) string {
+ // We need to find the end of the marker
+ idx := strings.IndexByte(heredoc, '\n')
+ if idx == -1 {
+ panic("heredoc doesn't contain newline")
+ }
+
+ unindent := heredoc[2] == '-'
+
+ // We can optimize if the heredoc isn't marked for indentation
+ if !unindent {
+ return string(heredoc[idx+1 : len(heredoc)-idx+1])
+ }
+
+ // We need to unindent each line based on the indentation level of the marker
+ lines := strings.Split(string(heredoc[idx+1:len(heredoc)-idx+2]), "\n")
+ whitespacePrefix := lines[len(lines)-1]
+
+ isIndented := true
+ for _, v := range lines {
+ if strings.HasPrefix(v, whitespacePrefix) {
+ continue
+ }
+
+ isIndented = false
+ break
+ }
+
+ // If all lines are not at least as indented as the terminating mark, return the
+ // heredoc as is, but trim the leading space from the marker on the final line.
+ if !isIndented {
+ return strings.TrimRight(string(heredoc[idx+1:len(heredoc)-idx+1]), " \t")
+ }
+
+ unindentedLines := make([]string, len(lines))
+ for k, v := range lines {
+ if k == len(lines)-1 {
+ unindentedLines[k] = ""
+ break
+ }
+
+ unindentedLines[k] = strings.TrimPrefix(v, whitespacePrefix)
+ }
+
+ return strings.Join(unindentedLines, "\n")
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/token/token_test.go b/vendor/github.com/hashicorp/hcl/hcl/token/token_test.go
new file mode 100644
index 000000000..e4b4af25b
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl/token/token_test.go
@@ -0,0 +1,69 @@
+package token
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestTypeString(t *testing.T) {
+ var tokens = []struct {
+ tt Type
+ str string
+ }{
+ {ILLEGAL, "ILLEGAL"},
+ {EOF, "EOF"},
+ {COMMENT, "COMMENT"},
+ {IDENT, "IDENT"},
+ {NUMBER, "NUMBER"},
+ {FLOAT, "FLOAT"},
+ {BOOL, "BOOL"},
+ {STRING, "STRING"},
+ {HEREDOC, "HEREDOC"},
+ {LBRACK, "LBRACK"},
+ {LBRACE, "LBRACE"},
+ {COMMA, "COMMA"},
+ {PERIOD, "PERIOD"},
+ {RBRACK, "RBRACK"},
+ {RBRACE, "RBRACE"},
+ {ASSIGN, "ASSIGN"},
+ {ADD, "ADD"},
+ {SUB, "SUB"},
+ }
+
+ for _, token := range tokens {
+ if token.tt.String() != token.str {
+ t.Errorf("want: %q got:%q\n", token.str, token.tt)
+ }
+ }
+
+}
+
+func TestTokenValue(t *testing.T) {
+ var tokens = []struct {
+ tt Token
+ v interface{}
+ }{
+ {Token{Type: BOOL, Text: `true`}, true},
+ {Token{Type: BOOL, Text: `false`}, false},
+ {Token{Type: FLOAT, Text: `3.14`}, float64(3.14)},
+ {Token{Type: NUMBER, Text: `42`}, int64(42)},
+ {Token{Type: IDENT, Text: `foo`}, "foo"},
+ {Token{Type: STRING, Text: `"foo"`}, "foo"},
+ {Token{Type: STRING, Text: `"foo\nbar"`}, "foo\nbar"},
+ {Token{Type: STRING, Text: `"${file("foo")}"`}, `${file("foo")}`},
+ {
+ Token{
+ Type: STRING,
+ Text: `"${replace("foo", ".", "\\.")}"`,
+ },
+ `${replace("foo", ".", "\\.")}`},
+ {Token{Type: HEREDOC, Text: "<<EOF\nfoo\nbar\nEOF"}, "foo\nbar"},
+ }
+
+ for _, token := range tokens {
+ if val := token.tt.Value(); !reflect.DeepEqual(val, token.v) {
+ t.Errorf("want: %v got:%v\n", token.v, val)
+ }
+ }
+
+}
diff --git a/vendor/github.com/hashicorp/hcl/hcl_test.go b/vendor/github.com/hashicorp/hcl/hcl_test.go
new file mode 100644
index 000000000..31dff7c9e
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/hcl_test.go
@@ -0,0 +1,19 @@
+package hcl
+
+import (
+ "io/ioutil"
+ "path/filepath"
+ "testing"
+)
+
+// This is the directory where our test fixtures are.
+const fixtureDir = "./test-fixtures"
+
+func testReadFile(t *testing.T, n string) string {
+ d, err := ioutil.ReadFile(filepath.Join(fixtureDir, n))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ return string(d)
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/flatten.go b/vendor/github.com/hashicorp/hcl/json/parser/flatten.go
new file mode 100644
index 000000000..f652d6fe7
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/parser/flatten.go
@@ -0,0 +1,117 @@
+package parser
+
+import "github.com/hashicorp/hcl/hcl/ast"
+
+// flattenObjects takes an AST node, walks it, and flattens
+func flattenObjects(node ast.Node) {
+ ast.Walk(node, func(n ast.Node) (ast.Node, bool) {
+ // We only care about lists, because this is what we modify
+ list, ok := n.(*ast.ObjectList)
+ if !ok {
+ return n, true
+ }
+
+ // Rebuild the item list
+ items := make([]*ast.ObjectItem, 0, len(list.Items))
+ frontier := make([]*ast.ObjectItem, len(list.Items))
+ copy(frontier, list.Items)
+ for len(frontier) > 0 {
+ // Pop the current item
+ n := len(frontier)
+ item := frontier[n-1]
+ frontier = frontier[:n-1]
+
+ switch v := item.Val.(type) {
+ case *ast.ObjectType:
+ items, frontier = flattenObjectType(v, item, items, frontier)
+ case *ast.ListType:
+ items, frontier = flattenListType(v, item, items, frontier)
+ default:
+ items = append(items, item)
+ }
+ }
+
+ // Reverse the list since the frontier model runs things backwards
+ for i := len(items)/2 - 1; i >= 0; i-- {
+ opp := len(items) - 1 - i
+ items[i], items[opp] = items[opp], items[i]
+ }
+
+ // Done! Set the original items
+ list.Items = items
+ return n, true
+ })
+}
+
+func flattenListType(
+ ot *ast.ListType,
+ item *ast.ObjectItem,
+ items []*ast.ObjectItem,
+ frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) {
+ // If the list is empty, keep the original list
+ if len(ot.List) == 0 {
+ items = append(items, item)
+ return items, frontier
+ }
+
+ // All the elements of this object must also be objects!
+ for _, subitem := range ot.List {
+ if _, ok := subitem.(*ast.ObjectType); !ok {
+ items = append(items, item)
+ return items, frontier
+ }
+ }
+
+ // Great! We have a match go through all the items and flatten
+ for _, elem := range ot.List {
+ // Add it to the frontier so that we can recurse
+ frontier = append(frontier, &ast.ObjectItem{
+ Keys: item.Keys,
+ Assign: item.Assign,
+ Val: elem,
+ LeadComment: item.LeadComment,
+ LineComment: item.LineComment,
+ })
+ }
+
+ return items, frontier
+}
+
+func flattenObjectType(
+ ot *ast.ObjectType,
+ item *ast.ObjectItem,
+ items []*ast.ObjectItem,
+ frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) {
+ // If the list has no items we do not have to flatten anything
+ if ot.List.Items == nil {
+ items = append(items, item)
+ return items, frontier
+ }
+
+ // All the elements of this object must also be objects!
+ for _, subitem := range ot.List.Items {
+ if _, ok := subitem.Val.(*ast.ObjectType); !ok {
+ items = append(items, item)
+ return items, frontier
+ }
+ }
+
+ // Great! We have a match go through all the items and flatten
+ for _, subitem := range ot.List.Items {
+ // Copy the new key
+ keys := make([]*ast.ObjectKey, len(item.Keys)+len(subitem.Keys))
+ copy(keys, item.Keys)
+ copy(keys[len(item.Keys):], subitem.Keys)
+
+ // Add it to the frontier so that we can recurse
+ frontier = append(frontier, &ast.ObjectItem{
+ Keys: keys,
+ Assign: item.Assign,
+ Val: subitem.Val,
+ LeadComment: item.LeadComment,
+ LineComment: item.LineComment,
+ })
+ }
+
+ return items, frontier
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/parser.go b/vendor/github.com/hashicorp/hcl/json/parser/parser.go
new file mode 100644
index 000000000..6f4608530
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/parser/parser.go
@@ -0,0 +1,313 @@
+package parser
+
+import (
+ "errors"
+ "fmt"
+
+ "github.com/hashicorp/hcl/hcl/ast"
+ hcltoken "github.com/hashicorp/hcl/hcl/token"
+ "github.com/hashicorp/hcl/json/scanner"
+ "github.com/hashicorp/hcl/json/token"
+)
+
+type Parser struct {
+ sc *scanner.Scanner
+
+ // Last read token
+ tok token.Token
+ commaPrev token.Token
+
+ enableTrace bool
+ indent int
+ n int // buffer size (max = 1)
+}
+
+func newParser(src []byte) *Parser {
+ return &Parser{
+ sc: scanner.New(src),
+ }
+}
+
+// Parse returns the fully parsed source and returns the abstract syntax tree.
+func Parse(src []byte) (*ast.File, error) {
+ p := newParser(src)
+ return p.Parse()
+}
+
+var errEofToken = errors.New("EOF token found")
+
+// Parse returns the fully parsed source and returns the abstract syntax tree.
+func (p *Parser) Parse() (*ast.File, error) {
+ f := &ast.File{}
+ var err, scerr error
+ p.sc.Error = func(pos token.Pos, msg string) {
+ scerr = fmt.Errorf("%s: %s", pos, msg)
+ }
+
+ // The root must be an object in JSON
+ object, err := p.object()
+ if scerr != nil {
+ return nil, scerr
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ // We make our final node an object list so it is more HCL compatible
+ f.Node = object.List
+
+ // Flatten it, which finds patterns and turns them into more HCL-like
+ // AST trees.
+ flattenObjects(f.Node)
+
+ return f, nil
+}
+
+func (p *Parser) objectList() (*ast.ObjectList, error) {
+ defer un(trace(p, "ParseObjectList"))
+ node := &ast.ObjectList{}
+
+ for {
+ n, err := p.objectItem()
+ if err == errEofToken {
+ break // we are finished
+ }
+
+ // we don't return a nil node, because might want to use already
+ // collected items.
+ if err != nil {
+ return node, err
+ }
+
+ node.Add(n)
+
+ // Check for a followup comma. If it isn't a comma, then we're done
+ if tok := p.scan(); tok.Type != token.COMMA {
+ break
+ }
+ }
+
+ return node, nil
+}
+
+// objectItem parses a single object item
+func (p *Parser) objectItem() (*ast.ObjectItem, error) {
+ defer un(trace(p, "ParseObjectItem"))
+
+ keys, err := p.objectKey()
+ if err != nil {
+ return nil, err
+ }
+
+ o := &ast.ObjectItem{
+ Keys: keys,
+ }
+
+ switch p.tok.Type {
+ case token.COLON:
+ pos := p.tok.Pos
+ o.Assign = hcltoken.Pos{
+ Filename: pos.Filename,
+ Offset: pos.Offset,
+ Line: pos.Line,
+ Column: pos.Column,
+ }
+
+ o.Val, err = p.objectValue()
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ return o, nil
+}
+
+// objectKey parses an object key and returns a ObjectKey AST
+func (p *Parser) objectKey() ([]*ast.ObjectKey, error) {
+ keyCount := 0
+ keys := make([]*ast.ObjectKey, 0)
+
+ for {
+ tok := p.scan()
+ switch tok.Type {
+ case token.EOF:
+ return nil, errEofToken
+ case token.STRING:
+ keyCount++
+ keys = append(keys, &ast.ObjectKey{
+ Token: p.tok.HCLToken(),
+ })
+ case token.COLON:
+ // If we have a zero keycount it means that we never got
+ // an object key, i.e. `{ :`. This is a syntax error.
+ if keyCount == 0 {
+ return nil, fmt.Errorf("expected: STRING got: %s", p.tok.Type)
+ }
+
+ // Done
+ return keys, nil
+ case token.ILLEGAL:
+ fmt.Println("illegal")
+ default:
+ return nil, fmt.Errorf("expected: STRING got: %s", p.tok.Type)
+ }
+ }
+}
+
+// object parses any type of object, such as number, bool, string, object or
+// list.
+func (p *Parser) objectValue() (ast.Node, error) {
+ defer un(trace(p, "ParseObjectValue"))
+ tok := p.scan()
+
+ switch tok.Type {
+ case token.NUMBER, token.FLOAT, token.BOOL, token.NULL, token.STRING:
+ return p.literalType()
+ case token.LBRACE:
+ return p.objectType()
+ case token.LBRACK:
+ return p.listType()
+ case token.EOF:
+ return nil, errEofToken
+ }
+
+ return nil, fmt.Errorf("Expected object value, got unknown token: %+v", tok)
+}
+
+// object parses any type of object, such as number, bool, string, object or
+// list.
+func (p *Parser) object() (*ast.ObjectType, error) {
+ defer un(trace(p, "ParseType"))
+ tok := p.scan()
+
+ switch tok.Type {
+ case token.LBRACE:
+ return p.objectType()
+ case token.EOF:
+ return nil, errEofToken
+ }
+
+ return nil, fmt.Errorf("Expected object, got unknown token: %+v", tok)
+}
+
+// objectType parses an object type and returns a ObjectType AST
+func (p *Parser) objectType() (*ast.ObjectType, error) {
+ defer un(trace(p, "ParseObjectType"))
+
+ // we assume that the currently scanned token is a LBRACE
+ o := &ast.ObjectType{}
+
+ l, err := p.objectList()
+
+ // if we hit RBRACE, we are good to go (means we parsed all Items), if it's
+ // not a RBRACE, it's an syntax error and we just return it.
+ if err != nil && p.tok.Type != token.RBRACE {
+ return nil, err
+ }
+
+ o.List = l
+ return o, nil
+}
+
+// listType parses a list type and returns a ListType AST
+func (p *Parser) listType() (*ast.ListType, error) {
+ defer un(trace(p, "ParseListType"))
+
+ // we assume that the currently scanned token is a LBRACK
+ l := &ast.ListType{}
+
+ for {
+ tok := p.scan()
+ switch tok.Type {
+ case token.NUMBER, token.FLOAT, token.STRING:
+ node, err := p.literalType()
+ if err != nil {
+ return nil, err
+ }
+
+ l.Add(node)
+ case token.COMMA:
+ continue
+ case token.LBRACE:
+ node, err := p.objectType()
+ if err != nil {
+ return nil, err
+ }
+
+ l.Add(node)
+ case token.BOOL:
+ // TODO(arslan) should we support? not supported by HCL yet
+ case token.LBRACK:
+ // TODO(arslan) should we support nested lists? Even though it's
+ // written in README of HCL, it's not a part of the grammar
+ // (not defined in parse.y)
+ case token.RBRACK:
+ // finished
+ return l, nil
+ default:
+ return nil, fmt.Errorf("unexpected token while parsing list: %s", tok.Type)
+ }
+
+ }
+}
+
+// literalType parses a literal type and returns a LiteralType AST
+func (p *Parser) literalType() (*ast.LiteralType, error) {
+ defer un(trace(p, "ParseLiteral"))
+
+ return &ast.LiteralType{
+ Token: p.tok.HCLToken(),
+ }, nil
+}
+
+// scan returns the next token from the underlying scanner. If a token has
+// been unscanned then read that instead.
+func (p *Parser) scan() token.Token {
+ // If we have a token on the buffer, then return it.
+ if p.n != 0 {
+ p.n = 0
+ return p.tok
+ }
+
+ p.tok = p.sc.Scan()
+ return p.tok
+}
+
+// unscan pushes the previously read token back onto the buffer.
+func (p *Parser) unscan() {
+ p.n = 1
+}
+
+// ----------------------------------------------------------------------------
+// Parsing support
+
+func (p *Parser) printTrace(a ...interface{}) {
+ if !p.enableTrace {
+ return
+ }
+
+ const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+ const n = len(dots)
+ fmt.Printf("%5d:%3d: ", p.tok.Pos.Line, p.tok.Pos.Column)
+
+ i := 2 * p.indent
+ for i > n {
+ fmt.Print(dots)
+ i -= n
+ }
+ // i <= n
+ fmt.Print(dots[0:i])
+ fmt.Println(a...)
+}
+
+func trace(p *Parser, msg string) *Parser {
+ p.printTrace(msg, "(")
+ p.indent++
+ return p
+}
+
+// Usage pattern: defer un(trace(p, "..."))
+func un(p *Parser) {
+ p.indent--
+ p.printTrace(")")
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/parser_test.go b/vendor/github.com/hashicorp/hcl/json/parser/parser_test.go
new file mode 100644
index 000000000..e0cebf50a
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/parser/parser_test.go
@@ -0,0 +1,384 @@
+package parser
+
+import (
+ "fmt"
+ "io/ioutil"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "testing"
+
+ "github.com/hashicorp/hcl/hcl/ast"
+ "github.com/hashicorp/hcl/hcl/token"
+)
+
+func TestType(t *testing.T) {
+ var literals = []struct {
+ typ token.Type
+ src string
+ }{
+ {token.STRING, `"foo": "bar"`},
+ {token.NUMBER, `"foo": 123`},
+ {token.FLOAT, `"foo": 123.12`},
+ {token.FLOAT, `"foo": -123.12`},
+ {token.BOOL, `"foo": true`},
+ {token.STRING, `"foo": null`},
+ }
+
+ for _, l := range literals {
+ t.Logf("Testing: %s", l.src)
+
+ p := newParser([]byte(l.src))
+ item, err := p.objectItem()
+ if err != nil {
+ t.Error(err)
+ }
+
+ lit, ok := item.Val.(*ast.LiteralType)
+ if !ok {
+ t.Errorf("node should be of type LiteralType, got: %T", item.Val)
+ }
+
+ if lit.Token.Type != l.typ {
+ t.Errorf("want: %s, got: %s", l.typ, lit.Token.Type)
+ }
+ }
+}
+
+func TestListType(t *testing.T) {
+ var literals = []struct {
+ src string
+ tokens []token.Type
+ }{
+ {
+ `"foo": ["123", 123]`,
+ []token.Type{token.STRING, token.NUMBER},
+ },
+ {
+ `"foo": [123, "123",]`,
+ []token.Type{token.NUMBER, token.STRING},
+ },
+ {
+ `"foo": []`,
+ []token.Type{},
+ },
+ {
+ `"foo": ["123", 123]`,
+ []token.Type{token.STRING, token.NUMBER},
+ },
+ {
+ `"foo": ["123", {}]`,
+ []token.Type{token.STRING, token.LBRACE},
+ },
+ }
+
+ for _, l := range literals {
+ t.Logf("Testing: %s", l.src)
+
+ p := newParser([]byte(l.src))
+ item, err := p.objectItem()
+ if err != nil {
+ t.Error(err)
+ }
+
+ list, ok := item.Val.(*ast.ListType)
+ if !ok {
+ t.Errorf("node should be of type LiteralType, got: %T", item.Val)
+ }
+
+ tokens := []token.Type{}
+ for _, li := range list.List {
+ switch v := li.(type) {
+ case *ast.LiteralType:
+ tokens = append(tokens, v.Token.Type)
+ case *ast.ObjectType:
+ tokens = append(tokens, token.LBRACE)
+ }
+ }
+
+ equals(t, l.tokens, tokens)
+ }
+}
+
+func TestObjectType(t *testing.T) {
+ var literals = []struct {
+ src string
+ nodeType []ast.Node
+ itemLen int
+ }{
+ {
+ `"foo": {}`,
+ nil,
+ 0,
+ },
+ {
+ `"foo": {
+ "bar": "fatih"
+ }`,
+ []ast.Node{&ast.LiteralType{}},
+ 1,
+ },
+ {
+ `"foo": {
+ "bar": "fatih",
+ "baz": ["arslan"]
+ }`,
+ []ast.Node{
+ &ast.LiteralType{},
+ &ast.ListType{},
+ },
+ 2,
+ },
+ {
+ `"foo": {
+ "bar": {}
+ }`,
+ []ast.Node{
+ &ast.ObjectType{},
+ },
+ 1,
+ },
+ {
+ `"foo": {
+ "bar": {},
+ "foo": true
+ }`,
+ []ast.Node{
+ &ast.ObjectType{},
+ &ast.LiteralType{},
+ },
+ 2,
+ },
+ }
+
+ for _, l := range literals {
+ t.Logf("Testing:\n%s\n", l.src)
+
+ p := newParser([]byte(l.src))
+ // p.enableTrace = true
+ item, err := p.objectItem()
+ if err != nil {
+ t.Error(err)
+ }
+
+ // we know that the ObjectKey name is foo for all cases, what matters
+ // is the object
+ obj, ok := item.Val.(*ast.ObjectType)
+ if !ok {
+ t.Errorf("node should be of type LiteralType, got: %T", item.Val)
+ }
+
+ // check if the total length of items are correct
+ equals(t, l.itemLen, len(obj.List.Items))
+
+ // check if the types are correct
+ for i, item := range obj.List.Items {
+ equals(t, reflect.TypeOf(l.nodeType[i]), reflect.TypeOf(item.Val))
+ }
+ }
+}
+
+func TestFlattenObjects(t *testing.T) {
+ var literals = []struct {
+ src string
+ nodeType []ast.Node
+ itemLen int
+ }{
+ {
+ `{
+ "foo": [
+ {
+ "foo": "svh",
+ "bar": "fatih"
+ }
+ ]
+ }`,
+ []ast.Node{
+ &ast.ObjectType{},
+ &ast.LiteralType{},
+ &ast.LiteralType{},
+ },
+ 3,
+ },
+ {
+ `{
+ "variable": {
+ "foo": {}
+ }
+ }`,
+ []ast.Node{
+ &ast.ObjectType{},
+ },
+ 1,
+ },
+ {
+ `{
+ "empty": []
+ }`,
+ []ast.Node{
+ &ast.ListType{},
+ },
+ 1,
+ },
+ {
+ `{
+ "basic": [1, 2, 3]
+ }`,
+ []ast.Node{
+ &ast.ListType{},
+ },
+ 1,
+ },
+ }
+
+ for _, l := range literals {
+ t.Logf("Testing:\n%s\n", l.src)
+
+ f, err := Parse([]byte(l.src))
+ if err != nil {
+ t.Error(err)
+ }
+
+ // the first object is always an ObjectList so just assert that one
+ // so we can use it as such
+ obj, ok := f.Node.(*ast.ObjectList)
+ if !ok {
+ t.Errorf("node should be *ast.ObjectList, got: %T", f.Node)
+ }
+
+ // check if the types are correct
+ var i int
+ for _, item := range obj.Items {
+ equals(t, reflect.TypeOf(l.nodeType[i]), reflect.TypeOf(item.Val))
+ i++
+
+ if obj, ok := item.Val.(*ast.ObjectType); ok {
+ for _, item := range obj.List.Items {
+ equals(t, reflect.TypeOf(l.nodeType[i]), reflect.TypeOf(item.Val))
+ i++
+ }
+ }
+ }
+
+ // check if the number of items is correct
+ equals(t, l.itemLen, i)
+
+ }
+}
+
+func TestObjectKey(t *testing.T) {
+ keys := []struct {
+ exp []token.Type
+ src string
+ }{
+ {[]token.Type{token.STRING}, `"foo": {}`},
+ }
+
+ for _, k := range keys {
+ p := newParser([]byte(k.src))
+ keys, err := p.objectKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ tokens := []token.Type{}
+ for _, o := range keys {
+ tokens = append(tokens, o.Token.Type)
+ }
+
+ equals(t, k.exp, tokens)
+ }
+
+ errKeys := []struct {
+ src string
+ }{
+ {`foo 12 {}`},
+ {`foo bar = {}`},
+ {`foo []`},
+ {`12 {}`},
+ }
+
+ for _, k := range errKeys {
+ p := newParser([]byte(k.src))
+ _, err := p.objectKey()
+ if err == nil {
+ t.Errorf("case '%s' should give an error", k.src)
+ }
+ }
+}
+
+// Official HCL tests
+func TestParse(t *testing.T) {
+ cases := []struct {
+ Name string
+ Err bool
+ }{
+ {
+ "array.json",
+ false,
+ },
+ {
+ "basic.json",
+ false,
+ },
+ {
+ "object.json",
+ false,
+ },
+ {
+ "types.json",
+ false,
+ },
+ {
+ "bad_input_128.json",
+ true,
+ },
+ {
+ "bad_input_tf_8110.json",
+ true,
+ },
+ {
+ "good_input_tf_8110.json",
+ false,
+ },
+ }
+
+ const fixtureDir = "./test-fixtures"
+
+ for _, tc := range cases {
+ d, err := ioutil.ReadFile(filepath.Join(fixtureDir, tc.Name))
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ _, err = Parse(d)
+ if (err != nil) != tc.Err {
+ t.Fatalf("Input: %s\n\nError: %s", tc.Name, err)
+ }
+ }
+}
+
+func TestParse_inline(t *testing.T) {
+ cases := []struct {
+ Value string
+ Err bool
+ }{
+ {"{:{", true},
+ }
+
+ for _, tc := range cases {
+ _, err := Parse([]byte(tc.Value))
+ if (err != nil) != tc.Err {
+ t.Fatalf("Input: %q\n\nError: %s", tc.Value, err)
+ }
+ }
+}
+
+// equals fails the test if exp is not equal to act.
+func equals(tb testing.TB, exp, act interface{}) {
+ if !reflect.DeepEqual(exp, act) {
+ _, file, line, _ := runtime.Caller(1)
+ fmt.Printf("\033[31m%s:%d:\n\n\texp: %s\n\n\tgot: %s\033[39m\n\n", filepath.Base(file), line, exp, act)
+ tb.FailNow()
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/array.json b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/array.json
new file mode 100644
index 000000000..e320f17ab
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/array.json
@@ -0,0 +1,4 @@
+{
+ "foo": [1, 2, "bar"],
+ "bar": "baz"
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/bad_input_128.json b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/bad_input_128.json
new file mode 100644
index 000000000..b5f850c96
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/bad_input_128.json
@@ -0,0 +1 @@
+{:{
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/bad_input_tf_8110.json b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/bad_input_tf_8110.json
new file mode 100644
index 000000000..a04385833
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/bad_input_tf_8110.json
@@ -0,0 +1,7 @@
+{
+ "variable": {
+ "poc": {
+ "default": "${replace("europe-west", "-", " ")}"
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/basic.json b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/basic.json
new file mode 100644
index 000000000..b54bde96c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/basic.json
@@ -0,0 +1,3 @@
+{
+ "foo": "bar"
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/good_input_tf_8110.json b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/good_input_tf_8110.json
new file mode 100644
index 000000000..f21aa090d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/good_input_tf_8110.json
@@ -0,0 +1,7 @@
+{
+ "variable": {
+ "poc": {
+ "default": "${replace(\"europe-west\", \"-\", \" \")}"
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/object.json b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/object.json
new file mode 100644
index 000000000..72168a3cc
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/object.json
@@ -0,0 +1,5 @@
+{
+ "foo": {
+ "bar": [1,2]
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/types.json b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/types.json
new file mode 100644
index 000000000..9a142a6ca
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/parser/test-fixtures/types.json
@@ -0,0 +1,10 @@
+{
+ "foo": "bar",
+ "bar": 7,
+ "baz": [1,2,3],
+ "foo": -12,
+ "bar": 3.14159,
+ "foo": true,
+ "bar": false,
+ "foo": null
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go
new file mode 100644
index 000000000..dd5c72bb3
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go
@@ -0,0 +1,451 @@
+package scanner
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/hashicorp/hcl/json/token"
+)
+
+// eof represents a marker rune for the end of the reader.
+const eof = rune(0)
+
+// Scanner defines a lexical scanner
+type Scanner struct {
+ buf *bytes.Buffer // Source buffer for advancing and scanning
+ src []byte // Source buffer for immutable access
+
+ // Source Position
+ srcPos token.Pos // current position
+ prevPos token.Pos // previous position, used for peek() method
+
+ lastCharLen int // length of last character in bytes
+ lastLineLen int // length of last line in characters (for correct column reporting)
+
+ tokStart int // token text start position
+ tokEnd int // token text end position
+
+ // Error is called for each error encountered. If no Error
+ // function is set, the error is reported to os.Stderr.
+ Error func(pos token.Pos, msg string)
+
+ // ErrorCount is incremented by one for each error encountered.
+ ErrorCount int
+
+ // tokPos is the start position of most recently scanned token; set by
+ // Scan. The Filename field is always left untouched by the Scanner. If
+ // an error is reported (via Error) and Position is invalid, the scanner is
+ // not inside a token.
+ tokPos token.Pos
+}
+
+// New creates and initializes a new instance of Scanner using src as
+// its source content.
+func New(src []byte) *Scanner {
+ // even though we accept a src, we read from a io.Reader compatible type
+ // (*bytes.Buffer). So in the future we might easily change it to streaming
+ // read.
+ b := bytes.NewBuffer(src)
+ s := &Scanner{
+ buf: b,
+ src: src,
+ }
+
+ // srcPosition always starts with 1
+ s.srcPos.Line = 1
+ return s
+}
+
+// next reads the next rune from the bufferred reader. Returns the rune(0) if
+// an error occurs (or io.EOF is returned).
+func (s *Scanner) next() rune {
+ ch, size, err := s.buf.ReadRune()
+ if err != nil {
+ // advance for error reporting
+ s.srcPos.Column++
+ s.srcPos.Offset += size
+ s.lastCharLen = size
+ return eof
+ }
+
+ if ch == utf8.RuneError && size == 1 {
+ s.srcPos.Column++
+ s.srcPos.Offset += size
+ s.lastCharLen = size
+ s.err("illegal UTF-8 encoding")
+ return ch
+ }
+
+ // remember last position
+ s.prevPos = s.srcPos
+
+ s.srcPos.Column++
+ s.lastCharLen = size
+ s.srcPos.Offset += size
+
+ if ch == '\n' {
+ s.srcPos.Line++
+ s.lastLineLen = s.srcPos.Column
+ s.srcPos.Column = 0
+ }
+
+ // debug
+ // fmt.Printf("ch: %q, offset:column: %d:%d\n", ch, s.srcPos.Offset, s.srcPos.Column)
+ return ch
+}
+
+// unread unreads the previous read Rune and updates the source position
+func (s *Scanner) unread() {
+ if err := s.buf.UnreadRune(); err != nil {
+ panic(err) // this is user fault, we should catch it
+ }
+ s.srcPos = s.prevPos // put back last position
+}
+
+// peek returns the next rune without advancing the reader.
+func (s *Scanner) peek() rune {
+ peek, _, err := s.buf.ReadRune()
+ if err != nil {
+ return eof
+ }
+
+ s.buf.UnreadRune()
+ return peek
+}
+
+// Scan scans the next token and returns the token.
+func (s *Scanner) Scan() token.Token {
+ ch := s.next()
+
+ // skip white space
+ for isWhitespace(ch) {
+ ch = s.next()
+ }
+
+ var tok token.Type
+
+ // token text markings
+ s.tokStart = s.srcPos.Offset - s.lastCharLen
+
+ // token position, initial next() is moving the offset by one(size of rune
+ // actually), though we are interested with the starting point
+ s.tokPos.Offset = s.srcPos.Offset - s.lastCharLen
+ if s.srcPos.Column > 0 {
+ // common case: last character was not a '\n'
+ s.tokPos.Line = s.srcPos.Line
+ s.tokPos.Column = s.srcPos.Column
+ } else {
+ // last character was a '\n'
+ // (we cannot be at the beginning of the source
+ // since we have called next() at least once)
+ s.tokPos.Line = s.srcPos.Line - 1
+ s.tokPos.Column = s.lastLineLen
+ }
+
+ switch {
+ case isLetter(ch):
+ lit := s.scanIdentifier()
+ if lit == "true" || lit == "false" {
+ tok = token.BOOL
+ } else if lit == "null" {
+ tok = token.NULL
+ } else {
+ s.err("illegal char")
+ }
+ case isDecimal(ch):
+ tok = s.scanNumber(ch)
+ default:
+ switch ch {
+ case eof:
+ tok = token.EOF
+ case '"':
+ tok = token.STRING
+ s.scanString()
+ case '.':
+ tok = token.PERIOD
+ ch = s.peek()
+ if isDecimal(ch) {
+ tok = token.FLOAT
+ ch = s.scanMantissa(ch)
+ ch = s.scanExponent(ch)
+ }
+ case '[':
+ tok = token.LBRACK
+ case ']':
+ tok = token.RBRACK
+ case '{':
+ tok = token.LBRACE
+ case '}':
+ tok = token.RBRACE
+ case ',':
+ tok = token.COMMA
+ case ':':
+ tok = token.COLON
+ case '-':
+ if isDecimal(s.peek()) {
+ ch := s.next()
+ tok = s.scanNumber(ch)
+ } else {
+ s.err("illegal char")
+ }
+ default:
+ s.err("illegal char: " + string(ch))
+ }
+ }
+
+ // finish token ending
+ s.tokEnd = s.srcPos.Offset
+
+ // create token literal
+ var tokenText string
+ if s.tokStart >= 0 {
+ tokenText = string(s.src[s.tokStart:s.tokEnd])
+ }
+ s.tokStart = s.tokEnd // ensure idempotency of tokenText() call
+
+ return token.Token{
+ Type: tok,
+ Pos: s.tokPos,
+ Text: tokenText,
+ }
+}
+
+// scanNumber scans a HCL number definition starting with the given rune
+func (s *Scanner) scanNumber(ch rune) token.Type {
+ zero := ch == '0'
+ pos := s.srcPos
+
+ s.scanMantissa(ch)
+ ch = s.next() // seek forward
+ if ch == 'e' || ch == 'E' {
+ ch = s.scanExponent(ch)
+ return token.FLOAT
+ }
+
+ if ch == '.' {
+ ch = s.scanFraction(ch)
+ if ch == 'e' || ch == 'E' {
+ ch = s.next()
+ ch = s.scanExponent(ch)
+ }
+ return token.FLOAT
+ }
+
+ if ch != eof {
+ s.unread()
+ }
+
+ // If we have a larger number and this is zero, error
+ if zero && pos != s.srcPos {
+ s.err("numbers cannot start with 0")
+ }
+
+ return token.NUMBER
+}
+
+// scanMantissa scans the mantissa begining from the rune. It returns the next
+// non decimal rune. It's used to determine wheter it's a fraction or exponent.
+func (s *Scanner) scanMantissa(ch rune) rune {
+ scanned := false
+ for isDecimal(ch) {
+ ch = s.next()
+ scanned = true
+ }
+
+ if scanned && ch != eof {
+ s.unread()
+ }
+ return ch
+}
+
+// scanFraction scans the fraction after the '.' rune
+func (s *Scanner) scanFraction(ch rune) rune {
+ if ch == '.' {
+ ch = s.peek() // we peek just to see if we can move forward
+ ch = s.scanMantissa(ch)
+ }
+ return ch
+}
+
+// scanExponent scans the remaining parts of an exponent after the 'e' or 'E'
+// rune.
+func (s *Scanner) scanExponent(ch rune) rune {
+ if ch == 'e' || ch == 'E' {
+ ch = s.next()
+ if ch == '-' || ch == '+' {
+ ch = s.next()
+ }
+ ch = s.scanMantissa(ch)
+ }
+ return ch
+}
+
+// scanString scans a quoted string
+func (s *Scanner) scanString() {
+ braces := 0
+ for {
+ // '"' opening already consumed
+ // read character after quote
+ ch := s.next()
+
+ if ch == '\n' || ch < 0 || ch == eof {
+ s.err("literal not terminated")
+ return
+ }
+
+ if ch == '"' {
+ break
+ }
+
+ // If we're going into a ${} then we can ignore quotes for awhile
+ if braces == 0 && ch == '$' && s.peek() == '{' {
+ braces++
+ s.next()
+ } else if braces > 0 && ch == '{' {
+ braces++
+ }
+ if braces > 0 && ch == '}' {
+ braces--
+ }
+
+ if ch == '\\' {
+ s.scanEscape()
+ }
+ }
+
+ return
+}
+
+// scanEscape scans an escape sequence
+func (s *Scanner) scanEscape() rune {
+ // http://en.cppreference.com/w/cpp/language/escape
+ ch := s.next() // read character after '/'
+ switch ch {
+ case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"':
+ // nothing to do
+ case '0', '1', '2', '3', '4', '5', '6', '7':
+ // octal notation
+ ch = s.scanDigits(ch, 8, 3)
+ case 'x':
+ // hexademical notation
+ ch = s.scanDigits(s.next(), 16, 2)
+ case 'u':
+ // universal character name
+ ch = s.scanDigits(s.next(), 16, 4)
+ case 'U':
+ // universal character name
+ ch = s.scanDigits(s.next(), 16, 8)
+ default:
+ s.err("illegal char escape")
+ }
+ return ch
+}
+
+// scanDigits scans a rune with the given base for n times. For example an
+// octal notation \184 would yield in scanDigits(ch, 8, 3)
+func (s *Scanner) scanDigits(ch rune, base, n int) rune {
+ for n > 0 && digitVal(ch) < base {
+ ch = s.next()
+ n--
+ }
+ if n > 0 {
+ s.err("illegal char escape")
+ }
+
+ // we scanned all digits, put the last non digit char back
+ s.unread()
+ return ch
+}
+
+// scanIdentifier scans an identifier and returns the literal string
+func (s *Scanner) scanIdentifier() string {
+ offs := s.srcPos.Offset - s.lastCharLen
+ ch := s.next()
+ for isLetter(ch) || isDigit(ch) || ch == '-' {
+ ch = s.next()
+ }
+
+ if ch != eof {
+ s.unread() // we got identifier, put back latest char
+ }
+
+ return string(s.src[offs:s.srcPos.Offset])
+}
+
+// recentPosition returns the position of the character immediately after the
+// character or token returned by the last call to Scan.
+func (s *Scanner) recentPosition() (pos token.Pos) {
+ pos.Offset = s.srcPos.Offset - s.lastCharLen
+ switch {
+ case s.srcPos.Column > 0:
+ // common case: last character was not a '\n'
+ pos.Line = s.srcPos.Line
+ pos.Column = s.srcPos.Column
+ case s.lastLineLen > 0:
+ // last character was a '\n'
+ // (we cannot be at the beginning of the source
+ // since we have called next() at least once)
+ pos.Line = s.srcPos.Line - 1
+ pos.Column = s.lastLineLen
+ default:
+ // at the beginning of the source
+ pos.Line = 1
+ pos.Column = 1
+ }
+ return
+}
+
+// err prints the error of any scanning to s.Error function. If the function is
+// not defined, by default it prints them to os.Stderr
+func (s *Scanner) err(msg string) {
+ s.ErrorCount++
+ pos := s.recentPosition()
+
+ if s.Error != nil {
+ s.Error(pos, msg)
+ return
+ }
+
+ fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg)
+}
+
+// isHexadecimal returns true if the given rune is a letter
+func isLetter(ch rune) bool {
+ return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
+}
+
+// isHexadecimal returns true if the given rune is a decimal digit
+func isDigit(ch rune) bool {
+ return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch)
+}
+
+// isHexadecimal returns true if the given rune is a decimal number
+func isDecimal(ch rune) bool {
+ return '0' <= ch && ch <= '9'
+}
+
+// isHexadecimal returns true if the given rune is an hexadecimal number
+func isHexadecimal(ch rune) bool {
+ return '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' || 'A' <= ch && ch <= 'F'
+}
+
+// isWhitespace returns true if the rune is a space, tab, newline or carriage return
+func isWhitespace(ch rune) bool {
+ return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
+}
+
+// digitVal returns the integer value of a given octal,decimal or hexadecimal rune
+func digitVal(ch rune) int {
+ switch {
+ case '0' <= ch && ch <= '9':
+ return int(ch - '0')
+ case 'a' <= ch && ch <= 'f':
+ return int(ch - 'a' + 10)
+ case 'A' <= ch && ch <= 'F':
+ return int(ch - 'A' + 10)
+ }
+ return 16 // larger than any legal digit val
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/scanner/scanner_test.go b/vendor/github.com/hashicorp/hcl/json/scanner/scanner_test.go
new file mode 100644
index 000000000..3033a5797
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/scanner/scanner_test.go
@@ -0,0 +1,362 @@
+package scanner
+
+import (
+ "bytes"
+ "fmt"
+ "testing"
+
+ "github.com/hashicorp/hcl/json/token"
+)
+
+var f100 = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
+
+type tokenPair struct {
+ tok token.Type
+ text string
+}
+
+var tokenLists = map[string][]tokenPair{
+ "operator": []tokenPair{
+ {token.LBRACK, "["},
+ {token.LBRACE, "{"},
+ {token.COMMA, ","},
+ {token.PERIOD, "."},
+ {token.RBRACK, "]"},
+ {token.RBRACE, "}"},
+ },
+ "bool": []tokenPair{
+ {token.BOOL, "true"},
+ {token.BOOL, "false"},
+ },
+ "string": []tokenPair{
+ {token.STRING, `" "`},
+ {token.STRING, `"a"`},
+ {token.STRING, `"本"`},
+ {token.STRING, `"${file(\"foo\")}"`},
+ {token.STRING, `"\a"`},
+ {token.STRING, `"\b"`},
+ {token.STRING, `"\f"`},
+ {token.STRING, `"\n"`},
+ {token.STRING, `"\r"`},
+ {token.STRING, `"\t"`},
+ {token.STRING, `"\v"`},
+ {token.STRING, `"\""`},
+ {token.STRING, `"\000"`},
+ {token.STRING, `"\777"`},
+ {token.STRING, `"\x00"`},
+ {token.STRING, `"\xff"`},
+ {token.STRING, `"\u0000"`},
+ {token.STRING, `"\ufA16"`},
+ {token.STRING, `"\U00000000"`},
+ {token.STRING, `"\U0000ffAB"`},
+ {token.STRING, `"` + f100 + `"`},
+ },
+ "number": []tokenPair{
+ {token.NUMBER, "0"},
+ {token.NUMBER, "1"},
+ {token.NUMBER, "9"},
+ {token.NUMBER, "42"},
+ {token.NUMBER, "1234567890"},
+ {token.NUMBER, "-0"},
+ {token.NUMBER, "-1"},
+ {token.NUMBER, "-9"},
+ {token.NUMBER, "-42"},
+ {token.NUMBER, "-1234567890"},
+ },
+ "float": []tokenPair{
+ {token.FLOAT, "0."},
+ {token.FLOAT, "1."},
+ {token.FLOAT, "42."},
+ {token.FLOAT, "01234567890."},
+ {token.FLOAT, ".0"},
+ {token.FLOAT, ".1"},
+ {token.FLOAT, ".42"},
+ {token.FLOAT, ".0123456789"},
+ {token.FLOAT, "0.0"},
+ {token.FLOAT, "1.0"},
+ {token.FLOAT, "42.0"},
+ {token.FLOAT, "01234567890.0"},
+ {token.FLOAT, "0e0"},
+ {token.FLOAT, "1e0"},
+ {token.FLOAT, "42e0"},
+ {token.FLOAT, "01234567890e0"},
+ {token.FLOAT, "0E0"},
+ {token.FLOAT, "1E0"},
+ {token.FLOAT, "42E0"},
+ {token.FLOAT, "01234567890E0"},
+ {token.FLOAT, "0e+10"},
+ {token.FLOAT, "1e-10"},
+ {token.FLOAT, "42e+10"},
+ {token.FLOAT, "01234567890e-10"},
+ {token.FLOAT, "0E+10"},
+ {token.FLOAT, "1E-10"},
+ {token.FLOAT, "42E+10"},
+ {token.FLOAT, "01234567890E-10"},
+ {token.FLOAT, "01.8e0"},
+ {token.FLOAT, "1.4e0"},
+ {token.FLOAT, "42.2e0"},
+ {token.FLOAT, "01234567890.12e0"},
+ {token.FLOAT, "0.E0"},
+ {token.FLOAT, "1.12E0"},
+ {token.FLOAT, "42.123E0"},
+ {token.FLOAT, "01234567890.213E0"},
+ {token.FLOAT, "0.2e+10"},
+ {token.FLOAT, "1.2e-10"},
+ {token.FLOAT, "42.54e+10"},
+ {token.FLOAT, "01234567890.98e-10"},
+ {token.FLOAT, "0.1E+10"},
+ {token.FLOAT, "1.1E-10"},
+ {token.FLOAT, "42.1E+10"},
+ {token.FLOAT, "01234567890.1E-10"},
+ {token.FLOAT, "-0.0"},
+ {token.FLOAT, "-1.0"},
+ {token.FLOAT, "-42.0"},
+ {token.FLOAT, "-01234567890.0"},
+ {token.FLOAT, "-0e0"},
+ {token.FLOAT, "-1e0"},
+ {token.FLOAT, "-42e0"},
+ {token.FLOAT, "-01234567890e0"},
+ {token.FLOAT, "-0E0"},
+ {token.FLOAT, "-1E0"},
+ {token.FLOAT, "-42E0"},
+ {token.FLOAT, "-01234567890E0"},
+ {token.FLOAT, "-0e+10"},
+ {token.FLOAT, "-1e-10"},
+ {token.FLOAT, "-42e+10"},
+ {token.FLOAT, "-01234567890e-10"},
+ {token.FLOAT, "-0E+10"},
+ {token.FLOAT, "-1E-10"},
+ {token.FLOAT, "-42E+10"},
+ {token.FLOAT, "-01234567890E-10"},
+ {token.FLOAT, "-01.8e0"},
+ {token.FLOAT, "-1.4e0"},
+ {token.FLOAT, "-42.2e0"},
+ {token.FLOAT, "-01234567890.12e0"},
+ {token.FLOAT, "-0.E0"},
+ {token.FLOAT, "-1.12E0"},
+ {token.FLOAT, "-42.123E0"},
+ {token.FLOAT, "-01234567890.213E0"},
+ {token.FLOAT, "-0.2e+10"},
+ {token.FLOAT, "-1.2e-10"},
+ {token.FLOAT, "-42.54e+10"},
+ {token.FLOAT, "-01234567890.98e-10"},
+ {token.FLOAT, "-0.1E+10"},
+ {token.FLOAT, "-1.1E-10"},
+ {token.FLOAT, "-42.1E+10"},
+ {token.FLOAT, "-01234567890.1E-10"},
+ },
+}
+
+var orderedTokenLists = []string{
+ "comment",
+ "operator",
+ "bool",
+ "string",
+ "number",
+ "float",
+}
+
+func TestPosition(t *testing.T) {
+ // create artifical source code
+ buf := new(bytes.Buffer)
+
+ for _, listName := range orderedTokenLists {
+ for _, ident := range tokenLists[listName] {
+ fmt.Fprintf(buf, "\t\t\t\t%s\n", ident.text)
+ }
+ }
+
+ s := New(buf.Bytes())
+
+ pos := token.Pos{"", 4, 1, 5}
+ s.Scan()
+ for _, listName := range orderedTokenLists {
+
+ for _, k := range tokenLists[listName] {
+ curPos := s.tokPos
+ // fmt.Printf("[%q] s = %+v:%+v\n", k.text, curPos.Offset, curPos.Column)
+
+ if curPos.Offset != pos.Offset {
+ t.Fatalf("offset = %d, want %d for %q", curPos.Offset, pos.Offset, k.text)
+ }
+ if curPos.Line != pos.Line {
+ t.Fatalf("line = %d, want %d for %q", curPos.Line, pos.Line, k.text)
+ }
+ if curPos.Column != pos.Column {
+ t.Fatalf("column = %d, want %d for %q", curPos.Column, pos.Column, k.text)
+ }
+ pos.Offset += 4 + len(k.text) + 1 // 4 tabs + token bytes + newline
+ pos.Line += countNewlines(k.text) + 1 // each token is on a new line
+
+ s.Error = func(pos token.Pos, msg string) {
+ t.Errorf("error %q for %q", msg, k.text)
+ }
+
+ s.Scan()
+ }
+ }
+ // make sure there were no token-internal errors reported by scanner
+ if s.ErrorCount != 0 {
+ t.Errorf("%d errors", s.ErrorCount)
+ }
+}
+
+func TestComment(t *testing.T) {
+ testTokenList(t, tokenLists["comment"])
+}
+
+func TestOperator(t *testing.T) {
+ testTokenList(t, tokenLists["operator"])
+}
+
+func TestBool(t *testing.T) {
+ testTokenList(t, tokenLists["bool"])
+}
+
+func TestIdent(t *testing.T) {
+ testTokenList(t, tokenLists["ident"])
+}
+
+func TestString(t *testing.T) {
+ testTokenList(t, tokenLists["string"])
+}
+
+func TestNumber(t *testing.T) {
+ testTokenList(t, tokenLists["number"])
+}
+
+func TestFloat(t *testing.T) {
+ testTokenList(t, tokenLists["float"])
+}
+
+func TestRealExample(t *testing.T) {
+ complexReal := `
+{
+ "variable": {
+ "foo": {
+ "default": "bar",
+ "description": "bar",
+ "depends_on": ["something"]
+ }
+ }
+}`
+
+ literals := []struct {
+ tokenType token.Type
+ literal string
+ }{
+ {token.LBRACE, `{`},
+ {token.STRING, `"variable"`},
+ {token.COLON, `:`},
+ {token.LBRACE, `{`},
+ {token.STRING, `"foo"`},
+ {token.COLON, `:`},
+ {token.LBRACE, `{`},
+ {token.STRING, `"default"`},
+ {token.COLON, `:`},
+ {token.STRING, `"bar"`},
+ {token.COMMA, `,`},
+ {token.STRING, `"description"`},
+ {token.COLON, `:`},
+ {token.STRING, `"bar"`},
+ {token.COMMA, `,`},
+ {token.STRING, `"depends_on"`},
+ {token.COLON, `:`},
+ {token.LBRACK, `[`},
+ {token.STRING, `"something"`},
+ {token.RBRACK, `]`},
+ {token.RBRACE, `}`},
+ {token.RBRACE, `}`},
+ {token.RBRACE, `}`},
+ {token.EOF, ``},
+ }
+
+ s := New([]byte(complexReal))
+ for _, l := range literals {
+ tok := s.Scan()
+ if l.tokenType != tok.Type {
+ t.Errorf("got: %s want %s for %s\n", tok, l.tokenType, tok.String())
+ }
+
+ if l.literal != tok.Text {
+ t.Errorf("got: %s want %s\n", tok, l.literal)
+ }
+ }
+
+}
+
+func TestError(t *testing.T) {
+ testError(t, "\x80", "1:1", "illegal UTF-8 encoding", token.ILLEGAL)
+ testError(t, "\xff", "1:1", "illegal UTF-8 encoding", token.ILLEGAL)
+
+ testError(t, `"ab`+"\x80", "1:4", "illegal UTF-8 encoding", token.STRING)
+ testError(t, `"abc`+"\xff", "1:5", "illegal UTF-8 encoding", token.STRING)
+
+ testError(t, `01238`, "1:7", "numbers cannot start with 0", token.NUMBER)
+ testError(t, `01238123`, "1:10", "numbers cannot start with 0", token.NUMBER)
+ testError(t, `'aa'`, "1:1", "illegal char: '", token.ILLEGAL)
+
+ testError(t, `"`, "1:2", "literal not terminated", token.STRING)
+ testError(t, `"abc`, "1:5", "literal not terminated", token.STRING)
+ testError(t, `"abc`+"\n", "1:5", "literal not terminated", token.STRING)
+}
+
+func testError(t *testing.T, src, pos, msg string, tok token.Type) {
+ s := New([]byte(src))
+
+ errorCalled := false
+ s.Error = func(p token.Pos, m string) {
+ if !errorCalled {
+ if pos != p.String() {
+ t.Errorf("pos = %q, want %q for %q", p, pos, src)
+ }
+
+ if m != msg {
+ t.Errorf("msg = %q, want %q for %q", m, msg, src)
+ }
+ errorCalled = true
+ }
+ }
+
+ tk := s.Scan()
+ if tk.Type != tok {
+ t.Errorf("tok = %s, want %s for %q", tk, tok, src)
+ }
+ if !errorCalled {
+ t.Errorf("error handler not called for %q", src)
+ }
+ if s.ErrorCount == 0 {
+ t.Errorf("count = %d, want > 0 for %q", s.ErrorCount, src)
+ }
+}
+
+func testTokenList(t *testing.T, tokenList []tokenPair) {
+ // create artifical source code
+ buf := new(bytes.Buffer)
+ for _, ident := range tokenList {
+ fmt.Fprintf(buf, "%s\n", ident.text)
+ }
+
+ s := New(buf.Bytes())
+ for _, ident := range tokenList {
+ tok := s.Scan()
+ if tok.Type != ident.tok {
+ t.Errorf("tok = %q want %q for %q\n", tok, ident.tok, ident.text)
+ }
+
+ if tok.Text != ident.text {
+ t.Errorf("text = %q want %q", tok.String(), ident.text)
+ }
+
+ }
+}
+
+func countNewlines(s string) int {
+ n := 0
+ for _, ch := range s {
+ if ch == '\n' {
+ n++
+ }
+ }
+ return n
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/test-fixtures/array.json b/vendor/github.com/hashicorp/hcl/json/test-fixtures/array.json
new file mode 100644
index 000000000..e320f17ab
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/test-fixtures/array.json
@@ -0,0 +1,4 @@
+{
+ "foo": [1, 2, "bar"],
+ "bar": "baz"
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/test-fixtures/basic.json b/vendor/github.com/hashicorp/hcl/json/test-fixtures/basic.json
new file mode 100644
index 000000000..b54bde96c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/test-fixtures/basic.json
@@ -0,0 +1,3 @@
+{
+ "foo": "bar"
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/test-fixtures/object.json b/vendor/github.com/hashicorp/hcl/json/test-fixtures/object.json
new file mode 100644
index 000000000..72168a3cc
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/test-fixtures/object.json
@@ -0,0 +1,5 @@
+{
+ "foo": {
+ "bar": [1,2]
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/test-fixtures/types.json b/vendor/github.com/hashicorp/hcl/json/test-fixtures/types.json
new file mode 100644
index 000000000..9a142a6ca
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/test-fixtures/types.json
@@ -0,0 +1,10 @@
+{
+ "foo": "bar",
+ "bar": 7,
+ "baz": [1,2,3],
+ "foo": -12,
+ "bar": 3.14159,
+ "foo": true,
+ "bar": false,
+ "foo": null
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/token/position.go b/vendor/github.com/hashicorp/hcl/json/token/position.go
new file mode 100644
index 000000000..59c1bb72d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/token/position.go
@@ -0,0 +1,46 @@
+package token
+
+import "fmt"
+
+// Pos describes an arbitrary source position
+// including the file, line, and column location.
+// A Position is valid if the line number is > 0.
+type Pos struct {
+ Filename string // filename, if any
+ Offset int // offset, starting at 0
+ Line int // line number, starting at 1
+ Column int // column number, starting at 1 (character count)
+}
+
+// IsValid returns true if the position is valid.
+func (p *Pos) IsValid() bool { return p.Line > 0 }
+
+// String returns a string in one of several forms:
+//
+// file:line:column valid position with file name
+// line:column valid position without file name
+// file invalid position with file name
+// - invalid position without file name
+func (p Pos) String() string {
+ s := p.Filename
+ if p.IsValid() {
+ if s != "" {
+ s += ":"
+ }
+ s += fmt.Sprintf("%d:%d", p.Line, p.Column)
+ }
+ if s == "" {
+ s = "-"
+ }
+ return s
+}
+
+// Before reports whether the position p is before u.
+func (p Pos) Before(u Pos) bool {
+ return u.Offset > p.Offset || u.Line > p.Line
+}
+
+// After reports whether the position p is after u.
+func (p Pos) After(u Pos) bool {
+ return u.Offset < p.Offset || u.Line < p.Line
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/token/token.go b/vendor/github.com/hashicorp/hcl/json/token/token.go
new file mode 100644
index 000000000..95a0c3eee
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/token/token.go
@@ -0,0 +1,118 @@
+package token
+
+import (
+ "fmt"
+ "strconv"
+
+ hcltoken "github.com/hashicorp/hcl/hcl/token"
+)
+
+// Token defines a single HCL token which can be obtained via the Scanner
+type Token struct {
+ Type Type
+ Pos Pos
+ Text string
+}
+
+// Type is the set of lexical tokens of the HCL (HashiCorp Configuration Language)
+type Type int
+
+const (
+ // Special tokens
+ ILLEGAL Type = iota
+ EOF
+
+ identifier_beg
+ literal_beg
+ NUMBER // 12345
+ FLOAT // 123.45
+ BOOL // true,false
+ STRING // "abc"
+ NULL // null
+ literal_end
+ identifier_end
+
+ operator_beg
+ LBRACK // [
+ LBRACE // {
+ COMMA // ,
+ PERIOD // .
+ COLON // :
+
+ RBRACK // ]
+ RBRACE // }
+
+ operator_end
+)
+
+var tokens = [...]string{
+ ILLEGAL: "ILLEGAL",
+
+ EOF: "EOF",
+
+ NUMBER: "NUMBER",
+ FLOAT: "FLOAT",
+ BOOL: "BOOL",
+ STRING: "STRING",
+ NULL: "NULL",
+
+ LBRACK: "LBRACK",
+ LBRACE: "LBRACE",
+ COMMA: "COMMA",
+ PERIOD: "PERIOD",
+ COLON: "COLON",
+
+ RBRACK: "RBRACK",
+ RBRACE: "RBRACE",
+}
+
+// String returns the string corresponding to the token tok.
+func (t Type) String() string {
+ s := ""
+ if 0 <= t && t < Type(len(tokens)) {
+ s = tokens[t]
+ }
+ if s == "" {
+ s = "token(" + strconv.Itoa(int(t)) + ")"
+ }
+ return s
+}
+
+// IsIdentifier returns true for tokens corresponding to identifiers and basic
+// type literals; it returns false otherwise.
+func (t Type) IsIdentifier() bool { return identifier_beg < t && t < identifier_end }
+
+// IsLiteral returns true for tokens corresponding to basic type literals; it
+// returns false otherwise.
+func (t Type) IsLiteral() bool { return literal_beg < t && t < literal_end }
+
+// IsOperator returns true for tokens corresponding to operators and
+// delimiters; it returns false otherwise.
+func (t Type) IsOperator() bool { return operator_beg < t && t < operator_end }
+
+// String returns the token's literal text. Note that this is only
+// applicable for certain token types, such as token.IDENT,
+// token.STRING, etc..
+func (t Token) String() string {
+ return fmt.Sprintf("%s %s %s", t.Pos.String(), t.Type.String(), t.Text)
+}
+
+// HCLToken converts this token to an HCL token.
+//
+// The token type must be a literal type or this will panic.
+func (t Token) HCLToken() hcltoken.Token {
+ switch t.Type {
+ case BOOL:
+ return hcltoken.Token{Type: hcltoken.BOOL, Text: t.Text}
+ case FLOAT:
+ return hcltoken.Token{Type: hcltoken.FLOAT, Text: t.Text}
+ case NULL:
+ return hcltoken.Token{Type: hcltoken.STRING, Text: ""}
+ case NUMBER:
+ return hcltoken.Token{Type: hcltoken.NUMBER, Text: t.Text}
+ case STRING:
+ return hcltoken.Token{Type: hcltoken.STRING, Text: t.Text, JSON: true}
+ default:
+ panic(fmt.Sprintf("unimplemented HCLToken for type: %s", t.Type))
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/json/token/token_test.go b/vendor/github.com/hashicorp/hcl/json/token/token_test.go
new file mode 100644
index 000000000..a83fdd55b
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/json/token/token_test.go
@@ -0,0 +1,34 @@
+package token
+
+import (
+ "testing"
+)
+
+func TestTypeString(t *testing.T) {
+ var tokens = []struct {
+ tt Type
+ str string
+ }{
+ {ILLEGAL, "ILLEGAL"},
+ {EOF, "EOF"},
+ {NUMBER, "NUMBER"},
+ {FLOAT, "FLOAT"},
+ {BOOL, "BOOL"},
+ {STRING, "STRING"},
+ {NULL, "NULL"},
+ {LBRACK, "LBRACK"},
+ {LBRACE, "LBRACE"},
+ {COMMA, "COMMA"},
+ {PERIOD, "PERIOD"},
+ {RBRACK, "RBRACK"},
+ {RBRACE, "RBRACE"},
+ }
+
+ for _, token := range tokens {
+ if token.tt.String() != token.str {
+ t.Errorf("want: %q got:%q\n", token.str, token.tt)
+
+ }
+ }
+
+}
diff --git a/vendor/github.com/hashicorp/hcl/lex.go b/vendor/github.com/hashicorp/hcl/lex.go
new file mode 100644
index 000000000..d9993c292
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/lex.go
@@ -0,0 +1,38 @@
+package hcl
+
+import (
+ "unicode"
+ "unicode/utf8"
+)
+
+type lexModeValue byte
+
+const (
+ lexModeUnknown lexModeValue = iota
+ lexModeHcl
+ lexModeJson
+)
+
+// lexMode returns whether we're going to be parsing in JSON
+// mode or HCL mode.
+func lexMode(v []byte) lexModeValue {
+ var (
+ r rune
+ w int
+ offset int
+ )
+
+ for {
+ r, w = utf8.DecodeRune(v[offset:])
+ offset += w
+ if unicode.IsSpace(r) {
+ continue
+ }
+ if r == '{' {
+ return lexModeJson
+ }
+ break
+ }
+
+ return lexModeHcl
+}
diff --git a/vendor/github.com/hashicorp/hcl/lex_test.go b/vendor/github.com/hashicorp/hcl/lex_test.go
new file mode 100644
index 000000000..806276444
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/lex_test.go
@@ -0,0 +1,37 @@
+package hcl
+
+import (
+ "testing"
+)
+
+func TestLexMode(t *testing.T) {
+ cases := []struct {
+ Input string
+ Mode lexModeValue
+ }{
+ {
+ "",
+ lexModeHcl,
+ },
+ {
+ "foo",
+ lexModeHcl,
+ },
+ {
+ "{}",
+ lexModeJson,
+ },
+ {
+ " {}",
+ lexModeJson,
+ },
+ }
+
+ for i, tc := range cases {
+ actual := lexMode([]byte(tc.Input))
+
+ if actual != tc.Mode {
+ t.Fatalf("%d: %#v", i, actual)
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/parse.go b/vendor/github.com/hashicorp/hcl/parse.go
new file mode 100644
index 000000000..1fca53c4c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/parse.go
@@ -0,0 +1,39 @@
+package hcl
+
+import (
+ "fmt"
+
+ "github.com/hashicorp/hcl/hcl/ast"
+ hclParser "github.com/hashicorp/hcl/hcl/parser"
+ jsonParser "github.com/hashicorp/hcl/json/parser"
+)
+
+// ParseBytes accepts as input byte slice and returns ast tree.
+//
+// Input can be either JSON or HCL
+func ParseBytes(in []byte) (*ast.File, error) {
+ return parse(in)
+}
+
+// ParseString accepts input as a string and returns ast tree.
+func ParseString(input string) (*ast.File, error) {
+ return parse([]byte(input))
+}
+
+func parse(in []byte) (*ast.File, error) {
+ switch lexMode(in) {
+ case lexModeHcl:
+ return hclParser.Parse(in)
+ case lexModeJson:
+ return jsonParser.Parse(in)
+ }
+
+ return nil, fmt.Errorf("unknown config format")
+}
+
+// Parse parses the given input and returns the root object.
+//
+// The input format can be either HCL or JSON.
+func Parse(input string) (*ast.File, error) {
+ return parse([]byte(input))
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/assign_deep.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/assign_deep.hcl
new file mode 100644
index 000000000..dd3151cb7
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/assign_deep.hcl
@@ -0,0 +1,5 @@
+resource = [{
+ foo = [{
+ bar = {}
+ }]
+}]
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/basic.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/basic.hcl
new file mode 100644
index 000000000..949994487
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/basic.hcl
@@ -0,0 +1,2 @@
+foo = "bar"
+bar = "${file("bing/bong.txt")}"
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/basic.json b/vendor/github.com/hashicorp/hcl/test-fixtures/basic.json
new file mode 100644
index 000000000..7bdddc84b
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/basic.json
@@ -0,0 +1,4 @@
+{
+ "foo": "bar",
+ "bar": "${file(\"bing/bong.txt\")}"
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/basic_int_string.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/basic_int_string.hcl
new file mode 100644
index 000000000..4e415da20
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/basic_int_string.hcl
@@ -0,0 +1 @@
+count = "3"
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/basic_squish.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/basic_squish.hcl
new file mode 100644
index 000000000..363697b49
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/basic_squish.hcl
@@ -0,0 +1,3 @@
+foo="bar"
+bar="${file("bing/bong.txt")}"
+foo-bar="baz"
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/block_assign.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/block_assign.hcl
new file mode 100644
index 000000000..ee8b06fe3
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/block_assign.hcl
@@ -0,0 +1,2 @@
+environment = "aws" {
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/decode_policy.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/decode_policy.hcl
new file mode 100644
index 000000000..5b185cc91
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/decode_policy.hcl
@@ -0,0 +1,15 @@
+key "" {
+ policy = "read"
+}
+
+key "foo/" {
+ policy = "write"
+}
+
+key "foo/bar/" {
+ policy = "read"
+}
+
+key "foo/bar/baz" {
+ policy = "deny"
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/decode_policy.json b/vendor/github.com/hashicorp/hcl/test-fixtures/decode_policy.json
new file mode 100644
index 000000000..151864ee8
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/decode_policy.json
@@ -0,0 +1,19 @@
+{
+ "key": {
+ "": {
+ "policy": "read"
+ },
+
+ "foo/": {
+ "policy": "write"
+ },
+
+ "foo/bar/": {
+ "policy": "read"
+ },
+
+ "foo/bar/baz": {
+ "policy": "deny"
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/decode_tf_variable.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/decode_tf_variable.hcl
new file mode 100644
index 000000000..52dcaa1bc
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/decode_tf_variable.hcl
@@ -0,0 +1,10 @@
+variable "foo" {
+ default = "bar"
+ description = "bar"
+}
+
+variable "amis" {
+ default = {
+ east = "foo"
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/decode_tf_variable.json b/vendor/github.com/hashicorp/hcl/test-fixtures/decode_tf_variable.json
new file mode 100644
index 000000000..49f921ed0
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/decode_tf_variable.json
@@ -0,0 +1,14 @@
+{
+ "variable": {
+ "foo": {
+ "default": "bar",
+ "description": "bar"
+ },
+
+ "amis": {
+ "default": {
+ "east": "foo"
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/empty.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/empty.hcl
new file mode 100644
index 000000000..5be1b2315
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/empty.hcl
@@ -0,0 +1 @@
+resource "foo" {}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/escape.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/escape.hcl
new file mode 100644
index 000000000..f818b15e0
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/escape.hcl
@@ -0,0 +1,6 @@
+foo = "bar\"baz\\n"
+bar = "new\nline"
+qux = "back\\slash"
+qax = "slash\\:colon"
+nested = "${HH\\:mm\\:ss}"
+nestedquotes = "${"\"stringwrappedinquotes\""}"
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/escape_backslash.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/escape_backslash.hcl
new file mode 100644
index 000000000..bc337fb7c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/escape_backslash.hcl
@@ -0,0 +1,5 @@
+output {
+ one = "${replace(var.sub_domain, ".", "\\.")}"
+ two = "${replace(var.sub_domain, ".", "\\\\.")}"
+ many = "${replace(var.sub_domain, ".", "\\\\\\\\.")}"
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/flat.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/flat.hcl
new file mode 100644
index 000000000..9bca551f8
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/flat.hcl
@@ -0,0 +1,2 @@
+foo = "bar"
+Key = 7
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/float.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/float.hcl
new file mode 100644
index 000000000..eed44e542
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/float.hcl
@@ -0,0 +1 @@
+a = 1.02
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/float.json b/vendor/github.com/hashicorp/hcl/test-fixtures/float.json
new file mode 100644
index 000000000..a9d1ab4b0
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/float.json
@@ -0,0 +1,3 @@
+{
+ "a": 1.02
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/git_crypt.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/git_crypt.hcl
new file mode 100644
index 000000000..f691948e1
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/git_crypt.hcl
Binary files differ
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/interpolate.json b/vendor/github.com/hashicorp/hcl/test-fixtures/interpolate.json
new file mode 100644
index 000000000..cad015198
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/interpolate.json
@@ -0,0 +1,3 @@
+{
+ "default": "${replace(\"europe-west\", \"-\", \" \")}"
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/list_of_lists.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/list_of_lists.hcl
new file mode 100644
index 000000000..8af345849
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/list_of_lists.hcl
@@ -0,0 +1,2 @@
+foo = [["foo"], ["bar"]]
+
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/list_of_maps.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/list_of_maps.hcl
new file mode 100644
index 000000000..985a33bae
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/list_of_maps.hcl
@@ -0,0 +1,4 @@
+foo = [
+ {somekey1 = "someval1"},
+ {somekey2 = "someval2", someextrakey = "someextraval"},
+]
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/multiline.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline.hcl
new file mode 100644
index 000000000..f883bd707
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline.hcl
@@ -0,0 +1,4 @@
+foo = <<EOF
+bar
+baz
+EOF
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/multiline.json b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline.json
new file mode 100644
index 000000000..93f7cc55c
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline.json
@@ -0,0 +1,3 @@
+{
+ "foo": "bar\nbaz"
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_bad.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_bad.hcl
new file mode 100644
index 000000000..4cd0f4dd7
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_bad.hcl
@@ -0,0 +1,4 @@
+foo = <EOF
+bar
+baz
+EOF
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_indented.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_indented.hcl
new file mode 100644
index 000000000..f1d7a843d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_indented.hcl
@@ -0,0 +1,4 @@
+foo = <<-EOF
+ bar
+ baz
+ EOF
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_literal.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_literal.hcl
new file mode 100644
index 000000000..f89fdfc71
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_literal.hcl
@@ -0,0 +1,2 @@
+multiline_literal = "hello
+ world" \ No newline at end of file
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_literal_with_hil.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_literal_with_hil.hcl
new file mode 100644
index 000000000..b55a361ca
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_literal_with_hil.hcl
@@ -0,0 +1,2 @@
+multiline_literal_with_hil = "${hello
+ world}" \ No newline at end of file
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_eof.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_eof.hcl
new file mode 100644
index 000000000..faa13290b
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_eof.hcl
@@ -0,0 +1,5 @@
+foo = <<EOF
+bar
+baz
+EOF
+key = "value"
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_hanging_indent.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_hanging_indent.hcl
new file mode 100644
index 000000000..c4331eeae
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_hanging_indent.hcl
@@ -0,0 +1,5 @@
+foo = <<-EOF
+ baz
+ bar
+ foo
+ EOF
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_marker.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_marker.hcl
new file mode 100644
index 000000000..55c173966
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/multiline_no_marker.hcl
@@ -0,0 +1 @@
+foo = <<
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/nested_block_comment.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/nested_block_comment.hcl
new file mode 100644
index 000000000..e827782fe
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/nested_block_comment.hcl
@@ -0,0 +1,5 @@
+/*
+foo = "bar/*"
+*/
+
+bar = "value"
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/nested_provider_bad.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/nested_provider_bad.hcl
new file mode 100644
index 000000000..94a753a5a
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/nested_provider_bad.hcl
@@ -0,0 +1,5 @@
+resource "aws" "web" {
+ provider = "aws" {
+ region = "us-west-2"
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/null_strings.json b/vendor/github.com/hashicorp/hcl/test-fixtures/null_strings.json
new file mode 100644
index 000000000..a5b8a5af2
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/null_strings.json
@@ -0,0 +1,7 @@
+{
+ "module": {
+ "app": {
+ "foo": null
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/object_list.json b/vendor/github.com/hashicorp/hcl/test-fixtures/object_list.json
new file mode 100644
index 000000000..73f367438
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/object_list.json
@@ -0,0 +1,15 @@
+{
+ "resource": {
+ "aws_instance": {
+ "db": {
+ "vpc": "foo",
+ "provisioner": [{
+ "file": {
+ "source": "foo",
+ "destination": "bar"
+ }
+ }]
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/object_with_bool.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/object_with_bool.hcl
new file mode 100644
index 000000000..e565fb477
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/object_with_bool.hcl
@@ -0,0 +1,6 @@
+path {
+ policy = "write"
+ permissions = {
+ "bool" = [false]
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/scientific.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/scientific.hcl
new file mode 100644
index 000000000..b9eca28dd
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/scientific.hcl
@@ -0,0 +1,6 @@
+a = 1e-10
+b = 1e+10
+c = 1e10
+d = 1.2e-10
+e = 1.2e+10
+f = 1.2e10
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/scientific.json b/vendor/github.com/hashicorp/hcl/test-fixtures/scientific.json
new file mode 100644
index 000000000..c1fce3c9d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/scientific.json
@@ -0,0 +1,8 @@
+{
+ "a": 1e-10,
+ "b": 1e+10,
+ "c": 1e10,
+ "d": 1.2e-10,
+ "e": 1.2e+10,
+ "f": 1.2e10
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/slice_expand.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/slice_expand.hcl
new file mode 100644
index 000000000..4d3725fc1
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/slice_expand.hcl
@@ -0,0 +1,7 @@
+service "my-service-0" {
+ key = "value"
+}
+
+service "my-service-1" {
+ key = "value"
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/structure.hcl
new file mode 100644
index 000000000..18b6b1e9f
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure.hcl
@@ -0,0 +1,5 @@
+// This is a test structure for the lexer
+foo "baz" {
+ key = 7
+ foo = "bar"
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure.json b/vendor/github.com/hashicorp/hcl/test-fixtures/structure.json
new file mode 100644
index 000000000..30aa7654e
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure.json
@@ -0,0 +1,8 @@
+{
+ "foo": [{
+ "baz": [{
+ "key": 7,
+ "foo": "bar"
+ }]
+ }]
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure2.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/structure2.hcl
new file mode 100644
index 000000000..7577ffc0e
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure2.hcl
@@ -0,0 +1,9 @@
+// This is a test structure for the lexer
+foo "baz" {
+ key = 7
+ foo = "bar"
+}
+
+foo {
+ key = 7
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure2.json b/vendor/github.com/hashicorp/hcl/test-fixtures/structure2.json
new file mode 100644
index 000000000..c51fcf544
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure2.json
@@ -0,0 +1,10 @@
+{
+ "foo": [{
+ "baz": {
+ "key": 7,
+ "foo": "bar"
+ }
+ }, {
+ "key": 7
+ }]
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure_flat.json b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_flat.json
new file mode 100644
index 000000000..5256db475
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_flat.json
@@ -0,0 +1,8 @@
+{
+ "foo": {
+ "baz": {
+ "key": 7,
+ "foo": "bar"
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure_flatmap.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_flatmap.hcl
new file mode 100644
index 000000000..fcf689e19
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_flatmap.hcl
@@ -0,0 +1,7 @@
+foo {
+ key = 7
+}
+
+foo {
+ foo = "bar"
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list.hcl
new file mode 100644
index 000000000..33193ae53
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list.hcl
@@ -0,0 +1,6 @@
+foo {
+ key = 7
+}
+foo {
+ key = 12
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list.json b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list.json
new file mode 100644
index 000000000..806a60e3e
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list.json
@@ -0,0 +1,7 @@
+{
+ "foo": [{
+ "key": 7
+ }, {
+ "key": 12
+ }]
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list_deep.json b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list_deep.json
new file mode 100644
index 000000000..46e98bef3
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list_deep.json
@@ -0,0 +1,16 @@
+{
+ "bar": {
+ "foo": {
+ "name": "terraform_example",
+ "ingress": [
+ {
+ "from_port": 22
+ },
+ {
+ "from_port": 80
+ }
+ ]
+ }
+ }
+}
+
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list_empty.json b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list_empty.json
new file mode 100644
index 000000000..d99606fb1
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_list_empty.json
@@ -0,0 +1,3 @@
+{
+ "foo": []
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure_multi.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_multi.hcl
new file mode 100644
index 000000000..e45b23d52
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_multi.hcl
@@ -0,0 +1,7 @@
+foo "baz" {
+ key = 7
+}
+
+foo "bar" {
+ key = 12
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/structure_multi.json b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_multi.json
new file mode 100644
index 000000000..773761aca
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/structure_multi.json
@@ -0,0 +1,11 @@
+{
+ "foo": {
+ "baz": {
+ "key": 7
+ },
+
+ "bar": {
+ "key": 12
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/terraform_heroku.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/terraform_heroku.hcl
new file mode 100644
index 000000000..fda9241a4
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/terraform_heroku.hcl
@@ -0,0 +1,5 @@
+name = "terraform-test-app"
+
+config_vars {
+ FOO = "bar"
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/terraform_heroku.json b/vendor/github.com/hashicorp/hcl/test-fixtures/terraform_heroku.json
new file mode 100644
index 000000000..e8c6fac3d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/terraform_heroku.json
@@ -0,0 +1,6 @@
+{
+ "name": "terraform-test-app",
+ "config_vars": {
+ "FOO": "bar"
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/terraform_variable_invalid.json b/vendor/github.com/hashicorp/hcl/test-fixtures/terraform_variable_invalid.json
new file mode 100644
index 000000000..081247ea4
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/terraform_variable_invalid.json
@@ -0,0 +1,5 @@
+{
+ "variable": {
+ "whatever": "abc123"
+ }
+}
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/tfvars.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/tfvars.hcl
new file mode 100644
index 000000000..5f623e04d
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/tfvars.hcl
@@ -0,0 +1,3 @@
+regularvar = "Should work"
+map.key1 = "Value"
+map.key2 = "Other value"
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/unterminated_block_comment.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/unterminated_block_comment.hcl
new file mode 100644
index 000000000..c0ce34d04
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/unterminated_block_comment.hcl
@@ -0,0 +1,2 @@
+/*
+Foo
diff --git a/vendor/github.com/hashicorp/hcl/test-fixtures/unterminated_brace.hcl b/vendor/github.com/hashicorp/hcl/test-fixtures/unterminated_brace.hcl
new file mode 100644
index 000000000..31b37c4f9
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/test-fixtures/unterminated_brace.hcl
@@ -0,0 +1,2 @@
+foo "baz" {
+ bar = "baz"
diff --git a/vendor/github.com/hashicorp/hcl/testhelper/unix2dos.go b/vendor/github.com/hashicorp/hcl/testhelper/unix2dos.go
new file mode 100644
index 000000000..827ac6f1e
--- /dev/null
+++ b/vendor/github.com/hashicorp/hcl/testhelper/unix2dos.go
@@ -0,0 +1,15 @@
+package testhelper
+
+import (
+ "runtime"
+ "strings"
+)
+
+// Converts the line endings when on Windows
+func Unix2dos(unix string) string {
+ if runtime.GOOS != "windows" {
+ return unix
+ }
+
+ return strings.Replace(unix, "\n", "\r\n", -1)
+}
diff --git a/vendor/github.com/lib/pq/conn.go b/vendor/github.com/lib/pq/conn.go
index 4b2fb4462..c005cf9c4 100644
--- a/vendor/github.com/lib/pq/conn.go
+++ b/vendor/github.com/lib/pq/conn.go
@@ -98,7 +98,7 @@ type conn struct {
namei int
scratch [512]byte
txnStatus transactionStatus
- txnClosed chan<- struct{}
+ txnFinish func()
// Save connection arguments to use during CancelRequest.
dialer Dialer
@@ -528,9 +528,8 @@ func (cn *conn) Begin() (_ driver.Tx, err error) {
}
func (cn *conn) closeTxn() {
- if cn.txnClosed != nil {
- close(cn.txnClosed)
- cn.txnClosed = nil
+ if finish := cn.txnFinish; finish != nil {
+ finish()
}
}
@@ -893,16 +892,9 @@ func (cn *conn) send(m *writeBuf) {
}
}
-func (cn *conn) sendStartupPacket(m *writeBuf) {
- // sanity check
- if m.buf[0] != 0 {
- panic("oops")
- }
-
+func (cn *conn) sendStartupPacket(m *writeBuf) error {
_, err := cn.c.Write((m.wrap())[1:])
- if err != nil {
- panic(err)
- }
+ return err
}
// Send a message of type typ to the server on the other end of cn. The
@@ -1024,7 +1016,9 @@ func (cn *conn) ssl(o values) {
w := cn.writeBuf(0)
w.int32(80877103)
- cn.sendStartupPacket(w)
+ if err := cn.sendStartupPacket(w); err != nil {
+ panic(err)
+ }
b := cn.scratch[:1]
_, err := io.ReadFull(cn.c, b)
@@ -1085,7 +1079,9 @@ func (cn *conn) startup(o values) {
w.string(v)
}
w.string("")
- cn.sendStartupPacket(w)
+ if err := cn.sendStartupPacket(w); err != nil {
+ panic(err)
+ }
for {
t, r := cn.recv()
@@ -1319,7 +1315,7 @@ func (cn *conn) parseComplete(commandTag string) (driver.Result, string) {
type rows struct {
cn *conn
- closed chan<- struct{}
+ finish func()
colNames []string
colTyps []oid.Oid
colFmts []format
@@ -1330,8 +1326,8 @@ type rows struct {
}
func (rs *rows) Close() error {
- if rs.closed != nil {
- defer close(rs.closed)
+ if finish := rs.finish; finish != nil {
+ defer finish()
}
// no need to look at cn.bad as Next() will
for {
diff --git a/vendor/github.com/lib/pq/conn_go18.go b/vendor/github.com/lib/pq/conn_go18.go
index 43cc35f7b..fa3755d99 100644
--- a/vendor/github.com/lib/pq/conn_go18.go
+++ b/vendor/github.com/lib/pq/conn_go18.go
@@ -6,6 +6,8 @@ import (
"context"
"database/sql/driver"
"errors"
+ "io"
+ "io/ioutil"
)
// Implement the "QueryerContext" interface
@@ -14,12 +16,12 @@ func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.Na
for i, nv := range args {
list[i] = nv.Value
}
- closed := cn.watchCancel(ctx)
+ finish := cn.watchCancel(ctx)
r, err := cn.query(query, list)
if err != nil {
return nil, err
}
- r.closed = closed
+ r.finish = finish
return r, nil
}
@@ -30,8 +32,8 @@ func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.Nam
list[i] = nv.Value
}
- if closed := cn.watchCancel(ctx); closed != nil {
- defer close(closed)
+ if finish := cn.watchCancel(ctx); finish != nil {
+ defer finish()
}
return cn.Exec(query, list)
@@ -49,41 +51,57 @@ func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx,
if err != nil {
return nil, err
}
- cn.txnClosed = cn.watchCancel(ctx)
+ cn.txnFinish = cn.watchCancel(ctx)
return tx, nil
}
-func (cn *conn) watchCancel(ctx context.Context) chan<- struct{} {
+func (cn *conn) watchCancel(ctx context.Context) func() {
if done := ctx.Done(); done != nil {
- closed := make(chan struct{})
+ finished := make(chan struct{})
go func() {
select {
case <-done:
- cn.cancel()
- case <-closed:
+ _ = cn.cancel()
+ finished <- struct{}{}
+ case <-finished:
}
}()
- return closed
+ return func() {
+ select {
+ case <-finished:
+ case finished <- struct{}{}:
+ }
+ }
}
return nil
}
-func (cn *conn) cancel() {
- var err error
- can := &conn{}
- can.c, err = dial(cn.dialer, cn.opts)
+func (cn *conn) cancel() error {
+ c, err := dial(cn.dialer, cn.opts)
if err != nil {
- return
+ return err
}
- can.ssl(cn.opts)
+ defer c.Close()
- defer can.errRecover(&err)
+ {
+ can := conn{
+ c: c,
+ }
+ can.ssl(cn.opts)
- w := can.writeBuf(0)
- w.int32(80877102) // cancel request code
- w.int32(cn.processID)
- w.int32(cn.secretKey)
+ w := can.writeBuf(0)
+ w.int32(80877102) // cancel request code
+ w.int32(cn.processID)
+ w.int32(cn.secretKey)
- can.sendStartupPacket(w)
- _ = can.c.Close()
+ if err := can.sendStartupPacket(w); err != nil {
+ return err
+ }
+ }
+
+ // Read until EOF to ensure that the server received the cancel.
+ {
+ _, err := io.Copy(ioutil.Discard, c)
+ return err
+ }
}
diff --git a/vendor/github.com/lib/pq/go18_test.go b/vendor/github.com/lib/pq/go18_test.go
index 5d17e4d92..cddbfb6a4 100644
--- a/vendor/github.com/lib/pq/go18_test.go
+++ b/vendor/github.com/lib/pq/go18_test.go
@@ -72,6 +72,8 @@ func TestMultipleSimpleQuery(t *testing.T) {
}
}
+const contextRaceIterations = 100
+
func TestContextCancelExec(t *testing.T) {
db := openTestConn(t)
defer db.Close()
@@ -94,6 +96,20 @@ func TestContextCancelExec(t *testing.T) {
} else if err.Error() != "context canceled" {
t.Fatalf("unexpected error: %s", err)
}
+
+ for i := 0; i < contextRaceIterations; i++ {
+ func() {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ if _, err := db.ExecContext(ctx, "select 1"); err != nil {
+ t.Fatal(err)
+ }
+ }()
+
+ if _, err := db.Exec("select 1"); err != nil {
+ t.Fatal(err)
+ }
+ }
}
func TestContextCancelQuery(t *testing.T) {
@@ -118,6 +134,25 @@ func TestContextCancelQuery(t *testing.T) {
} else if err.Error() != "context canceled" {
t.Fatalf("unexpected error: %s", err)
}
+
+ for i := 0; i < contextRaceIterations; i++ {
+ func() {
+ ctx, cancel := context.WithCancel(context.Background())
+ rows, err := db.QueryContext(ctx, "select 1")
+ cancel()
+ if err != nil {
+ t.Fatal(err)
+ } else if err := rows.Close(); err != nil {
+ t.Fatal(err)
+ }
+ }()
+
+ if rows, err := db.Query("select 1"); err != nil {
+ t.Fatal(err)
+ } else if err := rows.Close(); err != nil {
+ t.Fatal(err)
+ }
+ }
}
func TestContextCancelBegin(t *testing.T) {
@@ -153,4 +188,23 @@ func TestContextCancelBegin(t *testing.T) {
} else if err.Error() != "context canceled" {
t.Fatalf("unexpected error: %s", err)
}
+
+ for i := 0; i < contextRaceIterations; i++ {
+ func() {
+ ctx, cancel := context.WithCancel(context.Background())
+ tx, err := db.BeginTx(ctx, nil)
+ cancel()
+ if err != nil {
+ t.Fatal(err)
+ } else if err := tx.Rollback(); err != nil && err != sql.ErrTxDone {
+ t.Fatal(err)
+ }
+ }()
+
+ if tx, err := db.Begin(); err != nil {
+ t.Fatal(err)
+ } else if err := tx.Rollback(); err != nil {
+ t.Fatal(err)
+ }
+ }
}
diff --git a/vendor/github.com/magiconair/properties/.gitignore b/vendor/github.com/magiconair/properties/.gitignore
new file mode 100644
index 000000000..e7081ff52
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/.gitignore
@@ -0,0 +1,6 @@
+*.sublime-project
+*.sublime-workspace
+*.un~
+*.swp
+.idea/
+*.iml
diff --git a/vendor/github.com/magiconair/properties/.travis.yml b/vendor/github.com/magiconair/properties/.travis.yml
new file mode 100644
index 000000000..60436b202
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/.travis.yml
@@ -0,0 +1,8 @@
+language: go
+go:
+ - 1.4.x
+ - 1.5.x
+ - 1.6.x
+ - 1.7.x
+ - 1.8.x
+ - tip
diff --git a/vendor/github.com/magiconair/properties/CHANGELOG.md b/vendor/github.com/magiconair/properties/CHANGELOG.md
new file mode 100644
index 000000000..1d86d0c18
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/CHANGELOG.md
@@ -0,0 +1,96 @@
+## Changelog
+
+### Unreleased
+
+ * [Issue #17](https://github.com/magiconair/properties/issues/17): Add [SetValue()](http://godoc.org/github.com/magiconair/properties#Properties.SetValue) method to set values generically
+ * [Issue #22](https://github.com/magiconair/properties/issues/22): Add [LoadMap()](http://godoc.org/github.com/magiconair/properties#LoadMap) function to load properties from a string map
+
+### [1.7.2](https://github.com/magiconair/properties/tags/v1.7.2) - 20 Mar 2017
+
+ * [Issue #15](https://github.com/magiconair/properties/issues/15): Drop gocheck dependency
+ * [PR #21](https://github.com/magiconair/properties/pull/21): Add [Map()](http://godoc.org/github.com/magiconair/properties#Properties.Map) and [FilterFunc()](http://godoc.org/github.com/magiconair/properties#Properties.FilterFunc)
+
+### [1.7.1](https://github.com/magiconair/properties/tags/v1.7.1) - 13 Jan 2017
+
+ * [PR #16](https://github.com/magiconair/properties/pull/16): Keep gofmt happy
+ * [PR #18](https://github.com/magiconair/properties/pull/18): Fix Delete() function
+
+### [1.7.0](https://github.com/magiconair/properties/tags/v1.7.0) - 20 Mar 2016
+
+ * [Issue #10](https://github.com/magiconair/properties/issues/10): Add [LoadURL,LoadURLs,MustLoadURL,MustLoadURLs](http://godoc.org/github.com/magiconair/properties#LoadURL) method to load properties from a URL.
+ * [Issue #11](https://github.com/magiconair/properties/issues/11): Add [LoadString,MustLoadString](http://godoc.org/github.com/magiconair/properties#LoadString) method to load properties from an UTF8 string.
+ * [PR #8](https://github.com/magiconair/properties/pull/8): Add [MustFlag](http://godoc.org/github.com/magiconair/properties#Properties.MustFlag) method to provide overrides via command line flags. (@pascaldekloe)
+
+### [1.6.0](https://github.com/magiconair/properties/tags/v1.6.0) - 11 Dec 2015
+
+ * Add [Decode](http://godoc.org/github.com/magiconair/properties#Properties.Decode) method to populate struct from properties via tags.
+
+### [1.5.6](https://github.com/magiconair/properties/tags/v1.5.6) - 18 Oct 2015
+
+ * Vendored in gopkg.in/check.v1
+
+### [1.5.5](https://github.com/magiconair/properties/tags/v1.5.5) - 31 Jul 2015
+
+ * [PR #6](https://github.com/magiconair/properties/pull/6): Add [Delete](http://godoc.org/github.com/magiconair/properties#Properties.Delete) method to remove keys including comments. (@gerbenjacobs)
+
+### [1.5.4](https://github.com/magiconair/properties/tags/v1.5.4) - 23 Jun 2015
+
+ * [Issue #5](https://github.com/magiconair/properties/issues/5): Allow disabling of property expansion [DisableExpansion](http://godoc.org/github.com/magiconair/properties#Properties.DisableExpansion). When property expansion is disabled Properties become a simple key/value store and don't check for circular references.
+
+### [1.5.3](https://github.com/magiconair/properties/tags/v1.5.3) - 02 Jun 2015
+
+ * [Issue #4](https://github.com/magiconair/properties/issues/4): Maintain key order in [Filter()](http://godoc.org/github.com/magiconair/properties#Properties.Filter), [FilterPrefix()](http://godoc.org/github.com/magiconair/properties#Properties.FilterPrefix) and [FilterRegexp()](http://godoc.org/github.com/magiconair/properties#Properties.FilterRegexp)
+
+### [1.5.2](https://github.com/magiconair/properties/tags/v1.5.2) - 10 Apr 2015
+
+ * [Issue #3](https://github.com/magiconair/properties/issues/3): Don't print comments in [WriteComment()](http://godoc.org/github.com/magiconair/properties#Properties.WriteComment) if they are all empty
+ * Add clickable links to README
+
+### [1.5.1](https://github.com/magiconair/properties/tags/v1.5.1) - 08 Dec 2014
+
+ * Added [GetParsedDuration()](http://godoc.org/github.com/magiconair/properties#Properties.GetParsedDuration) and [MustGetParsedDuration()](http://godoc.org/github.com/magiconair/properties#Properties.MustGetParsedDuration) for values specified compatible with
+ [time.ParseDuration()](http://golang.org/pkg/time/#ParseDuration).
+
+### [1.5.0](https://github.com/magiconair/properties/tags/v1.5.0) - 18 Nov 2014
+
+ * Added support for single and multi-line comments (reading, writing and updating)
+ * The order of keys is now preserved
+ * Calling [Set()](http://godoc.org/github.com/magiconair/properties#Properties.Set) with an empty key now silently ignores the call and does not create a new entry
+ * Added a [MustSet()](http://godoc.org/github.com/magiconair/properties#Properties.MustSet) method
+ * Migrated test library from launchpad.net/gocheck to [gopkg.in/check.v1](http://gopkg.in/check.v1)
+
+### [1.4.2](https://github.com/magiconair/properties/tags/v1.4.2) - 15 Nov 2014
+
+ * [Issue #2](https://github.com/magiconair/properties/issues/2): Fixed goroutine leak in parser which created two lexers but cleaned up only one
+
+### [1.4.1](https://github.com/magiconair/properties/tags/v1.4.1) - 13 Nov 2014
+
+ * [Issue #1](https://github.com/magiconair/properties/issues/1): Fixed bug in Keys() method which returned an empty string
+
+### [1.4.0](https://github.com/magiconair/properties/tags/v1.4.0) - 23 Sep 2014
+
+ * Added [Keys()](http://godoc.org/github.com/magiconair/properties#Properties.Keys) to get the keys
+ * Added [Filter()](http://godoc.org/github.com/magiconair/properties#Properties.Filter), [FilterRegexp()](http://godoc.org/github.com/magiconair/properties#Properties.FilterRegexp) and [FilterPrefix()](http://godoc.org/github.com/magiconair/properties#Properties.FilterPrefix) to get a subset of the properties
+
+### [1.3.0](https://github.com/magiconair/properties/tags/v1.3.0) - 18 Mar 2014
+
+* Added support for time.Duration
+* Made MustXXX() failure beha[ior configurable (log.Fatal, panic](https://github.com/magiconair/properties/tags/vior configurable (log.Fatal, panic) - custom)
+* Changed default of MustXXX() failure from panic to log.Fatal
+
+### [1.2.0](https://github.com/magiconair/properties/tags/v1.2.0) - 05 Mar 2014
+
+* Added MustGet... functions
+* Added support for int and uint with range checks on 32 bit platforms
+
+### [1.1.0](https://github.com/magiconair/properties/tags/v1.1.0) - 20 Jan 2014
+
+* Renamed from goproperties to properties
+* Added support for expansion of environment vars in
+ filenames and value expressions
+* Fixed bug where value expressions were not at the
+ start of the string
+
+### [1.0.0](https://github.com/magiconair/properties/tags/v1.0.0) - 7 Jan 2014
+
+* Initial release
diff --git a/vendor/github.com/magiconair/properties/LICENSE b/vendor/github.com/magiconair/properties/LICENSE
new file mode 100644
index 000000000..7eab43b6b
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/LICENSE
@@ -0,0 +1,25 @@
+goproperties - properties file decoder for Go
+
+Copyright (c) 2013-2014 - Frank Schroeder
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/magiconair/properties/README.md b/vendor/github.com/magiconair/properties/README.md
new file mode 100644
index 000000000..71b6a5359
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/README.md
@@ -0,0 +1,100 @@
+Overview [![Build Status](https://travis-ci.org/magiconair/properties.svg?branch=master)](https://travis-ci.org/magiconair/properties)
+========
+
+#### Current version: 1.7.2
+
+properties is a Go library for reading and writing properties files.
+
+It supports reading from multiple files or URLs and Spring style recursive
+property expansion of expressions like `${key}` to their corresponding value.
+Value expressions can refer to other keys like in `${key}` or to environment
+variables like in `${USER}`. Filenames can also contain environment variables
+like in `/home/${USER}/myapp.properties`.
+
+Properties can be decoded into structs, maps, arrays and values through
+struct tags.
+
+Comments and the order of keys are preserved. Comments can be modified
+and can be written to the output.
+
+The properties library supports both ISO-8859-1 and UTF-8 encoded data.
+
+Starting from version 1.3.0 the behavior of the MustXXX() functions is
+configurable by providing a custom `ErrorHandler` function. The default has
+changed from `panic` to `log.Fatal` but this is configurable and custom
+error handling functions can be provided. See the package documentation for
+details.
+
+Read the full documentation on [GoDoc](https://godoc.org/github.com/magiconair/properties) [![GoDoc](https://godoc.org/github.com/magiconair/properties?status.png)](https://godoc.org/github.com/magiconair/properties)
+
+Getting Started
+---------------
+
+```go
+import (
+ "flag"
+ "github.com/magiconair/properties"
+)
+
+func main() {
+ // init from a file
+ p := properties.MustLoadFile("${HOME}/config.properties", properties.UTF8)
+
+ // or multiple files
+ p = properties.MustLoadFiles([]string{
+ "${HOME}/config.properties",
+ "${HOME}/config-${USER}.properties",
+ }, properties.UTF8, true)
+
+ // or from a map
+ p = properties.LoadMap(map[string]string{"key": "value", "abc": "def"})
+
+ // or from a string
+ p = properties.MustLoadString("key=value\nabc=def")
+
+ // or from a URL
+ p = properties.MustLoadURL("http://host/path")
+
+ // or from multiple URLs
+ p = properties.MustLoadURL([]string{
+ "http://host/config",
+ "http://host/config-${USER}",
+ }, true)
+
+ // or from flags
+ p.MustFlag(flag.CommandLine)
+
+ // get values through getters
+ host := p.MustGetString("host")
+ port := p.GetInt("port", 8080)
+
+ // or through Decode
+ type Config struct {
+ Host string `properties:"host"`
+ Port int `properties:"port,default=9000"`
+ Accept []string `properties:"accept,default=image/png;image;gif"`
+ Timeout time.Duration `properties:"timeout,default=5s"`
+ }
+ var cfg Config
+ if err := p.Decode(&cfg); err != nil {
+ log.Fatal(err)
+ }
+}
+
+```
+
+Installation and Upgrade
+------------------------
+
+```
+$ go get -u github.com/magiconair/properties
+```
+
+License
+-------
+
+2 clause BSD license. See [LICENSE](https://github.com/magiconair/properties/blob/master/LICENSE) file for details.
+
+ToDo
+----
+* Dump contents with passwords and secrets obscured
diff --git a/vendor/github.com/magiconair/properties/assert/assert.go b/vendor/github.com/magiconair/properties/assert/assert.go
new file mode 100644
index 000000000..cb1097baa
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/assert/assert.go
@@ -0,0 +1,90 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package assert provides helper functions for testing.
+package assert
+
+import (
+ "fmt"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+// skip defines the default call depth
+const skip = 2
+
+// Equal asserts that got and want are equal as defined by
+// reflect.DeepEqual. The test fails with msg if they are not equal.
+func Equal(t *testing.T, got, want interface{}, msg ...string) {
+ if x := equal(2, got, want, msg...); x != "" {
+ fmt.Println(x)
+ t.Fail()
+ }
+}
+
+func equal(skip int, got, want interface{}, msg ...string) string {
+ if !reflect.DeepEqual(got, want) {
+ return fail(skip, "got %v want %v %s", got, want, strings.Join(msg, " "))
+ }
+ return ""
+}
+
+// Panic asserts that function fn() panics.
+// It assumes that recover() either returns a string or
+// an error and fails if the message does not match
+// the regular expression in 'matches'.
+func Panic(t *testing.T, fn func(), matches string) {
+ if x := doesPanic(2, fn, matches); x != "" {
+ fmt.Println(x)
+ t.Fail()
+ }
+}
+
+func doesPanic(skip int, fn func(), expr string) (err string) {
+ defer func() {
+ r := recover()
+ if r == nil {
+ err = fail(skip, "did not panic")
+ return
+ }
+ var v string
+ switch r.(type) {
+ case error:
+ v = r.(error).Error()
+ case string:
+ v = r.(string)
+ }
+ err = matches(skip, v, expr)
+ }()
+ fn()
+ return ""
+}
+
+// Matches asserts that a value matches a given regular expression.
+func Matches(t *testing.T, value, expr string) {
+ if x := matches(2, value, expr); x != "" {
+ fmt.Println(x)
+ t.Fail()
+ }
+}
+
+func matches(skip int, value, expr string) string {
+ ok, err := regexp.MatchString(expr, value)
+ if err != nil {
+ return fail(skip, "invalid pattern %q. %s", expr, err)
+ }
+ if !ok {
+ return fail(skip, "got %s which does not match %s", value, expr)
+ }
+ return ""
+}
+
+func fail(skip int, format string, args ...interface{}) string {
+ _, file, line, _ := runtime.Caller(skip)
+ return fmt.Sprintf("\t%s:%d: %s\n", filepath.Base(file), line, fmt.Sprintf(format, args...))
+}
diff --git a/vendor/github.com/magiconair/properties/assert/assert_test.go b/vendor/github.com/magiconair/properties/assert/assert_test.go
new file mode 100644
index 000000000..dcef73dfc
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/assert/assert_test.go
@@ -0,0 +1,55 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package assert
+
+import "testing"
+
+func TestEqualEquals(t *testing.T) {
+ if got, want := equal(2, "a", "a"), ""; got != want {
+ t.Fatalf("got %q want %q", got, want)
+ }
+}
+
+func TestEqualFails(t *testing.T) {
+ if got, want := equal(2, "a", "b"), "\tassert_test.go:16: got a want b \n"; got != want {
+ t.Fatalf("got %q want %q", got, want)
+ }
+}
+
+func TestPanicPanics(t *testing.T) {
+ if got, want := doesPanic(2, func() { panic("foo") }, ""), ""; got != want {
+ t.Fatalf("got %q want %q", got, want)
+ }
+}
+
+func TestPanicPanicsAndMatches(t *testing.T) {
+ if got, want := doesPanic(2, func() { panic("foo") }, "foo"), ""; got != want {
+ t.Fatalf("got %q want %q", got, want)
+ }
+}
+
+func TestPanicPanicsAndDoesNotMatch(t *testing.T) {
+ if got, want := doesPanic(2, func() { panic("foo") }, "bar"), "\tassert.go:62: got foo which does not match bar\n"; got != want {
+ t.Fatalf("got %q want %q", got, want)
+ }
+}
+
+func TestPanicPanicsAndDoesNotPanic(t *testing.T) {
+ if got, want := doesPanic(2, func() {}, "bar"), "\tassert.go:65: did not panic\n"; got != want {
+ t.Fatalf("got %q want %q", got, want)
+ }
+}
+
+func TestMatchesMatches(t *testing.T) {
+ if got, want := matches(2, "aaa", "a"), ""; got != want {
+ t.Fatalf("got %q want %q", got, want)
+ }
+}
+
+func TestMatchesDoesNotMatch(t *testing.T) {
+ if got, want := matches(2, "aaa", "b"), "\tassert_test.go:52: got aaa which does not match b\n"; got != want {
+ t.Fatalf("got %q want %q", got, want)
+ }
+}
diff --git a/vendor/github.com/magiconair/properties/benchmark_test.go b/vendor/github.com/magiconair/properties/benchmark_test.go
new file mode 100644
index 000000000..62c7cc571
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/benchmark_test.go
@@ -0,0 +1,24 @@
+// Copyright 2013-2014 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import (
+ "fmt"
+ "testing"
+)
+
+// Benchmarks the decoder by creating a property file with 1000 key/value pairs.
+func BenchmarkLoad(b *testing.B) {
+ input := ""
+ for i := 0; i < 1000; i++ {
+ input += fmt.Sprintf("key%d=value%d\n", i, i)
+ }
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ if _, err := Load([]byte(input), ISO_8859_1); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
diff --git a/vendor/github.com/magiconair/properties/decode.go b/vendor/github.com/magiconair/properties/decode.go
new file mode 100644
index 000000000..0a961bb04
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/decode.go
@@ -0,0 +1,289 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import (
+ "fmt"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// Decode assigns property values to exported fields of a struct.
+//
+// Decode traverses v recursively and returns an error if a value cannot be
+// converted to the field type or a required value is missing for a field.
+//
+// The following type dependent decodings are used:
+//
+// String, boolean, numeric fields have the value of the property key assigned.
+// The property key name is the name of the field. A different key and a default
+// value can be set in the field's tag. Fields without default value are
+// required. If the value cannot be converted to the field type an error is
+// returned.
+//
+// time.Duration fields have the result of time.ParseDuration() assigned.
+//
+// time.Time fields have the vaule of time.Parse() assigned. The default layout
+// is time.RFC3339 but can be set in the field's tag.
+//
+// Arrays and slices of string, boolean, numeric, time.Duration and time.Time
+// fields have the value interpreted as a comma separated list of values. The
+// individual values are trimmed of whitespace and empty values are ignored. A
+// default value can be provided as a semicolon separated list in the field's
+// tag.
+//
+// Struct fields are decoded recursively using the field name plus "." as
+// prefix. The prefix (without dot) can be overridden in the field's tag.
+// Default values are not supported in the field's tag. Specify them on the
+// fields of the inner struct instead.
+//
+// Map fields must have a key of type string and are decoded recursively by
+// using the field's name plus ".' as prefix and the next element of the key
+// name as map key. The prefix (without dot) can be overridden in the field's
+// tag. Default values are not supported.
+//
+// Examples:
+//
+// // Field is ignored.
+// Field int `properties:"-"`
+//
+// // Field is assigned value of 'Field'.
+// Field int
+//
+// // Field is assigned value of 'myName'.
+// Field int `properties:"myName"`
+//
+// // Field is assigned value of key 'myName' and has a default
+// // value 15 if the key does not exist.
+// Field int `properties:"myName,default=15"`
+//
+// // Field is assigned value of key 'Field' and has a default
+// // value 15 if the key does not exist.
+// Field int `properties:",default=15"`
+//
+// // Field is assigned value of key 'date' and the date
+// // is in format 2006-01-02
+// Field time.Time `properties:"date,layout=2006-01-02"`
+//
+// // Field is assigned the non-empty and whitespace trimmed
+// // values of key 'Field' split by commas.
+// Field []string
+//
+// // Field is assigned the non-empty and whitespace trimmed
+// // values of key 'Field' split by commas and has a default
+// // value ["a", "b", "c"] if the key does not exist.
+// Field []string `properties:",default=a;b;c"`
+//
+// // Field is decoded recursively with "Field." as key prefix.
+// Field SomeStruct
+//
+// // Field is decoded recursively with "myName." as key prefix.
+// Field SomeStruct `properties:"myName"`
+//
+// // Field is decoded recursively with "Field." as key prefix
+// // and the next dotted element of the key as map key.
+// Field map[string]string
+//
+// // Field is decoded recursively with "myName." as key prefix
+// // and the next dotted element of the key as map key.
+// Field map[string]string `properties:"myName"`
+func (p *Properties) Decode(x interface{}) error {
+ t, v := reflect.TypeOf(x), reflect.ValueOf(x)
+ if t.Kind() != reflect.Ptr || v.Elem().Type().Kind() != reflect.Struct {
+ return fmt.Errorf("not a pointer to struct: %s", t)
+ }
+ if err := dec(p, "", nil, nil, v); err != nil {
+ return err
+ }
+ return nil
+}
+
+func dec(p *Properties, key string, def *string, opts map[string]string, v reflect.Value) error {
+ t := v.Type()
+
+ // value returns the property value for key or the default if provided.
+ value := func() (string, error) {
+ if val, ok := p.Get(key); ok {
+ return val, nil
+ }
+ if def != nil {
+ return *def, nil
+ }
+ return "", fmt.Errorf("missing required key %s", key)
+ }
+
+ // conv converts a string to a value of the given type.
+ conv := func(s string, t reflect.Type) (val reflect.Value, err error) {
+ var v interface{}
+
+ switch {
+ case isDuration(t):
+ v, err = time.ParseDuration(s)
+
+ case isTime(t):
+ layout := opts["layout"]
+ if layout == "" {
+ layout = time.RFC3339
+ }
+ v, err = time.Parse(layout, s)
+
+ case isBool(t):
+ v, err = boolVal(s), nil
+
+ case isString(t):
+ v, err = s, nil
+
+ case isFloat(t):
+ v, err = strconv.ParseFloat(s, 64)
+
+ case isInt(t):
+ v, err = strconv.ParseInt(s, 10, 64)
+
+ case isUint(t):
+ v, err = strconv.ParseUint(s, 10, 64)
+
+ default:
+ return reflect.Zero(t), fmt.Errorf("unsupported type %s", t)
+ }
+ if err != nil {
+ return reflect.Zero(t), err
+ }
+ return reflect.ValueOf(v).Convert(t), nil
+ }
+
+ // keydef returns the property key and the default value based on the
+ // name of the struct field and the options in the tag.
+ keydef := func(f reflect.StructField) (string, *string, map[string]string) {
+ _key, _opts := parseTag(f.Tag.Get("properties"))
+
+ var _def *string
+ if d, ok := _opts["default"]; ok {
+ _def = &d
+ }
+ if _key != "" {
+ return _key, _def, _opts
+ }
+ return f.Name, _def, _opts
+ }
+
+ switch {
+ case isDuration(t) || isTime(t) || isBool(t) || isString(t) || isFloat(t) || isInt(t) || isUint(t):
+ s, err := value()
+ if err != nil {
+ return err
+ }
+ val, err := conv(s, t)
+ if err != nil {
+ return err
+ }
+ v.Set(val)
+
+ case isPtr(t):
+ return dec(p, key, def, opts, v.Elem())
+
+ case isStruct(t):
+ for i := 0; i < v.NumField(); i++ {
+ fv := v.Field(i)
+ fk, def, opts := keydef(t.Field(i))
+ if !fv.CanSet() {
+ return fmt.Errorf("cannot set %s", t.Field(i).Name)
+ }
+ if fk == "-" {
+ continue
+ }
+ if key != "" {
+ fk = key + "." + fk
+ }
+ if err := dec(p, fk, def, opts, fv); err != nil {
+ return err
+ }
+ }
+ return nil
+
+ case isArray(t):
+ val, err := value()
+ if err != nil {
+ return err
+ }
+ vals := split(val, ";")
+ a := reflect.MakeSlice(t, 0, len(vals))
+ for _, s := range vals {
+ val, err := conv(s, t.Elem())
+ if err != nil {
+ return err
+ }
+ a = reflect.Append(a, val)
+ }
+ v.Set(a)
+
+ case isMap(t):
+ valT := t.Elem()
+ m := reflect.MakeMap(t)
+ for postfix := range p.FilterStripPrefix(key + ".").m {
+ pp := strings.SplitN(postfix, ".", 2)
+ mk, mv := pp[0], reflect.New(valT)
+ if err := dec(p, key+"."+mk, nil, nil, mv); err != nil {
+ return err
+ }
+ m.SetMapIndex(reflect.ValueOf(mk), mv.Elem())
+ }
+ v.Set(m)
+
+ default:
+ return fmt.Errorf("unsupported type %s", t)
+ }
+ return nil
+}
+
+// split splits a string on sep, trims whitespace of elements
+// and omits empty elements
+func split(s string, sep string) []string {
+ var a []string
+ for _, v := range strings.Split(s, sep) {
+ if v = strings.TrimSpace(v); v != "" {
+ a = append(a, v)
+ }
+ }
+ return a
+}
+
+// parseTag parses a "key,k=v,k=v,..."
+func parseTag(tag string) (key string, opts map[string]string) {
+ opts = map[string]string{}
+ for i, s := range strings.Split(tag, ",") {
+ if i == 0 {
+ key = s
+ continue
+ }
+
+ pp := strings.SplitN(s, "=", 2)
+ if len(pp) == 1 {
+ opts[pp[0]] = ""
+ } else {
+ opts[pp[0]] = pp[1]
+ }
+ }
+ return key, opts
+}
+
+func isArray(t reflect.Type) bool { return t.Kind() == reflect.Array || t.Kind() == reflect.Slice }
+func isBool(t reflect.Type) bool { return t.Kind() == reflect.Bool }
+func isDuration(t reflect.Type) bool { return t == reflect.TypeOf(time.Second) }
+func isMap(t reflect.Type) bool { return t.Kind() == reflect.Map }
+func isPtr(t reflect.Type) bool { return t.Kind() == reflect.Ptr }
+func isString(t reflect.Type) bool { return t.Kind() == reflect.String }
+func isStruct(t reflect.Type) bool { return t.Kind() == reflect.Struct }
+func isTime(t reflect.Type) bool { return t == reflect.TypeOf(time.Time{}) }
+func isFloat(t reflect.Type) bool {
+ return t.Kind() == reflect.Float32 || t.Kind() == reflect.Float64
+}
+func isInt(t reflect.Type) bool {
+ return t.Kind() == reflect.Int || t.Kind() == reflect.Int8 || t.Kind() == reflect.Int16 || t.Kind() == reflect.Int32 || t.Kind() == reflect.Int64
+}
+func isUint(t reflect.Type) bool {
+ return t.Kind() == reflect.Uint || t.Kind() == reflect.Uint8 || t.Kind() == reflect.Uint16 || t.Kind() == reflect.Uint32 || t.Kind() == reflect.Uint64
+}
diff --git a/vendor/github.com/magiconair/properties/decode_test.go b/vendor/github.com/magiconair/properties/decode_test.go
new file mode 100644
index 000000000..c82931482
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/decode_test.go
@@ -0,0 +1,299 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import (
+ "reflect"
+ "testing"
+ "time"
+)
+
+func TestDecodeValues(t *testing.T) {
+ type S struct {
+ S string
+ BT bool
+ BF bool
+ I int
+ I8 int8
+ I16 int16
+ I32 int32
+ I64 int64
+ U uint
+ U8 uint8
+ U16 uint16
+ U32 uint32
+ U64 uint64
+ F32 float32
+ F64 float64
+ D time.Duration
+ TM time.Time
+ }
+ in := `
+ S=abc
+ BT=true
+ BF=false
+ I=-1
+ I8=-8
+ I16=-16
+ I32=-32
+ I64=-64
+ U=1
+ U8=8
+ U16=16
+ U32=32
+ U64=64
+ F32=3.2
+ F64=6.4
+ D=5s
+ TM=2015-01-02T12:34:56Z
+ `
+ out := &S{
+ S: "abc",
+ BT: true,
+ BF: false,
+ I: -1,
+ I8: -8,
+ I16: -16,
+ I32: -32,
+ I64: -64,
+ U: 1,
+ U8: 8,
+ U16: 16,
+ U32: 32,
+ U64: 64,
+ F32: 3.2,
+ F64: 6.4,
+ D: 5 * time.Second,
+ TM: tm(t, time.RFC3339, "2015-01-02T12:34:56Z"),
+ }
+ testDecode(t, in, &S{}, out)
+}
+
+func TestDecodeValueDefaults(t *testing.T) {
+ type S struct {
+ S string `properties:",default=abc"`
+ BT bool `properties:",default=true"`
+ BF bool `properties:",default=false"`
+ I int `properties:",default=-1"`
+ I8 int8 `properties:",default=-8"`
+ I16 int16 `properties:",default=-16"`
+ I32 int32 `properties:",default=-32"`
+ I64 int64 `properties:",default=-64"`
+ U uint `properties:",default=1"`
+ U8 uint8 `properties:",default=8"`
+ U16 uint16 `properties:",default=16"`
+ U32 uint32 `properties:",default=32"`
+ U64 uint64 `properties:",default=64"`
+ F32 float32 `properties:",default=3.2"`
+ F64 float64 `properties:",default=6.4"`
+ D time.Duration `properties:",default=5s"`
+ TM time.Time `properties:",default=2015-01-02T12:34:56Z"`
+ }
+ out := &S{
+ S: "abc",
+ BT: true,
+ BF: false,
+ I: -1,
+ I8: -8,
+ I16: -16,
+ I32: -32,
+ I64: -64,
+ U: 1,
+ U8: 8,
+ U16: 16,
+ U32: 32,
+ U64: 64,
+ F32: 3.2,
+ F64: 6.4,
+ D: 5 * time.Second,
+ TM: tm(t, time.RFC3339, "2015-01-02T12:34:56Z"),
+ }
+ testDecode(t, "", &S{}, out)
+}
+
+func TestDecodeArrays(t *testing.T) {
+ type S struct {
+ S []string
+ B []bool
+ I []int
+ I8 []int8
+ I16 []int16
+ I32 []int32
+ I64 []int64
+ U []uint
+ U8 []uint8
+ U16 []uint16
+ U32 []uint32
+ U64 []uint64
+ F32 []float32
+ F64 []float64
+ D []time.Duration
+ TM []time.Time
+ }
+ in := `
+ S=a;b
+ B=true;false
+ I=-1;-2
+ I8=-8;-9
+ I16=-16;-17
+ I32=-32;-33
+ I64=-64;-65
+ U=1;2
+ U8=8;9
+ U16=16;17
+ U32=32;33
+ U64=64;65
+ F32=3.2;3.3
+ F64=6.4;6.5
+ D=4s;5s
+ TM=2015-01-01T00:00:00Z;2016-01-01T00:00:00Z
+ `
+ out := &S{
+ S: []string{"a", "b"},
+ B: []bool{true, false},
+ I: []int{-1, -2},
+ I8: []int8{-8, -9},
+ I16: []int16{-16, -17},
+ I32: []int32{-32, -33},
+ I64: []int64{-64, -65},
+ U: []uint{1, 2},
+ U8: []uint8{8, 9},
+ U16: []uint16{16, 17},
+ U32: []uint32{32, 33},
+ U64: []uint64{64, 65},
+ F32: []float32{3.2, 3.3},
+ F64: []float64{6.4, 6.5},
+ D: []time.Duration{4 * time.Second, 5 * time.Second},
+ TM: []time.Time{tm(t, time.RFC3339, "2015-01-01T00:00:00Z"), tm(t, time.RFC3339, "2016-01-01T00:00:00Z")},
+ }
+ testDecode(t, in, &S{}, out)
+}
+
+func TestDecodeArrayDefaults(t *testing.T) {
+ type S struct {
+ S []string `properties:",default=a;b"`
+ B []bool `properties:",default=true;false"`
+ I []int `properties:",default=-1;-2"`
+ I8 []int8 `properties:",default=-8;-9"`
+ I16 []int16 `properties:",default=-16;-17"`
+ I32 []int32 `properties:",default=-32;-33"`
+ I64 []int64 `properties:",default=-64;-65"`
+ U []uint `properties:",default=1;2"`
+ U8 []uint8 `properties:",default=8;9"`
+ U16 []uint16 `properties:",default=16;17"`
+ U32 []uint32 `properties:",default=32;33"`
+ U64 []uint64 `properties:",default=64;65"`
+ F32 []float32 `properties:",default=3.2;3.3"`
+ F64 []float64 `properties:",default=6.4;6.5"`
+ D []time.Duration `properties:",default=4s;5s"`
+ TM []time.Time `properties:",default=2015-01-01T00:00:00Z;2016-01-01T00:00:00Z"`
+ }
+ out := &S{
+ S: []string{"a", "b"},
+ B: []bool{true, false},
+ I: []int{-1, -2},
+ I8: []int8{-8, -9},
+ I16: []int16{-16, -17},
+ I32: []int32{-32, -33},
+ I64: []int64{-64, -65},
+ U: []uint{1, 2},
+ U8: []uint8{8, 9},
+ U16: []uint16{16, 17},
+ U32: []uint32{32, 33},
+ U64: []uint64{64, 65},
+ F32: []float32{3.2, 3.3},
+ F64: []float64{6.4, 6.5},
+ D: []time.Duration{4 * time.Second, 5 * time.Second},
+ TM: []time.Time{tm(t, time.RFC3339, "2015-01-01T00:00:00Z"), tm(t, time.RFC3339, "2016-01-01T00:00:00Z")},
+ }
+ testDecode(t, "", &S{}, out)
+}
+
+func TestDecodeSkipUndef(t *testing.T) {
+ type S struct {
+ X string `properties:"-"`
+ Undef string `properties:",default=some value"`
+ }
+ in := `X=ignore`
+ out := &S{"", "some value"}
+ testDecode(t, in, &S{}, out)
+}
+
+func TestDecodeStruct(t *testing.T) {
+ type A struct {
+ S string
+ T string `properties:"t"`
+ U string `properties:"u,default=uuu"`
+ }
+ type S struct {
+ A A
+ B A `properties:"b"`
+ }
+ in := `
+ A.S=sss
+ A.t=ttt
+ b.S=SSS
+ b.t=TTT
+ `
+ out := &S{
+ A{S: "sss", T: "ttt", U: "uuu"},
+ A{S: "SSS", T: "TTT", U: "uuu"},
+ }
+ testDecode(t, in, &S{}, out)
+}
+
+func TestDecodeMap(t *testing.T) {
+ type S struct {
+ A string `properties:"a"`
+ }
+ type X struct {
+ A map[string]string
+ B map[string][]string
+ C map[string]map[string]string
+ D map[string]S
+ E map[string]int
+ F map[string]int `properties:"-"`
+ }
+ in := `
+ A.foo=bar
+ A.bar=bang
+ B.foo=a;b;c
+ B.bar=1;2;3
+ C.foo.one=1
+ C.foo.two=2
+ C.bar.three=3
+ C.bar.four=4
+ D.foo.a=bar
+ `
+ out := &X{
+ A: map[string]string{"foo": "bar", "bar": "bang"},
+ B: map[string][]string{"foo": []string{"a", "b", "c"}, "bar": []string{"1", "2", "3"}},
+ C: map[string]map[string]string{"foo": map[string]string{"one": "1", "two": "2"}, "bar": map[string]string{"three": "3", "four": "4"}},
+ D: map[string]S{"foo": S{"bar"}},
+ E: map[string]int{},
+ }
+ testDecode(t, in, &X{}, out)
+}
+
+func testDecode(t *testing.T, in string, v, out interface{}) {
+ p, err := parse(in)
+ if err != nil {
+ t.Fatalf("got %v want nil", err)
+ }
+ if err := p.Decode(v); err != nil {
+ t.Fatalf("got %v want nil", err)
+ }
+ if got, want := v, out; !reflect.DeepEqual(got, want) {
+ t.Fatalf("\ngot %+v\nwant %+v", got, want)
+ }
+}
+
+func tm(t *testing.T, layout, s string) time.Time {
+ tm, err := time.Parse(layout, s)
+ if err != nil {
+ t.Fatalf("got %v want nil", err)
+ }
+ return tm
+}
diff --git a/vendor/github.com/magiconair/properties/doc.go b/vendor/github.com/magiconair/properties/doc.go
new file mode 100644
index 000000000..36c836808
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/doc.go
@@ -0,0 +1,156 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package properties provides functions for reading and writing
+// ISO-8859-1 and UTF-8 encoded .properties files and has
+// support for recursive property expansion.
+//
+// Java properties files are ISO-8859-1 encoded and use Unicode
+// literals for characters outside the ISO character set. Unicode
+// literals can be used in UTF-8 encoded properties files but
+// aren't necessary.
+//
+// To load a single properties file use MustLoadFile():
+//
+// p := properties.MustLoadFile(filename, properties.UTF8)
+//
+// To load multiple properties files use MustLoadFiles()
+// which loads the files in the given order and merges the
+// result. Missing properties files can be ignored if the
+// 'ignoreMissing' flag is set to true.
+//
+// Filenames can contain environment variables which are expanded
+// before loading.
+//
+// f1 := "/etc/myapp/myapp.conf"
+// f2 := "/home/${USER}/myapp.conf"
+// p := MustLoadFiles([]string{f1, f2}, properties.UTF8, true)
+//
+// All of the different key/value delimiters ' ', ':' and '=' are
+// supported as well as the comment characters '!' and '#' and
+// multi-line values.
+//
+// ! this is a comment
+// # and so is this
+//
+// # the following expressions are equal
+// key value
+// key=value
+// key:value
+// key = value
+// key : value
+// key = val\
+// ue
+//
+// Properties stores all comments preceding a key and provides
+// GetComments() and SetComments() methods to retrieve and
+// update them. The convenience functions GetComment() and
+// SetComment() allow access to the last comment. The
+// WriteComment() method writes properties files including
+// the comments and with the keys in the original order.
+// This can be used for sanitizing properties files.
+//
+// Property expansion is recursive and circular references
+// and malformed expressions are not allowed and cause an
+// error. Expansion of environment variables is supported.
+//
+// # standard property
+// key = value
+//
+// # property expansion: key2 = value
+// key2 = ${key}
+//
+// # recursive expansion: key3 = value
+// key3 = ${key2}
+//
+// # circular reference (error)
+// key = ${key}
+//
+// # malformed expression (error)
+// key = ${ke
+//
+// # refers to the users' home dir
+// home = ${HOME}
+//
+// # local key takes precendence over env var: u = foo
+// USER = foo
+// u = ${USER}
+//
+// The default property expansion format is ${key} but can be
+// changed by setting different pre- and postfix values on the
+// Properties object.
+//
+// p := properties.NewProperties()
+// p.Prefix = "#["
+// p.Postfix = "]#"
+//
+// Properties provides convenience functions for getting typed
+// values with default values if the key does not exist or the
+// type conversion failed.
+//
+// # Returns true if the value is either "1", "on", "yes" or "true"
+// # Returns false for every other value and the default value if
+// # the key does not exist.
+// v = p.GetBool("key", false)
+//
+// # Returns the value if the key exists and the format conversion
+// # was successful. Otherwise, the default value is returned.
+// v = p.GetInt64("key", 999)
+// v = p.GetUint64("key", 999)
+// v = p.GetFloat64("key", 123.0)
+// v = p.GetString("key", "def")
+// v = p.GetDuration("key", 999)
+//
+// As an alterantive properties may be applied with the standard
+// library's flag implementation at any time.
+//
+// # Standard configuration
+// v = flag.Int("key", 999, "help message")
+// flag.Parse()
+//
+// # Merge p into the flag set
+// p.MustFlag(flag.CommandLine)
+//
+// Properties provides several MustXXX() convenience functions
+// which will terminate the app if an error occurs. The behavior
+// of the failure is configurable and the default is to call
+// log.Fatal(err). To have the MustXXX() functions panic instead
+// of logging the error set a different ErrorHandler before
+// you use the Properties package.
+//
+// properties.ErrorHandler = properties.PanicHandler
+//
+// # Will panic instead of logging an error
+// p := properties.MustLoadFile("config.properties")
+//
+// You can also provide your own ErrorHandler function. The only requirement
+// is that the error handler function must exit after handling the error.
+//
+// properties.ErrorHandler = func(err error) {
+// fmt.Println(err)
+// os.Exit(1)
+// }
+//
+// # Will write to stdout and then exit
+// p := properties.MustLoadFile("config.properties")
+//
+// Properties can also be loaded into a struct via the `Decode`
+// method, e.g.
+//
+// type S struct {
+// A string `properties:"a,default=foo"`
+// D time.Duration `properties:"timeout,default=5s"`
+// E time.Time `properties:"expires,layout=2006-01-02,default=2015-01-01"`
+// }
+//
+// See `Decode()` method for the full documentation.
+//
+// The following documents provide a description of the properties
+// file format.
+//
+// http://en.wikipedia.org/wiki/.properties
+//
+// http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html#load%28java.io.Reader%29
+//
+package properties
diff --git a/vendor/github.com/magiconair/properties/example_test.go b/vendor/github.com/magiconair/properties/example_test.go
new file mode 100644
index 000000000..6f21dfbd8
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/example_test.go
@@ -0,0 +1,93 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import (
+ "fmt"
+ "log"
+)
+
+func ExampleLoad_iso88591() {
+ buf := []byte("key = ISO-8859-1 value with unicode literal \\u2318 and umlaut \xE4") // 0xE4 == ä
+ p, _ := Load(buf, ISO_8859_1)
+ v, ok := p.Get("key")
+ fmt.Println(ok)
+ fmt.Println(v)
+ // Output:
+ // true
+ // ISO-8859-1 value with unicode literal ⌘ and umlaut ä
+}
+
+func ExampleLoad_utf8() {
+ p, _ := Load([]byte("key = UTF-8 value with unicode character ⌘ and umlaut ä"), UTF8)
+ v, ok := p.Get("key")
+ fmt.Println(ok)
+ fmt.Println(v)
+ // Output:
+ // true
+ // UTF-8 value with unicode character ⌘ and umlaut ä
+}
+
+func ExampleProperties_GetBool() {
+ var input = `
+ key=1
+ key2=On
+ key3=YES
+ key4=true`
+ p, _ := Load([]byte(input), ISO_8859_1)
+ fmt.Println(p.GetBool("key", false))
+ fmt.Println(p.GetBool("key2", false))
+ fmt.Println(p.GetBool("key3", false))
+ fmt.Println(p.GetBool("key4", false))
+ fmt.Println(p.GetBool("keyX", false))
+ // Output:
+ // true
+ // true
+ // true
+ // true
+ // false
+}
+
+func ExampleProperties_GetString() {
+ p, _ := Load([]byte("key=value"), ISO_8859_1)
+ v := p.GetString("another key", "default value")
+ fmt.Println(v)
+ // Output:
+ // default value
+}
+
+func Example() {
+ // Decode some key/value pairs with expressions
+ p, err := Load([]byte("key=value\nkey2=${key}"), ISO_8859_1)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ // Get a valid key
+ if v, ok := p.Get("key"); ok {
+ fmt.Println(v)
+ }
+
+ // Get an invalid key
+ if _, ok := p.Get("does not exist"); !ok {
+ fmt.Println("invalid key")
+ }
+
+ // Get a key with a default value
+ v := p.GetString("does not exist", "some value")
+ fmt.Println(v)
+
+ // Dump the expanded key/value pairs of the Properties
+ fmt.Println("Expanded key/value pairs")
+ fmt.Println(p)
+
+ // Output:
+ // value
+ // invalid key
+ // some value
+ // Expanded key/value pairs
+ // key = value
+ // key2 = value
+}
diff --git a/vendor/github.com/magiconair/properties/integrate.go b/vendor/github.com/magiconair/properties/integrate.go
new file mode 100644
index 000000000..0d775e035
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/integrate.go
@@ -0,0 +1,34 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import "flag"
+
+// MustFlag sets flags that are skipped by dst.Parse when p contains
+// the respective key for flag.Flag.Name.
+//
+// It's use is recommended with command line arguments as in:
+// flag.Parse()
+// p.MustFlag(flag.CommandLine)
+func (p *Properties) MustFlag(dst *flag.FlagSet) {
+ m := make(map[string]*flag.Flag)
+ dst.VisitAll(func(f *flag.Flag) {
+ m[f.Name] = f
+ })
+ dst.Visit(func(f *flag.Flag) {
+ delete(m, f.Name) // overridden
+ })
+
+ for name, f := range m {
+ v, ok := p.Get(name)
+ if !ok {
+ continue
+ }
+
+ if err := f.Value.Set(v); err != nil {
+ ErrorHandler(err)
+ }
+ }
+}
diff --git a/vendor/github.com/magiconair/properties/integrate_test.go b/vendor/github.com/magiconair/properties/integrate_test.go
new file mode 100644
index 000000000..cbee181f6
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/integrate_test.go
@@ -0,0 +1,76 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import (
+ "flag"
+ "fmt"
+ "testing"
+)
+
+// TestFlag verifies Properties.MustFlag without flag.FlagSet.Parse
+func TestFlag(t *testing.T) {
+ f := flag.NewFlagSet("src", flag.PanicOnError)
+ gotS := f.String("s", "?", "string flag")
+ gotI := f.Int("i", -1, "int flag")
+
+ p := NewProperties()
+ p.MustSet("s", "t")
+ p.MustSet("i", "9")
+ p.MustFlag(f)
+
+ if want := "t"; *gotS != want {
+ t.Errorf("Got string s=%q, want %q", *gotS, want)
+ }
+ if want := 9; *gotI != want {
+ t.Errorf("Got int i=%d, want %d", *gotI, want)
+ }
+}
+
+// TestFlagOverride verifies Properties.MustFlag with flag.FlagSet.Parse.
+func TestFlagOverride(t *testing.T) {
+ f := flag.NewFlagSet("src", flag.PanicOnError)
+ gotA := f.Int("a", 1, "remain default")
+ gotB := f.Int("b", 2, "customized")
+ gotC := f.Int("c", 3, "overridden")
+
+ if err := f.Parse([]string{"-c", "4"}); err != nil {
+ t.Fatal(err)
+ }
+
+ p := NewProperties()
+ p.MustSet("b", "5")
+ p.MustSet("c", "6")
+ p.MustFlag(f)
+
+ if want := 1; *gotA != want {
+ t.Errorf("Got remain default a=%d, want %d", *gotA, want)
+ }
+ if want := 5; *gotB != want {
+ t.Errorf("Got customized b=%d, want %d", *gotB, want)
+ }
+ if want := 4; *gotC != want {
+ t.Errorf("Got overriden c=%d, want %d", *gotC, want)
+ }
+}
+
+func ExampleProperties_MustFlag() {
+ x := flag.Int("x", 0, "demo customize")
+ y := flag.Int("y", 0, "demo override")
+
+ // Demo alternative for flag.Parse():
+ flag.CommandLine.Parse([]string{"-y", "10"})
+ fmt.Printf("flagged as x=%d, y=%d\n", *x, *y)
+
+ p := NewProperties()
+ p.MustSet("x", "7")
+ p.MustSet("y", "42") // note discard
+ p.MustFlag(flag.CommandLine)
+ fmt.Printf("configured to x=%d, y=%d\n", *x, *y)
+
+ // Output:
+ // flagged as x=0, y=10
+ // configured to x=7, y=10
+}
diff --git a/vendor/github.com/magiconair/properties/lex.go b/vendor/github.com/magiconair/properties/lex.go
new file mode 100644
index 000000000..a3cba0319
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/lex.go
@@ -0,0 +1,408 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+//
+// Parts of the lexer are from the template/text/parser package
+// For these parts the following applies:
+//
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file of the go 1.2
+// distribution.
+
+package properties
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+)
+
+// item represents a token or text string returned from the scanner.
+type item struct {
+ typ itemType // The type of this item.
+ pos int // The starting position, in bytes, of this item in the input string.
+ val string // The value of this item.
+}
+
+func (i item) String() string {
+ switch {
+ case i.typ == itemEOF:
+ return "EOF"
+ case i.typ == itemError:
+ return i.val
+ case len(i.val) > 10:
+ return fmt.Sprintf("%.10q...", i.val)
+ }
+ return fmt.Sprintf("%q", i.val)
+}
+
+// itemType identifies the type of lex items.
+type itemType int
+
+const (
+ itemError itemType = iota // error occurred; value is text of error
+ itemEOF
+ itemKey // a key
+ itemValue // a value
+ itemComment // a comment
+)
+
+// defines a constant for EOF
+const eof = -1
+
+// permitted whitespace characters space, FF and TAB
+const whitespace = " \f\t"
+
+// stateFn represents the state of the scanner as a function that returns the next state.
+type stateFn func(*lexer) stateFn
+
+// lexer holds the state of the scanner.
+type lexer struct {
+ input string // the string being scanned
+ state stateFn // the next lexing function to enter
+ pos int // current position in the input
+ start int // start position of this item
+ width int // width of last rune read from input
+ lastPos int // position of most recent item returned by nextItem
+ runes []rune // scanned runes for this item
+ items chan item // channel of scanned items
+}
+
+// next returns the next rune in the input.
+func (l *lexer) next() rune {
+ if l.pos >= len(l.input) {
+ l.width = 0
+ return eof
+ }
+ r, w := utf8.DecodeRuneInString(l.input[l.pos:])
+ l.width = w
+ l.pos += l.width
+ return r
+}
+
+// peek returns but does not consume the next rune in the input.
+func (l *lexer) peek() rune {
+ r := l.next()
+ l.backup()
+ return r
+}
+
+// backup steps back one rune. Can only be called once per call of next.
+func (l *lexer) backup() {
+ l.pos -= l.width
+}
+
+// emit passes an item back to the client.
+func (l *lexer) emit(t itemType) {
+ i := item{t, l.start, string(l.runes)}
+ l.items <- i
+ l.start = l.pos
+ l.runes = l.runes[:0]
+}
+
+// ignore skips over the pending input before this point.
+func (l *lexer) ignore() {
+ l.start = l.pos
+}
+
+// appends the rune to the current value
+func (l *lexer) appendRune(r rune) {
+ l.runes = append(l.runes, r)
+}
+
+// accept consumes the next rune if it's from the valid set.
+func (l *lexer) accept(valid string) bool {
+ if strings.ContainsRune(valid, l.next()) {
+ return true
+ }
+ l.backup()
+ return false
+}
+
+// acceptRun consumes a run of runes from the valid set.
+func (l *lexer) acceptRun(valid string) {
+ for strings.ContainsRune(valid, l.next()) {
+ }
+ l.backup()
+}
+
+// acceptRunUntil consumes a run of runes up to a terminator.
+func (l *lexer) acceptRunUntil(term rune) {
+ for term != l.next() {
+ }
+ l.backup()
+}
+
+// hasText returns true if the current parsed text is not empty.
+func (l *lexer) isNotEmpty() bool {
+ return l.pos > l.start
+}
+
+// lineNumber reports which line we're on, based on the position of
+// the previous item returned by nextItem. Doing it this way
+// means we don't have to worry about peek double counting.
+func (l *lexer) lineNumber() int {
+ return 1 + strings.Count(l.input[:l.lastPos], "\n")
+}
+
+// errorf returns an error token and terminates the scan by passing
+// back a nil pointer that will be the next state, terminating l.nextItem.
+func (l *lexer) errorf(format string, args ...interface{}) stateFn {
+ l.items <- item{itemError, l.start, fmt.Sprintf(format, args...)}
+ return nil
+}
+
+// nextItem returns the next item from the input.
+func (l *lexer) nextItem() item {
+ i := <-l.items
+ l.lastPos = i.pos
+ return i
+}
+
+// lex creates a new scanner for the input string.
+func lex(input string) *lexer {
+ l := &lexer{
+ input: input,
+ items: make(chan item),
+ runes: make([]rune, 0, 32),
+ }
+ go l.run()
+ return l
+}
+
+// run runs the state machine for the lexer.
+func (l *lexer) run() {
+ for l.state = lexBeforeKey(l); l.state != nil; {
+ l.state = l.state(l)
+ }
+}
+
+// state functions
+
+// lexBeforeKey scans until a key begins.
+func lexBeforeKey(l *lexer) stateFn {
+ switch r := l.next(); {
+ case isEOF(r):
+ l.emit(itemEOF)
+ return nil
+
+ case isEOL(r):
+ l.ignore()
+ return lexBeforeKey
+
+ case isComment(r):
+ return lexComment
+
+ case isWhitespace(r):
+ l.acceptRun(whitespace)
+ l.ignore()
+ return lexKey
+
+ default:
+ l.backup()
+ return lexKey
+ }
+}
+
+// lexComment scans a comment line. The comment character has already been scanned.
+func lexComment(l *lexer) stateFn {
+ l.acceptRun(whitespace)
+ l.ignore()
+ for {
+ switch r := l.next(); {
+ case isEOF(r):
+ l.ignore()
+ l.emit(itemEOF)
+ return nil
+ case isEOL(r):
+ l.emit(itemComment)
+ return lexBeforeKey
+ default:
+ l.appendRune(r)
+ }
+ }
+}
+
+// lexKey scans the key up to a delimiter
+func lexKey(l *lexer) stateFn {
+ var r rune
+
+Loop:
+ for {
+ switch r = l.next(); {
+
+ case isEscape(r):
+ err := l.scanEscapeSequence()
+ if err != nil {
+ return l.errorf(err.Error())
+ }
+
+ case isEndOfKey(r):
+ l.backup()
+ break Loop
+
+ case isEOF(r):
+ break Loop
+
+ default:
+ l.appendRune(r)
+ }
+ }
+
+ if len(l.runes) > 0 {
+ l.emit(itemKey)
+ }
+
+ if isEOF(r) {
+ l.emit(itemEOF)
+ return nil
+ }
+
+ return lexBeforeValue
+}
+
+// lexBeforeValue scans the delimiter between key and value.
+// Leading and trailing whitespace is ignored.
+// We expect to be just after the key.
+func lexBeforeValue(l *lexer) stateFn {
+ l.acceptRun(whitespace)
+ l.accept(":=")
+ l.acceptRun(whitespace)
+ l.ignore()
+ return lexValue
+}
+
+// lexValue scans text until the end of the line. We expect to be just after the delimiter.
+func lexValue(l *lexer) stateFn {
+ for {
+ switch r := l.next(); {
+ case isEscape(r):
+ if isEOL(l.peek()) {
+ l.next()
+ l.acceptRun(whitespace)
+ } else {
+ err := l.scanEscapeSequence()
+ if err != nil {
+ return l.errorf(err.Error())
+ }
+ }
+
+ case isEOL(r):
+ l.emit(itemValue)
+ l.ignore()
+ return lexBeforeKey
+
+ case isEOF(r):
+ l.emit(itemValue)
+ l.emit(itemEOF)
+ return nil
+
+ default:
+ l.appendRune(r)
+ }
+ }
+}
+
+// scanEscapeSequence scans either one of the escaped characters
+// or a unicode literal. We expect to be after the escape character.
+func (l *lexer) scanEscapeSequence() error {
+ switch r := l.next(); {
+
+ case isEscapedCharacter(r):
+ l.appendRune(decodeEscapedCharacter(r))
+ return nil
+
+ case atUnicodeLiteral(r):
+ return l.scanUnicodeLiteral()
+
+ case isEOF(r):
+ return fmt.Errorf("premature EOF")
+
+ // silently drop the escape character and append the rune as is
+ default:
+ l.appendRune(r)
+ return nil
+ }
+}
+
+// scans a unicode literal in the form \uXXXX. We expect to be after the \u.
+func (l *lexer) scanUnicodeLiteral() error {
+ // scan the digits
+ d := make([]rune, 4)
+ for i := 0; i < 4; i++ {
+ d[i] = l.next()
+ if d[i] == eof || !strings.ContainsRune("0123456789abcdefABCDEF", d[i]) {
+ return fmt.Errorf("invalid unicode literal")
+ }
+ }
+
+ // decode the digits into a rune
+ r, err := strconv.ParseInt(string(d), 16, 0)
+ if err != nil {
+ return err
+ }
+
+ l.appendRune(rune(r))
+ return nil
+}
+
+// decodeEscapedCharacter returns the unescaped rune. We expect to be after the escape character.
+func decodeEscapedCharacter(r rune) rune {
+ switch r {
+ case 'f':
+ return '\f'
+ case 'n':
+ return '\n'
+ case 'r':
+ return '\r'
+ case 't':
+ return '\t'
+ default:
+ return r
+ }
+}
+
+// atUnicodeLiteral reports whether we are at a unicode literal.
+// The escape character has already been consumed.
+func atUnicodeLiteral(r rune) bool {
+ return r == 'u'
+}
+
+// isComment reports whether we are at the start of a comment.
+func isComment(r rune) bool {
+ return r == '#' || r == '!'
+}
+
+// isEndOfKey reports whether the rune terminates the current key.
+func isEndOfKey(r rune) bool {
+ return strings.ContainsRune(" \f\t\r\n:=", r)
+}
+
+// isEOF reports whether we are at EOF.
+func isEOF(r rune) bool {
+ return r == eof
+}
+
+// isEOL reports whether we are at a new line character.
+func isEOL(r rune) bool {
+ return r == '\n' || r == '\r'
+}
+
+// isEscape reports whether the rune is the escape character which
+// prefixes unicode literals and other escaped characters.
+func isEscape(r rune) bool {
+ return r == '\\'
+}
+
+// isEscapedCharacter reports whether we are at one of the characters that need escaping.
+// The escape character has already been consumed.
+func isEscapedCharacter(r rune) bool {
+ return strings.ContainsRune(" :=fnrt", r)
+}
+
+// isWhitespace reports whether the rune is a whitespace character.
+func isWhitespace(r rune) bool {
+ return strings.ContainsRune(whitespace, r)
+}
diff --git a/vendor/github.com/magiconair/properties/load.go b/vendor/github.com/magiconair/properties/load.go
new file mode 100644
index 000000000..278cc2ea0
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/load.go
@@ -0,0 +1,241 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import (
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "os"
+ "strings"
+)
+
+// Encoding specifies encoding of the input data.
+type Encoding uint
+
+const (
+ // UTF8 interprets the input data as UTF-8.
+ UTF8 Encoding = 1 << iota
+
+ // ISO_8859_1 interprets the input data as ISO-8859-1.
+ ISO_8859_1
+)
+
+// Load reads a buffer into a Properties struct.
+func Load(buf []byte, enc Encoding) (*Properties, error) {
+ return loadBuf(buf, enc)
+}
+
+// LoadString reads an UTF8 string into a properties struct.
+func LoadString(s string) (*Properties, error) {
+ return loadBuf([]byte(s), UTF8)
+}
+
+// LoadMap creates a new Properties struct from a string map.
+func LoadMap(m map[string]string) *Properties {
+ p := NewProperties()
+ for k, v := range m {
+ p.Set(k, v)
+ }
+ return p
+}
+
+// LoadFile reads a file into a Properties struct.
+func LoadFile(filename string, enc Encoding) (*Properties, error) {
+ return loadAll([]string{filename}, enc, false)
+}
+
+// LoadFiles reads multiple files in the given order into
+// a Properties struct. If 'ignoreMissing' is true then
+// non-existent files will not be reported as error.
+func LoadFiles(filenames []string, enc Encoding, ignoreMissing bool) (*Properties, error) {
+ return loadAll(filenames, enc, ignoreMissing)
+}
+
+// LoadURL reads the content of the URL into a Properties struct.
+//
+// The encoding is determined via the Content-Type header which
+// should be set to 'text/plain'. If the 'charset' parameter is
+// missing, 'iso-8859-1' or 'latin1' the encoding is set to
+// ISO-8859-1. If the 'charset' parameter is set to 'utf-8' the
+// encoding is set to UTF-8. A missing content type header is
+// interpreted as 'text/plain; charset=utf-8'.
+func LoadURL(url string) (*Properties, error) {
+ return loadAll([]string{url}, UTF8, false)
+}
+
+// LoadURLs reads the content of multiple URLs in the given order into a
+// Properties struct. If 'ignoreMissing' is true then a 404 status code will
+// not be reported as error. See LoadURL for the Content-Type header
+// and the encoding.
+func LoadURLs(urls []string, ignoreMissing bool) (*Properties, error) {
+ return loadAll(urls, UTF8, ignoreMissing)
+}
+
+// LoadAll reads the content of multiple URLs or files in the given order into a
+// Properties struct. If 'ignoreMissing' is true then a 404 status code or missing file will
+// not be reported as error. Encoding sets the encoding for files. For the URLs please see
+// LoadURL for the Content-Type header and the encoding.
+func LoadAll(names []string, enc Encoding, ignoreMissing bool) (*Properties, error) {
+ return loadAll(names, enc, ignoreMissing)
+}
+
+// MustLoadString reads an UTF8 string into a Properties struct and
+// panics on error.
+func MustLoadString(s string) *Properties {
+ return must(LoadString(s))
+}
+
+// MustLoadFile reads a file into a Properties struct and
+// panics on error.
+func MustLoadFile(filename string, enc Encoding) *Properties {
+ return must(LoadFile(filename, enc))
+}
+
+// MustLoadFiles reads multiple files in the given order into
+// a Properties struct and panics on error. If 'ignoreMissing'
+// is true then non-existent files will not be reported as error.
+func MustLoadFiles(filenames []string, enc Encoding, ignoreMissing bool) *Properties {
+ return must(LoadFiles(filenames, enc, ignoreMissing))
+}
+
+// MustLoadURL reads the content of a URL into a Properties struct and
+// panics on error.
+func MustLoadURL(url string) *Properties {
+ return must(LoadURL(url))
+}
+
+// MustLoadURLs reads the content of multiple URLs in the given order into a
+// Properties struct and panics on error. If 'ignoreMissing' is true then a 404
+// status code will not be reported as error.
+func MustLoadURLs(urls []string, ignoreMissing bool) *Properties {
+ return must(LoadURLs(urls, ignoreMissing))
+}
+
+// MustLoadAll reads the content of multiple URLs or files in the given order into a
+// Properties struct. If 'ignoreMissing' is true then a 404 status code or missing file will
+// not be reported as error. Encoding sets the encoding for files. For the URLs please see
+// LoadURL for the Content-Type header and the encoding. It panics on error.
+func MustLoadAll(names []string, enc Encoding, ignoreMissing bool) *Properties {
+ return must(LoadAll(names, enc, ignoreMissing))
+}
+
+func loadBuf(buf []byte, enc Encoding) (*Properties, error) {
+ p, err := parse(convert(buf, enc))
+ if err != nil {
+ return nil, err
+ }
+ return p, p.check()
+}
+
+func loadAll(names []string, enc Encoding, ignoreMissing bool) (*Properties, error) {
+ result := NewProperties()
+ for _, name := range names {
+ n, err := expandName(name)
+ if err != nil {
+ return nil, err
+ }
+ var p *Properties
+ if strings.HasPrefix(n, "http://") || strings.HasPrefix(n, "https://") {
+ p, err = loadURL(n, ignoreMissing)
+ } else {
+ p, err = loadFile(n, enc, ignoreMissing)
+ }
+ if err != nil {
+ return nil, err
+ }
+ result.Merge(p)
+
+ }
+ return result, result.check()
+}
+
+func loadFile(filename string, enc Encoding, ignoreMissing bool) (*Properties, error) {
+ data, err := ioutil.ReadFile(filename)
+ if err != nil {
+ if ignoreMissing && os.IsNotExist(err) {
+ LogPrintf("properties: %s not found. skipping", filename)
+ return NewProperties(), nil
+ }
+ return nil, err
+ }
+ p, err := parse(convert(data, enc))
+ if err != nil {
+ return nil, err
+ }
+ return p, nil
+}
+
+func loadURL(url string, ignoreMissing bool) (*Properties, error) {
+ resp, err := http.Get(url)
+ if err != nil {
+ return nil, fmt.Errorf("properties: error fetching %q. %s", url, err)
+ }
+ if resp.StatusCode == 404 && ignoreMissing {
+ LogPrintf("properties: %s returned %d. skipping", url, resp.StatusCode)
+ return NewProperties(), nil
+ }
+ if resp.StatusCode != 200 {
+ return nil, fmt.Errorf("properties: %s returned %d", url, resp.StatusCode)
+ }
+ body, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("properties: %s error reading response. %s", url, err)
+ }
+ if err = resp.Body.Close(); err != nil {
+ return nil, fmt.Errorf("properties: %s error reading response. %s", url, err)
+ }
+
+ ct := resp.Header.Get("Content-Type")
+ var enc Encoding
+ switch strings.ToLower(ct) {
+ case "text/plain", "text/plain; charset=iso-8859-1", "text/plain; charset=latin1":
+ enc = ISO_8859_1
+ case "", "text/plain; charset=utf-8":
+ enc = UTF8
+ default:
+ return nil, fmt.Errorf("properties: invalid content type %s", ct)
+ }
+
+ p, err := parse(convert(body, enc))
+ if err != nil {
+ return nil, err
+ }
+ return p, nil
+}
+
+func must(p *Properties, err error) *Properties {
+ if err != nil {
+ ErrorHandler(err)
+ }
+ return p
+}
+
+// expandName expands ${ENV_VAR} expressions in a name.
+// If the environment variable does not exist then it will be replaced
+// with an empty string. Malformed expressions like "${ENV_VAR" will
+// be reported as error.
+func expandName(name string) (string, error) {
+ return expand(name, make(map[string]bool), "${", "}", make(map[string]string))
+}
+
+// Interprets a byte buffer either as an ISO-8859-1 or UTF-8 encoded string.
+// For ISO-8859-1 we can convert each byte straight into a rune since the
+// first 256 unicode code points cover ISO-8859-1.
+func convert(buf []byte, enc Encoding) string {
+ switch enc {
+ case UTF8:
+ return string(buf)
+ case ISO_8859_1:
+ runes := make([]rune, len(buf))
+ for i, b := range buf {
+ runes[i] = rune(b)
+ }
+ return string(runes)
+ default:
+ ErrorHandler(fmt.Errorf("unsupported encoding %v", enc))
+ }
+ panic("ErrorHandler should exit")
+}
diff --git a/vendor/github.com/magiconair/properties/load_test.go b/vendor/github.com/magiconair/properties/load_test.go
new file mode 100644
index 000000000..d8770c8a0
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/load_test.go
@@ -0,0 +1,231 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import (
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/magiconair/properties/assert"
+)
+
+func TestLoadFailsWithNotExistingFile(t *testing.T) {
+ _, err := LoadFile("doesnotexist.properties", ISO_8859_1)
+ assert.Equal(t, err != nil, true, "")
+ assert.Matches(t, err.Error(), "open.*no such file or directory")
+}
+
+func TestLoadFilesFailsOnNotExistingFile(t *testing.T) {
+ _, err := LoadFile("doesnotexist.properties", ISO_8859_1)
+ assert.Equal(t, err != nil, true, "")
+ assert.Matches(t, err.Error(), "open.*no such file or directory")
+}
+
+func TestLoadFilesDoesNotFailOnNotExistingFileAndIgnoreMissing(t *testing.T) {
+ p, err := LoadFiles([]string{"doesnotexist.properties"}, ISO_8859_1, true)
+ assert.Equal(t, err, nil)
+ assert.Equal(t, p.Len(), 0)
+}
+
+func TestLoadString(t *testing.T) {
+ x := "key=äüö"
+ p1 := MustLoadString(x)
+ p2 := must(Load([]byte(x), UTF8))
+ assert.Equal(t, p1, p2)
+}
+
+func TestLoadMap(t *testing.T) {
+ // LoadMap does not guarantee the same import order
+ // of keys every time since map access is randomized.
+ // Therefore, we need to compare the generated maps.
+ m := map[string]string{"key": "value", "abc": "def"}
+ assert.Equal(t, LoadMap(m).Map(), m)
+}
+
+func TestLoadFile(t *testing.T) {
+ tf := make(tempFiles, 0)
+ defer tf.removeAll()
+
+ filename := tf.makeFile("key=value")
+ p := MustLoadFile(filename, ISO_8859_1)
+
+ assert.Equal(t, p.Len(), 1)
+ assertKeyValues(t, "", p, "key", "value")
+}
+
+func TestLoadFiles(t *testing.T) {
+ tf := make(tempFiles, 0)
+ defer tf.removeAll()
+
+ filename := tf.makeFile("key=value")
+ filename2 := tf.makeFile("key2=value2")
+ p := MustLoadFiles([]string{filename, filename2}, ISO_8859_1, false)
+ assertKeyValues(t, "", p, "key", "value", "key2", "value2")
+}
+
+func TestLoadExpandedFile(t *testing.T) {
+ tf := make(tempFiles, 0)
+ defer tf.removeAll()
+
+ if err := os.Setenv("_VARX", "some-value"); err != nil {
+ t.Fatal(err)
+ }
+ filename := tf.makeFilePrefix(os.Getenv("_VARX"), "key=value")
+ filename = strings.Replace(filename, os.Getenv("_VARX"), "${_VARX}", -1)
+ p := MustLoadFile(filename, ISO_8859_1)
+ assertKeyValues(t, "", p, "key", "value")
+}
+
+func TestLoadFilesAndIgnoreMissing(t *testing.T) {
+ tf := make(tempFiles, 0)
+ defer tf.removeAll()
+
+ filename := tf.makeFile("key=value")
+ filename2 := tf.makeFile("key2=value2")
+ p := MustLoadFiles([]string{filename, filename + "foo", filename2, filename2 + "foo"}, ISO_8859_1, true)
+ assertKeyValues(t, "", p, "key", "value", "key2", "value2")
+}
+
+func TestLoadURL(t *testing.T) {
+ srv := testServer()
+ defer srv.Close()
+ p := MustLoadURL(srv.URL + "/a")
+ assertKeyValues(t, "", p, "key", "value")
+}
+
+func TestLoadURLs(t *testing.T) {
+ srv := testServer()
+ defer srv.Close()
+ p := MustLoadURLs([]string{srv.URL + "/a", srv.URL + "/b"}, false)
+ assertKeyValues(t, "", p, "key", "value", "key2", "value2")
+}
+
+func TestLoadURLsAndFailMissing(t *testing.T) {
+ srv := testServer()
+ defer srv.Close()
+ p, err := LoadURLs([]string{srv.URL + "/a", srv.URL + "/c"}, false)
+ assert.Equal(t, p, (*Properties)(nil))
+ assert.Matches(t, err.Error(), ".*returned 404.*")
+}
+
+func TestLoadURLsAndIgnoreMissing(t *testing.T) {
+ srv := testServer()
+ defer srv.Close()
+ p := MustLoadURLs([]string{srv.URL + "/a", srv.URL + "/b", srv.URL + "/c"}, true)
+ assertKeyValues(t, "", p, "key", "value", "key2", "value2")
+}
+
+func TestLoadURLEncoding(t *testing.T) {
+ srv := testServer()
+ defer srv.Close()
+
+ uris := []string{"/none", "/utf8", "/plain", "/latin1", "/iso88591"}
+ for i, uri := range uris {
+ p := MustLoadURL(srv.URL + uri)
+ assert.Equal(t, p.GetString("key", ""), "äöü", fmt.Sprintf("%d", i))
+ }
+}
+
+func TestLoadURLFailInvalidEncoding(t *testing.T) {
+ srv := testServer()
+ defer srv.Close()
+
+ p, err := LoadURL(srv.URL + "/json")
+ assert.Equal(t, p, (*Properties)(nil))
+ assert.Matches(t, err.Error(), ".*invalid content type.*")
+}
+
+func TestLoadAll(t *testing.T) {
+ tf := make(tempFiles, 0)
+ defer tf.removeAll()
+
+ filename := tf.makeFile("key=value")
+ filename2 := tf.makeFile("key2=value3")
+ filename3 := tf.makeFile("key=value4")
+ srv := testServer()
+ defer srv.Close()
+ p := MustLoadAll([]string{filename, filename2, srv.URL + "/a", srv.URL + "/b", filename3}, UTF8, false)
+ assertKeyValues(t, "", p, "key", "value4", "key2", "value2")
+}
+
+type tempFiles []string
+
+func (tf *tempFiles) removeAll() {
+ for _, path := range *tf {
+ err := os.Remove(path)
+ if err != nil {
+ fmt.Printf("os.Remove: %v", err)
+ }
+ }
+}
+
+func (tf *tempFiles) makeFile(data string) string {
+ return tf.makeFilePrefix("properties", data)
+}
+
+func (tf *tempFiles) makeFilePrefix(prefix, data string) string {
+ f, err := ioutil.TempFile("", prefix)
+ if err != nil {
+ panic("ioutil.TempFile: " + err.Error())
+ }
+
+ // remember the temp file so that we can remove it later
+ *tf = append(*tf, f.Name())
+
+ n, err := fmt.Fprint(f, data)
+ if err != nil {
+ panic("fmt.Fprintln: " + err.Error())
+ }
+ if n != len(data) {
+ panic(fmt.Sprintf("Data size mismatch. expected=%d wrote=%d\n", len(data), n))
+ }
+
+ err = f.Close()
+ if err != nil {
+ panic("f.Close: " + err.Error())
+ }
+
+ return f.Name()
+}
+
+func testServer() *httptest.Server {
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ send := func(data []byte, contentType string) {
+ w.Header().Set("Content-Type", contentType)
+ if _, err := w.Write(data); err != nil {
+ panic(err)
+ }
+ }
+
+ utf8 := []byte("key=äöü")
+ iso88591 := []byte{0x6b, 0x65, 0x79, 0x3d, 0xe4, 0xf6, 0xfc} // key=äöü
+
+ switch r.RequestURI {
+ case "/a":
+ send([]byte("key=value"), "")
+ case "/b":
+ send([]byte("key2=value2"), "")
+ case "/none":
+ send(utf8, "")
+ case "/utf8":
+ send(utf8, "text/plain; charset=utf-8")
+ case "/json":
+ send(utf8, "application/json; charset=utf-8")
+ case "/plain":
+ send(iso88591, "text/plain")
+ case "/latin1":
+ send(iso88591, "text/plain; charset=latin1")
+ case "/iso88591":
+ send(iso88591, "text/plain; charset=iso-8859-1")
+ default:
+ w.WriteHeader(404)
+ }
+ }))
+}
diff --git a/vendor/github.com/magiconair/properties/parser.go b/vendor/github.com/magiconair/properties/parser.go
new file mode 100644
index 000000000..90f555cb9
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/parser.go
@@ -0,0 +1,95 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import (
+ "fmt"
+ "runtime"
+)
+
+type parser struct {
+ lex *lexer
+}
+
+func parse(input string) (properties *Properties, err error) {
+ p := &parser{lex: lex(input)}
+ defer p.recover(&err)
+
+ properties = NewProperties()
+ key := ""
+ comments := []string{}
+
+ for {
+ token := p.expectOneOf(itemComment, itemKey, itemEOF)
+ switch token.typ {
+ case itemEOF:
+ goto done
+ case itemComment:
+ comments = append(comments, token.val)
+ continue
+ case itemKey:
+ key = token.val
+ if _, ok := properties.m[key]; !ok {
+ properties.k = append(properties.k, key)
+ }
+ }
+
+ token = p.expectOneOf(itemValue, itemEOF)
+ if len(comments) > 0 {
+ properties.c[key] = comments
+ comments = []string{}
+ }
+ switch token.typ {
+ case itemEOF:
+ properties.m[key] = ""
+ goto done
+ case itemValue:
+ properties.m[key] = token.val
+ }
+ }
+
+done:
+ return properties, nil
+}
+
+func (p *parser) errorf(format string, args ...interface{}) {
+ format = fmt.Sprintf("properties: Line %d: %s", p.lex.lineNumber(), format)
+ panic(fmt.Errorf(format, args...))
+}
+
+func (p *parser) expect(expected itemType) (token item) {
+ token = p.lex.nextItem()
+ if token.typ != expected {
+ p.unexpected(token)
+ }
+ return token
+}
+
+func (p *parser) expectOneOf(expected ...itemType) (token item) {
+ token = p.lex.nextItem()
+ for _, v := range expected {
+ if token.typ == v {
+ return token
+ }
+ }
+ p.unexpected(token)
+ panic("unexpected token")
+}
+
+func (p *parser) unexpected(token item) {
+ p.errorf(token.String())
+}
+
+// recover is the handler that turns panics into returns from the top level of Parse.
+func (p *parser) recover(errp *error) {
+ e := recover()
+ if e != nil {
+ if _, ok := e.(runtime.Error); ok {
+ panic(e)
+ }
+ *errp = e.(error)
+ }
+ return
+}
diff --git a/vendor/github.com/magiconair/properties/properties.go b/vendor/github.com/magiconair/properties/properties.go
new file mode 100644
index 000000000..4f3d5a458
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/properties.go
@@ -0,0 +1,808 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+// BUG(frank): Set() does not check for invalid unicode literals since this is currently handled by the lexer.
+// BUG(frank): Write() does not allow to configure the newline character. Therefore, on Windows LF is used.
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+ "unicode/utf8"
+)
+
+// ErrorHandlerFunc defines the type of function which handles failures
+// of the MustXXX() functions. An error handler function must exit
+// the application after handling the error.
+type ErrorHandlerFunc func(error)
+
+// ErrorHandler is the function which handles failures of the MustXXX()
+// functions. The default is LogFatalHandler.
+var ErrorHandler ErrorHandlerFunc = LogFatalHandler
+
+// LogHandlerFunc defines the function prototype for logging errors.
+type LogHandlerFunc func(fmt string, args ...interface{})
+
+// LogPrintf defines a log handler which uses log.Printf.
+var LogPrintf LogHandlerFunc = log.Printf
+
+// LogFatalHandler handles the error by logging a fatal error and exiting.
+func LogFatalHandler(err error) {
+ log.Fatal(err)
+}
+
+// PanicHandler handles the error by panicking.
+func PanicHandler(err error) {
+ panic(err)
+}
+
+// -----------------------------------------------------------------------------
+
+// A Properties contains the key/value pairs from the properties input.
+// All values are stored in unexpanded form and are expanded at runtime
+type Properties struct {
+ // Pre-/Postfix for property expansion.
+ Prefix string
+ Postfix string
+
+ // DisableExpansion controls the expansion of properties on Get()
+ // and the check for circular references on Set(). When set to
+ // true Properties behaves like a simple key/value store and does
+ // not check for circular references on Get() or on Set().
+ DisableExpansion bool
+
+ // Stores the key/value pairs
+ m map[string]string
+
+ // Stores the comments per key.
+ c map[string][]string
+
+ // Stores the keys in order of appearance.
+ k []string
+}
+
+// NewProperties creates a new Properties struct with the default
+// configuration for "${key}" expressions.
+func NewProperties() *Properties {
+ return &Properties{
+ Prefix: "${",
+ Postfix: "}",
+ m: map[string]string{},
+ c: map[string][]string{},
+ k: []string{},
+ }
+}
+
+// Get returns the expanded value for the given key if exists.
+// Otherwise, ok is false.
+func (p *Properties) Get(key string) (value string, ok bool) {
+ v, ok := p.m[key]
+ if p.DisableExpansion {
+ return v, ok
+ }
+ if !ok {
+ return "", false
+ }
+
+ expanded, err := p.expand(v)
+
+ // we guarantee that the expanded value is free of
+ // circular references and malformed expressions
+ // so we panic if we still get an error here.
+ if err != nil {
+ ErrorHandler(fmt.Errorf("%s in %q", err, key+" = "+v))
+ }
+
+ return expanded, true
+}
+
+// MustGet returns the expanded value for the given key if exists.
+// Otherwise, it panics.
+func (p *Properties) MustGet(key string) string {
+ if v, ok := p.Get(key); ok {
+ return v
+ }
+ ErrorHandler(invalidKeyError(key))
+ panic("ErrorHandler should exit")
+}
+
+// ----------------------------------------------------------------------------
+
+// ClearComments removes the comments for all keys.
+func (p *Properties) ClearComments() {
+ p.c = map[string][]string{}
+}
+
+// ----------------------------------------------------------------------------
+
+// GetComment returns the last comment before the given key or an empty string.
+func (p *Properties) GetComment(key string) string {
+ comments, ok := p.c[key]
+ if !ok || len(comments) == 0 {
+ return ""
+ }
+ return comments[len(comments)-1]
+}
+
+// ----------------------------------------------------------------------------
+
+// GetComments returns all comments that appeared before the given key or nil.
+func (p *Properties) GetComments(key string) []string {
+ if comments, ok := p.c[key]; ok {
+ return comments
+ }
+ return nil
+}
+
+// ----------------------------------------------------------------------------
+
+// SetComment sets the comment for the key.
+func (p *Properties) SetComment(key, comment string) {
+ p.c[key] = []string{comment}
+}
+
+// ----------------------------------------------------------------------------
+
+// SetComments sets the comments for the key. If the comments are nil then
+// all comments for this key are deleted.
+func (p *Properties) SetComments(key string, comments []string) {
+ if comments == nil {
+ delete(p.c, key)
+ return
+ }
+ p.c[key] = comments
+}
+
+// ----------------------------------------------------------------------------
+
+// GetBool checks if the expanded value is one of '1', 'yes',
+// 'true' or 'on' if the key exists. The comparison is case-insensitive.
+// If the key does not exist the default value is returned.
+func (p *Properties) GetBool(key string, def bool) bool {
+ v, err := p.getBool(key)
+ if err != nil {
+ return def
+ }
+ return v
+}
+
+// MustGetBool checks if the expanded value is one of '1', 'yes',
+// 'true' or 'on' if the key exists. The comparison is case-insensitive.
+// If the key does not exist the function panics.
+func (p *Properties) MustGetBool(key string) bool {
+ v, err := p.getBool(key)
+ if err != nil {
+ ErrorHandler(err)
+ }
+ return v
+}
+
+func (p *Properties) getBool(key string) (value bool, err error) {
+ if v, ok := p.Get(key); ok {
+ return boolVal(v), nil
+ }
+ return false, invalidKeyError(key)
+}
+
+func boolVal(v string) bool {
+ v = strings.ToLower(v)
+ return v == "1" || v == "true" || v == "yes" || v == "on"
+}
+
+// ----------------------------------------------------------------------------
+
+// GetDuration parses the expanded value as an time.Duration (in ns) if the
+// key exists. If key does not exist or the value cannot be parsed the default
+// value is returned. In almost all cases you want to use GetParsedDuration().
+func (p *Properties) GetDuration(key string, def time.Duration) time.Duration {
+ v, err := p.getInt64(key)
+ if err != nil {
+ return def
+ }
+ return time.Duration(v)
+}
+
+// MustGetDuration parses the expanded value as an time.Duration (in ns) if
+// the key exists. If key does not exist or the value cannot be parsed the
+// function panics. In almost all cases you want to use MustGetParsedDuration().
+func (p *Properties) MustGetDuration(key string) time.Duration {
+ v, err := p.getInt64(key)
+ if err != nil {
+ ErrorHandler(err)
+ }
+ return time.Duration(v)
+}
+
+// ----------------------------------------------------------------------------
+
+// GetParsedDuration parses the expanded value with time.ParseDuration() if the key exists.
+// If key does not exist or the value cannot be parsed the default
+// value is returned.
+func (p *Properties) GetParsedDuration(key string, def time.Duration) time.Duration {
+ s, ok := p.Get(key)
+ if !ok {
+ return def
+ }
+ v, err := time.ParseDuration(s)
+ if err != nil {
+ return def
+ }
+ return v
+}
+
+// MustGetParsedDuration parses the expanded value with time.ParseDuration() if the key exists.
+// If key does not exist or the value cannot be parsed the function panics.
+func (p *Properties) MustGetParsedDuration(key string) time.Duration {
+ s, ok := p.Get(key)
+ if !ok {
+ ErrorHandler(invalidKeyError(key))
+ }
+ v, err := time.ParseDuration(s)
+ if err != nil {
+ ErrorHandler(err)
+ }
+ return v
+}
+
+// ----------------------------------------------------------------------------
+
+// GetFloat64 parses the expanded value as a float64 if the key exists.
+// If key does not exist or the value cannot be parsed the default
+// value is returned.
+func (p *Properties) GetFloat64(key string, def float64) float64 {
+ v, err := p.getFloat64(key)
+ if err != nil {
+ return def
+ }
+ return v
+}
+
+// MustGetFloat64 parses the expanded value as a float64 if the key exists.
+// If key does not exist or the value cannot be parsed the function panics.
+func (p *Properties) MustGetFloat64(key string) float64 {
+ v, err := p.getFloat64(key)
+ if err != nil {
+ ErrorHandler(err)
+ }
+ return v
+}
+
+func (p *Properties) getFloat64(key string) (value float64, err error) {
+ if v, ok := p.Get(key); ok {
+ value, err = strconv.ParseFloat(v, 64)
+ if err != nil {
+ return 0, err
+ }
+ return value, nil
+ }
+ return 0, invalidKeyError(key)
+}
+
+// ----------------------------------------------------------------------------
+
+// GetInt parses the expanded value as an int if the key exists.
+// If key does not exist or the value cannot be parsed the default
+// value is returned. If the value does not fit into an int the
+// function panics with an out of range error.
+func (p *Properties) GetInt(key string, def int) int {
+ v, err := p.getInt64(key)
+ if err != nil {
+ return def
+ }
+ return intRangeCheck(key, v)
+}
+
+// MustGetInt parses the expanded value as an int if the key exists.
+// If key does not exist or the value cannot be parsed the function panics.
+// If the value does not fit into an int the function panics with
+// an out of range error.
+func (p *Properties) MustGetInt(key string) int {
+ v, err := p.getInt64(key)
+ if err != nil {
+ ErrorHandler(err)
+ }
+ return intRangeCheck(key, v)
+}
+
+// ----------------------------------------------------------------------------
+
+// GetInt64 parses the expanded value as an int64 if the key exists.
+// If key does not exist or the value cannot be parsed the default
+// value is returned.
+func (p *Properties) GetInt64(key string, def int64) int64 {
+ v, err := p.getInt64(key)
+ if err != nil {
+ return def
+ }
+ return v
+}
+
+// MustGetInt64 parses the expanded value as an int if the key exists.
+// If key does not exist or the value cannot be parsed the function panics.
+func (p *Properties) MustGetInt64(key string) int64 {
+ v, err := p.getInt64(key)
+ if err != nil {
+ ErrorHandler(err)
+ }
+ return v
+}
+
+func (p *Properties) getInt64(key string) (value int64, err error) {
+ if v, ok := p.Get(key); ok {
+ value, err = strconv.ParseInt(v, 10, 64)
+ if err != nil {
+ return 0, err
+ }
+ return value, nil
+ }
+ return 0, invalidKeyError(key)
+}
+
+// ----------------------------------------------------------------------------
+
+// GetUint parses the expanded value as an uint if the key exists.
+// If key does not exist or the value cannot be parsed the default
+// value is returned. If the value does not fit into an int the
+// function panics with an out of range error.
+func (p *Properties) GetUint(key string, def uint) uint {
+ v, err := p.getUint64(key)
+ if err != nil {
+ return def
+ }
+ return uintRangeCheck(key, v)
+}
+
+// MustGetUint parses the expanded value as an int if the key exists.
+// If key does not exist or the value cannot be parsed the function panics.
+// If the value does not fit into an int the function panics with
+// an out of range error.
+func (p *Properties) MustGetUint(key string) uint {
+ v, err := p.getUint64(key)
+ if err != nil {
+ ErrorHandler(err)
+ }
+ return uintRangeCheck(key, v)
+}
+
+// ----------------------------------------------------------------------------
+
+// GetUint64 parses the expanded value as an uint64 if the key exists.
+// If key does not exist or the value cannot be parsed the default
+// value is returned.
+func (p *Properties) GetUint64(key string, def uint64) uint64 {
+ v, err := p.getUint64(key)
+ if err != nil {
+ return def
+ }
+ return v
+}
+
+// MustGetUint64 parses the expanded value as an int if the key exists.
+// If key does not exist or the value cannot be parsed the function panics.
+func (p *Properties) MustGetUint64(key string) uint64 {
+ v, err := p.getUint64(key)
+ if err != nil {
+ ErrorHandler(err)
+ }
+ return v
+}
+
+func (p *Properties) getUint64(key string) (value uint64, err error) {
+ if v, ok := p.Get(key); ok {
+ value, err = strconv.ParseUint(v, 10, 64)
+ if err != nil {
+ return 0, err
+ }
+ return value, nil
+ }
+ return 0, invalidKeyError(key)
+}
+
+// ----------------------------------------------------------------------------
+
+// GetString returns the expanded value for the given key if exists or
+// the default value otherwise.
+func (p *Properties) GetString(key, def string) string {
+ if v, ok := p.Get(key); ok {
+ return v
+ }
+ return def
+}
+
+// MustGetString returns the expanded value for the given key if exists or
+// panics otherwise.
+func (p *Properties) MustGetString(key string) string {
+ if v, ok := p.Get(key); ok {
+ return v
+ }
+ ErrorHandler(invalidKeyError(key))
+ panic("ErrorHandler should exit")
+}
+
+// ----------------------------------------------------------------------------
+
+// Filter returns a new properties object which contains all properties
+// for which the key matches the pattern.
+func (p *Properties) Filter(pattern string) (*Properties, error) {
+ re, err := regexp.Compile(pattern)
+ if err != nil {
+ return nil, err
+ }
+
+ return p.FilterRegexp(re), nil
+}
+
+// FilterRegexp returns a new properties object which contains all properties
+// for which the key matches the regular expression.
+func (p *Properties) FilterRegexp(re *regexp.Regexp) *Properties {
+ pp := NewProperties()
+ for _, k := range p.k {
+ if re.MatchString(k) {
+ // TODO(fs): we are ignoring the error which flags a circular reference.
+ // TODO(fs): since we are just copying a subset of keys this cannot happen (fingers crossed)
+ pp.Set(k, p.m[k])
+ }
+ }
+ return pp
+}
+
+// FilterPrefix returns a new properties object with a subset of all keys
+// with the given prefix.
+func (p *Properties) FilterPrefix(prefix string) *Properties {
+ pp := NewProperties()
+ for _, k := range p.k {
+ if strings.HasPrefix(k, prefix) {
+ // TODO(fs): we are ignoring the error which flags a circular reference.
+ // TODO(fs): since we are just copying a subset of keys this cannot happen (fingers crossed)
+ pp.Set(k, p.m[k])
+ }
+ }
+ return pp
+}
+
+// FilterStripPrefix returns a new properties object with a subset of all keys
+// with the given prefix and the prefix removed from the keys.
+func (p *Properties) FilterStripPrefix(prefix string) *Properties {
+ pp := NewProperties()
+ n := len(prefix)
+ for _, k := range p.k {
+ if len(k) > len(prefix) && strings.HasPrefix(k, prefix) {
+ // TODO(fs): we are ignoring the error which flags a circular reference.
+ // TODO(fs): since we are modifying keys I am not entirely sure whether we can create a circular reference
+ // TODO(fs): this function should probably return an error but the signature is fixed
+ pp.Set(k[n:], p.m[k])
+ }
+ }
+ return pp
+}
+
+// Len returns the number of keys.
+func (p *Properties) Len() int {
+ return len(p.m)
+}
+
+// Keys returns all keys in the same order as in the input.
+func (p *Properties) Keys() []string {
+ keys := make([]string, len(p.k))
+ copy(keys, p.k)
+ return keys
+}
+
+// Set sets the property key to the corresponding value.
+// If a value for key existed before then ok is true and prev
+// contains the previous value. If the value contains a
+// circular reference or a malformed expression then
+// an error is returned.
+// An empty key is silently ignored.
+func (p *Properties) Set(key, value string) (prev string, ok bool, err error) {
+ if key == "" {
+ return "", false, nil
+ }
+
+ // if expansion is disabled we allow circular references
+ if p.DisableExpansion {
+ prev, ok = p.Get(key)
+ p.m[key] = value
+ return prev, ok, nil
+ }
+
+ // to check for a circular reference we temporarily need
+ // to set the new value. If there is an error then revert
+ // to the previous state. Only if all tests are successful
+ // then we add the key to the p.k list.
+ prev, ok = p.Get(key)
+ p.m[key] = value
+
+ // now check for a circular reference
+ _, err = p.expand(value)
+ if err != nil {
+
+ // revert to the previous state
+ if ok {
+ p.m[key] = prev
+ } else {
+ delete(p.m, key)
+ }
+
+ return "", false, err
+ }
+
+ if !ok {
+ p.k = append(p.k, key)
+ }
+
+ return prev, ok, nil
+}
+
+// SetValue sets property key to the default string value
+// as defined by fmt.Sprintf("%v").
+func (p *Properties) SetValue(key string, value interface{}) error {
+ _, _, err := p.Set(key, fmt.Sprintf("%v", value))
+ return err
+}
+
+// MustSet sets the property key to the corresponding value.
+// If a value for key existed before then ok is true and prev
+// contains the previous value. An empty key is silently ignored.
+func (p *Properties) MustSet(key, value string) (prev string, ok bool) {
+ prev, ok, err := p.Set(key, value)
+ if err != nil {
+ ErrorHandler(err)
+ }
+ return prev, ok
+}
+
+// String returns a string of all expanded 'key = value' pairs.
+func (p *Properties) String() string {
+ var s string
+ for _, key := range p.k {
+ value, _ := p.Get(key)
+ s = fmt.Sprintf("%s%s = %s\n", s, key, value)
+ }
+ return s
+}
+
+// Write writes all unexpanded 'key = value' pairs to the given writer.
+// Write returns the number of bytes written and any write error encountered.
+func (p *Properties) Write(w io.Writer, enc Encoding) (n int, err error) {
+ return p.WriteComment(w, "", enc)
+}
+
+// WriteComment writes all unexpanced 'key = value' pairs to the given writer.
+// If prefix is not empty then comments are written with a blank line and the
+// given prefix. The prefix should be either "# " or "! " to be compatible with
+// the properties file format. Otherwise, the properties parser will not be
+// able to read the file back in. It returns the number of bytes written and
+// any write error encountered.
+func (p *Properties) WriteComment(w io.Writer, prefix string, enc Encoding) (n int, err error) {
+ var x int
+
+ for _, key := range p.k {
+ value := p.m[key]
+
+ if prefix != "" {
+ if comments, ok := p.c[key]; ok {
+ // don't print comments if they are all empty
+ allEmpty := true
+ for _, c := range comments {
+ if c != "" {
+ allEmpty = false
+ break
+ }
+ }
+
+ if !allEmpty {
+ // add a blank line between entries but not at the top
+ if len(comments) > 0 && n > 0 {
+ x, err = fmt.Fprintln(w)
+ if err != nil {
+ return
+ }
+ n += x
+ }
+
+ for _, c := range comments {
+ x, err = fmt.Fprintf(w, "%s%s\n", prefix, encode(c, "", enc))
+ if err != nil {
+ return
+ }
+ n += x
+ }
+ }
+ }
+ }
+
+ x, err = fmt.Fprintf(w, "%s = %s\n", encode(key, " :", enc), encode(value, "", enc))
+ if err != nil {
+ return
+ }
+ n += x
+ }
+ return
+}
+
+// Map returns a copy of the properties as a map.
+func (p *Properties) Map() map[string]string {
+ m := make(map[string]string)
+ for k, v := range p.m {
+ m[k] = v
+ }
+ return m
+}
+
+// FilterFunc returns a copy of the properties which includes the values which passed all filters.
+func (p *Properties) FilterFunc(filters ...func(k, v string) bool) *Properties {
+ pp := NewProperties()
+outer:
+ for k, v := range p.m {
+ for _, f := range filters {
+ if !f(k, v) {
+ continue outer
+ }
+ pp.Set(k, v)
+ }
+ }
+ return pp
+}
+
+// ----------------------------------------------------------------------------
+
+// Delete removes the key and its comments.
+func (p *Properties) Delete(key string) {
+ delete(p.m, key)
+ delete(p.c, key)
+ newKeys := []string{}
+ for _, k := range p.k {
+ if k != key {
+ newKeys = append(newKeys, k)
+ }
+ }
+ p.k = newKeys
+}
+
+// Merge merges properties, comments and keys from other *Properties into p
+func (p *Properties) Merge(other *Properties) {
+ for k, v := range other.m {
+ p.m[k] = v
+ }
+ for k, v := range other.c {
+ p.c[k] = v
+ }
+
+outer:
+ for _, otherKey := range other.k {
+ for _, key := range p.k {
+ if otherKey == key {
+ continue outer
+ }
+ }
+ p.k = append(p.k, otherKey)
+ }
+}
+
+// ----------------------------------------------------------------------------
+
+// check expands all values and returns an error if a circular reference or
+// a malformed expression was found.
+func (p *Properties) check() error {
+ for _, value := range p.m {
+ if _, err := p.expand(value); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (p *Properties) expand(input string) (string, error) {
+ // no pre/postfix -> nothing to expand
+ if p.Prefix == "" && p.Postfix == "" {
+ return input, nil
+ }
+
+ return expand(input, make(map[string]bool), p.Prefix, p.Postfix, p.m)
+}
+
+// expand recursively expands expressions of '(prefix)key(postfix)' to their corresponding values.
+// The function keeps track of the keys that were already expanded and stops if it
+// detects a circular reference or a malformed expression of the form '(prefix)key'.
+func expand(s string, keys map[string]bool, prefix, postfix string, values map[string]string) (string, error) {
+ start := strings.Index(s, prefix)
+ if start == -1 {
+ return s, nil
+ }
+
+ keyStart := start + len(prefix)
+ keyLen := strings.Index(s[keyStart:], postfix)
+ if keyLen == -1 {
+ return "", fmt.Errorf("malformed expression")
+ }
+
+ end := keyStart + keyLen + len(postfix) - 1
+ key := s[keyStart : keyStart+keyLen]
+
+ // fmt.Printf("s:%q pp:%q start:%d end:%d keyStart:%d keyLen:%d key:%q\n", s, prefix + "..." + postfix, start, end, keyStart, keyLen, key)
+
+ if _, ok := keys[key]; ok {
+ return "", fmt.Errorf("circular reference")
+ }
+
+ val, ok := values[key]
+ if !ok {
+ val = os.Getenv(key)
+ }
+
+ // remember that we've seen the key
+ keys[key] = true
+
+ return expand(s[:start]+val+s[end+1:], keys, prefix, postfix, values)
+}
+
+// encode encodes a UTF-8 string to ISO-8859-1 and escapes some characters.
+func encode(s string, special string, enc Encoding) string {
+ switch enc {
+ case UTF8:
+ return encodeUtf8(s, special)
+ case ISO_8859_1:
+ return encodeIso(s, special)
+ default:
+ panic(fmt.Sprintf("unsupported encoding %v", enc))
+ }
+}
+
+func encodeUtf8(s string, special string) string {
+ v := ""
+ for pos := 0; pos < len(s); {
+ r, w := utf8.DecodeRuneInString(s[pos:])
+ pos += w
+ v += escape(r, special)
+ }
+ return v
+}
+
+func encodeIso(s string, special string) string {
+ var r rune
+ var w int
+ var v string
+ for pos := 0; pos < len(s); {
+ switch r, w = utf8.DecodeRuneInString(s[pos:]); {
+ case r < 1<<8: // single byte rune -> escape special chars only
+ v += escape(r, special)
+ case r < 1<<16: // two byte rune -> unicode literal
+ v += fmt.Sprintf("\\u%04x", r)
+ default: // more than two bytes per rune -> can't encode
+ v += "?"
+ }
+ pos += w
+ }
+ return v
+}
+
+func escape(r rune, special string) string {
+ switch r {
+ case '\f':
+ return "\\f"
+ case '\n':
+ return "\\n"
+ case '\r':
+ return "\\r"
+ case '\t':
+ return "\\t"
+ default:
+ if strings.ContainsRune(special, r) {
+ return "\\" + string(r)
+ }
+ return string(r)
+ }
+}
+
+func invalidKeyError(key string) error {
+ return fmt.Errorf("unknown property: %s", key)
+}
diff --git a/vendor/github.com/magiconair/properties/properties_test.go b/vendor/github.com/magiconair/properties/properties_test.go
new file mode 100644
index 000000000..0eac1f492
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/properties_test.go
@@ -0,0 +1,934 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import (
+ "bytes"
+ "flag"
+ "fmt"
+ "math"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/magiconair/properties/assert"
+)
+
+var verbose = flag.Bool("verbose", false, "Verbose output")
+
+func init() {
+ ErrorHandler = PanicHandler
+}
+
+// ----------------------------------------------------------------------------
+
+// define test cases in the form of
+// {"input", "key1", "value1", "key2", "value2", ...}
+var complexTests = [][]string{
+ // whitespace prefix
+ {" key=value", "key", "value"}, // SPACE prefix
+ {"\fkey=value", "key", "value"}, // FF prefix
+ {"\tkey=value", "key", "value"}, // TAB prefix
+ {" \f\tkey=value", "key", "value"}, // mix prefix
+
+ // multiple keys
+ {"key1=value1\nkey2=value2\n", "key1", "value1", "key2", "value2"},
+ {"key1=value1\rkey2=value2\r", "key1", "value1", "key2", "value2"},
+ {"key1=value1\r\nkey2=value2\r\n", "key1", "value1", "key2", "value2"},
+
+ // blank lines
+ {"\nkey=value\n", "key", "value"},
+ {"\rkey=value\r", "key", "value"},
+ {"\r\nkey=value\r\n", "key", "value"},
+
+ // escaped chars in key
+ {"k\\ ey = value", "k ey", "value"},
+ {"k\\:ey = value", "k:ey", "value"},
+ {"k\\=ey = value", "k=ey", "value"},
+ {"k\\fey = value", "k\fey", "value"},
+ {"k\\ney = value", "k\ney", "value"},
+ {"k\\rey = value", "k\rey", "value"},
+ {"k\\tey = value", "k\tey", "value"},
+
+ // escaped chars in value
+ {"key = v\\ alue", "key", "v alue"},
+ {"key = v\\:alue", "key", "v:alue"},
+ {"key = v\\=alue", "key", "v=alue"},
+ {"key = v\\falue", "key", "v\falue"},
+ {"key = v\\nalue", "key", "v\nalue"},
+ {"key = v\\ralue", "key", "v\ralue"},
+ {"key = v\\talue", "key", "v\talue"},
+
+ // silently dropped escape character
+ {"k\\zey = value", "kzey", "value"},
+ {"key = v\\zalue", "key", "vzalue"},
+
+ // unicode literals
+ {"key\\u2318 = value", "key⌘", "value"},
+ {"k\\u2318ey = value", "k⌘ey", "value"},
+ {"key = value\\u2318", "key", "value⌘"},
+ {"key = valu\\u2318e", "key", "valu⌘e"},
+
+ // multiline values
+ {"key = valueA,\\\n valueB", "key", "valueA,valueB"}, // SPACE indent
+ {"key = valueA,\\\n\f\f\fvalueB", "key", "valueA,valueB"}, // FF indent
+ {"key = valueA,\\\n\t\t\tvalueB", "key", "valueA,valueB"}, // TAB indent
+ {"key = valueA,\\\n \f\tvalueB", "key", "valueA,valueB"}, // mix indent
+
+ // comments
+ {"# this is a comment\n! and so is this\nkey1=value1\nkey#2=value#2\n\nkey!3=value!3\n# and another one\n! and the final one", "key1", "value1", "key#2", "value#2", "key!3", "value!3"},
+
+ // expansion tests
+ {"key=value\nkey2=${key}", "key", "value", "key2", "value"},
+ {"key=value\nkey2=aa${key}", "key", "value", "key2", "aavalue"},
+ {"key=value\nkey2=${key}bb", "key", "value", "key2", "valuebb"},
+ {"key=value\nkey2=aa${key}bb", "key", "value", "key2", "aavaluebb"},
+ {"key=value\nkey2=${key}\nkey3=${key2}", "key", "value", "key2", "value", "key3", "value"},
+ {"key=${USER}", "key", os.Getenv("USER")},
+ {"key=${USER}\nUSER=value", "key", "value", "USER", "value"},
+}
+
+// ----------------------------------------------------------------------------
+
+var commentTests = []struct {
+ input, key, value string
+ comments []string
+}{
+ {"key=value", "key", "value", nil},
+ {"#\nkey=value", "key", "value", []string{""}},
+ {"#comment\nkey=value", "key", "value", []string{"comment"}},
+ {"# comment\nkey=value", "key", "value", []string{"comment"}},
+ {"# comment\nkey=value", "key", "value", []string{"comment"}},
+ {"# comment\n\nkey=value", "key", "value", []string{"comment"}},
+ {"# comment1\n# comment2\nkey=value", "key", "value", []string{"comment1", "comment2"}},
+ {"# comment1\n\n# comment2\n\nkey=value", "key", "value", []string{"comment1", "comment2"}},
+ {"!comment\nkey=value", "key", "value", []string{"comment"}},
+ {"! comment\nkey=value", "key", "value", []string{"comment"}},
+ {"! comment\nkey=value", "key", "value", []string{"comment"}},
+ {"! comment\n\nkey=value", "key", "value", []string{"comment"}},
+ {"! comment1\n! comment2\nkey=value", "key", "value", []string{"comment1", "comment2"}},
+ {"! comment1\n\n! comment2\n\nkey=value", "key", "value", []string{"comment1", "comment2"}},
+}
+
+// ----------------------------------------------------------------------------
+
+var errorTests = []struct {
+ input, msg string
+}{
+ // unicode literals
+ {"key\\u1 = value", "invalid unicode literal"},
+ {"key\\u12 = value", "invalid unicode literal"},
+ {"key\\u123 = value", "invalid unicode literal"},
+ {"key\\u123g = value", "invalid unicode literal"},
+ {"key\\u123", "invalid unicode literal"},
+
+ // circular references
+ {"key=${key}", "circular reference"},
+ {"key1=${key2}\nkey2=${key1}", "circular reference"},
+
+ // malformed expressions
+ {"key=${ke", "malformed expression"},
+ {"key=valu${ke", "malformed expression"},
+}
+
+// ----------------------------------------------------------------------------
+
+var writeTests = []struct {
+ input, output, encoding string
+}{
+ // ISO-8859-1 tests
+ {"key = value", "key = value\n", "ISO-8859-1"},
+ {"key = value \\\n continued", "key = value continued\n", "ISO-8859-1"},
+ {"key⌘ = value", "key\\u2318 = value\n", "ISO-8859-1"},
+ {"ke\\ \\:y = value", "ke\\ \\:y = value\n", "ISO-8859-1"},
+
+ // UTF-8 tests
+ {"key = value", "key = value\n", "UTF-8"},
+ {"key = value \\\n continued", "key = value continued\n", "UTF-8"},
+ {"key⌘ = value⌘", "key⌘ = value⌘\n", "UTF-8"},
+ {"ke\\ \\:y = value", "ke\\ \\:y = value\n", "UTF-8"},
+}
+
+// ----------------------------------------------------------------------------
+
+var writeCommentTests = []struct {
+ input, output, encoding string
+}{
+ // ISO-8859-1 tests
+ {"key = value", "key = value\n", "ISO-8859-1"},
+ {"#\nkey = value", "key = value\n", "ISO-8859-1"},
+ {"#\n#\n#\nkey = value", "key = value\n", "ISO-8859-1"},
+ {"# comment\nkey = value", "# comment\nkey = value\n", "ISO-8859-1"},
+ {"\n# comment\nkey = value", "# comment\nkey = value\n", "ISO-8859-1"},
+ {"# comment\n\nkey = value", "# comment\nkey = value\n", "ISO-8859-1"},
+ {"# comment1\n# comment2\nkey = value", "# comment1\n# comment2\nkey = value\n", "ISO-8859-1"},
+ {"#comment1\nkey1 = value1\n#comment2\nkey2 = value2", "# comment1\nkey1 = value1\n\n# comment2\nkey2 = value2\n", "ISO-8859-1"},
+
+ // UTF-8 tests
+ {"key = value", "key = value\n", "UTF-8"},
+ {"# comment⌘\nkey = value⌘", "# comment⌘\nkey = value⌘\n", "UTF-8"},
+ {"\n# comment⌘\nkey = value⌘", "# comment⌘\nkey = value⌘\n", "UTF-8"},
+ {"# comment⌘\n\nkey = value⌘", "# comment⌘\nkey = value⌘\n", "UTF-8"},
+ {"# comment1⌘\n# comment2⌘\nkey = value⌘", "# comment1⌘\n# comment2⌘\nkey = value⌘\n", "UTF-8"},
+ {"#comment1⌘\nkey1 = value1⌘\n#comment2⌘\nkey2 = value2⌘", "# comment1⌘\nkey1 = value1⌘\n\n# comment2⌘\nkey2 = value2⌘\n", "UTF-8"},
+}
+
+// ----------------------------------------------------------------------------
+
+var boolTests = []struct {
+ input, key string
+ def, value bool
+}{
+ // valid values for TRUE
+ {"key = 1", "key", false, true},
+ {"key = on", "key", false, true},
+ {"key = On", "key", false, true},
+ {"key = ON", "key", false, true},
+ {"key = true", "key", false, true},
+ {"key = True", "key", false, true},
+ {"key = TRUE", "key", false, true},
+ {"key = yes", "key", false, true},
+ {"key = Yes", "key", false, true},
+ {"key = YES", "key", false, true},
+
+ // valid values for FALSE (all other)
+ {"key = 0", "key", true, false},
+ {"key = off", "key", true, false},
+ {"key = false", "key", true, false},
+ {"key = no", "key", true, false},
+
+ // non existent key
+ {"key = true", "key2", false, false},
+}
+
+// ----------------------------------------------------------------------------
+
+var durationTests = []struct {
+ input, key string
+ def, value time.Duration
+}{
+ // valid values
+ {"key = 1", "key", 999, 1},
+ {"key = 0", "key", 999, 0},
+ {"key = -1", "key", 999, -1},
+ {"key = 0123", "key", 999, 123},
+
+ // invalid values
+ {"key = 0xff", "key", 999, 999},
+ {"key = 1.0", "key", 999, 999},
+ {"key = a", "key", 999, 999},
+
+ // non existent key
+ {"key = 1", "key2", 999, 999},
+}
+
+// ----------------------------------------------------------------------------
+
+var parsedDurationTests = []struct {
+ input, key string
+ def, value time.Duration
+}{
+ // valid values
+ {"key = -1ns", "key", 999, -1 * time.Nanosecond},
+ {"key = 300ms", "key", 999, 300 * time.Millisecond},
+ {"key = 5s", "key", 999, 5 * time.Second},
+ {"key = 3h", "key", 999, 3 * time.Hour},
+ {"key = 2h45m", "key", 999, 2*time.Hour + 45*time.Minute},
+
+ // invalid values
+ {"key = 0xff", "key", 999, 999},
+ {"key = 1.0", "key", 999, 999},
+ {"key = a", "key", 999, 999},
+ {"key = 1", "key", 999, 999},
+ {"key = 0", "key", 999, 0},
+
+ // non existent key
+ {"key = 1", "key2", 999, 999},
+}
+
+// ----------------------------------------------------------------------------
+
+var floatTests = []struct {
+ input, key string
+ def, value float64
+}{
+ // valid values
+ {"key = 1.0", "key", 999, 1.0},
+ {"key = 0.0", "key", 999, 0.0},
+ {"key = -1.0", "key", 999, -1.0},
+ {"key = 1", "key", 999, 1},
+ {"key = 0", "key", 999, 0},
+ {"key = -1", "key", 999, -1},
+ {"key = 0123", "key", 999, 123},
+
+ // invalid values
+ {"key = 0xff", "key", 999, 999},
+ {"key = a", "key", 999, 999},
+
+ // non existent key
+ {"key = 1", "key2", 999, 999},
+}
+
+// ----------------------------------------------------------------------------
+
+var int64Tests = []struct {
+ input, key string
+ def, value int64
+}{
+ // valid values
+ {"key = 1", "key", 999, 1},
+ {"key = 0", "key", 999, 0},
+ {"key = -1", "key", 999, -1},
+ {"key = 0123", "key", 999, 123},
+
+ // invalid values
+ {"key = 0xff", "key", 999, 999},
+ {"key = 1.0", "key", 999, 999},
+ {"key = a", "key", 999, 999},
+
+ // non existent key
+ {"key = 1", "key2", 999, 999},
+}
+
+// ----------------------------------------------------------------------------
+
+var uint64Tests = []struct {
+ input, key string
+ def, value uint64
+}{
+ // valid values
+ {"key = 1", "key", 999, 1},
+ {"key = 0", "key", 999, 0},
+ {"key = 0123", "key", 999, 123},
+
+ // invalid values
+ {"key = -1", "key", 999, 999},
+ {"key = 0xff", "key", 999, 999},
+ {"key = 1.0", "key", 999, 999},
+ {"key = a", "key", 999, 999},
+
+ // non existent key
+ {"key = 1", "key2", 999, 999},
+}
+
+// ----------------------------------------------------------------------------
+
+var stringTests = []struct {
+ input, key string
+ def, value string
+}{
+ // valid values
+ {"key = abc", "key", "def", "abc"},
+
+ // non existent key
+ {"key = abc", "key2", "def", "def"},
+}
+
+// ----------------------------------------------------------------------------
+
+var keysTests = []struct {
+ input string
+ keys []string
+}{
+ {"", []string{}},
+ {"key = abc", []string{"key"}},
+ {"key = abc\nkey2=def", []string{"key", "key2"}},
+ {"key2 = abc\nkey=def", []string{"key2", "key"}},
+ {"key = abc\nkey=def", []string{"key"}},
+}
+
+// ----------------------------------------------------------------------------
+
+var filterTests = []struct {
+ input string
+ pattern string
+ keys []string
+ err string
+}{
+ {"", "", []string{}, ""},
+ {"", "abc", []string{}, ""},
+ {"key=value", "", []string{"key"}, ""},
+ {"key=value", "key=", []string{}, ""},
+ {"key=value\nfoo=bar", "", []string{"foo", "key"}, ""},
+ {"key=value\nfoo=bar", "f", []string{"foo"}, ""},
+ {"key=value\nfoo=bar", "fo", []string{"foo"}, ""},
+ {"key=value\nfoo=bar", "foo", []string{"foo"}, ""},
+ {"key=value\nfoo=bar", "fooo", []string{}, ""},
+ {"key=value\nkey2=value2\nfoo=bar", "ey", []string{"key", "key2"}, ""},
+ {"key=value\nkey2=value2\nfoo=bar", "key", []string{"key", "key2"}, ""},
+ {"key=value\nkey2=value2\nfoo=bar", "^key", []string{"key", "key2"}, ""},
+ {"key=value\nkey2=value2\nfoo=bar", "^(key|foo)", []string{"foo", "key", "key2"}, ""},
+ {"key=value\nkey2=value2\nfoo=bar", "[ abc", nil, "error parsing regexp.*"},
+}
+
+// ----------------------------------------------------------------------------
+
+var filterPrefixTests = []struct {
+ input string
+ prefix string
+ keys []string
+}{
+ {"", "", []string{}},
+ {"", "abc", []string{}},
+ {"key=value", "", []string{"key"}},
+ {"key=value", "key=", []string{}},
+ {"key=value\nfoo=bar", "", []string{"foo", "key"}},
+ {"key=value\nfoo=bar", "f", []string{"foo"}},
+ {"key=value\nfoo=bar", "fo", []string{"foo"}},
+ {"key=value\nfoo=bar", "foo", []string{"foo"}},
+ {"key=value\nfoo=bar", "fooo", []string{}},
+ {"key=value\nkey2=value2\nfoo=bar", "key", []string{"key", "key2"}},
+}
+
+// ----------------------------------------------------------------------------
+
+var filterStripPrefixTests = []struct {
+ input string
+ prefix string
+ keys []string
+}{
+ {"", "", []string{}},
+ {"", "abc", []string{}},
+ {"key=value", "", []string{"key"}},
+ {"key=value", "key=", []string{}},
+ {"key=value\nfoo=bar", "", []string{"foo", "key"}},
+ {"key=value\nfoo=bar", "f", []string{"foo"}},
+ {"key=value\nfoo=bar", "fo", []string{"foo"}},
+ {"key=value\nfoo=bar", "foo", []string{"foo"}},
+ {"key=value\nfoo=bar", "fooo", []string{}},
+ {"key=value\nkey2=value2\nfoo=bar", "key", []string{"key", "key2"}},
+}
+
+// ----------------------------------------------------------------------------
+
+var setTests = []struct {
+ input string
+ key, value string
+ prev string
+ ok bool
+ err string
+ keys []string
+}{
+ {"", "", "", "", false, "", []string{}},
+ {"", "key", "value", "", false, "", []string{"key"}},
+ {"key=value", "key2", "value2", "", false, "", []string{"key", "key2"}},
+ {"key=value", "abc", "value3", "", false, "", []string{"key", "abc"}},
+ {"key=value", "key", "value3", "value", true, "", []string{"key"}},
+}
+
+// ----------------------------------------------------------------------------
+
+// TestBasic tests basic single key/value combinations with all possible
+// whitespace, delimiter and newline permutations.
+func TestBasic(t *testing.T) {
+ testWhitespaceAndDelimiterCombinations(t, "key", "")
+ testWhitespaceAndDelimiterCombinations(t, "key", "value")
+ testWhitespaceAndDelimiterCombinations(t, "key", "value ")
+}
+
+func TestComplex(t *testing.T) {
+ for _, test := range complexTests {
+ testKeyValue(t, test[0], test[1:]...)
+ }
+}
+
+func TestErrors(t *testing.T) {
+ for _, test := range errorTests {
+ _, err := Load([]byte(test.input), ISO_8859_1)
+ assert.Equal(t, err != nil, true, "want error")
+ assert.Equal(t, strings.Contains(err.Error(), test.msg), true)
+ }
+}
+
+func TestDisableExpansion(t *testing.T) {
+ input := "key=value\nkey2=${key}"
+ p := mustParse(t, input)
+ p.DisableExpansion = true
+ assert.Equal(t, p.MustGet("key"), "value")
+ assert.Equal(t, p.MustGet("key2"), "${key}")
+
+ // with expansion disabled we can introduce circular references
+ p.MustSet("keyA", "${keyB}")
+ p.MustSet("keyB", "${keyA}")
+ assert.Equal(t, p.MustGet("keyA"), "${keyB}")
+ assert.Equal(t, p.MustGet("keyB"), "${keyA}")
+}
+
+func TestMustGet(t *testing.T) {
+ input := "key = value\nkey2 = ghi"
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGet("key"), "value")
+ assert.Panic(t, func() { p.MustGet("invalid") }, "unknown property: invalid")
+}
+
+func TestGetBool(t *testing.T) {
+ for _, test := range boolTests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.Len(), 1)
+ assert.Equal(t, p.GetBool(test.key, test.def), test.value)
+ }
+}
+
+func TestMustGetBool(t *testing.T) {
+ input := "key = true\nkey2 = ghi"
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetBool("key"), true)
+ assert.Panic(t, func() { p.MustGetBool("invalid") }, "unknown property: invalid")
+}
+
+func TestGetDuration(t *testing.T) {
+ for _, test := range durationTests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.Len(), 1)
+ assert.Equal(t, p.GetDuration(test.key, test.def), test.value)
+ }
+}
+
+func TestMustGetDuration(t *testing.T) {
+ input := "key = 123\nkey2 = ghi"
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetDuration("key"), time.Duration(123))
+ assert.Panic(t, func() { p.MustGetDuration("key2") }, "strconv.ParseInt: parsing.*")
+ assert.Panic(t, func() { p.MustGetDuration("invalid") }, "unknown property: invalid")
+}
+
+func TestGetParsedDuration(t *testing.T) {
+ for _, test := range parsedDurationTests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.Len(), 1)
+ assert.Equal(t, p.GetParsedDuration(test.key, test.def), test.value)
+ }
+}
+
+func TestMustGetParsedDuration(t *testing.T) {
+ input := "key = 123ms\nkey2 = ghi"
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetParsedDuration("key"), 123*time.Millisecond)
+ assert.Panic(t, func() { p.MustGetParsedDuration("key2") }, "time: invalid duration ghi")
+ assert.Panic(t, func() { p.MustGetParsedDuration("invalid") }, "unknown property: invalid")
+}
+
+func TestGetFloat64(t *testing.T) {
+ for _, test := range floatTests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.Len(), 1)
+ assert.Equal(t, p.GetFloat64(test.key, test.def), test.value)
+ }
+}
+
+func TestMustGetFloat64(t *testing.T) {
+ input := "key = 123\nkey2 = ghi"
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetFloat64("key"), float64(123))
+ assert.Panic(t, func() { p.MustGetFloat64("key2") }, "strconv.ParseFloat: parsing.*")
+ assert.Panic(t, func() { p.MustGetFloat64("invalid") }, "unknown property: invalid")
+}
+
+func TestGetInt(t *testing.T) {
+ for _, test := range int64Tests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.Len(), 1)
+ assert.Equal(t, p.GetInt(test.key, int(test.def)), int(test.value))
+ }
+}
+
+func TestMustGetInt(t *testing.T) {
+ input := "key = 123\nkey2 = ghi"
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetInt("key"), int(123))
+ assert.Panic(t, func() { p.MustGetInt("key2") }, "strconv.ParseInt: parsing.*")
+ assert.Panic(t, func() { p.MustGetInt("invalid") }, "unknown property: invalid")
+}
+
+func TestGetInt64(t *testing.T) {
+ for _, test := range int64Tests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.Len(), 1)
+ assert.Equal(t, p.GetInt64(test.key, test.def), test.value)
+ }
+}
+
+func TestMustGetInt64(t *testing.T) {
+ input := "key = 123\nkey2 = ghi"
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetInt64("key"), int64(123))
+ assert.Panic(t, func() { p.MustGetInt64("key2") }, "strconv.ParseInt: parsing.*")
+ assert.Panic(t, func() { p.MustGetInt64("invalid") }, "unknown property: invalid")
+}
+
+func TestGetUint(t *testing.T) {
+ for _, test := range uint64Tests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.Len(), 1)
+ assert.Equal(t, p.GetUint(test.key, uint(test.def)), uint(test.value))
+ }
+}
+
+func TestMustGetUint(t *testing.T) {
+ input := "key = 123\nkey2 = ghi"
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetUint("key"), uint(123))
+ assert.Panic(t, func() { p.MustGetUint64("key2") }, "strconv.ParseUint: parsing.*")
+ assert.Panic(t, func() { p.MustGetUint64("invalid") }, "unknown property: invalid")
+}
+
+func TestGetUint64(t *testing.T) {
+ for _, test := range uint64Tests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.Len(), 1)
+ assert.Equal(t, p.GetUint64(test.key, test.def), test.value)
+ }
+}
+
+func TestMustGetUint64(t *testing.T) {
+ input := "key = 123\nkey2 = ghi"
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetUint64("key"), uint64(123))
+ assert.Panic(t, func() { p.MustGetUint64("key2") }, "strconv.ParseUint: parsing.*")
+ assert.Panic(t, func() { p.MustGetUint64("invalid") }, "unknown property: invalid")
+}
+
+func TestGetString(t *testing.T) {
+ for _, test := range stringTests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.Len(), 1)
+ assert.Equal(t, p.GetString(test.key, test.def), test.value)
+ }
+}
+
+func TestMustGetString(t *testing.T) {
+ input := `key = value`
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetString("key"), "value")
+ assert.Panic(t, func() { p.MustGetString("invalid") }, "unknown property: invalid")
+}
+
+func TestComment(t *testing.T) {
+ for _, test := range commentTests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.MustGetString(test.key), test.value)
+ assert.Equal(t, p.GetComments(test.key), test.comments)
+ if test.comments != nil {
+ assert.Equal(t, p.GetComment(test.key), test.comments[len(test.comments)-1])
+ } else {
+ assert.Equal(t, p.GetComment(test.key), "")
+ }
+
+ // test setting comments
+ if len(test.comments) > 0 {
+ // set single comment
+ p.ClearComments()
+ assert.Equal(t, len(p.c), 0)
+ p.SetComment(test.key, test.comments[0])
+ assert.Equal(t, p.GetComment(test.key), test.comments[0])
+
+ // set multiple comments
+ p.ClearComments()
+ assert.Equal(t, len(p.c), 0)
+ p.SetComments(test.key, test.comments)
+ assert.Equal(t, p.GetComments(test.key), test.comments)
+
+ // clear comments for a key
+ p.SetComments(test.key, nil)
+ assert.Equal(t, p.GetComment(test.key), "")
+ assert.Equal(t, p.GetComments(test.key), ([]string)(nil))
+ }
+ }
+}
+
+func TestFilter(t *testing.T) {
+ for _, test := range filterTests {
+ p := mustParse(t, test.input)
+ pp, err := p.Filter(test.pattern)
+ if err != nil {
+ assert.Matches(t, err.Error(), test.err)
+ continue
+ }
+ assert.Equal(t, pp != nil, true, "want properties")
+ assert.Equal(t, pp.Len(), len(test.keys))
+ for _, key := range test.keys {
+ v1, ok1 := p.Get(key)
+ v2, ok2 := pp.Get(key)
+ assert.Equal(t, ok1, true)
+ assert.Equal(t, ok2, true)
+ assert.Equal(t, v1, v2)
+ }
+ }
+}
+
+func TestFilterPrefix(t *testing.T) {
+ for _, test := range filterPrefixTests {
+ p := mustParse(t, test.input)
+ pp := p.FilterPrefix(test.prefix)
+ assert.Equal(t, pp != nil, true, "want properties")
+ assert.Equal(t, pp.Len(), len(test.keys))
+ for _, key := range test.keys {
+ v1, ok1 := p.Get(key)
+ v2, ok2 := pp.Get(key)
+ assert.Equal(t, ok1, true)
+ assert.Equal(t, ok2, true)
+ assert.Equal(t, v1, v2)
+ }
+ }
+}
+
+func TestFilterStripPrefix(t *testing.T) {
+ for _, test := range filterStripPrefixTests {
+ p := mustParse(t, test.input)
+ pp := p.FilterPrefix(test.prefix)
+ assert.Equal(t, pp != nil, true, "want properties")
+ assert.Equal(t, pp.Len(), len(test.keys))
+ for _, key := range test.keys {
+ v1, ok1 := p.Get(key)
+ v2, ok2 := pp.Get(key)
+ assert.Equal(t, ok1, true)
+ assert.Equal(t, ok2, true)
+ assert.Equal(t, v1, v2)
+ }
+ }
+}
+
+func TestKeys(t *testing.T) {
+ for _, test := range keysTests {
+ p := mustParse(t, test.input)
+ assert.Equal(t, p.Len(), len(test.keys))
+ assert.Equal(t, len(p.Keys()), len(test.keys))
+ assert.Equal(t, p.Keys(), test.keys)
+ }
+}
+
+func TestSet(t *testing.T) {
+ for _, test := range setTests {
+ p := mustParse(t, test.input)
+ prev, ok, err := p.Set(test.key, test.value)
+ if test.err != "" {
+ assert.Matches(t, err.Error(), test.err)
+ continue
+ }
+
+ assert.Equal(t, err, nil)
+ assert.Equal(t, ok, test.ok)
+ if ok {
+ assert.Equal(t, prev, test.prev)
+ }
+ assert.Equal(t, p.Keys(), test.keys)
+ }
+}
+
+func TestSetValue(t *testing.T) {
+ tests := []interface{}{
+ true, false,
+ int8(123), int16(123), int32(123), int64(123), int(123),
+ uint8(123), uint16(123), uint32(123), uint64(123), uint(123),
+ float32(1.23), float64(1.23),
+ "abc",
+ }
+
+ for _, v := range tests {
+ p := NewProperties()
+ err := p.SetValue("x", v)
+ assert.Equal(t, err, nil)
+ assert.Equal(t, p.GetString("x", ""), fmt.Sprintf("%v", v))
+ }
+}
+
+func TestMustSet(t *testing.T) {
+ input := "key=${key}"
+ p := mustParse(t, input)
+ assert.Panic(t, func() { p.MustSet("key", "${key}") }, "circular reference .*")
+}
+
+func TestWrite(t *testing.T) {
+ for _, test := range writeTests {
+ p, err := parse(test.input)
+
+ buf := new(bytes.Buffer)
+ var n int
+ switch test.encoding {
+ case "UTF-8":
+ n, err = p.Write(buf, UTF8)
+ case "ISO-8859-1":
+ n, err = p.Write(buf, ISO_8859_1)
+ }
+ assert.Equal(t, err, nil)
+ s := string(buf.Bytes())
+ assert.Equal(t, n, len(test.output), fmt.Sprintf("input=%q expected=%q obtained=%q", test.input, test.output, s))
+ assert.Equal(t, s, test.output, fmt.Sprintf("input=%q expected=%q obtained=%q", test.input, test.output, s))
+ }
+}
+
+func TestWriteComment(t *testing.T) {
+ for _, test := range writeCommentTests {
+ p, err := parse(test.input)
+
+ buf := new(bytes.Buffer)
+ var n int
+ switch test.encoding {
+ case "UTF-8":
+ n, err = p.WriteComment(buf, "# ", UTF8)
+ case "ISO-8859-1":
+ n, err = p.WriteComment(buf, "# ", ISO_8859_1)
+ }
+ assert.Equal(t, err, nil)
+ s := string(buf.Bytes())
+ assert.Equal(t, n, len(test.output), fmt.Sprintf("input=%q expected=%q obtained=%q", test.input, test.output, s))
+ assert.Equal(t, s, test.output, fmt.Sprintf("input=%q expected=%q obtained=%q", test.input, test.output, s))
+ }
+}
+
+func TestCustomExpansionExpression(t *testing.T) {
+ testKeyValuePrePostfix(t, "*[", "]*", "key=value\nkey2=*[key]*", "key", "value", "key2", "value")
+}
+
+func TestPanicOn32BitIntOverflow(t *testing.T) {
+ is32Bit = true
+ var min, max int64 = math.MinInt32 - 1, math.MaxInt32 + 1
+ input := fmt.Sprintf("min=%d\nmax=%d", min, max)
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetInt64("min"), min)
+ assert.Equal(t, p.MustGetInt64("max"), max)
+ assert.Panic(t, func() { p.MustGetInt("min") }, ".* out of range")
+ assert.Panic(t, func() { p.MustGetInt("max") }, ".* out of range")
+}
+
+func TestPanicOn32BitUintOverflow(t *testing.T) {
+ is32Bit = true
+ var max uint64 = math.MaxUint32 + 1
+ input := fmt.Sprintf("max=%d", max)
+ p := mustParse(t, input)
+ assert.Equal(t, p.MustGetUint64("max"), max)
+ assert.Panic(t, func() { p.MustGetUint("max") }, ".* out of range")
+}
+
+func TestDeleteKey(t *testing.T) {
+ input := "#comments should also be gone\nkey=to-be-deleted\nsecond=key"
+ p := mustParse(t, input)
+ assert.Equal(t, len(p.m), 2)
+ assert.Equal(t, len(p.c), 1)
+ assert.Equal(t, len(p.k), 2)
+ p.Delete("key")
+ assert.Equal(t, len(p.m), 1)
+ assert.Equal(t, len(p.c), 0)
+ assert.Equal(t, len(p.k), 1)
+ assert.Equal(t, p.k[0], "second")
+ assert.Equal(t, p.m["second"], "key")
+}
+
+func TestDeleteUnknownKey(t *testing.T) {
+ input := "#comments should also be gone\nkey=to-be-deleted"
+ p := mustParse(t, input)
+ assert.Equal(t, len(p.m), 1)
+ assert.Equal(t, len(p.c), 1)
+ assert.Equal(t, len(p.k), 1)
+ p.Delete("wrong-key")
+ assert.Equal(t, len(p.m), 1)
+ assert.Equal(t, len(p.c), 1)
+ assert.Equal(t, len(p.k), 1)
+}
+
+func TestMerge(t *testing.T) {
+ input1 := "#comment\nkey=value\nkey2=value2"
+ input2 := "#another comment\nkey=another value\nkey3=value3"
+ p1 := mustParse(t, input1)
+ p2 := mustParse(t, input2)
+ p1.Merge(p2)
+ assert.Equal(t, len(p1.m), 3)
+ assert.Equal(t, len(p1.c), 1)
+ assert.Equal(t, len(p1.k), 3)
+ assert.Equal(t, p1.MustGet("key"), "another value")
+ assert.Equal(t, p1.GetComment("key"), "another comment")
+}
+
+func TestMap(t *testing.T) {
+ input := "key=value\nabc=def"
+ p := mustParse(t, input)
+ m := map[string]string{"key": "value", "abc": "def"}
+ assert.Equal(t, p.Map(), m)
+}
+
+func TestFilterFunc(t *testing.T) {
+ input := "key=value\nabc=def"
+ p := mustParse(t, input)
+ pp := p.FilterFunc(func(k, v string) bool {
+ return k != "abc"
+ })
+ m := map[string]string{"key": "value"}
+ assert.Equal(t, pp.Map(), m)
+}
+
+// ----------------------------------------------------------------------------
+
+// tests all combinations of delimiters, leading and/or trailing whitespace and newlines.
+func testWhitespaceAndDelimiterCombinations(t *testing.T, key, value string) {
+ whitespace := []string{"", " ", "\f", "\t"}
+ delimiters := []string{"", " ", "=", ":"}
+ newlines := []string{"", "\r", "\n", "\r\n"}
+ for _, dl := range delimiters {
+ for _, ws1 := range whitespace {
+ for _, ws2 := range whitespace {
+ for _, nl := range newlines {
+ // skip the one case where there is nothing between a key and a value
+ if ws1 == "" && dl == "" && ws2 == "" && value != "" {
+ continue
+ }
+
+ input := fmt.Sprintf("%s%s%s%s%s%s", key, ws1, dl, ws2, value, nl)
+ testKeyValue(t, input, key, value)
+ }
+ }
+ }
+ }
+}
+
+// tests whether key/value pairs exist for a given input.
+// keyvalues is expected to be an even number of strings of "key", "value", ...
+func testKeyValue(t *testing.T, input string, keyvalues ...string) {
+ testKeyValuePrePostfix(t, "${", "}", input, keyvalues...)
+}
+
+// tests whether key/value pairs exist for a given input.
+// keyvalues is expected to be an even number of strings of "key", "value", ...
+func testKeyValuePrePostfix(t *testing.T, prefix, postfix, input string, keyvalues ...string) {
+ p, err := Load([]byte(input), ISO_8859_1)
+ assert.Equal(t, err, nil)
+ p.Prefix = prefix
+ p.Postfix = postfix
+ assertKeyValues(t, input, p, keyvalues...)
+}
+
+// tests whether key/value pairs exist for a given input.
+// keyvalues is expected to be an even number of strings of "key", "value", ...
+func assertKeyValues(t *testing.T, input string, p *Properties, keyvalues ...string) {
+ assert.Equal(t, p != nil, true, "want properties")
+ assert.Equal(t, 2*p.Len(), len(keyvalues), "Odd number of key/value pairs.")
+
+ for i := 0; i < len(keyvalues); i += 2 {
+ key, value := keyvalues[i], keyvalues[i+1]
+ v, ok := p.Get(key)
+ if !ok {
+ t.Errorf("No key %q found (input=%q)", key, input)
+ }
+ if got, want := v, value; !reflect.DeepEqual(got, want) {
+ t.Errorf("Value %q does not match %q (input=%q)", v, value, input)
+ }
+ }
+}
+
+func mustParse(t *testing.T, s string) *Properties {
+ p, err := parse(s)
+ if err != nil {
+ t.Fatalf("parse failed with %s", err)
+ }
+ return p
+}
+
+// prints to stderr if the -verbose flag was given.
+func printf(format string, args ...interface{}) {
+ if *verbose {
+ fmt.Fprintf(os.Stderr, format, args...)
+ }
+}
diff --git a/vendor/github.com/magiconair/properties/rangecheck.go b/vendor/github.com/magiconair/properties/rangecheck.go
new file mode 100644
index 000000000..2e907d540
--- /dev/null
+++ b/vendor/github.com/magiconair/properties/rangecheck.go
@@ -0,0 +1,31 @@
+// Copyright 2017 Frank Schroeder. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package properties
+
+import (
+ "fmt"
+ "math"
+)
+
+// make this a var to overwrite it in a test
+var is32Bit = ^uint(0) == math.MaxUint32
+
+// intRangeCheck checks if the value fits into the int type and
+// panics if it does not.
+func intRangeCheck(key string, v int64) int {
+ if is32Bit && (v < math.MinInt32 || v > math.MaxInt32) {
+ panic(fmt.Sprintf("Value %d for key %s out of range", v, key))
+ }
+ return int(v)
+}
+
+// uintRangeCheck checks if the value fits into the uint type and
+// panics if it does not.
+func uintRangeCheck(key string, v uint64) uint {
+ if is32Bit && v > math.MaxUint32 {
+ panic(fmt.Sprintf("Value %d for key %s out of range", v, key))
+ }
+ return uint(v)
+}
diff --git a/vendor/github.com/miekg/dns/README.md b/vendor/github.com/miekg/dns/README.md
index 2acc7f1ff..e8b0ec6a5 100644
--- a/vendor/github.com/miekg/dns/README.md
+++ b/vendor/github.com/miekg/dns/README.md
@@ -57,6 +57,7 @@ A not-so-up-to-date-list-that-may-be-actually-current:
* https://github.com/fffaraz/microdns
* http://quilt.io
* https://github.com/ipdcode/hades (JD.COM)
+* https://github.com/StackExchange/dnscontrol/
Send pull request if you want to be listed here.
diff --git a/vendor/github.com/miekg/dns/client.go b/vendor/github.com/miekg/dns/client.go
index d54d6422e..301dab9c1 100644
--- a/vendor/github.com/miekg/dns/client.go
+++ b/vendor/github.com/miekg/dns/client.go
@@ -103,7 +103,7 @@ func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
// case of truncation.
// It is up to the caller to create a message that allows for larger responses to be
// returned. Specifically this means adding an EDNS0 OPT RR that will advertise a larger
-// buffer, see SetEdns0. Messsages without an OPT RR will fallback to the historic limit
+// buffer, see SetEdns0. Messages without an OPT RR will fallback to the historic limit
// of 512 bytes.
func (c *Client) Exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
if !c.SingleInflight {
diff --git a/vendor/github.com/miekg/dns/issue_test.go b/vendor/github.com/miekg/dns/issue_test.go
index 3025fc98c..265ad56c0 100644
--- a/vendor/github.com/miekg/dns/issue_test.go
+++ b/vendor/github.com/miekg/dns/issue_test.go
@@ -2,7 +2,10 @@ package dns
// Tests that solve that an specific issue.
-import "testing"
+import (
+ "strings"
+ "testing"
+)
func TestTCPRtt(t *testing.T) {
m := new(Msg)
@@ -21,3 +24,45 @@ func TestTCPRtt(t *testing.T) {
}
}
}
+
+func TestNSEC3MissingSalt(t *testing.T) {
+ rr, err := NewRR("ji6neoaepv8b5o6k4ev33abha8ht9fgc.example. NSEC3 1 1 12 aabbccdd K8UDEMVP1J2F7EG6JEBPS17VP3N8I58H")
+ if err != nil {
+ t.Fatalf("failed to parse example rr: %s", err)
+ }
+ m := new(Msg)
+ m.Answer = []RR{rr}
+ mb, err := m.Pack()
+ if err != nil {
+ t.Fatalf("expected to pack message. err: %s", err)
+ }
+ if err := m.Unpack(mb); err != nil {
+ t.Fatalf("expected to unpack message. missing salt? err: %s", err)
+ }
+ in := rr.(*NSEC3).Salt
+ out := m.Answer[0].(*NSEC3).Salt
+ if in != out {
+ t.Fatalf("expected salts to match. packed: `%s`. returned: `%s`", in, out)
+ }
+}
+
+func TestNSEC3MixedNextDomain(t *testing.T) {
+ rr, err := NewRR("ji6neoaepv8b5o6k4ev33abha8ht9fgc.example. NSEC3 1 1 12 - k8udemvp1j2f7eg6jebps17vp3n8i58h")
+ if err != nil {
+ t.Fatalf("failed to parse example rr: %s", err)
+ }
+ m := new(Msg)
+ m.Answer = []RR{rr}
+ mb, err := m.Pack()
+ if err != nil {
+ t.Fatalf("expected to pack message. err: %s", err)
+ }
+ if err := m.Unpack(mb); err != nil {
+ t.Fatalf("expected to unpack message. err: %s", err)
+ }
+ in := strings.ToUpper(rr.(*NSEC3).NextDomain)
+ out := m.Answer[0].(*NSEC3).NextDomain
+ if in != out {
+ t.Fatalf("expected round trip to produce NextDomain `%s`, instead `%s`", in, out)
+ }
+}
diff --git a/vendor/github.com/miekg/dns/msg.go b/vendor/github.com/miekg/dns/msg.go
index b5c074f05..57262a10c 100644
--- a/vendor/github.com/miekg/dns/msg.go
+++ b/vendor/github.com/miekg/dns/msg.go
@@ -327,7 +327,6 @@ End:
// UnpackDomainName unpacks a domain name into a string.
func UnpackDomainName(msg []byte, off int) (string, int, error) {
s := make([]byte, 0, 64)
- labels := 0
off1 := 0
lenmsg := len(msg)
ptr := 0 // number of pointers followed
@@ -370,15 +369,6 @@ Loop:
}
}
}
- // never exceed the allowed label count lenght (63)
- if labels >= 63 {
- return "", lenmsg, &Error{err: "name exceeds 63 labels"}
- }
- labels += 1
- // never exceed the allowed doman name length (255 octets)
- if len(s) >= 255 {
- return "", lenmsg, &Error{err: "name exceeded allowed 255 octets"}
- }
s = append(s, '.')
off += c
case 0xC0:
@@ -398,9 +388,6 @@ Loop:
if ptr++; ptr > 10 {
return "", lenmsg, &Error{err: "too many compression pointers"}
}
- // pointer should guarantee that it advances and points forwards at least
- // but the condition on previous three lines guarantees that it's
- // at least loop-free
off = (c^0xC0)<<8 | int(c1)
default:
// 0x80 and 0x40 are reserved
diff --git a/vendor/github.com/miekg/dns/msg_generate.go b/vendor/github.com/miekg/dns/msg_generate.go
index c29447a10..4d9f81d43 100644
--- a/vendor/github.com/miekg/dns/msg_generate.go
+++ b/vendor/github.com/miekg/dns/msg_generate.go
@@ -139,8 +139,17 @@ return off, err
case st.Tag(i) == `dns:"base64"`:
o("off, err = packStringBase64(rr.%s, msg, off)\n")
- case strings.HasPrefix(st.Tag(i), `dns:"size-hex:SaltLength`): // Hack to fix empty salt length for NSEC3
- o("if rr.%s == \"-\" { /* do nothing, empty salt */ }\n")
+ case strings.HasPrefix(st.Tag(i), `dns:"size-hex:SaltLength`):
+ // directly write instead of using o() so we get the error check in the correct place
+ field := st.Field(i).Name()
+ fmt.Fprintf(b, `// Only pack salt if value is not "-", i.e. empty
+if rr.%s != "-" {
+ off, err = packStringHex(rr.%s, msg, off)
+ if err != nil {
+ return off, err
+ }
+}
+`, field, field)
continue
case strings.HasPrefix(st.Tag(i), `dns:"size-hex`): // size-hex can be packed just like hex
fallthrough
diff --git a/vendor/github.com/miekg/dns/msg_helpers.go b/vendor/github.com/miekg/dns/msg_helpers.go
index 494c05377..615274ab0 100644
--- a/vendor/github.com/miekg/dns/msg_helpers.go
+++ b/vendor/github.com/miekg/dns/msg_helpers.go
@@ -142,6 +142,11 @@ func truncateMsgFromRdlength(msg []byte, off int, rdlength uint16) (truncmsg []b
}
func fromBase32(s []byte) (buf []byte, err error) {
+ for i, b := range s {
+ if b >= 'a' && b <= 'z' {
+ s[i] = b - 32
+ }
+ }
buflen := base32.HexEncoding.DecodedLen(len(s))
buf = make([]byte, buflen)
n, err := base32.HexEncoding.Decode(buf, s)
diff --git a/vendor/github.com/miekg/dns/zmsg.go b/vendor/github.com/miekg/dns/zmsg.go
index 94627e35e..9b98e1bb2 100644
--- a/vendor/github.com/miekg/dns/zmsg.go
+++ b/vendor/github.com/miekg/dns/zmsg.go
@@ -801,10 +801,12 @@ func (rr *NSEC3) pack(msg []byte, off int, compression map[string]int, compress
if err != nil {
return off, err
}
- if rr.Salt == "-" { /* do nothing, empty salt */
- }
- if err != nil {
- return off, err
+ // Only pack salt if value is not "-", i.e. empty
+ if rr.Salt != "-" {
+ off, err = packStringHex(rr.Salt, msg, off)
+ if err != nil {
+ return off, err
+ }
}
off, err = packUint8(rr.HashLength, msg, off)
if err != nil {
@@ -844,10 +846,12 @@ func (rr *NSEC3PARAM) pack(msg []byte, off int, compression map[string]int, comp
if err != nil {
return off, err
}
- if rr.Salt == "-" { /* do nothing, empty salt */
- }
- if err != nil {
- return off, err
+ // Only pack salt if value is not "-", i.e. empty
+ if rr.Salt != "-" {
+ off, err = packStringHex(rr.Salt, msg, off)
+ if err != nil {
+ return off, err
+ }
}
rr.Header().Rdlength = uint16(off - headerEnd)
return off, nil
diff --git a/vendor/github.com/mitchellh/mapstructure/.travis.yml b/vendor/github.com/mitchellh/mapstructure/.travis.yml
new file mode 100644
index 000000000..7f3fe9a96
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/.travis.yml
@@ -0,0 +1,7 @@
+language: go
+
+go:
+ - 1.4
+
+script:
+ - go test
diff --git a/vendor/github.com/mitchellh/mapstructure/LICENSE b/vendor/github.com/mitchellh/mapstructure/LICENSE
new file mode 100644
index 000000000..f9c841a51
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Mitchell Hashimoto
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/vendor/github.com/mitchellh/mapstructure/README.md b/vendor/github.com/mitchellh/mapstructure/README.md
new file mode 100644
index 000000000..659d6885f
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/README.md
@@ -0,0 +1,46 @@
+# mapstructure
+
+mapstructure is a Go library for decoding generic map values to structures
+and vice versa, while providing helpful error handling.
+
+This library is most useful when decoding values from some data stream (JSON,
+Gob, etc.) where you don't _quite_ know the structure of the underlying data
+until you read a part of it. You can therefore read a `map[string]interface{}`
+and use this library to decode it into the proper underlying native Go
+structure.
+
+## Installation
+
+Standard `go get`:
+
+```
+$ go get github.com/mitchellh/mapstructure
+```
+
+## Usage & Example
+
+For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/mapstructure).
+
+The `Decode` function has examples associated with it there.
+
+## But Why?!
+
+Go offers fantastic standard libraries for decoding formats such as JSON.
+The standard method is to have a struct pre-created, and populate that struct
+from the bytes of the encoded format. This is great, but the problem is if
+you have configuration or an encoding that changes slightly depending on
+specific fields. For example, consider this JSON:
+
+```json
+{
+ "type": "person",
+ "name": "Mitchell"
+}
+```
+
+Perhaps we can't populate a specific structure without first reading
+the "type" field from the JSON. We could always do two passes over the
+decoding of the JSON (reading the "type" first, and the rest later).
+However, it is much simpler to just decode this into a `map[string]interface{}`
+structure, read the "type" key, then use something like this library
+to decode it into the proper structure.
diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
new file mode 100644
index 000000000..115ae67c1
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
@@ -0,0 +1,154 @@
+package mapstructure
+
+import (
+ "errors"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns
+// it into the proper DecodeHookFunc type, such as DecodeHookFuncType.
+func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc {
+ // Create variables here so we can reference them with the reflect pkg
+ var f1 DecodeHookFuncType
+ var f2 DecodeHookFuncKind
+
+ // Fill in the variables into this interface and the rest is done
+ // automatically using the reflect package.
+ potential := []interface{}{f1, f2}
+
+ v := reflect.ValueOf(h)
+ vt := v.Type()
+ for _, raw := range potential {
+ pt := reflect.ValueOf(raw).Type()
+ if vt.ConvertibleTo(pt) {
+ return v.Convert(pt).Interface()
+ }
+ }
+
+ return nil
+}
+
+// DecodeHookExec executes the given decode hook. This should be used
+// since it'll naturally degrade to the older backwards compatible DecodeHookFunc
+// that took reflect.Kind instead of reflect.Type.
+func DecodeHookExec(
+ raw DecodeHookFunc,
+ from reflect.Type, to reflect.Type,
+ data interface{}) (interface{}, error) {
+ // Build our arguments that reflect expects
+ argVals := make([]reflect.Value, 3)
+ argVals[0] = reflect.ValueOf(from)
+ argVals[1] = reflect.ValueOf(to)
+ argVals[2] = reflect.ValueOf(data)
+
+ switch f := typedDecodeHook(raw).(type) {
+ case DecodeHookFuncType:
+ return f(from, to, data)
+ case DecodeHookFuncKind:
+ return f(from.Kind(), to.Kind(), data)
+ default:
+ return nil, errors.New("invalid decode hook signature")
+ }
+}
+
+// ComposeDecodeHookFunc creates a single DecodeHookFunc that
+// automatically composes multiple DecodeHookFuncs.
+//
+// The composed funcs are called in order, with the result of the
+// previous transformation.
+func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc {
+ return func(
+ f reflect.Type,
+ t reflect.Type,
+ data interface{}) (interface{}, error) {
+ var err error
+ for _, f1 := range fs {
+ data, err = DecodeHookExec(f1, f, t, data)
+ if err != nil {
+ return nil, err
+ }
+
+ // Modify the from kind to be correct with the new data
+ f = nil
+ if val := reflect.ValueOf(data); val.IsValid() {
+ f = val.Type()
+ }
+ }
+
+ return data, nil
+ }
+}
+
+// StringToSliceHookFunc returns a DecodeHookFunc that converts
+// string to []string by splitting on the given sep.
+func StringToSliceHookFunc(sep string) DecodeHookFunc {
+ return func(
+ f reflect.Kind,
+ t reflect.Kind,
+ data interface{}) (interface{}, error) {
+ if f != reflect.String || t != reflect.Slice {
+ return data, nil
+ }
+
+ raw := data.(string)
+ if raw == "" {
+ return []string{}, nil
+ }
+
+ return strings.Split(raw, sep), nil
+ }
+}
+
+// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts
+// strings to time.Duration.
+func StringToTimeDurationHookFunc() DecodeHookFunc {
+ return func(
+ f reflect.Type,
+ t reflect.Type,
+ data interface{}) (interface{}, error) {
+ if f.Kind() != reflect.String {
+ return data, nil
+ }
+ if t != reflect.TypeOf(time.Duration(5)) {
+ return data, nil
+ }
+
+ // Convert it by parsing
+ return time.ParseDuration(data.(string))
+ }
+}
+
+func WeaklyTypedHook(
+ f reflect.Kind,
+ t reflect.Kind,
+ data interface{}) (interface{}, error) {
+ dataVal := reflect.ValueOf(data)
+ switch t {
+ case reflect.String:
+ switch f {
+ case reflect.Bool:
+ if dataVal.Bool() {
+ return "1", nil
+ } else {
+ return "0", nil
+ }
+ case reflect.Float32:
+ return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil
+ case reflect.Int:
+ return strconv.FormatInt(dataVal.Int(), 10), nil
+ case reflect.Slice:
+ dataType := dataVal.Type()
+ elemKind := dataType.Elem().Kind()
+ if elemKind == reflect.Uint8 {
+ return string(dataVal.Interface().([]uint8)), nil
+ }
+ case reflect.Uint:
+ return strconv.FormatUint(dataVal.Uint(), 10), nil
+ }
+ }
+
+ return data, nil
+}
diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go
new file mode 100644
index 000000000..53289afcf
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go
@@ -0,0 +1,229 @@
+package mapstructure
+
+import (
+ "errors"
+ "reflect"
+ "testing"
+ "time"
+)
+
+func TestComposeDecodeHookFunc(t *testing.T) {
+ f1 := func(
+ f reflect.Kind,
+ t reflect.Kind,
+ data interface{}) (interface{}, error) {
+ return data.(string) + "foo", nil
+ }
+
+ f2 := func(
+ f reflect.Kind,
+ t reflect.Kind,
+ data interface{}) (interface{}, error) {
+ return data.(string) + "bar", nil
+ }
+
+ f := ComposeDecodeHookFunc(f1, f2)
+
+ result, err := DecodeHookExec(
+ f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), "")
+ if err != nil {
+ t.Fatalf("bad: %s", err)
+ }
+ if result.(string) != "foobar" {
+ t.Fatalf("bad: %#v", result)
+ }
+}
+
+func TestComposeDecodeHookFunc_err(t *testing.T) {
+ f1 := func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) {
+ return nil, errors.New("foo")
+ }
+
+ f2 := func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) {
+ panic("NOPE")
+ }
+
+ f := ComposeDecodeHookFunc(f1, f2)
+
+ _, err := DecodeHookExec(
+ f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), 42)
+ if err.Error() != "foo" {
+ t.Fatalf("bad: %s", err)
+ }
+}
+
+func TestComposeDecodeHookFunc_kinds(t *testing.T) {
+ var f2From reflect.Kind
+
+ f1 := func(
+ f reflect.Kind,
+ t reflect.Kind,
+ data interface{}) (interface{}, error) {
+ return int(42), nil
+ }
+
+ f2 := func(
+ f reflect.Kind,
+ t reflect.Kind,
+ data interface{}) (interface{}, error) {
+ f2From = f
+ return data, nil
+ }
+
+ f := ComposeDecodeHookFunc(f1, f2)
+
+ _, err := DecodeHookExec(
+ f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), "")
+ if err != nil {
+ t.Fatalf("bad: %s", err)
+ }
+ if f2From != reflect.Int {
+ t.Fatalf("bad: %#v", f2From)
+ }
+}
+
+func TestStringToSliceHookFunc(t *testing.T) {
+ f := StringToSliceHookFunc(",")
+
+ strType := reflect.TypeOf("")
+ sliceType := reflect.TypeOf([]byte(""))
+ cases := []struct {
+ f, t reflect.Type
+ data interface{}
+ result interface{}
+ err bool
+ }{
+ {sliceType, sliceType, 42, 42, false},
+ {strType, strType, 42, 42, false},
+ {
+ strType,
+ sliceType,
+ "foo,bar,baz",
+ []string{"foo", "bar", "baz"},
+ false,
+ },
+ {
+ strType,
+ sliceType,
+ "",
+ []string{},
+ false,
+ },
+ }
+
+ for i, tc := range cases {
+ actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data)
+ if tc.err != (err != nil) {
+ t.Fatalf("case %d: expected err %#v", i, tc.err)
+ }
+ if !reflect.DeepEqual(actual, tc.result) {
+ t.Fatalf(
+ "case %d: expected %#v, got %#v",
+ i, tc.result, actual)
+ }
+ }
+}
+
+func TestStringToTimeDurationHookFunc(t *testing.T) {
+ f := StringToTimeDurationHookFunc()
+
+ strType := reflect.TypeOf("")
+ timeType := reflect.TypeOf(time.Duration(5))
+ cases := []struct {
+ f, t reflect.Type
+ data interface{}
+ result interface{}
+ err bool
+ }{
+ {strType, timeType, "5s", 5 * time.Second, false},
+ {strType, timeType, "5", time.Duration(0), true},
+ {strType, strType, "5", "5", false},
+ }
+
+ for i, tc := range cases {
+ actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data)
+ if tc.err != (err != nil) {
+ t.Fatalf("case %d: expected err %#v", i, tc.err)
+ }
+ if !reflect.DeepEqual(actual, tc.result) {
+ t.Fatalf(
+ "case %d: expected %#v, got %#v",
+ i, tc.result, actual)
+ }
+ }
+}
+
+func TestWeaklyTypedHook(t *testing.T) {
+ var f DecodeHookFunc = WeaklyTypedHook
+
+ boolType := reflect.TypeOf(true)
+ strType := reflect.TypeOf("")
+ sliceType := reflect.TypeOf([]byte(""))
+ cases := []struct {
+ f, t reflect.Type
+ data interface{}
+ result interface{}
+ err bool
+ }{
+ // TO STRING
+ {
+ boolType,
+ strType,
+ false,
+ "0",
+ false,
+ },
+
+ {
+ boolType,
+ strType,
+ true,
+ "1",
+ false,
+ },
+
+ {
+ reflect.TypeOf(float32(1)),
+ strType,
+ float32(7),
+ "7",
+ false,
+ },
+
+ {
+ reflect.TypeOf(int(1)),
+ strType,
+ int(7),
+ "7",
+ false,
+ },
+
+ {
+ sliceType,
+ strType,
+ []uint8("foo"),
+ "foo",
+ false,
+ },
+
+ {
+ reflect.TypeOf(uint(1)),
+ strType,
+ uint(7),
+ "7",
+ false,
+ },
+ }
+
+ for i, tc := range cases {
+ actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data)
+ if tc.err != (err != nil) {
+ t.Fatalf("case %d: expected err %#v", i, tc.err)
+ }
+ if !reflect.DeepEqual(actual, tc.result) {
+ t.Fatalf(
+ "case %d: expected %#v, got %#v",
+ i, tc.result, actual)
+ }
+ }
+}
diff --git a/vendor/github.com/mitchellh/mapstructure/error.go b/vendor/github.com/mitchellh/mapstructure/error.go
new file mode 100644
index 000000000..47a99e5af
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/error.go
@@ -0,0 +1,50 @@
+package mapstructure
+
+import (
+ "errors"
+ "fmt"
+ "sort"
+ "strings"
+)
+
+// Error implements the error interface and can represents multiple
+// errors that occur in the course of a single decode.
+type Error struct {
+ Errors []string
+}
+
+func (e *Error) Error() string {
+ points := make([]string, len(e.Errors))
+ for i, err := range e.Errors {
+ points[i] = fmt.Sprintf("* %s", err)
+ }
+
+ sort.Strings(points)
+ return fmt.Sprintf(
+ "%d error(s) decoding:\n\n%s",
+ len(e.Errors), strings.Join(points, "\n"))
+}
+
+// WrappedErrors implements the errwrap.Wrapper interface to make this
+// return value more useful with the errwrap and go-multierror libraries.
+func (e *Error) WrappedErrors() []error {
+ if e == nil {
+ return nil
+ }
+
+ result := make([]error, len(e.Errors))
+ for i, e := range e.Errors {
+ result[i] = errors.New(e)
+ }
+
+ return result
+}
+
+func appendErrors(errors []string, err error) []string {
+ switch e := err.(type) {
+ case *Error:
+ return append(errors, e.Errors...)
+ default:
+ return append(errors, e.Error())
+ }
+}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go
new file mode 100644
index 000000000..6dee0ef0a
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go
@@ -0,0 +1,823 @@
+// The mapstructure package exposes functionality to convert an
+// arbitrary map[string]interface{} into a native Go structure.
+//
+// The Go structure can be arbitrarily complex, containing slices,
+// other structs, etc. and the decoder will properly decode nested
+// maps and so on into the proper structures in the native Go struct.
+// See the examples to see what the decoder is capable of.
+package mapstructure
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+// DecodeHookFunc is the callback function that can be used for
+// data transformations. See "DecodeHook" in the DecoderConfig
+// struct.
+//
+// The type should be DecodeHookFuncType or DecodeHookFuncKind.
+// Either is accepted. Types are a superset of Kinds (Types can return
+// Kinds) and are generally a richer thing to use, but Kinds are simpler
+// if you only need those.
+//
+// The reason DecodeHookFunc is multi-typed is for backwards compatibility:
+// we started with Kinds and then realized Types were the better solution,
+// but have a promise to not break backwards compat so we now support
+// both.
+type DecodeHookFunc interface{}
+
+type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error)
+type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error)
+
+// DecoderConfig is the configuration that is used to create a new decoder
+// and allows customization of various aspects of decoding.
+type DecoderConfig struct {
+ // DecodeHook, if set, will be called before any decoding and any
+ // type conversion (if WeaklyTypedInput is on). This lets you modify
+ // the values before they're set down onto the resulting struct.
+ //
+ // If an error is returned, the entire decode will fail with that
+ // error.
+ DecodeHook DecodeHookFunc
+
+ // If ErrorUnused is true, then it is an error for there to exist
+ // keys in the original map that were unused in the decoding process
+ // (extra keys).
+ ErrorUnused bool
+
+ // ZeroFields, if set to true, will zero fields before writing them.
+ // For example, a map will be emptied before decoded values are put in
+ // it. If this is false, a map will be merged.
+ ZeroFields bool
+
+ // If WeaklyTypedInput is true, the decoder will make the following
+ // "weak" conversions:
+ //
+ // - bools to string (true = "1", false = "0")
+ // - numbers to string (base 10)
+ // - bools to int/uint (true = 1, false = 0)
+ // - strings to int/uint (base implied by prefix)
+ // - int to bool (true if value != 0)
+ // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F,
+ // FALSE, false, False. Anything else is an error)
+ // - empty array = empty map and vice versa
+ // - negative numbers to overflowed uint values (base 10)
+ // - slice of maps to a merged map
+ // - single values are converted to slices if required. Each
+ // element is weakly decoded. For example: "4" can become []int{4}
+ // if the target type is an int slice.
+ //
+ WeaklyTypedInput bool
+
+ // Metadata is the struct that will contain extra metadata about
+ // the decoding. If this is nil, then no metadata will be tracked.
+ Metadata *Metadata
+
+ // Result is a pointer to the struct that will contain the decoded
+ // value.
+ Result interface{}
+
+ // The tag name that mapstructure reads for field names. This
+ // defaults to "mapstructure"
+ TagName string
+}
+
+// A Decoder takes a raw interface value and turns it into structured
+// data, keeping track of rich error information along the way in case
+// anything goes wrong. Unlike the basic top-level Decode method, you can
+// more finely control how the Decoder behaves using the DecoderConfig
+// structure. The top-level Decode method is just a convenience that sets
+// up the most basic Decoder.
+type Decoder struct {
+ config *DecoderConfig
+}
+
+// Metadata contains information about decoding a structure that
+// is tedious or difficult to get otherwise.
+type Metadata struct {
+ // Keys are the keys of the structure which were successfully decoded
+ Keys []string
+
+ // Unused is a slice of keys that were found in the raw value but
+ // weren't decoded since there was no matching field in the result interface
+ Unused []string
+}
+
+// Decode takes a map and uses reflection to convert it into the
+// given Go native structure. val must be a pointer to a struct.
+func Decode(m interface{}, rawVal interface{}) error {
+ config := &DecoderConfig{
+ Metadata: nil,
+ Result: rawVal,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ return err
+ }
+
+ return decoder.Decode(m)
+}
+
+// WeakDecode is the same as Decode but is shorthand to enable
+// WeaklyTypedInput. See DecoderConfig for more info.
+func WeakDecode(input, output interface{}) error {
+ config := &DecoderConfig{
+ Metadata: nil,
+ Result: output,
+ WeaklyTypedInput: true,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ return err
+ }
+
+ return decoder.Decode(input)
+}
+
+// NewDecoder returns a new decoder for the given configuration. Once
+// a decoder has been returned, the same configuration must not be used
+// again.
+func NewDecoder(config *DecoderConfig) (*Decoder, error) {
+ val := reflect.ValueOf(config.Result)
+ if val.Kind() != reflect.Ptr {
+ return nil, errors.New("result must be a pointer")
+ }
+
+ val = val.Elem()
+ if !val.CanAddr() {
+ return nil, errors.New("result must be addressable (a pointer)")
+ }
+
+ if config.Metadata != nil {
+ if config.Metadata.Keys == nil {
+ config.Metadata.Keys = make([]string, 0)
+ }
+
+ if config.Metadata.Unused == nil {
+ config.Metadata.Unused = make([]string, 0)
+ }
+ }
+
+ if config.TagName == "" {
+ config.TagName = "mapstructure"
+ }
+
+ result := &Decoder{
+ config: config,
+ }
+
+ return result, nil
+}
+
+// Decode decodes the given raw interface to the target pointer specified
+// by the configuration.
+func (d *Decoder) Decode(raw interface{}) error {
+ return d.decode("", raw, reflect.ValueOf(d.config.Result).Elem())
+}
+
+// Decodes an unknown data type into a specific reflection value.
+func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error {
+ if data == nil {
+ // If the data is nil, then we don't set anything.
+ return nil
+ }
+
+ dataVal := reflect.ValueOf(data)
+ if !dataVal.IsValid() {
+ // If the data value is invalid, then we just set the value
+ // to be the zero value.
+ val.Set(reflect.Zero(val.Type()))
+ return nil
+ }
+
+ if d.config.DecodeHook != nil {
+ // We have a DecodeHook, so let's pre-process the data.
+ var err error
+ data, err = DecodeHookExec(
+ d.config.DecodeHook,
+ dataVal.Type(), val.Type(), data)
+ if err != nil {
+ return fmt.Errorf("error decoding '%s': %s", name, err)
+ }
+ }
+
+ var err error
+ dataKind := getKind(val)
+ switch dataKind {
+ case reflect.Bool:
+ err = d.decodeBool(name, data, val)
+ case reflect.Interface:
+ err = d.decodeBasic(name, data, val)
+ case reflect.String:
+ err = d.decodeString(name, data, val)
+ case reflect.Int:
+ err = d.decodeInt(name, data, val)
+ case reflect.Uint:
+ err = d.decodeUint(name, data, val)
+ case reflect.Float32:
+ err = d.decodeFloat(name, data, val)
+ case reflect.Struct:
+ err = d.decodeStruct(name, data, val)
+ case reflect.Map:
+ err = d.decodeMap(name, data, val)
+ case reflect.Ptr:
+ err = d.decodePtr(name, data, val)
+ case reflect.Slice:
+ err = d.decodeSlice(name, data, val)
+ case reflect.Func:
+ err = d.decodeFunc(name, data, val)
+ default:
+ // If we reached this point then we weren't able to decode it
+ return fmt.Errorf("%s: unsupported type: %s", name, dataKind)
+ }
+
+ // If we reached here, then we successfully decoded SOMETHING, so
+ // mark the key as used if we're tracking metadata.
+ if d.config.Metadata != nil && name != "" {
+ d.config.Metadata.Keys = append(d.config.Metadata.Keys, name)
+ }
+
+ return err
+}
+
+// This decodes a basic type (bool, int, string, etc.) and sets the
+// value to "data" of that type.
+func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ if !dataVal.IsValid() {
+ dataVal = reflect.Zero(val.Type())
+ }
+
+ dataValType := dataVal.Type()
+ if !dataValType.AssignableTo(val.Type()) {
+ return fmt.Errorf(
+ "'%s' expected type '%s', got '%s'",
+ name, val.Type(), dataValType)
+ }
+
+ val.Set(dataVal)
+ return nil
+}
+
+func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ dataKind := getKind(dataVal)
+
+ converted := true
+ switch {
+ case dataKind == reflect.String:
+ val.SetString(dataVal.String())
+ case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
+ if dataVal.Bool() {
+ val.SetString("1")
+ } else {
+ val.SetString("0")
+ }
+ case dataKind == reflect.Int && d.config.WeaklyTypedInput:
+ val.SetString(strconv.FormatInt(dataVal.Int(), 10))
+ case dataKind == reflect.Uint && d.config.WeaklyTypedInput:
+ val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
+ case dataKind == reflect.Float32 && d.config.WeaklyTypedInput:
+ val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64))
+ case dataKind == reflect.Slice && d.config.WeaklyTypedInput:
+ dataType := dataVal.Type()
+ elemKind := dataType.Elem().Kind()
+ switch {
+ case elemKind == reflect.Uint8:
+ val.SetString(string(dataVal.Interface().([]uint8)))
+ default:
+ converted = false
+ }
+ default:
+ converted = false
+ }
+
+ if !converted {
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ dataKind := getKind(dataVal)
+ dataType := dataVal.Type()
+
+ switch {
+ case dataKind == reflect.Int:
+ val.SetInt(dataVal.Int())
+ case dataKind == reflect.Uint:
+ val.SetInt(int64(dataVal.Uint()))
+ case dataKind == reflect.Float32:
+ val.SetInt(int64(dataVal.Float()))
+ case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
+ if dataVal.Bool() {
+ val.SetInt(1)
+ } else {
+ val.SetInt(0)
+ }
+ case dataKind == reflect.String && d.config.WeaklyTypedInput:
+ i, err := strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
+ if err == nil {
+ val.SetInt(i)
+ } else {
+ return fmt.Errorf("cannot parse '%s' as int: %s", name, err)
+ }
+ case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
+ jn := data.(json.Number)
+ i, err := jn.Int64()
+ if err != nil {
+ return fmt.Errorf(
+ "error decoding json.Number into %s: %s", name, err)
+ }
+ val.SetInt(i)
+ default:
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ dataKind := getKind(dataVal)
+
+ switch {
+ case dataKind == reflect.Int:
+ i := dataVal.Int()
+ if i < 0 && !d.config.WeaklyTypedInput {
+ return fmt.Errorf("cannot parse '%s', %d overflows uint",
+ name, i)
+ }
+ val.SetUint(uint64(i))
+ case dataKind == reflect.Uint:
+ val.SetUint(dataVal.Uint())
+ case dataKind == reflect.Float32:
+ f := dataVal.Float()
+ if f < 0 && !d.config.WeaklyTypedInput {
+ return fmt.Errorf("cannot parse '%s', %f overflows uint",
+ name, f)
+ }
+ val.SetUint(uint64(f))
+ case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
+ if dataVal.Bool() {
+ val.SetUint(1)
+ } else {
+ val.SetUint(0)
+ }
+ case dataKind == reflect.String && d.config.WeaklyTypedInput:
+ i, err := strconv.ParseUint(dataVal.String(), 0, val.Type().Bits())
+ if err == nil {
+ val.SetUint(i)
+ } else {
+ return fmt.Errorf("cannot parse '%s' as uint: %s", name, err)
+ }
+ default:
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ dataKind := getKind(dataVal)
+
+ switch {
+ case dataKind == reflect.Bool:
+ val.SetBool(dataVal.Bool())
+ case dataKind == reflect.Int && d.config.WeaklyTypedInput:
+ val.SetBool(dataVal.Int() != 0)
+ case dataKind == reflect.Uint && d.config.WeaklyTypedInput:
+ val.SetBool(dataVal.Uint() != 0)
+ case dataKind == reflect.Float32 && d.config.WeaklyTypedInput:
+ val.SetBool(dataVal.Float() != 0)
+ case dataKind == reflect.String && d.config.WeaklyTypedInput:
+ b, err := strconv.ParseBool(dataVal.String())
+ if err == nil {
+ val.SetBool(b)
+ } else if dataVal.String() == "" {
+ val.SetBool(false)
+ } else {
+ return fmt.Errorf("cannot parse '%s' as bool: %s", name, err)
+ }
+ default:
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ dataKind := getKind(dataVal)
+ dataType := dataVal.Type()
+
+ switch {
+ case dataKind == reflect.Int:
+ val.SetFloat(float64(dataVal.Int()))
+ case dataKind == reflect.Uint:
+ val.SetFloat(float64(dataVal.Uint()))
+ case dataKind == reflect.Float32:
+ val.SetFloat(float64(dataVal.Float()))
+ case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
+ if dataVal.Bool() {
+ val.SetFloat(1)
+ } else {
+ val.SetFloat(0)
+ }
+ case dataKind == reflect.String && d.config.WeaklyTypedInput:
+ f, err := strconv.ParseFloat(dataVal.String(), val.Type().Bits())
+ if err == nil {
+ val.SetFloat(f)
+ } else {
+ return fmt.Errorf("cannot parse '%s' as float: %s", name, err)
+ }
+ case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
+ jn := data.(json.Number)
+ i, err := jn.Float64()
+ if err != nil {
+ return fmt.Errorf(
+ "error decoding json.Number into %s: %s", name, err)
+ }
+ val.SetFloat(i)
+ default:
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error {
+ valType := val.Type()
+ valKeyType := valType.Key()
+ valElemType := valType.Elem()
+
+ // By default we overwrite keys in the current map
+ valMap := val
+
+ // If the map is nil or we're purposely zeroing fields, make a new map
+ if valMap.IsNil() || d.config.ZeroFields {
+ // Make a new map to hold our result
+ mapType := reflect.MapOf(valKeyType, valElemType)
+ valMap = reflect.MakeMap(mapType)
+ }
+
+ // Check input type
+ dataVal := reflect.Indirect(reflect.ValueOf(data))
+ if dataVal.Kind() != reflect.Map {
+ // In weak mode, we accept a slice of maps as an input...
+ if d.config.WeaklyTypedInput {
+ switch dataVal.Kind() {
+ case reflect.Array, reflect.Slice:
+ // Special case for BC reasons (covered by tests)
+ if dataVal.Len() == 0 {
+ val.Set(valMap)
+ return nil
+ }
+
+ for i := 0; i < dataVal.Len(); i++ {
+ err := d.decode(
+ fmt.Sprintf("%s[%d]", name, i),
+ dataVal.Index(i).Interface(), val)
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+ }
+ }
+
+ return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
+ }
+
+ // Accumulate errors
+ errors := make([]string, 0)
+
+ for _, k := range dataVal.MapKeys() {
+ fieldName := fmt.Sprintf("%s[%s]", name, k)
+
+ // First decode the key into the proper type
+ currentKey := reflect.Indirect(reflect.New(valKeyType))
+ if err := d.decode(fieldName, k.Interface(), currentKey); err != nil {
+ errors = appendErrors(errors, err)
+ continue
+ }
+
+ // Next decode the data into the proper type
+ v := dataVal.MapIndex(k).Interface()
+ currentVal := reflect.Indirect(reflect.New(valElemType))
+ if err := d.decode(fieldName, v, currentVal); err != nil {
+ errors = appendErrors(errors, err)
+ continue
+ }
+
+ valMap.SetMapIndex(currentKey, currentVal)
+ }
+
+ // Set the built up map to the value
+ val.Set(valMap)
+
+ // If we had errors, return those
+ if len(errors) > 0 {
+ return &Error{errors}
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) error {
+ // Create an element of the concrete (non pointer) type and decode
+ // into that. Then set the value of the pointer to this type.
+ valType := val.Type()
+ valElemType := valType.Elem()
+
+ realVal := val
+ if realVal.IsNil() || d.config.ZeroFields {
+ realVal = reflect.New(valElemType)
+ }
+
+ if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil {
+ return err
+ }
+
+ val.Set(realVal)
+ return nil
+}
+
+func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error {
+ // Create an element of the concrete (non pointer) type and decode
+ // into that. Then set the value of the pointer to this type.
+ dataVal := reflect.Indirect(reflect.ValueOf(data))
+ if val.Type() != dataVal.Type() {
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+ val.Set(dataVal)
+ return nil
+}
+
+func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.Indirect(reflect.ValueOf(data))
+ dataValKind := dataVal.Kind()
+ valType := val.Type()
+ valElemType := valType.Elem()
+ sliceType := reflect.SliceOf(valElemType)
+
+ valSlice := val
+ if valSlice.IsNil() || d.config.ZeroFields {
+ // Check input type
+ if dataValKind != reflect.Array && dataValKind != reflect.Slice {
+ if d.config.WeaklyTypedInput {
+ switch {
+ // Empty maps turn into empty slices
+ case dataValKind == reflect.Map:
+ if dataVal.Len() == 0 {
+ val.Set(reflect.MakeSlice(sliceType, 0, 0))
+ return nil
+ }
+
+ // All other types we try to convert to the slice type
+ // and "lift" it into it. i.e. a string becomes a string slice.
+ default:
+ // Just re-try this function with data as a slice.
+ return d.decodeSlice(name, []interface{}{data}, val)
+ }
+ }
+
+ return fmt.Errorf(
+ "'%s': source data must be an array or slice, got %s", name, dataValKind)
+
+ }
+
+ // Make a new slice to hold our result, same size as the original data.
+ valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len())
+ }
+
+ // Accumulate any errors
+ errors := make([]string, 0)
+
+ for i := 0; i < dataVal.Len(); i++ {
+ currentData := dataVal.Index(i).Interface()
+ for valSlice.Len() <= i {
+ valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
+ }
+ currentField := valSlice.Index(i)
+
+ fieldName := fmt.Sprintf("%s[%d]", name, i)
+ if err := d.decode(fieldName, currentData, currentField); err != nil {
+ errors = appendErrors(errors, err)
+ }
+ }
+
+ // Finally, set the value to the slice we built up
+ val.Set(valSlice)
+
+ // If there were errors, we return those
+ if len(errors) > 0 {
+ return &Error{errors}
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.Indirect(reflect.ValueOf(data))
+
+ // If the type of the value to write to and the data match directly,
+ // then we just set it directly instead of recursing into the structure.
+ if dataVal.Type() == val.Type() {
+ val.Set(dataVal)
+ return nil
+ }
+
+ dataValKind := dataVal.Kind()
+ if dataValKind != reflect.Map {
+ return fmt.Errorf("'%s' expected a map, got '%s'", name, dataValKind)
+ }
+
+ dataValType := dataVal.Type()
+ if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface {
+ return fmt.Errorf(
+ "'%s' needs a map with string keys, has '%s' keys",
+ name, dataValType.Key().Kind())
+ }
+
+ dataValKeys := make(map[reflect.Value]struct{})
+ dataValKeysUnused := make(map[interface{}]struct{})
+ for _, dataValKey := range dataVal.MapKeys() {
+ dataValKeys[dataValKey] = struct{}{}
+ dataValKeysUnused[dataValKey.Interface()] = struct{}{}
+ }
+
+ errors := make([]string, 0)
+
+ // This slice will keep track of all the structs we'll be decoding.
+ // There can be more than one struct if there are embedded structs
+ // that are squashed.
+ structs := make([]reflect.Value, 1, 5)
+ structs[0] = val
+
+ // Compile the list of all the fields that we're going to be decoding
+ // from all the structs.
+ fields := make(map[*reflect.StructField]reflect.Value)
+ for len(structs) > 0 {
+ structVal := structs[0]
+ structs = structs[1:]
+
+ structType := structVal.Type()
+
+ for i := 0; i < structType.NumField(); i++ {
+ fieldType := structType.Field(i)
+ fieldKind := fieldType.Type.Kind()
+
+ // If "squash" is specified in the tag, we squash the field down.
+ squash := false
+ tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",")
+ for _, tag := range tagParts[1:] {
+ if tag == "squash" {
+ squash = true
+ break
+ }
+ }
+
+ if squash {
+ if fieldKind != reflect.Struct {
+ errors = appendErrors(errors,
+ fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind))
+ } else {
+ structs = append(structs, val.FieldByName(fieldType.Name))
+ }
+ continue
+ }
+
+ // Normal struct field, store it away
+ fields[&fieldType] = structVal.Field(i)
+ }
+ }
+
+ for fieldType, field := range fields {
+ fieldName := fieldType.Name
+
+ tagValue := fieldType.Tag.Get(d.config.TagName)
+ tagValue = strings.SplitN(tagValue, ",", 2)[0]
+ if tagValue != "" {
+ fieldName = tagValue
+ }
+
+ rawMapKey := reflect.ValueOf(fieldName)
+ rawMapVal := dataVal.MapIndex(rawMapKey)
+ if !rawMapVal.IsValid() {
+ // Do a slower search by iterating over each key and
+ // doing case-insensitive search.
+ for dataValKey := range dataValKeys {
+ mK, ok := dataValKey.Interface().(string)
+ if !ok {
+ // Not a string key
+ continue
+ }
+
+ if strings.EqualFold(mK, fieldName) {
+ rawMapKey = dataValKey
+ rawMapVal = dataVal.MapIndex(dataValKey)
+ break
+ }
+ }
+
+ if !rawMapVal.IsValid() {
+ // There was no matching key in the map for the value in
+ // the struct. Just ignore.
+ continue
+ }
+ }
+
+ // Delete the key we're using from the unused map so we stop tracking
+ delete(dataValKeysUnused, rawMapKey.Interface())
+
+ if !field.IsValid() {
+ // This should never happen
+ panic("field is not valid")
+ }
+
+ // If we can't set the field, then it is unexported or something,
+ // and we just continue onwards.
+ if !field.CanSet() {
+ continue
+ }
+
+ // If the name is empty string, then we're at the root, and we
+ // don't dot-join the fields.
+ if name != "" {
+ fieldName = fmt.Sprintf("%s.%s", name, fieldName)
+ }
+
+ if err := d.decode(fieldName, rawMapVal.Interface(), field); err != nil {
+ errors = appendErrors(errors, err)
+ }
+ }
+
+ if d.config.ErrorUnused && len(dataValKeysUnused) > 0 {
+ keys := make([]string, 0, len(dataValKeysUnused))
+ for rawKey := range dataValKeysUnused {
+ keys = append(keys, rawKey.(string))
+ }
+ sort.Strings(keys)
+
+ err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", "))
+ errors = appendErrors(errors, err)
+ }
+
+ if len(errors) > 0 {
+ return &Error{errors}
+ }
+
+ // Add the unused keys to the list of unused keys if we're tracking metadata
+ if d.config.Metadata != nil {
+ for rawKey := range dataValKeysUnused {
+ key := rawKey.(string)
+ if name != "" {
+ key = fmt.Sprintf("%s.%s", name, key)
+ }
+
+ d.config.Metadata.Unused = append(d.config.Metadata.Unused, key)
+ }
+ }
+
+ return nil
+}
+
+func getKind(val reflect.Value) reflect.Kind {
+ kind := val.Kind()
+
+ switch {
+ case kind >= reflect.Int && kind <= reflect.Int64:
+ return reflect.Int
+ case kind >= reflect.Uint && kind <= reflect.Uint64:
+ return reflect.Uint
+ case kind >= reflect.Float32 && kind <= reflect.Float64:
+ return reflect.Float32
+ default:
+ return kind
+ }
+}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go
new file mode 100644
index 000000000..41d2a41f7
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go
@@ -0,0 +1,279 @@
+package mapstructure
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func Benchmark_Decode(b *testing.B) {
+ type Person struct {
+ Name string
+ Age int
+ Emails []string
+ Extra map[string]string
+ }
+
+ input := map[string]interface{}{
+ "name": "Mitchell",
+ "age": 91,
+ "emails": []string{"one", "two", "three"},
+ "extra": map[string]string{
+ "twitter": "mitchellh",
+ },
+ }
+
+ var result Person
+ for i := 0; i < b.N; i++ {
+ Decode(input, &result)
+ }
+}
+
+// decodeViaJSON takes the map data and passes it through encoding/json to convert it into the
+// given Go native structure pointed to by v. v must be a pointer to a struct.
+func decodeViaJSON(data interface{}, v interface{}) error {
+ // Perform the task by simply marshalling the input into JSON,
+ // then unmarshalling it into target native Go struct.
+ b, err := json.Marshal(data)
+ if err != nil {
+ return err
+ }
+ return json.Unmarshal(b, v)
+}
+
+func Benchmark_DecodeViaJSON(b *testing.B) {
+ type Person struct {
+ Name string
+ Age int
+ Emails []string
+ Extra map[string]string
+ }
+
+ input := map[string]interface{}{
+ "name": "Mitchell",
+ "age": 91,
+ "emails": []string{"one", "two", "three"},
+ "extra": map[string]string{
+ "twitter": "mitchellh",
+ },
+ }
+
+ var result Person
+ for i := 0; i < b.N; i++ {
+ decodeViaJSON(input, &result)
+ }
+}
+
+func Benchmark_DecodeBasic(b *testing.B) {
+ input := map[string]interface{}{
+ "vstring": "foo",
+ "vint": 42,
+ "Vuint": 42,
+ "vbool": true,
+ "Vfloat": 42.42,
+ "vsilent": true,
+ "vdata": 42,
+ }
+
+ var result Basic
+ for i := 0; i < b.N; i++ {
+ Decode(input, &result)
+ }
+}
+
+func Benchmark_DecodeEmbedded(b *testing.B) {
+ input := map[string]interface{}{
+ "vstring": "foo",
+ "Basic": map[string]interface{}{
+ "vstring": "innerfoo",
+ },
+ "vunique": "bar",
+ }
+
+ var result Embedded
+ for i := 0; i < b.N; i++ {
+ Decode(input, &result)
+ }
+}
+
+func Benchmark_DecodeTypeConversion(b *testing.B) {
+ input := map[string]interface{}{
+ "IntToFloat": 42,
+ "IntToUint": 42,
+ "IntToBool": 1,
+ "IntToString": 42,
+ "UintToInt": 42,
+ "UintToFloat": 42,
+ "UintToBool": 42,
+ "UintToString": 42,
+ "BoolToInt": true,
+ "BoolToUint": true,
+ "BoolToFloat": true,
+ "BoolToString": true,
+ "FloatToInt": 42.42,
+ "FloatToUint": 42.42,
+ "FloatToBool": 42.42,
+ "FloatToString": 42.42,
+ "StringToInt": "42",
+ "StringToUint": "42",
+ "StringToBool": "1",
+ "StringToFloat": "42.42",
+ "SliceToMap": []interface{}{},
+ "MapToSlice": map[string]interface{}{},
+ }
+
+ var resultStrict TypeConversionResult
+ for i := 0; i < b.N; i++ {
+ Decode(input, &resultStrict)
+ }
+}
+
+func Benchmark_DecodeMap(b *testing.B) {
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vother": map[interface{}]interface{}{
+ "foo": "foo",
+ "bar": "bar",
+ },
+ }
+
+ var result Map
+ for i := 0; i < b.N; i++ {
+ Decode(input, &result)
+ }
+}
+
+func Benchmark_DecodeMapOfStruct(b *testing.B) {
+ input := map[string]interface{}{
+ "value": map[string]interface{}{
+ "foo": map[string]string{"vstring": "one"},
+ "bar": map[string]string{"vstring": "two"},
+ },
+ }
+
+ var result MapOfStruct
+ for i := 0; i < b.N; i++ {
+ Decode(input, &result)
+ }
+}
+
+func Benchmark_DecodeSlice(b *testing.B) {
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vbar": []string{"foo", "bar", "baz"},
+ }
+
+ var result Slice
+ for i := 0; i < b.N; i++ {
+ Decode(input, &result)
+ }
+}
+
+func Benchmark_DecodeSliceOfStruct(b *testing.B) {
+ input := map[string]interface{}{
+ "value": []map[string]interface{}{
+ {"vstring": "one"},
+ {"vstring": "two"},
+ },
+ }
+
+ var result SliceOfStruct
+ for i := 0; i < b.N; i++ {
+ Decode(input, &result)
+ }
+}
+
+func Benchmark_DecodeWeaklyTypedInput(b *testing.B) {
+ type Person struct {
+ Name string
+ Age int
+ Emails []string
+ }
+
+ // This input can come from anywhere, but typically comes from
+ // something like decoding JSON, generated by a weakly typed language
+ // such as PHP.
+ input := map[string]interface{}{
+ "name": 123, // number => string
+ "age": "42", // string => number
+ "emails": map[string]interface{}{}, // empty map => empty array
+ }
+
+ var result Person
+ config := &DecoderConfig{
+ WeaklyTypedInput: true,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ panic(err)
+ }
+
+ for i := 0; i < b.N; i++ {
+ decoder.Decode(input)
+ }
+}
+
+func Benchmark_DecodeMetadata(b *testing.B) {
+ type Person struct {
+ Name string
+ Age int
+ }
+
+ input := map[string]interface{}{
+ "name": "Mitchell",
+ "age": 91,
+ "email": "foo@bar.com",
+ }
+
+ var md Metadata
+ var result Person
+ config := &DecoderConfig{
+ Metadata: &md,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ panic(err)
+ }
+
+ for i := 0; i < b.N; i++ {
+ decoder.Decode(input)
+ }
+}
+
+func Benchmark_DecodeMetadataEmbedded(b *testing.B) {
+ input := map[string]interface{}{
+ "vstring": "foo",
+ "vunique": "bar",
+ }
+
+ var md Metadata
+ var result EmbeddedSquash
+ config := &DecoderConfig{
+ Metadata: &md,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ b.Fatalf("err: %s", err)
+ }
+
+ for i := 0; i < b.N; i++ {
+ decoder.Decode(input)
+ }
+}
+
+func Benchmark_DecodeTagged(b *testing.B) {
+ input := map[string]interface{}{
+ "foo": "bar",
+ "bar": "value",
+ }
+
+ var result Tagged
+ for i := 0; i < b.N; i++ {
+ Decode(input, &result)
+ }
+}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go
new file mode 100644
index 000000000..08e495664
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go
@@ -0,0 +1,260 @@
+package mapstructure
+
+import "testing"
+
+// GH-1
+func TestDecode_NilValue(t *testing.T) {
+ input := map[string]interface{}{
+ "vfoo": nil,
+ "vother": nil,
+ }
+
+ var result Map
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("should not error: %s", err)
+ }
+
+ if result.Vfoo != "" {
+ t.Fatalf("value should be default: %s", result.Vfoo)
+ }
+
+ if result.Vother != nil {
+ t.Fatalf("Vother should be nil: %s", result.Vother)
+ }
+}
+
+// GH-10
+func TestDecode_mapInterfaceInterface(t *testing.T) {
+ input := map[interface{}]interface{}{
+ "vfoo": nil,
+ "vother": nil,
+ }
+
+ var result Map
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("should not error: %s", err)
+ }
+
+ if result.Vfoo != "" {
+ t.Fatalf("value should be default: %s", result.Vfoo)
+ }
+
+ if result.Vother != nil {
+ t.Fatalf("Vother should be nil: %s", result.Vother)
+ }
+}
+
+// #48
+func TestNestedTypePointerWithDefaults(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vbar": map[string]interface{}{
+ "vstring": "foo",
+ "vint": 42,
+ "vbool": true,
+ },
+ }
+
+ result := NestedPointer{
+ Vbar: &Basic{
+ Vuint: 42,
+ },
+ }
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+
+ if result.Vfoo != "foo" {
+ t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
+ }
+
+ if result.Vbar.Vstring != "foo" {
+ t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring)
+ }
+
+ if result.Vbar.Vint != 42 {
+ t.Errorf("vint value should be 42: %#v", result.Vbar.Vint)
+ }
+
+ if result.Vbar.Vbool != true {
+ t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool)
+ }
+
+ if result.Vbar.Vextra != "" {
+ t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra)
+ }
+
+ // this is the error
+ if result.Vbar.Vuint != 42 {
+ t.Errorf("vuint value should be 42: %#v", result.Vbar.Vuint)
+ }
+
+}
+
+type NestedSlice struct {
+ Vfoo string
+ Vbars []Basic
+ Vempty []Basic
+}
+
+// #48
+func TestNestedTypeSliceWithDefaults(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vbars": []map[string]interface{}{
+ {"vstring": "foo", "vint": 42, "vbool": true},
+ {"vint": 42, "vbool": true},
+ },
+ "vempty": []map[string]interface{}{
+ {"vstring": "foo", "vint": 42, "vbool": true},
+ {"vint": 42, "vbool": true},
+ },
+ }
+
+ result := NestedSlice{
+ Vbars: []Basic{
+ {Vuint: 42},
+ {Vstring: "foo"},
+ },
+ }
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+
+ if result.Vfoo != "foo" {
+ t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
+ }
+
+ if result.Vbars[0].Vstring != "foo" {
+ t.Errorf("vstring value should be 'foo': %#v", result.Vbars[0].Vstring)
+ }
+ // this is the error
+ if result.Vbars[0].Vuint != 42 {
+ t.Errorf("vuint value should be 42: %#v", result.Vbars[0].Vuint)
+ }
+}
+
+// #48 workaround
+func TestNestedTypeWithDefaults(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vbar": map[string]interface{}{
+ "vstring": "foo",
+ "vint": 42,
+ "vbool": true,
+ },
+ }
+
+ result := Nested{
+ Vbar: Basic{
+ Vuint: 42,
+ },
+ }
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+
+ if result.Vfoo != "foo" {
+ t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
+ }
+
+ if result.Vbar.Vstring != "foo" {
+ t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring)
+ }
+
+ if result.Vbar.Vint != 42 {
+ t.Errorf("vint value should be 42: %#v", result.Vbar.Vint)
+ }
+
+ if result.Vbar.Vbool != true {
+ t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool)
+ }
+
+ if result.Vbar.Vextra != "" {
+ t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra)
+ }
+
+ // this is the error
+ if result.Vbar.Vuint != 42 {
+ t.Errorf("vuint value should be 42: %#v", result.Vbar.Vuint)
+ }
+
+}
+
+// #67 panic() on extending slices (decodeSlice with disabled ZeroValues)
+func TestDecodeSliceToEmptySliceWOZeroing(t *testing.T) {
+ t.Parallel()
+
+ type TestStruct struct {
+ Vfoo []string
+ }
+
+ decode := func(m interface{}, rawVal interface{}) error {
+ config := &DecoderConfig{
+ Metadata: nil,
+ Result: rawVal,
+ ZeroFields: false,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ return err
+ }
+
+ return decoder.Decode(m)
+ }
+
+ {
+ input := map[string]interface{}{
+ "vfoo": []string{"1"},
+ }
+
+ result := &TestStruct{}
+
+ err := decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+ }
+
+ {
+ input := map[string]interface{}{
+ "vfoo": []string{"1"},
+ }
+
+ result := &TestStruct{
+ Vfoo: []string{},
+ }
+
+ err := decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+ }
+
+ {
+ input := map[string]interface{}{
+ "vfoo": []string{"2", "3"},
+ }
+
+ result := &TestStruct{
+ Vfoo: []string{"1"},
+ }
+
+ err := decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+ }
+}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go
new file mode 100644
index 000000000..f17c214a8
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go
@@ -0,0 +1,203 @@
+package mapstructure
+
+import (
+ "fmt"
+)
+
+func ExampleDecode() {
+ type Person struct {
+ Name string
+ Age int
+ Emails []string
+ Extra map[string]string
+ }
+
+ // This input can come from anywhere, but typically comes from
+ // something like decoding JSON where we're not quite sure of the
+ // struct initially.
+ input := map[string]interface{}{
+ "name": "Mitchell",
+ "age": 91,
+ "emails": []string{"one", "two", "three"},
+ "extra": map[string]string{
+ "twitter": "mitchellh",
+ },
+ }
+
+ var result Person
+ err := Decode(input, &result)
+ if err != nil {
+ panic(err)
+ }
+
+ fmt.Printf("%#v", result)
+ // Output:
+ // mapstructure.Person{Name:"Mitchell", Age:91, Emails:[]string{"one", "two", "three"}, Extra:map[string]string{"twitter":"mitchellh"}}
+}
+
+func ExampleDecode_errors() {
+ type Person struct {
+ Name string
+ Age int
+ Emails []string
+ Extra map[string]string
+ }
+
+ // This input can come from anywhere, but typically comes from
+ // something like decoding JSON where we're not quite sure of the
+ // struct initially.
+ input := map[string]interface{}{
+ "name": 123,
+ "age": "bad value",
+ "emails": []int{1, 2, 3},
+ }
+
+ var result Person
+ err := Decode(input, &result)
+ if err == nil {
+ panic("should have an error")
+ }
+
+ fmt.Println(err.Error())
+ // Output:
+ // 5 error(s) decoding:
+ //
+ // * 'Age' expected type 'int', got unconvertible type 'string'
+ // * 'Emails[0]' expected type 'string', got unconvertible type 'int'
+ // * 'Emails[1]' expected type 'string', got unconvertible type 'int'
+ // * 'Emails[2]' expected type 'string', got unconvertible type 'int'
+ // * 'Name' expected type 'string', got unconvertible type 'int'
+}
+
+func ExampleDecode_metadata() {
+ type Person struct {
+ Name string
+ Age int
+ }
+
+ // This input can come from anywhere, but typically comes from
+ // something like decoding JSON where we're not quite sure of the
+ // struct initially.
+ input := map[string]interface{}{
+ "name": "Mitchell",
+ "age": 91,
+ "email": "foo@bar.com",
+ }
+
+ // For metadata, we make a more advanced DecoderConfig so we can
+ // more finely configure the decoder that is used. In this case, we
+ // just tell the decoder we want to track metadata.
+ var md Metadata
+ var result Person
+ config := &DecoderConfig{
+ Metadata: &md,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ panic(err)
+ }
+
+ if err := decoder.Decode(input); err != nil {
+ panic(err)
+ }
+
+ fmt.Printf("Unused keys: %#v", md.Unused)
+ // Output:
+ // Unused keys: []string{"email"}
+}
+
+func ExampleDecode_weaklyTypedInput() {
+ type Person struct {
+ Name string
+ Age int
+ Emails []string
+ }
+
+ // This input can come from anywhere, but typically comes from
+ // something like decoding JSON, generated by a weakly typed language
+ // such as PHP.
+ input := map[string]interface{}{
+ "name": 123, // number => string
+ "age": "42", // string => number
+ "emails": map[string]interface{}{}, // empty map => empty array
+ }
+
+ var result Person
+ config := &DecoderConfig{
+ WeaklyTypedInput: true,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ panic(err)
+ }
+
+ err = decoder.Decode(input)
+ if err != nil {
+ panic(err)
+ }
+
+ fmt.Printf("%#v", result)
+ // Output: mapstructure.Person{Name:"123", Age:42, Emails:[]string{}}
+}
+
+func ExampleDecode_tags() {
+ // Note that the mapstructure tags defined in the struct type
+ // can indicate which fields the values are mapped to.
+ type Person struct {
+ Name string `mapstructure:"person_name"`
+ Age int `mapstructure:"person_age"`
+ }
+
+ input := map[string]interface{}{
+ "person_name": "Mitchell",
+ "person_age": 91,
+ }
+
+ var result Person
+ err := Decode(input, &result)
+ if err != nil {
+ panic(err)
+ }
+
+ fmt.Printf("%#v", result)
+ // Output:
+ // mapstructure.Person{Name:"Mitchell", Age:91}
+}
+
+func ExampleDecode_embeddedStruct() {
+ // Squashing multiple embedded structs is allowed using the squash tag.
+ // This is demonstrated by creating a composite struct of multiple types
+ // and decoding into it. In this case, a person can carry with it both
+ // a Family and a Location, as well as their own FirstName.
+ type Family struct {
+ LastName string
+ }
+ type Location struct {
+ City string
+ }
+ type Person struct {
+ Family `mapstructure:",squash"`
+ Location `mapstructure:",squash"`
+ FirstName string
+ }
+
+ input := map[string]interface{}{
+ "FirstName": "Mitchell",
+ "LastName": "Hashimoto",
+ "City": "San Francisco",
+ }
+
+ var result Person
+ err := Decode(input, &result)
+ if err != nil {
+ panic(err)
+ }
+
+ fmt.Printf("%s %s, %s", result.FirstName, result.LastName, result.City)
+ // Output:
+ // Mitchell Hashimoto, San Francisco
+}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_test.go
new file mode 100644
index 000000000..932779d93
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/mapstructure_test.go
@@ -0,0 +1,1193 @@
+package mapstructure
+
+import (
+ "encoding/json"
+ "io"
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+)
+
+type Basic struct {
+ Vstring string
+ Vint int
+ Vuint uint
+ Vbool bool
+ Vfloat float64
+ Vextra string
+ vsilent bool
+ Vdata interface{}
+ VjsonInt int
+ VjsonFloat float64
+ VjsonNumber json.Number
+}
+
+type BasicSquash struct {
+ Test Basic `mapstructure:",squash"`
+}
+
+type Embedded struct {
+ Basic
+ Vunique string
+}
+
+type EmbeddedPointer struct {
+ *Basic
+ Vunique string
+}
+
+type EmbeddedSquash struct {
+ Basic `mapstructure:",squash"`
+ Vunique string
+}
+
+type SliceAlias []string
+
+type EmbeddedSlice struct {
+ SliceAlias `mapstructure:"slice_alias"`
+ Vunique string
+}
+
+type SquashOnNonStructType struct {
+ InvalidSquashType int `mapstructure:",squash"`
+}
+
+type Map struct {
+ Vfoo string
+ Vother map[string]string
+}
+
+type MapOfStruct struct {
+ Value map[string]Basic
+}
+
+type Nested struct {
+ Vfoo string
+ Vbar Basic
+}
+
+type NestedPointer struct {
+ Vfoo string
+ Vbar *Basic
+}
+
+type NilInterface struct {
+ W io.Writer
+}
+
+type Slice struct {
+ Vfoo string
+ Vbar []string
+}
+
+type SliceOfStruct struct {
+ Value []Basic
+}
+
+type Func struct {
+ Foo func() string
+}
+
+type Tagged struct {
+ Extra string `mapstructure:"bar,what,what"`
+ Value string `mapstructure:"foo"`
+}
+
+type TypeConversionResult struct {
+ IntToFloat float32
+ IntToUint uint
+ IntToBool bool
+ IntToString string
+ UintToInt int
+ UintToFloat float32
+ UintToBool bool
+ UintToString string
+ BoolToInt int
+ BoolToUint uint
+ BoolToFloat float32
+ BoolToString string
+ FloatToInt int
+ FloatToUint uint
+ FloatToBool bool
+ FloatToString string
+ SliceUint8ToString string
+ StringToInt int
+ StringToUint uint
+ StringToBool bool
+ StringToFloat float32
+ StringToStrSlice []string
+ StringToIntSlice []int
+ SliceToMap map[string]interface{}
+ MapToSlice []interface{}
+}
+
+func TestBasicTypes(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vstring": "foo",
+ "vint": 42,
+ "Vuint": 42,
+ "vbool": true,
+ "Vfloat": 42.42,
+ "vsilent": true,
+ "vdata": 42,
+ "vjsonInt": json.Number("1234"),
+ "vjsonFloat": json.Number("1234.5"),
+ "vjsonNumber": json.Number("1234.5"),
+ }
+
+ var result Basic
+ err := Decode(input, &result)
+ if err != nil {
+ t.Errorf("got an err: %s", err.Error())
+ t.FailNow()
+ }
+
+ if result.Vstring != "foo" {
+ t.Errorf("vstring value should be 'foo': %#v", result.Vstring)
+ }
+
+ if result.Vint != 42 {
+ t.Errorf("vint value should be 42: %#v", result.Vint)
+ }
+
+ if result.Vuint != 42 {
+ t.Errorf("vuint value should be 42: %#v", result.Vuint)
+ }
+
+ if result.Vbool != true {
+ t.Errorf("vbool value should be true: %#v", result.Vbool)
+ }
+
+ if result.Vfloat != 42.42 {
+ t.Errorf("vfloat value should be 42.42: %#v", result.Vfloat)
+ }
+
+ if result.Vextra != "" {
+ t.Errorf("vextra value should be empty: %#v", result.Vextra)
+ }
+
+ if result.vsilent != false {
+ t.Error("vsilent should not be set, it is unexported")
+ }
+
+ if result.Vdata != 42 {
+ t.Error("vdata should be valid")
+ }
+
+ if result.VjsonInt != 1234 {
+ t.Errorf("vjsonint value should be 1234: %#v", result.VjsonInt)
+ }
+
+ if result.VjsonFloat != 1234.5 {
+ t.Errorf("vjsonfloat value should be 1234.5: %#v", result.VjsonFloat)
+ }
+
+ if !reflect.DeepEqual(result.VjsonNumber, json.Number("1234.5")) {
+ t.Errorf("vjsonnumber value should be '1234.5': %T, %#v", result.VjsonNumber, result.VjsonNumber)
+ }
+}
+
+func TestBasic_IntWithFloat(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vint": float64(42),
+ }
+
+ var result Basic
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err)
+ }
+}
+
+func TestBasic_Merge(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vint": 42,
+ }
+
+ var result Basic
+ result.Vuint = 100
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err)
+ }
+
+ expected := Basic{
+ Vint: 42,
+ Vuint: 100,
+ }
+ if !reflect.DeepEqual(result, expected) {
+ t.Fatalf("bad: %#v", result)
+ }
+}
+
+func TestDecode_BasicSquash(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vstring": "foo",
+ }
+
+ var result BasicSquash
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+
+ if result.Test.Vstring != "foo" {
+ t.Errorf("vstring value should be 'foo': %#v", result.Test.Vstring)
+ }
+}
+
+func TestDecode_Embedded(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vstring": "foo",
+ "Basic": map[string]interface{}{
+ "vstring": "innerfoo",
+ },
+ "vunique": "bar",
+ }
+
+ var result Embedded
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+
+ if result.Vstring != "innerfoo" {
+ t.Errorf("vstring value should be 'innerfoo': %#v", result.Vstring)
+ }
+
+ if result.Vunique != "bar" {
+ t.Errorf("vunique value should be 'bar': %#v", result.Vunique)
+ }
+}
+
+func TestDecode_EmbeddedPointer(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vstring": "foo",
+ "Basic": map[string]interface{}{
+ "vstring": "innerfoo",
+ },
+ "vunique": "bar",
+ }
+
+ var result EmbeddedPointer
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ expected := EmbeddedPointer{
+ Basic: &Basic{
+ Vstring: "innerfoo",
+ },
+ Vunique: "bar",
+ }
+ if !reflect.DeepEqual(result, expected) {
+ t.Fatalf("bad: %#v", result)
+ }
+}
+
+func TestDecode_EmbeddedSlice(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "slice_alias": []string{"foo", "bar"},
+ "vunique": "bar",
+ }
+
+ var result EmbeddedSlice
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+
+ if !reflect.DeepEqual(result.SliceAlias, SliceAlias([]string{"foo", "bar"})) {
+ t.Errorf("slice value: %#v", result.SliceAlias)
+ }
+
+ if result.Vunique != "bar" {
+ t.Errorf("vunique value should be 'bar': %#v", result.Vunique)
+ }
+}
+
+func TestDecode_EmbeddedSquash(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vstring": "foo",
+ "vunique": "bar",
+ }
+
+ var result EmbeddedSquash
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+
+ if result.Vstring != "foo" {
+ t.Errorf("vstring value should be 'foo': %#v", result.Vstring)
+ }
+
+ if result.Vunique != "bar" {
+ t.Errorf("vunique value should be 'bar': %#v", result.Vunique)
+ }
+}
+
+func TestDecode_SquashOnNonStructType(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "InvalidSquashType": 42,
+ }
+
+ var result SquashOnNonStructType
+ err := Decode(input, &result)
+ if err == nil {
+ t.Fatal("unexpected success decoding invalid squash field type")
+ } else if !strings.Contains(err.Error(), "unsupported type for squash") {
+ t.Fatalf("unexpected error message for invalid squash field type: %s", err)
+ }
+}
+
+func TestDecode_DecodeHook(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vint": "WHAT",
+ }
+
+ decodeHook := func(from reflect.Kind, to reflect.Kind, v interface{}) (interface{}, error) {
+ if from == reflect.String && to != reflect.String {
+ return 5, nil
+ }
+
+ return v, nil
+ }
+
+ var result Basic
+ config := &DecoderConfig{
+ DecodeHook: decodeHook,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ err = decoder.Decode(input)
+ if err != nil {
+ t.Fatalf("got an err: %s", err)
+ }
+
+ if result.Vint != 5 {
+ t.Errorf("vint should be 5: %#v", result.Vint)
+ }
+}
+
+func TestDecode_DecodeHookType(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vint": "WHAT",
+ }
+
+ decodeHook := func(from reflect.Type, to reflect.Type, v interface{}) (interface{}, error) {
+ if from.Kind() == reflect.String &&
+ to.Kind() != reflect.String {
+ return 5, nil
+ }
+
+ return v, nil
+ }
+
+ var result Basic
+ config := &DecoderConfig{
+ DecodeHook: decodeHook,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ err = decoder.Decode(input)
+ if err != nil {
+ t.Fatalf("got an err: %s", err)
+ }
+
+ if result.Vint != 5 {
+ t.Errorf("vint should be 5: %#v", result.Vint)
+ }
+}
+
+func TestDecode_Nil(t *testing.T) {
+ t.Parallel()
+
+ var input interface{} = nil
+ result := Basic{
+ Vstring: "foo",
+ }
+
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ if result.Vstring != "foo" {
+ t.Fatalf("bad: %#v", result.Vstring)
+ }
+}
+
+func TestDecode_NilInterfaceHook(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "w": "",
+ }
+
+ decodeHook := func(f, t reflect.Type, v interface{}) (interface{}, error) {
+ if t.String() == "io.Writer" {
+ return nil, nil
+ }
+
+ return v, nil
+ }
+
+ var result NilInterface
+ config := &DecoderConfig{
+ DecodeHook: decodeHook,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ err = decoder.Decode(input)
+ if err != nil {
+ t.Fatalf("got an err: %s", err)
+ }
+
+ if result.W != nil {
+ t.Errorf("W should be nil: %#v", result.W)
+ }
+}
+
+func TestDecode_FuncHook(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "foo": "baz",
+ }
+
+ decodeHook := func(f, t reflect.Type, v interface{}) (interface{}, error) {
+ if t.Kind() != reflect.Func {
+ return v, nil
+ }
+ val := v.(string)
+ return func() string { return val }, nil
+ }
+
+ var result Func
+ config := &DecoderConfig{
+ DecodeHook: decodeHook,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ err = decoder.Decode(input)
+ if err != nil {
+ t.Fatalf("got an err: %s", err)
+ }
+
+ if result.Foo() != "baz" {
+ t.Errorf("Foo call result should be 'baz': %s", result.Foo())
+ }
+}
+
+func TestDecode_NonStruct(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "foo": "bar",
+ "bar": "baz",
+ }
+
+ var result map[string]string
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ if result["foo"] != "bar" {
+ t.Fatal("foo is not bar")
+ }
+}
+
+func TestDecode_StructMatch(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vbar": Basic{
+ Vstring: "foo",
+ },
+ }
+
+ var result Nested
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+
+ if result.Vbar.Vstring != "foo" {
+ t.Errorf("bad: %#v", result)
+ }
+}
+
+func TestDecode_TypeConversion(t *testing.T) {
+ input := map[string]interface{}{
+ "IntToFloat": 42,
+ "IntToUint": 42,
+ "IntToBool": 1,
+ "IntToString": 42,
+ "UintToInt": 42,
+ "UintToFloat": 42,
+ "UintToBool": 42,
+ "UintToString": 42,
+ "BoolToInt": true,
+ "BoolToUint": true,
+ "BoolToFloat": true,
+ "BoolToString": true,
+ "FloatToInt": 42.42,
+ "FloatToUint": 42.42,
+ "FloatToBool": 42.42,
+ "FloatToString": 42.42,
+ "SliceUint8ToString": []uint8("foo"),
+ "StringToInt": "42",
+ "StringToUint": "42",
+ "StringToBool": "1",
+ "StringToFloat": "42.42",
+ "StringToStrSlice": "A",
+ "StringToIntSlice": "42",
+ "SliceToMap": []interface{}{},
+ "MapToSlice": map[string]interface{}{},
+ }
+
+ expectedResultStrict := TypeConversionResult{
+ IntToFloat: 42.0,
+ IntToUint: 42,
+ UintToInt: 42,
+ UintToFloat: 42,
+ BoolToInt: 0,
+ BoolToUint: 0,
+ BoolToFloat: 0,
+ FloatToInt: 42,
+ FloatToUint: 42,
+ }
+
+ expectedResultWeak := TypeConversionResult{
+ IntToFloat: 42.0,
+ IntToUint: 42,
+ IntToBool: true,
+ IntToString: "42",
+ UintToInt: 42,
+ UintToFloat: 42,
+ UintToBool: true,
+ UintToString: "42",
+ BoolToInt: 1,
+ BoolToUint: 1,
+ BoolToFloat: 1,
+ BoolToString: "1",
+ FloatToInt: 42,
+ FloatToUint: 42,
+ FloatToBool: true,
+ FloatToString: "42.42",
+ SliceUint8ToString: "foo",
+ StringToInt: 42,
+ StringToUint: 42,
+ StringToBool: true,
+ StringToFloat: 42.42,
+ StringToStrSlice: []string{"A"},
+ StringToIntSlice: []int{42},
+ SliceToMap: map[string]interface{}{},
+ MapToSlice: []interface{}{},
+ }
+
+ // Test strict type conversion
+ var resultStrict TypeConversionResult
+ err := Decode(input, &resultStrict)
+ if err == nil {
+ t.Errorf("should return an error")
+ }
+ if !reflect.DeepEqual(resultStrict, expectedResultStrict) {
+ t.Errorf("expected %v, got: %v", expectedResultStrict, resultStrict)
+ }
+
+ // Test weak type conversion
+ var decoder *Decoder
+ var resultWeak TypeConversionResult
+
+ config := &DecoderConfig{
+ WeaklyTypedInput: true,
+ Result: &resultWeak,
+ }
+
+ decoder, err = NewDecoder(config)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ err = decoder.Decode(input)
+ if err != nil {
+ t.Fatalf("got an err: %s", err)
+ }
+
+ if !reflect.DeepEqual(resultWeak, expectedResultWeak) {
+ t.Errorf("expected \n%#v, got: \n%#v", expectedResultWeak, resultWeak)
+ }
+}
+
+func TestDecoder_ErrorUnused(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vstring": "hello",
+ "foo": "bar",
+ }
+
+ var result Basic
+ config := &DecoderConfig{
+ ErrorUnused: true,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ err = decoder.Decode(input)
+ if err == nil {
+ t.Fatal("expected error")
+ }
+}
+
+func TestMap(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vother": map[interface{}]interface{}{
+ "foo": "foo",
+ "bar": "bar",
+ },
+ }
+
+ var result Map
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an error: %s", err)
+ }
+
+ if result.Vfoo != "foo" {
+ t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
+ }
+
+ if result.Vother == nil {
+ t.Fatal("vother should not be nil")
+ }
+
+ if len(result.Vother) != 2 {
+ t.Error("vother should have two items")
+ }
+
+ if result.Vother["foo"] != "foo" {
+ t.Errorf("'foo' key should be foo, got: %#v", result.Vother["foo"])
+ }
+
+ if result.Vother["bar"] != "bar" {
+ t.Errorf("'bar' key should be bar, got: %#v", result.Vother["bar"])
+ }
+}
+
+func TestMapMerge(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vother": map[interface{}]interface{}{
+ "foo": "foo",
+ "bar": "bar",
+ },
+ }
+
+ var result Map
+ result.Vother = map[string]string{"hello": "world"}
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an error: %s", err)
+ }
+
+ if result.Vfoo != "foo" {
+ t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
+ }
+
+ expected := map[string]string{
+ "foo": "foo",
+ "bar": "bar",
+ "hello": "world",
+ }
+ if !reflect.DeepEqual(result.Vother, expected) {
+ t.Errorf("bad: %#v", result.Vother)
+ }
+}
+
+func TestMapOfStruct(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "value": map[string]interface{}{
+ "foo": map[string]string{"vstring": "one"},
+ "bar": map[string]string{"vstring": "two"},
+ },
+ }
+
+ var result MapOfStruct
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err)
+ }
+
+ if result.Value == nil {
+ t.Fatal("value should not be nil")
+ }
+
+ if len(result.Value) != 2 {
+ t.Error("value should have two items")
+ }
+
+ if result.Value["foo"].Vstring != "one" {
+ t.Errorf("foo value should be 'one', got: %s", result.Value["foo"].Vstring)
+ }
+
+ if result.Value["bar"].Vstring != "two" {
+ t.Errorf("bar value should be 'two', got: %s", result.Value["bar"].Vstring)
+ }
+}
+
+func TestNestedType(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vbar": map[string]interface{}{
+ "vstring": "foo",
+ "vint": 42,
+ "vbool": true,
+ },
+ }
+
+ var result Nested
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+
+ if result.Vfoo != "foo" {
+ t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
+ }
+
+ if result.Vbar.Vstring != "foo" {
+ t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring)
+ }
+
+ if result.Vbar.Vint != 42 {
+ t.Errorf("vint value should be 42: %#v", result.Vbar.Vint)
+ }
+
+ if result.Vbar.Vbool != true {
+ t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool)
+ }
+
+ if result.Vbar.Vextra != "" {
+ t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra)
+ }
+}
+
+func TestNestedTypePointer(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vbar": &map[string]interface{}{
+ "vstring": "foo",
+ "vint": 42,
+ "vbool": true,
+ },
+ }
+
+ var result NestedPointer
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got an err: %s", err.Error())
+ }
+
+ if result.Vfoo != "foo" {
+ t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
+ }
+
+ if result.Vbar.Vstring != "foo" {
+ t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring)
+ }
+
+ if result.Vbar.Vint != 42 {
+ t.Errorf("vint value should be 42: %#v", result.Vbar.Vint)
+ }
+
+ if result.Vbar.Vbool != true {
+ t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool)
+ }
+
+ if result.Vbar.Vextra != "" {
+ t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra)
+ }
+}
+
+func TestSlice(t *testing.T) {
+ t.Parallel()
+
+ inputStringSlice := map[string]interface{}{
+ "vfoo": "foo",
+ "vbar": []string{"foo", "bar", "baz"},
+ }
+
+ inputStringSlicePointer := map[string]interface{}{
+ "vfoo": "foo",
+ "vbar": &[]string{"foo", "bar", "baz"},
+ }
+
+ outputStringSlice := &Slice{
+ "foo",
+ []string{"foo", "bar", "baz"},
+ }
+
+ testSliceInput(t, inputStringSlice, outputStringSlice)
+ testSliceInput(t, inputStringSlicePointer, outputStringSlice)
+}
+
+func TestInvalidSlice(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vbar": 42,
+ }
+
+ result := Slice{}
+ err := Decode(input, &result)
+ if err == nil {
+ t.Errorf("expected failure")
+ }
+}
+
+func TestSliceOfStruct(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "value": []map[string]interface{}{
+ {"vstring": "one"},
+ {"vstring": "two"},
+ },
+ }
+
+ var result SliceOfStruct
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got unexpected error: %s", err)
+ }
+
+ if len(result.Value) != 2 {
+ t.Fatalf("expected two values, got %d", len(result.Value))
+ }
+
+ if result.Value[0].Vstring != "one" {
+ t.Errorf("first value should be 'one', got: %s", result.Value[0].Vstring)
+ }
+
+ if result.Value[1].Vstring != "two" {
+ t.Errorf("second value should be 'two', got: %s", result.Value[1].Vstring)
+ }
+}
+
+func TestSliceToMap(t *testing.T) {
+ t.Parallel()
+
+ input := []map[string]interface{}{
+ {
+ "foo": "bar",
+ },
+ {
+ "bar": "baz",
+ },
+ }
+
+ var result map[string]interface{}
+ err := WeakDecode(input, &result)
+ if err != nil {
+ t.Fatalf("got an error: %s", err)
+ }
+
+ expected := map[string]interface{}{
+ "foo": "bar",
+ "bar": "baz",
+ }
+ if !reflect.DeepEqual(result, expected) {
+ t.Errorf("bad: %#v", result)
+ }
+}
+
+func TestInvalidType(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vstring": 42,
+ }
+
+ var result Basic
+ err := Decode(input, &result)
+ if err == nil {
+ t.Fatal("error should exist")
+ }
+
+ derr, ok := err.(*Error)
+ if !ok {
+ t.Fatalf("error should be kind of Error, instead: %#v", err)
+ }
+
+ if derr.Errors[0] != "'Vstring' expected type 'string', got unconvertible type 'int'" {
+ t.Errorf("got unexpected error: %s", err)
+ }
+
+ inputNegIntUint := map[string]interface{}{
+ "vuint": -42,
+ }
+
+ err = Decode(inputNegIntUint, &result)
+ if err == nil {
+ t.Fatal("error should exist")
+ }
+
+ derr, ok = err.(*Error)
+ if !ok {
+ t.Fatalf("error should be kind of Error, instead: %#v", err)
+ }
+
+ if derr.Errors[0] != "cannot parse 'Vuint', -42 overflows uint" {
+ t.Errorf("got unexpected error: %s", err)
+ }
+
+ inputNegFloatUint := map[string]interface{}{
+ "vuint": -42.0,
+ }
+
+ err = Decode(inputNegFloatUint, &result)
+ if err == nil {
+ t.Fatal("error should exist")
+ }
+
+ derr, ok = err.(*Error)
+ if !ok {
+ t.Fatalf("error should be kind of Error, instead: %#v", err)
+ }
+
+ if derr.Errors[0] != "cannot parse 'Vuint', -42.000000 overflows uint" {
+ t.Errorf("got unexpected error: %s", err)
+ }
+}
+
+func TestMetadata(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vfoo": "foo",
+ "vbar": map[string]interface{}{
+ "vstring": "foo",
+ "Vuint": 42,
+ "foo": "bar",
+ },
+ "bar": "nil",
+ }
+
+ var md Metadata
+ var result Nested
+ config := &DecoderConfig{
+ Metadata: &md,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ err = decoder.Decode(input)
+ if err != nil {
+ t.Fatalf("err: %s", err.Error())
+ }
+
+ expectedKeys := []string{"Vbar", "Vbar.Vstring", "Vbar.Vuint", "Vfoo"}
+ sort.Strings(md.Keys)
+ if !reflect.DeepEqual(md.Keys, expectedKeys) {
+ t.Fatalf("bad keys: %#v", md.Keys)
+ }
+
+ expectedUnused := []string{"Vbar.foo", "bar"}
+ if !reflect.DeepEqual(md.Unused, expectedUnused) {
+ t.Fatalf("bad unused: %#v", md.Unused)
+ }
+}
+
+func TestMetadata_Embedded(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "vstring": "foo",
+ "vunique": "bar",
+ }
+
+ var md Metadata
+ var result EmbeddedSquash
+ config := &DecoderConfig{
+ Metadata: &md,
+ Result: &result,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ err = decoder.Decode(input)
+ if err != nil {
+ t.Fatalf("err: %s", err.Error())
+ }
+
+ expectedKeys := []string{"Vstring", "Vunique"}
+
+ sort.Strings(md.Keys)
+ if !reflect.DeepEqual(md.Keys, expectedKeys) {
+ t.Fatalf("bad keys: %#v", md.Keys)
+ }
+
+ expectedUnused := []string{}
+ if !reflect.DeepEqual(md.Unused, expectedUnused) {
+ t.Fatalf("bad unused: %#v", md.Unused)
+ }
+}
+
+func TestNonPtrValue(t *testing.T) {
+ t.Parallel()
+
+ err := Decode(map[string]interface{}{}, Basic{})
+ if err == nil {
+ t.Fatal("error should exist")
+ }
+
+ if err.Error() != "result must be a pointer" {
+ t.Errorf("got unexpected error: %s", err)
+ }
+}
+
+func TestTagged(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "foo": "bar",
+ "bar": "value",
+ }
+
+ var result Tagged
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("unexpected error: %s", err)
+ }
+
+ if result.Value != "bar" {
+ t.Errorf("value should be 'bar', got: %#v", result.Value)
+ }
+
+ if result.Extra != "value" {
+ t.Errorf("extra should be 'value', got: %#v", result.Extra)
+ }
+}
+
+func TestWeakDecode(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "foo": "4",
+ "bar": "value",
+ }
+
+ var result struct {
+ Foo int
+ Bar string
+ }
+
+ if err := WeakDecode(input, &result); err != nil {
+ t.Fatalf("err: %s", err)
+ }
+ if result.Foo != 4 {
+ t.Fatalf("bad: %#v", result)
+ }
+ if result.Bar != "value" {
+ t.Fatalf("bad: %#v", result)
+ }
+}
+
+func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) {
+ var result Slice
+ err := Decode(input, &result)
+ if err != nil {
+ t.Fatalf("got error: %s", err)
+ }
+
+ if result.Vfoo != expected.Vfoo {
+ t.Errorf("Vfoo expected '%s', got '%s'", expected.Vfoo, result.Vfoo)
+ }
+
+ if result.Vbar == nil {
+ t.Fatalf("Vbar a slice, got '%#v'", result.Vbar)
+ }
+
+ if len(result.Vbar) != len(expected.Vbar) {
+ t.Errorf("Vbar length should be %d, got %d", len(expected.Vbar), len(result.Vbar))
+ }
+
+ for i, v := range result.Vbar {
+ if v != expected.Vbar[i] {
+ t.Errorf(
+ "Vbar[%d] should be '%#v', got '%#v'",
+ i, expected.Vbar[i], v)
+ }
+ }
+}
diff --git a/vendor/github.com/pelletier/go-buffruneio/.gitignore b/vendor/github.com/pelletier/go-buffruneio/.gitignore
new file mode 100644
index 000000000..c56069fe2
--- /dev/null
+++ b/vendor/github.com/pelletier/go-buffruneio/.gitignore
@@ -0,0 +1 @@
+*.test \ No newline at end of file
diff --git a/vendor/github.com/pelletier/go-buffruneio/.travis.yml b/vendor/github.com/pelletier/go-buffruneio/.travis.yml
new file mode 100644
index 000000000..9720442cd
--- /dev/null
+++ b/vendor/github.com/pelletier/go-buffruneio/.travis.yml
@@ -0,0 +1,7 @@
+language: go
+sudo: false
+go:
+ - 1.3.3
+ - 1.4.3
+ - 1.5.3
+ - tip
diff --git a/vendor/github.com/pelletier/go-buffruneio/README.md b/vendor/github.com/pelletier/go-buffruneio/README.md
new file mode 100644
index 000000000..ff608b3ab
--- /dev/null
+++ b/vendor/github.com/pelletier/go-buffruneio/README.md
@@ -0,0 +1,62 @@
+# buffruneio
+
+[![Tests Status](https://travis-ci.org/pelletier/go-buffruneio.svg?branch=master)](https://travis-ci.org/pelletier/go-buffruneio)
+[![GoDoc](https://godoc.org/github.com/pelletier/go-buffruneio?status.svg)](https://godoc.org/github.com/pelletier/go-buffruneio)
+
+Buffruneio is a wrapper around bufio to provide buffered runes access with
+unlimited unreads.
+
+```go
+import "github.com/pelletier/go-buffruneio"
+```
+
+## Examples
+
+```go
+import (
+ "fmt"
+ "github.com/pelletier/go-buffruneio"
+ "strings"
+)
+
+reader := buffruneio.NewReader(strings.NewReader("abcd"))
+fmt.Println(reader.ReadRune()) // 'a'
+fmt.Println(reader.ReadRune()) // 'b'
+fmt.Println(reader.ReadRune()) // 'c'
+reader.UnreadRune()
+reader.UnreadRune()
+fmt.Println(reader.ReadRune()) // 'b'
+fmt.Println(reader.ReadRune()) // 'c'
+```
+
+## Documentation
+
+The documentation and additional examples are available at
+[godoc.org](http://godoc.org/github.com/pelletier/go-buffruneio).
+
+## Contribute
+
+Feel free to report bugs and patches using GitHub's pull requests system on
+[pelletier/go-toml](https://github.com/pelletier/go-buffruneio). Any feedback is
+much appreciated!
+
+## LICENSE
+
+Copyright (c) 2016 Thomas Pelletier
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/github.com/pelletier/go-buffruneio/buffruneio.go b/vendor/github.com/pelletier/go-buffruneio/buffruneio.go
new file mode 100644
index 000000000..4e6d6ea61
--- /dev/null
+++ b/vendor/github.com/pelletier/go-buffruneio/buffruneio.go
@@ -0,0 +1,117 @@
+// Package buffruneio is a wrapper around bufio to provide buffered runes access with unlimited unreads.
+package buffruneio
+
+import (
+ "bufio"
+ "container/list"
+ "errors"
+ "io"
+)
+
+// Rune to indicate end of file.
+const (
+ EOF = -(iota + 1)
+)
+
+// ErrNoRuneToUnread is returned by UnreadRune() when the read index is already at the beginning of the buffer.
+var ErrNoRuneToUnread = errors.New("no rune to unwind")
+
+// Reader implements runes buffering for an io.Reader object.
+type Reader struct {
+ buffer *list.List
+ current *list.Element
+ input *bufio.Reader
+}
+
+// NewReader returns a new Reader.
+func NewReader(rd io.Reader) *Reader {
+ return &Reader{
+ buffer: list.New(),
+ input: bufio.NewReader(rd),
+ }
+}
+
+type runeWithSize struct {
+ r rune
+ size int
+}
+
+func (rd *Reader) feedBuffer() error {
+ r, size, err := rd.input.ReadRune()
+
+ if err != nil {
+ if err != io.EOF {
+ return err
+ }
+ r = EOF
+ }
+
+ newRuneWithSize := runeWithSize{r, size}
+
+ rd.buffer.PushBack(newRuneWithSize)
+ if rd.current == nil {
+ rd.current = rd.buffer.Back()
+ }
+ return nil
+}
+
+// ReadRune reads the next rune from buffer, or from the underlying reader if needed.
+func (rd *Reader) ReadRune() (rune, int, error) {
+ if rd.current == rd.buffer.Back() || rd.current == nil {
+ err := rd.feedBuffer()
+ if err != nil {
+ return EOF, 0, err
+ }
+ }
+
+ runeWithSize := rd.current.Value.(runeWithSize)
+ rd.current = rd.current.Next()
+ return runeWithSize.r, runeWithSize.size, nil
+}
+
+// UnreadRune pushes back the previously read rune in the buffer, extending it if needed.
+func (rd *Reader) UnreadRune() error {
+ if rd.current == rd.buffer.Front() {
+ return ErrNoRuneToUnread
+ }
+ if rd.current == nil {
+ rd.current = rd.buffer.Back()
+ } else {
+ rd.current = rd.current.Prev()
+ }
+ return nil
+}
+
+// Forget removes runes stored before the current stream position index.
+func (rd *Reader) Forget() {
+ if rd.current == nil {
+ rd.current = rd.buffer.Back()
+ }
+ for ; rd.current != rd.buffer.Front(); rd.buffer.Remove(rd.current.Prev()) {
+ }
+}
+
+// PeekRune returns at most the next n runes, reading from the uderlying source if
+// needed. Does not move the current index. It includes EOF if reached.
+func (rd *Reader) PeekRunes(n int) []rune {
+ res := make([]rune, 0, n)
+ cursor := rd.current
+ for i := 0; i < n; i++ {
+ if cursor == nil {
+ err := rd.feedBuffer()
+ if err != nil {
+ return res
+ }
+ cursor = rd.buffer.Back()
+ }
+ if cursor != nil {
+ r := cursor.Value.(runeWithSize).r
+ res = append(res, r)
+ if r == EOF {
+ return res
+ }
+ cursor = cursor.Next()
+ }
+ }
+ return res
+}
diff --git a/vendor/github.com/pelletier/go-buffruneio/buffruneio_test.go b/vendor/github.com/pelletier/go-buffruneio/buffruneio_test.go
new file mode 100644
index 000000000..67b0cba9b
--- /dev/null
+++ b/vendor/github.com/pelletier/go-buffruneio/buffruneio_test.go
@@ -0,0 +1,145 @@
+package buffruneio
+
+import (
+ "runtime/debug"
+ "strings"
+ "testing"
+)
+
+func assertNoError(t *testing.T, err error) {
+ if err != nil {
+ t.Log("unexpected error", err)
+ debug.PrintStack()
+ t.FailNow()
+ }
+}
+
+func assumeRunesArray(t *testing.T, expected []rune, got []rune) {
+ if len(expected) != len(got) {
+ t.Fatal("expected", len(expected), "runes, but got", len(got))
+ }
+ for i := 0; i < len(got); i++ {
+ if expected[i] != got[i] {
+ t.Fatal("expected rune", expected[i], "at index", i, "but got", got[i])
+ }
+ }
+}
+
+func assumeRune(t *testing.T, rd *Reader, r rune) {
+ gotRune, size, err := rd.ReadRune()
+ assertNoError(t, err)
+ if gotRune != r {
+ t.Fatal("got", string(gotRune),
+ "(", []byte(string(gotRune)), ")",
+ "expected", string(r),
+ "(", []byte(string(r)), ")")
+ t.Fatal("got size", size,
+ "expected", len([]byte(string(r))))
+ }
+}
+
+func TestReadString(t *testing.T) {
+ s := "hello"
+ rd := NewReader(strings.NewReader(s))
+
+ assumeRune(t, rd, 'h')
+ assumeRune(t, rd, 'e')
+ assumeRune(t, rd, 'l')
+ assumeRune(t, rd, 'l')
+ assumeRune(t, rd, 'o')
+ assumeRune(t, rd, EOF)
+}
+
+func TestMultipleEOF(t *testing.T) {
+ s := ""
+ rd := NewReader(strings.NewReader(s))
+
+ assumeRune(t, rd, EOF)
+ assumeRune(t, rd, EOF)
+}
+
+func TestUnread(t *testing.T) {
+ s := "ab"
+ rd := NewReader(strings.NewReader(s))
+
+ assumeRune(t, rd, 'a')
+ assumeRune(t, rd, 'b')
+ assertNoError(t, rd.UnreadRune())
+ assumeRune(t, rd, 'b')
+ assumeRune(t, rd, EOF)
+}
+
+func TestUnreadEOF(t *testing.T) {
+ s := ""
+ rd := NewReader(strings.NewReader(s))
+
+ _ = rd.UnreadRune()
+ assumeRune(t, rd, EOF)
+ assumeRune(t, rd, EOF)
+ assertNoError(t, rd.UnreadRune())
+ assumeRune(t, rd, EOF)
+}
+
+func TestForget(t *testing.T) {
+ s := "hello"
+ rd := NewReader(strings.NewReader(s))
+
+ assumeRune(t, rd, 'h')
+ assumeRune(t, rd, 'e')
+ assumeRune(t, rd, 'l')
+ assumeRune(t, rd, 'l')
+ rd.Forget()
+ if rd.UnreadRune() != ErrNoRuneToUnread {
+ t.Fatal("no rune should be available")
+ }
+}
+
+func TestForgetEmpty(t *testing.T) {
+ s := ""
+ rd := NewReader(strings.NewReader(s))
+
+ rd.Forget()
+ assumeRune(t, rd, EOF)
+ rd.Forget()
+}
+
+func TestPeekEmpty(t *testing.T) {
+ s := ""
+ rd := NewReader(strings.NewReader(s))
+
+ runes := rd.PeekRunes(1)
+ if len(runes) != 1 {
+ t.Fatal("incorrect number of runes", len(runes))
+ }
+ if runes[0] != EOF {
+ t.Fatal("incorrect rune", runes[0])
+ }
+}
+
+func TestPeek(t *testing.T) {
+ s := "a"
+ rd := NewReader(strings.NewReader(s))
+
+ runes := rd.PeekRunes(1)
+ assumeRunesArray(t, []rune{'a'}, runes)
+
+ runes = rd.PeekRunes(1)
+ assumeRunesArray(t, []rune{'a'}, runes)
+
+ assumeRune(t, rd, 'a')
+ runes = rd.PeekRunes(1)
+ assumeRunesArray(t, []rune{EOF}, runes)
+
+ assumeRune(t, rd, EOF)
+}
+
+func TestPeekLarge(t *testing.T) {
+ s := "abcdefg"
+ rd := NewReader(strings.NewReader(s))
+
+ runes := rd.PeekRunes(100)
+ if len(runes) != len(s)+1 {
+ t.Fatal("incorrect number of runes", len(runes))
+ }
+ assumeRunesArray(t, []rune{'a', 'b', 'c', 'd', 'e', 'f', 'g', EOF}, runes)
+}
diff --git a/vendor/github.com/pelletier/go-toml/.gitignore b/vendor/github.com/pelletier/go-toml/.gitignore
new file mode 100644
index 000000000..f1b619018
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/.gitignore
@@ -0,0 +1 @@
+test_program/test_program_bin
diff --git a/vendor/github.com/pelletier/go-toml/.travis.yml b/vendor/github.com/pelletier/go-toml/.travis.yml
new file mode 100644
index 000000000..64f03809a
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/.travis.yml
@@ -0,0 +1,21 @@
+sudo: false
+language: go
+go:
+ - 1.6.4
+ - 1.7.5
+ - 1.8
+ - tip
+matrix:
+ allow_failures:
+ - go: tip
+ fast_finish: true
+script:
+ - ./test.sh
+before_install:
+ - go get github.com/axw/gocov/gocov
+ - go get github.com/mattn/goveralls
+ - if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi
+branches:
+ only: [master]
+after_success:
+ - $HOME/gopath/bin/goveralls -service=travis-ci -coverprofile=coverage.out -repotoken $COVERALLS_TOKEN
diff --git a/vendor/github.com/pelletier/go-toml/LICENSE b/vendor/github.com/pelletier/go-toml/LICENSE
new file mode 100644
index 000000000..583bdae62
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 - 2017 Thomas Pelletier, Eric Anderton
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/vendor/github.com/pelletier/go-toml/README.md b/vendor/github.com/pelletier/go-toml/README.md
new file mode 100644
index 000000000..b8137e022
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/README.md
@@ -0,0 +1,120 @@
+# go-toml
+
+Go library for the [TOML](https://github.com/mojombo/toml) format.
+
+This library supports TOML version
+[v0.4.0](https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md)
+
+[![GoDoc](https://godoc.org/github.com/pelletier/go-toml?status.svg)](http://godoc.org/github.com/pelletier/go-toml)
+[![license](https://img.shields.io/github/license/pelletier/go-toml.svg)](https://github.com/pelletier/go-toml/blob/master/LICENSE)
+[![Build Status](https://travis-ci.org/pelletier/go-toml.svg?branch=master)](https://travis-ci.org/pelletier/go-toml)
+[![Coverage Status](https://coveralls.io/repos/github/pelletier/go-toml/badge.svg?branch=master)](https://coveralls.io/github/pelletier/go-toml?branch=master)
+[![Go Report Card](https://goreportcard.com/badge/github.com/pelletier/go-toml)](https://goreportcard.com/report/github.com/pelletier/go-toml)
+
+## Features
+
+Go-toml provides the following features for using data parsed from TOML documents:
+
+* Load TOML documents from files and string data
+* Easily navigate TOML structure using TomlTree
+* Line & column position data for all parsed elements
+* Query support similar to JSON-Path
+* Syntax errors contain line and column numbers
+
+Go-toml is designed to help cover use-cases not covered by reflection-based TOML parsing:
+
+* Semantic evaluation of parsed TOML
+* Informing a user of mistakes in the source document, after it has been parsed
+* Programatic handling of default values on a case-by-case basis
+* Using a TOML document as a flexible data-store
+
+## Import
+
+ import "github.com/pelletier/go-toml"
+
+## Usage
+
+### Example
+
+Say you have a TOML file that looks like this:
+
+```toml
+[postgres]
+user = "pelletier"
+password = "mypassword"
+```
+
+Read the username and password like this:
+
+```go
+import (
+ "fmt"
+ "github.com/pelletier/go-toml"
+)
+
+config, err := toml.LoadFile("config.toml")
+if err != nil {
+ fmt.Println("Error ", err.Error())
+} else {
+ // retrieve data directly
+ user := config.Get("postgres.user").(string)
+ password := config.Get("postgres.password").(string)
+
+ // or using an intermediate object
+ configTree := config.Get("postgres").(*toml.TomlTree)
+ user = configTree.Get("user").(string)
+ password = configTree.Get("password").(string)
+ fmt.Println("User is ", user, ". Password is ", password)
+
+ // show where elements are in the file
+ fmt.Println("User position: %v", configTree.GetPosition("user"))
+ fmt.Println("Password position: %v", configTree.GetPosition("password"))
+
+ // use a query to gather elements without walking the tree
+ results, _ := config.Query("$..[user,password]")
+ for ii, item := range results.Values() {
+ fmt.Println("Query result %d: %v", ii, item)
+ }
+}
+```
+
+## Documentation
+
+The documentation and additional examples are available at
+[godoc.org](http://godoc.org/github.com/pelletier/go-toml).
+
+## Tools
+
+Go-toml provides two handy command line tools:
+
+* `tomll`: Reads TOML files and lint them.
+
+ ```
+ go install github.com/pelletier/go-toml/cmd/tomll
+ tomll --help
+ ```
+* `tomljson`: Reads a TOML file and outputs its JSON representation.
+
+ ```
+ go install github.com/pelletier/go-toml/cmd/tomljson
+ tomljson --help
+ ```
+
+## Contribute
+
+Feel free to report bugs and patches using GitHub's pull requests system on
+[pelletier/go-toml](https://github.com/pelletier/go-toml). Any feedback would be
+much appreciated!
+
+### Run tests
+
+You have to make sure two kind of tests run:
+
+1. The Go unit tests
+2. The TOML examples base
+
+You can run both of them using `./test.sh`.
+
+## License
+
+The MIT License (MIT). Read [LICENSE](LICENSE).
diff --git a/vendor/github.com/pelletier/go-toml/clean.sh b/vendor/github.com/pelletier/go-toml/clean.sh
new file mode 100755
index 000000000..44d49d936
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/clean.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# fail out of the script if anything here fails
+set -e
+
+# clear out stuff generated by test.sh
+rm -rf src test_program_bin toml-test
diff --git a/vendor/github.com/pelletier/go-toml/cmd/test_program.go b/vendor/github.com/pelletier/go-toml/cmd/test_program.go
new file mode 100644
index 000000000..58293446b
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/cmd/test_program.go
@@ -0,0 +1,91 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "log"
+ "os"
+ "time"
+
+ "github.com/pelletier/go-toml"
+)
+
+func main() {
+ bytes, err := ioutil.ReadAll(os.Stdin)
+ if err != nil {
+ log.Fatalf("Error during TOML read: %s", err)
+ os.Exit(2)
+ }
+ tree, err := toml.Load(string(bytes))
+ if err != nil {
+ log.Fatalf("Error during TOML load: %s", err)
+ os.Exit(1)
+ }
+
+ typedTree := translate(*tree)
+
+ if err := json.NewEncoder(os.Stdout).Encode(typedTree); err != nil {
+ log.Fatalf("Error encoding JSON: %s", err)
+ os.Exit(3)
+ }
+
+ os.Exit(0)
+}
+
+func translate(tomlData interface{}) interface{} {
+ switch orig := tomlData.(type) {
+ case map[string]interface{}:
+ typed := make(map[string]interface{}, len(orig))
+ for k, v := range orig {
+ typed[k] = translate(v)
+ }
+ return typed
+ case *toml.TomlTree:
+ return translate(*orig)
+ case toml.TomlTree:
+ keys := orig.Keys()
+ typed := make(map[string]interface{}, len(keys))
+ for _, k := range keys {
+ typed[k] = translate(orig.GetPath([]string{k}))
+ }
+ return typed
+ case []*toml.TomlTree:
+ typed := make([]map[string]interface{}, len(orig))
+ for i, v := range orig {
+ typed[i] = translate(v).(map[string]interface{})
+ }
+ return typed
+ case []map[string]interface{}:
+ typed := make([]map[string]interface{}, len(orig))
+ for i, v := range orig {
+ typed[i] = translate(v).(map[string]interface{})
+ }
+ return typed
+ case []interface{}:
+ typed := make([]interface{}, len(orig))
+ for i, v := range orig {
+ typed[i] = translate(v)
+ }
+ return tag("array", typed)
+ case time.Time:
+ return tag("datetime", orig.Format("2006-01-02T15:04:05Z"))
+ case bool:
+ return tag("bool", fmt.Sprintf("%v", orig))
+ case int64:
+ return tag("integer", fmt.Sprintf("%d", orig))
+ case float64:
+ return tag("float", fmt.Sprintf("%v", orig))
+ case string:
+ return tag("string", orig)
+ }
+
+ panic(fmt.Sprintf("Unknown type: %T", tomlData))
+}
+
+func tag(typeName string, data interface{}) map[string]interface{} {
+ return map[string]interface{}{
+ "type": typeName,
+ "value": data,
+ }
+}
diff --git a/vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go b/vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go
new file mode 100644
index 000000000..7e9dc467e
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go
@@ -0,0 +1,67 @@
+package main
+
+import (
+ "encoding/json"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+
+ "github.com/pelletier/go-toml"
+)
+
+func main() {
+ flag.Usage = func() {
+ fmt.Fprintln(os.Stderr, `tomljson can be used in two ways:
+Writing to STDIN and reading from STDOUT:
+ cat file.toml | tomljson > file.json
+
+Reading from a file name:
+ tomljson file.toml
+`)
+ }
+ flag.Parse()
+ os.Exit(processMain(flag.Args(), os.Stdin, os.Stdout, os.Stderr))
+}
+
+func processMain(files []string, defaultInput io.Reader, output io.Writer, errorOutput io.Writer) int {
+ // read from stdin and print to stdout
+ inputReader := defaultInput
+
+ if len(files) > 0 {
+ var err error
+ inputReader, err = os.Open(files[0])
+ if err != nil {
+ printError(err, errorOutput)
+ return -1
+ }
+ }
+ s, err := reader(inputReader)
+ if err != nil {
+ printError(err, errorOutput)
+ return -1
+ }
+ io.WriteString(output, s+"\n")
+ return 0
+}
+
+func printError(err error, output io.Writer) {
+ io.WriteString(output, err.Error()+"\n")
+}
+
+func reader(r io.Reader) (string, error) {
+ tree, err := toml.LoadReader(r)
+ if err != nil {
+ return "", err
+ }
+ return mapToJSON(tree)
+}
+
+func mapToJSON(tree *toml.TomlTree) (string, error) {
+ treeMap := tree.ToMap()
+ bytes, err := json.MarshalIndent(treeMap, "", " ")
+ if err != nil {
+ return "", err
+ }
+ return string(bytes[:]), nil
+}
diff --git a/vendor/github.com/pelletier/go-toml/cmd/tomljson/main_test.go b/vendor/github.com/pelletier/go-toml/cmd/tomljson/main_test.go
new file mode 100644
index 000000000..0b4bdbb11
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/cmd/tomljson/main_test.go
@@ -0,0 +1,82 @@
+package main
+
+import (
+ "bytes"
+ "io/ioutil"
+ "os"
+ "strings"
+ "testing"
+)
+
+func expectBufferEquality(t *testing.T, name string, buffer *bytes.Buffer, expected string) {
+ output := buffer.String()
+ if output != expected {
+ t.Errorf("incorrect %s:\n%s\n\nexpected %s:\n%s", name, output, name, expected)
+ t.Log([]rune(output))
+ t.Log([]rune(expected))
+ }
+}
+
+func expectProcessMainResults(t *testing.T, input string, args []string, exitCode int, expectedOutput string, expectedError string) {
+ inputReader := strings.NewReader(input)
+ outputBuffer := new(bytes.Buffer)
+ errorBuffer := new(bytes.Buffer)
+
+ returnCode := processMain(args, inputReader, outputBuffer, errorBuffer)
+
+ expectBufferEquality(t, "output", outputBuffer, expectedOutput)
+ expectBufferEquality(t, "error", errorBuffer, expectedError)
+
+ if returnCode != exitCode {
+ t.Error("incorrect return code:", returnCode, "expected", exitCode)
+ }
+}
+
+func TestProcessMainReadFromStdin(t *testing.T) {
+ input := `
+ [mytoml]
+ a = 42`
+ expectedOutput := `{
+ "mytoml": {
+ "a": 42
+ }
+}
+`
+ expectedError := ``
+ expectedExitCode := 0
+
+ expectProcessMainResults(t, input, []string{}, expectedExitCode, expectedOutput, expectedError)
+}
+
+func TestProcessMainReadFromFile(t *testing.T) {
+ input := `
+ [mytoml]
+ a = 42`
+
+ tmpfile, err := ioutil.TempFile("", "example.toml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tmpfile.Write([]byte(input)); err != nil {
+ t.Fatal(err)
+ }
+
+ defer os.Remove(tmpfile.Name())
+
+ expectedOutput := `{
+ "mytoml": {
+ "a": 42
+ }
+}
+`
+ expectedError := ``
+ expectedExitCode := 0
+
+ expectProcessMainResults(t, ``, []string{tmpfile.Name()}, expectedExitCode, expectedOutput, expectedError)
+}
+
+func TestProcessMainReadFromMissingFile(t *testing.T) {
+ expectedError := `open /this/file/does/not/exist: no such file or directory
+`
+ expectProcessMainResults(t, ``, []string{"/this/file/does/not/exist"}, -1, ``, expectedError)
+}
diff --git a/vendor/github.com/pelletier/go-toml/cmd/tomll/main.go b/vendor/github.com/pelletier/go-toml/cmd/tomll/main.go
new file mode 100644
index 000000000..f185c56b9
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/cmd/tomll/main.go
@@ -0,0 +1,61 @@
+package main
+
+import (
+ "flag"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+
+ "github.com/pelletier/go-toml"
+)
+
+func main() {
+ flag.Usage = func() {
+ fmt.Fprintln(os.Stderr, `tomll can be used in two ways:
+Writing to STDIN and reading from STDOUT:
+ cat file.toml | tomll > file.toml
+
+Reading and updating a list of files:
+ tomll a.toml b.toml c.toml
+
+When given a list of files, tomll will modify all files in place without asking.
+`)
+ }
+ flag.Parse()
+ // read from stdin and print to stdout
+ if flag.NArg() == 0 {
+ s, err := lintReader(os.Stdin)
+ if err != nil {
+ io.WriteString(os.Stderr, err.Error())
+ os.Exit(-1)
+ }
+ io.WriteString(os.Stdout, s)
+ } else {
+ // otherwise modify a list of files
+ for _, filename := range flag.Args() {
+ s, err := lintFile(filename)
+ if err != nil {
+ io.WriteString(os.Stderr, err.Error())
+ os.Exit(-1)
+ }
+ ioutil.WriteFile(filename, []byte(s), 0644)
+ }
+ }
+}
+
+func lintFile(filename string) (string, error) {
+ tree, err := toml.LoadFile(filename)
+ if err != nil {
+ return "", err
+ }
+ return tree.String(), nil
+}
+
+func lintReader(r io.Reader) (string, error) {
+ tree, err := toml.LoadReader(r)
+ if err != nil {
+ return "", err
+ }
+ return tree.String(), nil
+}
diff --git a/vendor/github.com/pelletier/go-toml/doc.go b/vendor/github.com/pelletier/go-toml/doc.go
new file mode 100644
index 000000000..9156b736f
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/doc.go
@@ -0,0 +1,250 @@
+// Package toml is a TOML markup language parser.
+//
+// This version supports the specification as described in
+// https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md
+//
+// TOML Parsing
+//
+// TOML data may be parsed in two ways: by file, or by string.
+//
+// // load TOML data by filename
+// tree, err := toml.LoadFile("filename.toml")
+//
+// // load TOML data stored in a string
+// tree, err := toml.Load(stringContainingTomlData)
+//
+// Either way, the result is a TomlTree object that can be used to navigate the
+// structure and data within the original document.
+//
+//
+// Getting data from the TomlTree
+//
+// After parsing TOML data with Load() or LoadFile(), use the Has() and Get()
+// methods on the returned TomlTree, to find your way through the document data.
+//
+// if tree.Has("foo") {
+// fmt.Println("foo is:", tree.Get("foo"))
+// }
+//
+// Working with Paths
+//
+// Go-toml has support for basic dot-separated key paths on the Has(), Get(), Set()
+// and GetDefault() methods. These are the same kind of key paths used within the
+// TOML specification for struct tames.
+//
+// // looks for a key named 'baz', within struct 'bar', within struct 'foo'
+// tree.Has("foo.bar.baz")
+//
+// // returns the key at this path, if it is there
+// tree.Get("foo.bar.baz")
+//
+// TOML allows keys to contain '.', which can cause this syntax to be problematic
+// for some documents. In such cases, use the GetPath(), HasPath(), and SetPath(),
+// methods to explicitly define the path. This form is also faster, since
+// it avoids having to parse the passed key for '.' delimiters.
+//
+// // looks for a key named 'baz', within struct 'bar', within struct 'foo'
+// tree.HasPath([]string{"foo","bar","baz"})
+//
+// // returns the key at this path, if it is there
+// tree.GetPath([]string{"foo","bar","baz"})
+//
+// Note that this is distinct from the heavyweight query syntax supported by
+// TomlTree.Query() and the Query() struct (see below).
+//
+// Position Support
+//
+// Each element within the TomlTree is stored with position metadata, which is
+// invaluable for providing semantic feedback to a user. This helps in
+// situations where the TOML file parses correctly, but contains data that is
+// not correct for the application. In such cases, an error message can be
+// generated that indicates the problem line and column number in the source
+// TOML document.
+//
+// // load TOML data
+// tree, _ := toml.Load("filename.toml")
+//
+// // get an entry and report an error if it's the wrong type
+// element := tree.Get("foo")
+// if value, ok := element.(int64); !ok {
+// return fmt.Errorf("%v: Element 'foo' must be an integer", tree.GetPosition("foo"))
+// }
+//
+// // report an error if an expected element is missing
+// if !tree.Has("bar") {
+// return fmt.Errorf("%v: Expected 'bar' element", tree.GetPosition(""))
+// }
+//
+// Query Support
+//
+// The TOML query path implementation is based loosely on the JSONPath specification:
+// http://goessner.net/articles/JsonPath/
+//
+// The idea behind a query path is to allow quick access to any element, or set
+// of elements within TOML document, with a single expression.
+//
+// result, err := tree.Query("$.foo.bar.baz")
+//
+// This is roughly equivalent to:
+//
+// next := tree.Get("foo")
+// if next != nil {
+// next = next.Get("bar")
+// if next != nil {
+// next = next.Get("baz")
+// }
+// }
+// result := next
+//
+// err is nil if any parsing exception occurs.
+//
+// If no node in the tree matches the query, result will simply contain an empty list of
+// items.
+//
+// As illustrated above, the query path is much more efficient, especially since
+// the structure of the TOML file can vary. Rather than making assumptions about
+// a document's structure, a query allows the programmer to make structured
+// requests into the document, and get zero or more values as a result.
+//
+// The syntax of a query begins with a root token, followed by any number
+// sub-expressions:
+//
+// $
+// Root of the TOML tree. This must always come first.
+// .name
+// Selects child of this node, where 'name' is a TOML key
+// name.
+// ['name']
+// Selects child of this node, where 'name' is a string
+// containing a TOML key name.
+// [index]
+// Selcts child array element at 'index'.
+// ..expr
+// Recursively selects all children, filtered by an a union,
+// index, or slice expression.
+// ..*
+// Recursive selection of all nodes at this point in the
+// tree.
+// .*
+// Selects all children of the current node.
+// [expr,expr]
+// Union operator - a logical 'or' grouping of two or more
+// sub-expressions: index, key name, or filter.
+// [start:end:step]
+// Slice operator - selects array elements from start to
+// end-1, at the given step. All three arguments are
+// optional.
+// [?(filter)]
+// Named filter expression - the function 'filter' is
+// used to filter children at this node.
+//
+// Query Indexes And Slices
+//
+// Index expressions perform no bounds checking, and will contribute no
+// values to the result set if the provided index or index range is invalid.
+// Negative indexes represent values from the end of the array, counting backwards.
+//
+// // select the last index of the array named 'foo'
+// tree.Query("$.foo[-1]")
+//
+// Slice expressions are supported, by using ':' to separate a start/end index pair.
+//
+// // select up to the first five elements in the array
+// tree.Query("$.foo[0:5]")
+//
+// Slice expressions also allow negative indexes for the start and stop
+// arguments.
+//
+// // select all array elements.
+// tree.Query("$.foo[0:-1]")
+//
+// Slice expressions may have an optional stride/step parameter:
+//
+// // select every other element
+// tree.Query("$.foo[0:-1:2]")
+//
+// Slice start and end parameters are also optional:
+//
+// // these are all equivalent and select all the values in the array
+// tree.Query("$.foo[:]")
+// tree.Query("$.foo[0:]")
+// tree.Query("$.foo[:-1]")
+// tree.Query("$.foo[0:-1:]")
+// tree.Query("$.foo[::1]")
+// tree.Query("$.foo[0::1]")
+// tree.Query("$.foo[:-1:1]")
+// tree.Query("$.foo[0:-1:1]")
+//
+// Query Filters
+//
+// Query filters are used within a Union [,] or single Filter [] expression.
+// A filter only allows nodes that qualify through to the next expression,
+// and/or into the result set.
+//
+// // returns children of foo that are permitted by the 'bar' filter.
+// tree.Query("$.foo[?(bar)]")
+//
+// There are several filters provided with the library:
+//
+// tree
+// Allows nodes of type TomlTree.
+// int
+// Allows nodes of type int64.
+// float
+// Allows nodes of type float64.
+// string
+// Allows nodes of type string.
+// time
+// Allows nodes of type time.Time.
+// bool
+// Allows nodes of type bool.
+//
+// Query Results
+//
+// An executed query returns a QueryResult object. This contains the nodes
+// in the TOML tree that qualify the query expression. Position information
+// is also available for each value in the set.
+//
+// // display the results of a query
+// results := tree.Query("$.foo.bar.baz")
+// for idx, value := results.Values() {
+// fmt.Println("%v: %v", results.Positions()[idx], value)
+// }
+//
+// Compiled Queries
+//
+// Queries may be executed directly on a TomlTree object, or compiled ahead
+// of time and executed discretely. The former is more convienent, but has the
+// penalty of having to recompile the query expression each time.
+//
+// // basic query
+// results := tree.Query("$.foo.bar.baz")
+//
+// // compiled query
+// query := toml.CompileQuery("$.foo.bar.baz")
+// results := query.Execute(tree)
+//
+// // run the compiled query again on a different tree
+// moreResults := query.Execute(anotherTree)
+//
+// User Defined Query Filters
+//
+// Filter expressions may also be user defined by using the SetFilter()
+// function on the Query object. The function must return true/false, which
+// signifies if the passed node is kept or discarded, respectively.
+//
+// // create a query that references a user-defined filter
+// query, _ := CompileQuery("$[?(bazOnly)]")
+//
+// // define the filter, and assign it to the query
+// query.SetFilter("bazOnly", func(node interface{}) bool{
+// if tree, ok := node.(*TomlTree); ok {
+// return tree.Has("baz")
+// }
+// return false // reject all other node types
+// })
+//
+// // run the query
+// query.Execute(tree)
+//
+package toml
diff --git a/vendor/github.com/pelletier/go-toml/doc_test.go b/vendor/github.com/pelletier/go-toml/doc_test.go
new file mode 100644
index 000000000..69452415a
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/doc_test.go
@@ -0,0 +1,81 @@
+// code examples for godoc
+
+package toml
+
+import (
+ "fmt"
+)
+
+func ExampleNodeFilterFn_filterExample() {
+ tree, _ := Load(`
+ [struct_one]
+ foo = "foo"
+ bar = "bar"
+
+ [struct_two]
+ baz = "baz"
+ gorf = "gorf"
+ `)
+
+ // create a query that references a user-defined-filter
+ query, _ := CompileQuery("$[?(bazOnly)]")
+
+ // define the filter, and assign it to the query
+ query.SetFilter("bazOnly", func(node interface{}) bool {
+ if tree, ok := node.(*TomlTree); ok {
+ return tree.Has("baz")
+ }
+ return false // reject all other node types
+ })
+
+ // results contain only the 'struct_two' TomlTree
+ query.Execute(tree)
+}
+
+func ExampleQuery_queryExample() {
+ config, _ := Load(`
+ [[book]]
+ title = "The Stand"
+ author = "Stephen King"
+ [[book]]
+ title = "For Whom the Bell Tolls"
+ author = "Ernest Hemmingway"
+ [[book]]
+ title = "Neuromancer"
+ author = "William Gibson"
+ `)
+
+ // find and print all the authors in the document
+ authors, _ := config.Query("$.book.author")
+ for _, name := range authors.Values() {
+ fmt.Println(name)
+ }
+}
+
+func Example_comprehensiveExample() {
+ config, err := LoadFile("config.toml")
+
+ if err != nil {
+ fmt.Println("Error ", err.Error())
+ } else {
+ // retrieve data directly
+ user := config.Get("postgres.user").(string)
+ password := config.Get("postgres.password").(string)
+
+ // or using an intermediate object
+ configTree := config.Get("postgres").(*TomlTree)
+ user = configTree.Get("user").(string)
+ password = configTree.Get("password").(string)
+ fmt.Println("User is ", user, ". Password is ", password)
+
+ // show where elements are in the file
+ fmt.Printf("User position: %v\n", configTree.GetPosition("user"))
+ fmt.Printf("Password position: %v\n", configTree.GetPosition("password"))
+
+ // use a query to gather elements without walking the tree
+ results, _ := config.Query("$..[user,password]")
+ for ii, item := range results.Values() {
+ fmt.Printf("Query result %d: %v\n", ii, item)
+ }
+ }
+}
diff --git a/vendor/github.com/pelletier/go-toml/example-crlf.toml b/vendor/github.com/pelletier/go-toml/example-crlf.toml
new file mode 100644
index 000000000..12950a163
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/example-crlf.toml
@@ -0,0 +1,29 @@
+# This is a TOML document. Boom.
+
+title = "TOML Example"
+
+[owner]
+name = "Tom Preston-Werner"
+organization = "GitHub"
+bio = "GitHub Cofounder & CEO\nLikes tater tots and beer."
+dob = 1979-05-27T07:32:00Z # First class dates? Why not?
+
+[database]
+server = "192.168.1.1"
+ports = [ 8001, 8001, 8002 ]
+connection_max = 5000
+enabled = true
+
+[servers]
+
+ # You can indent as you please. Tabs or spaces. TOML don't care.
+ [servers.alpha]
+ ip = "10.0.0.1"
+ dc = "eqdc10"
+
+ [servers.beta]
+ ip = "10.0.0.2"
+ dc = "eqdc10"
+
+[clients]
+data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it
diff --git a/vendor/github.com/pelletier/go-toml/example.toml b/vendor/github.com/pelletier/go-toml/example.toml
new file mode 100644
index 000000000..3d902f282
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/example.toml
@@ -0,0 +1,29 @@
+# This is a TOML document. Boom.
+
+title = "TOML Example"
+
+[owner]
+name = "Tom Preston-Werner"
+organization = "GitHub"
+bio = "GitHub Cofounder & CEO\nLikes tater tots and beer."
+dob = 1979-05-27T07:32:00Z # First class dates? Why not?
+
+[database]
+server = "192.168.1.1"
+ports = [ 8001, 8001, 8002 ]
+connection_max = 5000
+enabled = true
+
+[servers]
+
+ # You can indent as you please. Tabs or spaces. TOML don't care.
+ [servers.alpha]
+ ip = "10.0.0.1"
+ dc = "eqdc10"
+
+ [servers.beta]
+ ip = "10.0.0.2"
+ dc = "eqdc10"
+
+[clients]
+data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it
diff --git a/vendor/github.com/pelletier/go-toml/keysparsing.go b/vendor/github.com/pelletier/go-toml/keysparsing.go
new file mode 100644
index 000000000..d62ca5fd1
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/keysparsing.go
@@ -0,0 +1,94 @@
+// Parsing keys handling both bare and quoted keys.
+
+package toml
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "unicode"
+)
+
+func parseKey(key string) ([]string, error) {
+ groups := []string{}
+ var buffer bytes.Buffer
+ inQuotes := false
+ wasInQuotes := false
+ escapeNext := false
+ ignoreSpace := true
+ expectDot := false
+
+ for _, char := range key {
+ if ignoreSpace {
+ if char == ' ' {
+ continue
+ }
+ ignoreSpace = false
+ }
+ if escapeNext {
+ buffer.WriteRune(char)
+ escapeNext = false
+ continue
+ }
+ switch char {
+ case '\\':
+ escapeNext = true
+ continue
+ case '"':
+ if inQuotes {
+ groups = append(groups, buffer.String())
+ buffer.Reset()
+ wasInQuotes = true
+ }
+ inQuotes = !inQuotes
+ expectDot = false
+ case '.':
+ if inQuotes {
+ buffer.WriteRune(char)
+ } else {
+ if !wasInQuotes {
+ if buffer.Len() == 0 {
+ return nil, errors.New("empty table key")
+ }
+ groups = append(groups, buffer.String())
+ buffer.Reset()
+ }
+ ignoreSpace = true
+ expectDot = false
+ wasInQuotes = false
+ }
+ case ' ':
+ if inQuotes {
+ buffer.WriteRune(char)
+ } else {
+ expectDot = true
+ }
+ default:
+ if !inQuotes && !isValidBareChar(char) {
+ return nil, fmt.Errorf("invalid bare character: %c", char)
+ }
+ if !inQuotes && expectDot {
+ return nil, errors.New("what?")
+ }
+ buffer.WriteRune(char)
+ expectDot = false
+ }
+ }
+ if inQuotes {
+ return nil, errors.New("mismatched quotes")
+ }
+ if escapeNext {
+ return nil, errors.New("unfinished escape sequence")
+ }
+ if buffer.Len() > 0 {
+ groups = append(groups, buffer.String())
+ }
+ if len(groups) == 0 {
+ return nil, errors.New("empty key")
+ }
+ return groups, nil
+}
+
+func isValidBareChar(r rune) bool {
+ return isAlphanumeric(r) || r == '-' || unicode.IsNumber(r)
+}
diff --git a/vendor/github.com/pelletier/go-toml/keysparsing_test.go b/vendor/github.com/pelletier/go-toml/keysparsing_test.go
new file mode 100644
index 000000000..1a9ecccaa
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/keysparsing_test.go
@@ -0,0 +1,56 @@
+package toml
+
+import (
+ "fmt"
+ "testing"
+)
+
+func testResult(t *testing.T, key string, expected []string) {
+ parsed, err := parseKey(key)
+ t.Logf("key=%s expected=%s parsed=%s", key, expected, parsed)
+ if err != nil {
+ t.Fatal("Unexpected error:", err)
+ }
+ if len(expected) != len(parsed) {
+ t.Fatal("Expected length", len(expected), "but", len(parsed), "parsed")
+ }
+ for index, expectedKey := range expected {
+ if expectedKey != parsed[index] {
+ t.Fatal("Expected", expectedKey, "at index", index, "but found", parsed[index])
+ }
+ }
+}
+
+func testError(t *testing.T, key string, expectedError string) {
+ _, err := parseKey(key)
+ if fmt.Sprintf("%s", err) != expectedError {
+ t.Fatalf("Expected error \"%s\", but got \"%s\".", expectedError, err)
+ }
+}
+
+func TestBareKeyBasic(t *testing.T) {
+ testResult(t, "test", []string{"test"})
+}
+
+func TestBareKeyDotted(t *testing.T) {
+ testResult(t, "this.is.a.key", []string{"this", "is", "a", "key"})
+}
+
+func TestDottedKeyBasic(t *testing.T) {
+ testResult(t, "\"a.dotted.key\"", []string{"a.dotted.key"})
+}
+
+func TestBaseKeyPound(t *testing.T) {
+ testError(t, "hello#world", "invalid bare character: #")
+}
+
+func TestQuotedKeys(t *testing.T) {
+ testResult(t, `hello."foo".bar`, []string{"hello", "foo", "bar"})
+ testResult(t, `"hello!"`, []string{"hello!"})
+}
+
+func TestEmptyKey(t *testing.T) {
+ testError(t, "", "empty key")
+ testError(t, " ", "empty key")
+ testResult(t, `""`, []string{""})
+}
diff --git a/vendor/github.com/pelletier/go-toml/lexer.go b/vendor/github.com/pelletier/go-toml/lexer.go
new file mode 100644
index 000000000..104f3b1f4
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/lexer.go
@@ -0,0 +1,657 @@
+// TOML lexer.
+//
+// Written using the principles developed by Rob Pike in
+// http://www.youtube.com/watch?v=HxaD_trXwRE
+
+package toml
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "regexp"
+ "strconv"
+ "strings"
+
+ "github.com/pelletier/go-buffruneio"
+)
+
+var dateRegexp *regexp.Regexp
+
+// Define state functions
+type tomlLexStateFn func() tomlLexStateFn
+
+// Define lexer
+type tomlLexer struct {
+ input *buffruneio.Reader // Textual source
+ buffer []rune // Runes composing the current token
+ tokens chan token
+ depth int
+ line int
+ col int
+ endbufferLine int
+ endbufferCol int
+}
+
+// Basic read operations on input
+
+func (l *tomlLexer) read() rune {
+ r, _, err := l.input.ReadRune()
+ if err != nil {
+ panic(err)
+ }
+ if r == '\n' {
+ l.endbufferLine++
+ l.endbufferCol = 1
+ } else {
+ l.endbufferCol++
+ }
+ return r
+}
+
+func (l *tomlLexer) next() rune {
+ r := l.read()
+
+ if r != eof {
+ l.buffer = append(l.buffer, r)
+ }
+ return r
+}
+
+func (l *tomlLexer) ignore() {
+ l.buffer = make([]rune, 0)
+ l.line = l.endbufferLine
+ l.col = l.endbufferCol
+}
+
+func (l *tomlLexer) skip() {
+ l.next()
+ l.ignore()
+}
+
+func (l *tomlLexer) fastForward(n int) {
+ for i := 0; i < n; i++ {
+ l.next()
+ }
+}
+
+func (l *tomlLexer) emitWithValue(t tokenType, value string) {
+ l.tokens <- token{
+ Position: Position{l.line, l.col},
+ typ: t,
+ val: value,
+ }
+ l.ignore()
+}
+
+func (l *tomlLexer) emit(t tokenType) {
+ l.emitWithValue(t, string(l.buffer))
+}
+
+func (l *tomlLexer) peek() rune {
+ r, _, err := l.input.ReadRune()
+ if err != nil {
+ panic(err)
+ }
+ l.input.UnreadRune()
+ return r
+}
+
+func (l *tomlLexer) follow(next string) bool {
+ for _, expectedRune := range next {
+ r, _, err := l.input.ReadRune()
+ defer l.input.UnreadRune()
+ if err != nil {
+ panic(err)
+ }
+ if expectedRune != r {
+ return false
+ }
+ }
+ return true
+}
+
+// Error management
+
+func (l *tomlLexer) errorf(format string, args ...interface{}) tomlLexStateFn {
+ l.tokens <- token{
+ Position: Position{l.line, l.col},
+ typ: tokenError,
+ val: fmt.Sprintf(format, args...),
+ }
+ return nil
+}
+
+// State functions
+
+func (l *tomlLexer) lexVoid() tomlLexStateFn {
+ for {
+ next := l.peek()
+ switch next {
+ case '[':
+ return l.lexTableKey
+ case '#':
+ return l.lexComment(l.lexVoid)
+ case '=':
+ return l.lexEqual
+ case '\r':
+ fallthrough
+ case '\n':
+ l.skip()
+ continue
+ }
+
+ if isSpace(next) {
+ l.skip()
+ }
+
+ if l.depth > 0 {
+ return l.lexRvalue
+ }
+
+ if isKeyStartChar(next) {
+ return l.lexKey
+ }
+
+ if next == eof {
+ l.next()
+ break
+ }
+ }
+
+ l.emit(tokenEOF)
+ return nil
+}
+
+func (l *tomlLexer) lexRvalue() tomlLexStateFn {
+ for {
+ next := l.peek()
+ switch next {
+ case '.':
+ return l.errorf("cannot start float with a dot")
+ case '=':
+ return l.lexEqual
+ case '[':
+ l.depth++
+ return l.lexLeftBracket
+ case ']':
+ l.depth--
+ return l.lexRightBracket
+ case '{':
+ return l.lexLeftCurlyBrace
+ case '}':
+ return l.lexRightCurlyBrace
+ case '#':
+ return l.lexComment(l.lexRvalue)
+ case '"':
+ return l.lexString
+ case '\'':
+ return l.lexLiteralString
+ case ',':
+ return l.lexComma
+ case '\r':
+ fallthrough
+ case '\n':
+ l.skip()
+ if l.depth == 0 {
+ return l.lexVoid
+ }
+ return l.lexRvalue
+ case '_':
+ return l.errorf("cannot start number with underscore")
+ }
+
+ if l.follow("true") {
+ return l.lexTrue
+ }
+
+ if l.follow("false") {
+ return l.lexFalse
+ }
+
+ if isSpace(next) {
+ l.skip()
+ continue
+ }
+
+ if next == eof {
+ l.next()
+ break
+ }
+
+ possibleDate := string(l.input.PeekRunes(35))
+ dateMatch := dateRegexp.FindString(possibleDate)
+ if dateMatch != "" {
+ l.fastForward(len(dateMatch))
+ return l.lexDate
+ }
+
+ if next == '+' || next == '-' || isDigit(next) {
+ return l.lexNumber
+ }
+
+ if isAlphanumeric(next) {
+ return l.lexKey
+ }
+
+ return l.errorf("no value can start with %c", next)
+ }
+
+ l.emit(tokenEOF)
+ return nil
+}
+
+func (l *tomlLexer) lexLeftCurlyBrace() tomlLexStateFn {
+ l.next()
+ l.emit(tokenLeftCurlyBrace)
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) lexRightCurlyBrace() tomlLexStateFn {
+ l.next()
+ l.emit(tokenRightCurlyBrace)
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) lexDate() tomlLexStateFn {
+ l.emit(tokenDate)
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) lexTrue() tomlLexStateFn {
+ l.fastForward(4)
+ l.emit(tokenTrue)
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) lexFalse() tomlLexStateFn {
+ l.fastForward(5)
+ l.emit(tokenFalse)
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) lexEqual() tomlLexStateFn {
+ l.next()
+ l.emit(tokenEqual)
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) lexComma() tomlLexStateFn {
+ l.next()
+ l.emit(tokenComma)
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) lexKey() tomlLexStateFn {
+ growingString := ""
+
+ for r := l.peek(); isKeyChar(r) || r == '\n' || r == '\r'; r = l.peek() {
+ if r == '"' {
+ l.next()
+ str, err := l.lexStringAsString(`"`, false, true)
+ if err != nil {
+ return l.errorf(err.Error())
+ }
+ growingString += `"` + str + `"`
+ l.next()
+ continue
+ } else if r == '\n' {
+ return l.errorf("keys cannot contain new lines")
+ } else if isSpace(r) {
+ break
+ } else if !isValidBareChar(r) {
+ return l.errorf("keys cannot contain %c character", r)
+ }
+ growingString += string(r)
+ l.next()
+ }
+ l.emitWithValue(tokenKey, growingString)
+ return l.lexVoid
+}
+
+func (l *tomlLexer) lexComment(previousState tomlLexStateFn) tomlLexStateFn {
+ return func() tomlLexStateFn {
+ for next := l.peek(); next != '\n' && next != eof; next = l.peek() {
+ if next == '\r' && l.follow("\r\n") {
+ break
+ }
+ l.next()
+ }
+ l.ignore()
+ return previousState
+ }
+}
+
+func (l *tomlLexer) lexLeftBracket() tomlLexStateFn {
+ l.next()
+ l.emit(tokenLeftBracket)
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) lexLiteralStringAsString(terminator string, discardLeadingNewLine bool) (string, error) {
+ growingString := ""
+
+ if discardLeadingNewLine {
+ if l.follow("\r\n") {
+ l.skip()
+ l.skip()
+ } else if l.peek() == '\n' {
+ l.skip()
+ }
+ }
+
+ // find end of string
+ for {
+ if l.follow(terminator) {
+ return growingString, nil
+ }
+
+ next := l.peek()
+ if next == eof {
+ break
+ }
+ growingString += string(l.next())
+ }
+
+ return "", errors.New("unclosed string")
+}
+
+func (l *tomlLexer) lexLiteralString() tomlLexStateFn {
+ l.skip()
+
+ // handle special case for triple-quote
+ terminator := "'"
+ discardLeadingNewLine := false
+ if l.follow("''") {
+ l.skip()
+ l.skip()
+ terminator = "'''"
+ discardLeadingNewLine = true
+ }
+
+ str, err := l.lexLiteralStringAsString(terminator, discardLeadingNewLine)
+ if err != nil {
+ return l.errorf(err.Error())
+ }
+
+ l.emitWithValue(tokenString, str)
+ l.fastForward(len(terminator))
+ l.ignore()
+ return l.lexRvalue
+}
+
+// Lex a string and return the results as a string.
+// Terminator is the substring indicating the end of the token.
+// The resulting string does not include the terminator.
+func (l *tomlLexer) lexStringAsString(terminator string, discardLeadingNewLine, acceptNewLines bool) (string, error) {
+ growingString := ""
+
+ if discardLeadingNewLine {
+ if l.follow("\r\n") {
+ l.skip()
+ l.skip()
+ } else if l.peek() == '\n' {
+ l.skip()
+ }
+ }
+
+ for {
+ if l.follow(terminator) {
+ return growingString, nil
+ }
+
+ if l.follow("\\") {
+ l.next()
+ switch l.peek() {
+ case '\r':
+ fallthrough
+ case '\n':
+ fallthrough
+ case '\t':
+ fallthrough
+ case ' ':
+ // skip all whitespace chars following backslash
+ for strings.ContainsRune("\r\n\t ", l.peek()) {
+ l.next()
+ }
+ case '"':
+ growingString += "\""
+ l.next()
+ case 'n':
+ growingString += "\n"
+ l.next()
+ case 'b':
+ growingString += "\b"
+ l.next()
+ case 'f':
+ growingString += "\f"
+ l.next()
+ case '/':
+ growingString += "/"
+ l.next()
+ case 't':
+ growingString += "\t"
+ l.next()
+ case 'r':
+ growingString += "\r"
+ l.next()
+ case '\\':
+ growingString += "\\"
+ l.next()
+ case 'u':
+ l.next()
+ code := ""
+ for i := 0; i < 4; i++ {
+ c := l.peek()
+ if !isHexDigit(c) {
+ return "", errors.New("unfinished unicode escape")
+ }
+ l.next()
+ code = code + string(c)
+ }
+ intcode, err := strconv.ParseInt(code, 16, 32)
+ if err != nil {
+ return "", errors.New("invalid unicode escape: \\u" + code)
+ }
+ growingString += string(rune(intcode))
+ case 'U':
+ l.next()
+ code := ""
+ for i := 0; i < 8; i++ {
+ c := l.peek()
+ if !isHexDigit(c) {
+ return "", errors.New("unfinished unicode escape")
+ }
+ l.next()
+ code = code + string(c)
+ }
+ intcode, err := strconv.ParseInt(code, 16, 64)
+ if err != nil {
+ return "", errors.New("invalid unicode escape: \\U" + code)
+ }
+ growingString += string(rune(intcode))
+ default:
+ return "", errors.New("invalid escape sequence: \\" + string(l.peek()))
+ }
+ } else {
+ r := l.peek()
+
+ if 0x00 <= r && r <= 0x1F && !(acceptNewLines && (r == '\n' || r == '\r')) {
+ return "", fmt.Errorf("unescaped control character %U", r)
+ }
+ l.next()
+ growingString += string(r)
+ }
+
+ if l.peek() == eof {
+ break
+ }
+ }
+
+ return "", errors.New("unclosed string")
+}
+
+func (l *tomlLexer) lexString() tomlLexStateFn {
+ l.skip()
+
+ // handle special case for triple-quote
+ terminator := `"`
+ discardLeadingNewLine := false
+ acceptNewLines := false
+ if l.follow(`""`) {
+ l.skip()
+ l.skip()
+ terminator = `"""`
+ discardLeadingNewLine = true
+ acceptNewLines = true
+ }
+
+ str, err := l.lexStringAsString(terminator, discardLeadingNewLine, acceptNewLines)
+
+ if err != nil {
+ return l.errorf(err.Error())
+ }
+
+ l.emitWithValue(tokenString, str)
+ l.fastForward(len(terminator))
+ l.ignore()
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) lexTableKey() tomlLexStateFn {
+ l.next()
+
+ if l.peek() == '[' {
+ // token '[[' signifies an array of tables
+ l.next()
+ l.emit(tokenDoubleLeftBracket)
+ return l.lexInsideTableArrayKey
+ }
+ // vanilla table key
+ l.emit(tokenLeftBracket)
+ return l.lexInsideTableKey
+}
+
+func (l *tomlLexer) lexInsideTableArrayKey() tomlLexStateFn {
+ for r := l.peek(); r != eof; r = l.peek() {
+ switch r {
+ case ']':
+ if len(l.buffer) > 0 {
+ l.emit(tokenKeyGroupArray)
+ }
+ l.next()
+ if l.peek() != ']' {
+ break
+ }
+ l.next()
+ l.emit(tokenDoubleRightBracket)
+ return l.lexVoid
+ case '[':
+ return l.errorf("table array key cannot contain ']'")
+ default:
+ l.next()
+ }
+ }
+ return l.errorf("unclosed table array key")
+}
+
+func (l *tomlLexer) lexInsideTableKey() tomlLexStateFn {
+ for r := l.peek(); r != eof; r = l.peek() {
+ switch r {
+ case ']':
+ if len(l.buffer) > 0 {
+ l.emit(tokenKeyGroup)
+ }
+ l.next()
+ l.emit(tokenRightBracket)
+ return l.lexVoid
+ case '[':
+ return l.errorf("table key cannot contain ']'")
+ default:
+ l.next()
+ }
+ }
+ return l.errorf("unclosed table key")
+}
+
+func (l *tomlLexer) lexRightBracket() tomlLexStateFn {
+ l.next()
+ l.emit(tokenRightBracket)
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) lexNumber() tomlLexStateFn {
+ r := l.peek()
+ if r == '+' || r == '-' {
+ l.next()
+ }
+ pointSeen := false
+ expSeen := false
+ digitSeen := false
+ for {
+ next := l.peek()
+ if next == '.' {
+ if pointSeen {
+ return l.errorf("cannot have two dots in one float")
+ }
+ l.next()
+ if !isDigit(l.peek()) {
+ return l.errorf("float cannot end with a dot")
+ }
+ pointSeen = true
+ } else if next == 'e' || next == 'E' {
+ expSeen = true
+ l.next()
+ r := l.peek()
+ if r == '+' || r == '-' {
+ l.next()
+ }
+ } else if isDigit(next) {
+ digitSeen = true
+ l.next()
+ } else if next == '_' {
+ l.next()
+ } else {
+ break
+ }
+ if pointSeen && !digitSeen {
+ return l.errorf("cannot start float with a dot")
+ }
+ }
+
+ if !digitSeen {
+ return l.errorf("no digit in that number")
+ }
+ if pointSeen || expSeen {
+ l.emit(tokenFloat)
+ } else {
+ l.emit(tokenInteger)
+ }
+ return l.lexRvalue
+}
+
+func (l *tomlLexer) run() {
+ for state := l.lexVoid; state != nil; {
+ state = state()
+ }
+ close(l.tokens)
+}
+
+func init() {
+ dateRegexp = regexp.MustCompile(`^\d{1,4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})`)
+}
+
+// Entry point
+func lexToml(input io.Reader) chan token {
+ bufferedInput := buffruneio.NewReader(input)
+ l := &tomlLexer{
+ input: bufferedInput,
+ tokens: make(chan token),
+ line: 1,
+ col: 1,
+ endbufferLine: 1,
+ endbufferCol: 1,
+ }
+ go l.run()
+ return l.tokens
+}
diff --git a/vendor/github.com/pelletier/go-toml/lexer_test.go b/vendor/github.com/pelletier/go-toml/lexer_test.go
new file mode 100644
index 000000000..6b324ea0e
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/lexer_test.go
@@ -0,0 +1,750 @@
+package toml
+
+import (
+ "strings"
+ "testing"
+)
+
+func testFlow(t *testing.T, input string, expectedFlow []token) {
+ ch := lexToml(strings.NewReader(input))
+ for _, expected := range expectedFlow {
+ token := <-ch
+ if token != expected {
+ t.Log("While testing: ", input)
+ t.Log("compared (got)", token, "to (expected)", expected)
+ t.Log("\tvalue:", token.val, "<->", expected.val)
+ t.Log("\tvalue as bytes:", []byte(token.val), "<->", []byte(expected.val))
+ t.Log("\ttype:", token.typ.String(), "<->", expected.typ.String())
+ t.Log("\tline:", token.Line, "<->", expected.Line)
+ t.Log("\tcolumn:", token.Col, "<->", expected.Col)
+ t.Log("compared", token, "to", expected)
+ t.FailNow()
+ }
+ }
+
+ tok, ok := <-ch
+ if ok {
+ t.Log("channel is not closed!")
+ t.Log(len(ch)+1, "tokens remaining:")
+
+ t.Log("token ->", tok)
+ for token := range ch {
+ t.Log("token ->", token)
+ }
+ t.FailNow()
+ }
+}
+
+func TestValidKeyGroup(t *testing.T) {
+ testFlow(t, "[hello world]", []token{
+ {Position{1, 1}, tokenLeftBracket, "["},
+ {Position{1, 2}, tokenKeyGroup, "hello world"},
+ {Position{1, 13}, tokenRightBracket, "]"},
+ {Position{1, 14}, tokenEOF, ""},
+ })
+}
+
+func TestNestedQuotedUnicodeKeyGroup(t *testing.T) {
+ testFlow(t, `[ j . "ʞ" . l ]`, []token{
+ {Position{1, 1}, tokenLeftBracket, "["},
+ {Position{1, 2}, tokenKeyGroup, ` j . "ʞ" . l `},
+ {Position{1, 15}, tokenRightBracket, "]"},
+ {Position{1, 16}, tokenEOF, ""},
+ })
+}
+
+func TestUnclosedKeyGroup(t *testing.T) {
+ testFlow(t, "[hello world", []token{
+ {Position{1, 1}, tokenLeftBracket, "["},
+ {Position{1, 2}, tokenError, "unclosed table key"},
+ })
+}
+
+func TestComment(t *testing.T) {
+ testFlow(t, "# blahblah", []token{
+ {Position{1, 11}, tokenEOF, ""},
+ })
+}
+
+func TestKeyGroupComment(t *testing.T) {
+ testFlow(t, "[hello world] # blahblah", []token{
+ {Position{1, 1}, tokenLeftBracket, "["},
+ {Position{1, 2}, tokenKeyGroup, "hello world"},
+ {Position{1, 13}, tokenRightBracket, "]"},
+ {Position{1, 25}, tokenEOF, ""},
+ })
+}
+
+func TestMultipleKeyGroupsComment(t *testing.T) {
+ testFlow(t, "[hello world] # blahblah\n[test]", []token{
+ {Position{1, 1}, tokenLeftBracket, "["},
+ {Position{1, 2}, tokenKeyGroup, "hello world"},
+ {Position{1, 13}, tokenRightBracket, "]"},
+ {Position{2, 1}, tokenLeftBracket, "["},
+ {Position{2, 2}, tokenKeyGroup, "test"},
+ {Position{2, 6}, tokenRightBracket, "]"},
+ {Position{2, 7}, tokenEOF, ""},
+ })
+}
+
+func TestSimpleWindowsCRLF(t *testing.T) {
+ testFlow(t, "a=4\r\nb=2", []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 2}, tokenEqual, "="},
+ {Position{1, 3}, tokenInteger, "4"},
+ {Position{2, 1}, tokenKey, "b"},
+ {Position{2, 2}, tokenEqual, "="},
+ {Position{2, 3}, tokenInteger, "2"},
+ {Position{2, 4}, tokenEOF, ""},
+ })
+}
+
+func TestBasicKey(t *testing.T) {
+ testFlow(t, "hello", []token{
+ {Position{1, 1}, tokenKey, "hello"},
+ {Position{1, 6}, tokenEOF, ""},
+ })
+}
+
+func TestBasicKeyWithUnderscore(t *testing.T) {
+ testFlow(t, "hello_hello", []token{
+ {Position{1, 1}, tokenKey, "hello_hello"},
+ {Position{1, 12}, tokenEOF, ""},
+ })
+}
+
+func TestBasicKeyWithDash(t *testing.T) {
+ testFlow(t, "hello-world", []token{
+ {Position{1, 1}, tokenKey, "hello-world"},
+ {Position{1, 12}, tokenEOF, ""},
+ })
+}
+
+func TestBasicKeyWithUppercaseMix(t *testing.T) {
+ testFlow(t, "helloHELLOHello", []token{
+ {Position{1, 1}, tokenKey, "helloHELLOHello"},
+ {Position{1, 16}, tokenEOF, ""},
+ })
+}
+
+func TestBasicKeyWithInternationalCharacters(t *testing.T) {
+ testFlow(t, "héllÖ", []token{
+ {Position{1, 1}, tokenKey, "héllÖ"},
+ {Position{1, 6}, tokenEOF, ""},
+ })
+}
+
+func TestBasicKeyAndEqual(t *testing.T) {
+ testFlow(t, "hello =", []token{
+ {Position{1, 1}, tokenKey, "hello"},
+ {Position{1, 7}, tokenEqual, "="},
+ {Position{1, 8}, tokenEOF, ""},
+ })
+}
+
+func TestKeyWithSharpAndEqual(t *testing.T) {
+ testFlow(t, "key#name = 5", []token{
+ {Position{1, 1}, tokenError, "keys cannot contain # character"},
+ })
+}
+
+func TestKeyWithSymbolsAndEqual(t *testing.T) {
+ testFlow(t, "~!@$^&*()_+-`1234567890[]\\|/?><.,;:' = 5", []token{
+ {Position{1, 1}, tokenError, "keys cannot contain ~ character"},
+ })
+}
+
+func TestKeyEqualStringEscape(t *testing.T) {
+ testFlow(t, `foo = "hello\""`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, "hello\""},
+ {Position{1, 16}, tokenEOF, ""},
+ })
+}
+
+func TestKeyEqualStringUnfinished(t *testing.T) {
+ testFlow(t, `foo = "bar`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenError, "unclosed string"},
+ })
+}
+
+func TestKeyEqualString(t *testing.T) {
+ testFlow(t, `foo = "bar"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, "bar"},
+ {Position{1, 12}, tokenEOF, ""},
+ })
+}
+
+func TestKeyEqualTrue(t *testing.T) {
+ testFlow(t, "foo = true", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenTrue, "true"},
+ {Position{1, 11}, tokenEOF, ""},
+ })
+}
+
+func TestKeyEqualFalse(t *testing.T) {
+ testFlow(t, "foo = false", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenFalse, "false"},
+ {Position{1, 12}, tokenEOF, ""},
+ })
+}
+
+func TestArrayNestedString(t *testing.T) {
+ testFlow(t, `a = [ ["hello", "world"] ]`, []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenLeftBracket, "["},
+ {Position{1, 7}, tokenLeftBracket, "["},
+ {Position{1, 9}, tokenString, "hello"},
+ {Position{1, 15}, tokenComma, ","},
+ {Position{1, 18}, tokenString, "world"},
+ {Position{1, 24}, tokenRightBracket, "]"},
+ {Position{1, 26}, tokenRightBracket, "]"},
+ {Position{1, 27}, tokenEOF, ""},
+ })
+}
+
+func TestArrayNestedInts(t *testing.T) {
+ testFlow(t, "a = [ [42, 21], [10] ]", []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenLeftBracket, "["},
+ {Position{1, 7}, tokenLeftBracket, "["},
+ {Position{1, 8}, tokenInteger, "42"},
+ {Position{1, 10}, tokenComma, ","},
+ {Position{1, 12}, tokenInteger, "21"},
+ {Position{1, 14}, tokenRightBracket, "]"},
+ {Position{1, 15}, tokenComma, ","},
+ {Position{1, 17}, tokenLeftBracket, "["},
+ {Position{1, 18}, tokenInteger, "10"},
+ {Position{1, 20}, tokenRightBracket, "]"},
+ {Position{1, 22}, tokenRightBracket, "]"},
+ {Position{1, 23}, tokenEOF, ""},
+ })
+}
+
+func TestArrayInts(t *testing.T) {
+ testFlow(t, "a = [ 42, 21, 10, ]", []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenLeftBracket, "["},
+ {Position{1, 7}, tokenInteger, "42"},
+ {Position{1, 9}, tokenComma, ","},
+ {Position{1, 11}, tokenInteger, "21"},
+ {Position{1, 13}, tokenComma, ","},
+ {Position{1, 15}, tokenInteger, "10"},
+ {Position{1, 17}, tokenComma, ","},
+ {Position{1, 19}, tokenRightBracket, "]"},
+ {Position{1, 20}, tokenEOF, ""},
+ })
+}
+
+func TestMultilineArrayComments(t *testing.T) {
+ testFlow(t, "a = [1, # wow\n2, # such items\n3, # so array\n]", []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenLeftBracket, "["},
+ {Position{1, 6}, tokenInteger, "1"},
+ {Position{1, 7}, tokenComma, ","},
+ {Position{2, 1}, tokenInteger, "2"},
+ {Position{2, 2}, tokenComma, ","},
+ {Position{3, 1}, tokenInteger, "3"},
+ {Position{3, 2}, tokenComma, ","},
+ {Position{4, 1}, tokenRightBracket, "]"},
+ {Position{4, 2}, tokenEOF, ""},
+ })
+}
+
+func TestNestedArraysComment(t *testing.T) {
+ toml := `
+someArray = [
+# does not work
+["entry1"]
+]`
+ testFlow(t, toml, []token{
+ {Position{2, 1}, tokenKey, "someArray"},
+ {Position{2, 11}, tokenEqual, "="},
+ {Position{2, 13}, tokenLeftBracket, "["},
+ {Position{4, 1}, tokenLeftBracket, "["},
+ {Position{4, 3}, tokenString, "entry1"},
+ {Position{4, 10}, tokenRightBracket, "]"},
+ {Position{5, 1}, tokenRightBracket, "]"},
+ {Position{5, 2}, tokenEOF, ""},
+ })
+}
+
+func TestKeyEqualArrayBools(t *testing.T) {
+ testFlow(t, "foo = [true, false, true]", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenLeftBracket, "["},
+ {Position{1, 8}, tokenTrue, "true"},
+ {Position{1, 12}, tokenComma, ","},
+ {Position{1, 14}, tokenFalse, "false"},
+ {Position{1, 19}, tokenComma, ","},
+ {Position{1, 21}, tokenTrue, "true"},
+ {Position{1, 25}, tokenRightBracket, "]"},
+ {Position{1, 26}, tokenEOF, ""},
+ })
+}
+
+func TestKeyEqualArrayBoolsWithComments(t *testing.T) {
+ testFlow(t, "foo = [true, false, true] # YEAH", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenLeftBracket, "["},
+ {Position{1, 8}, tokenTrue, "true"},
+ {Position{1, 12}, tokenComma, ","},
+ {Position{1, 14}, tokenFalse, "false"},
+ {Position{1, 19}, tokenComma, ","},
+ {Position{1, 21}, tokenTrue, "true"},
+ {Position{1, 25}, tokenRightBracket, "]"},
+ {Position{1, 33}, tokenEOF, ""},
+ })
+}
+
+func TestDateRegexp(t *testing.T) {
+ if dateRegexp.FindString("1979-05-27T07:32:00Z") == "" {
+ t.Error("basic lexing")
+ }
+ if dateRegexp.FindString("1979-05-27T00:32:00-07:00") == "" {
+ t.Error("offset lexing")
+ }
+ if dateRegexp.FindString("1979-05-27T00:32:00.999999-07:00") == "" {
+ t.Error("nano precision lexing")
+ }
+}
+
+func TestKeyEqualDate(t *testing.T) {
+ testFlow(t, "foo = 1979-05-27T07:32:00Z", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenDate, "1979-05-27T07:32:00Z"},
+ {Position{1, 27}, tokenEOF, ""},
+ })
+ testFlow(t, "foo = 1979-05-27T00:32:00-07:00", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenDate, "1979-05-27T00:32:00-07:00"},
+ {Position{1, 32}, tokenEOF, ""},
+ })
+ testFlow(t, "foo = 1979-05-27T00:32:00.999999-07:00", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenDate, "1979-05-27T00:32:00.999999-07:00"},
+ {Position{1, 39}, tokenEOF, ""},
+ })
+}
+
+func TestFloatEndingWithDot(t *testing.T) {
+ testFlow(t, "foo = 42.", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenError, "float cannot end with a dot"},
+ })
+}
+
+func TestFloatWithTwoDots(t *testing.T) {
+ testFlow(t, "foo = 4.2.", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenError, "cannot have two dots in one float"},
+ })
+}
+
+func TestFloatWithExponent1(t *testing.T) {
+ testFlow(t, "a = 5e+22", []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenFloat, "5e+22"},
+ {Position{1, 10}, tokenEOF, ""},
+ })
+}
+
+func TestFloatWithExponent2(t *testing.T) {
+ testFlow(t, "a = 5E+22", []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenFloat, "5E+22"},
+ {Position{1, 10}, tokenEOF, ""},
+ })
+}
+
+func TestFloatWithExponent3(t *testing.T) {
+ testFlow(t, "a = -5e+22", []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenFloat, "-5e+22"},
+ {Position{1, 11}, tokenEOF, ""},
+ })
+}
+
+func TestFloatWithExponent4(t *testing.T) {
+ testFlow(t, "a = -5e-22", []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenFloat, "-5e-22"},
+ {Position{1, 11}, tokenEOF, ""},
+ })
+}
+
+func TestFloatWithExponent5(t *testing.T) {
+ testFlow(t, "a = 6.626e-34", []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenFloat, "6.626e-34"},
+ {Position{1, 14}, tokenEOF, ""},
+ })
+}
+
+func TestInvalidEsquapeSequence(t *testing.T) {
+ testFlow(t, `foo = "\x"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenError, "invalid escape sequence: \\x"},
+ })
+}
+
+func TestNestedArrays(t *testing.T) {
+ testFlow(t, "foo = [[[]]]", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenLeftBracket, "["},
+ {Position{1, 8}, tokenLeftBracket, "["},
+ {Position{1, 9}, tokenLeftBracket, "["},
+ {Position{1, 10}, tokenRightBracket, "]"},
+ {Position{1, 11}, tokenRightBracket, "]"},
+ {Position{1, 12}, tokenRightBracket, "]"},
+ {Position{1, 13}, tokenEOF, ""},
+ })
+}
+
+func TestKeyEqualNumber(t *testing.T) {
+ testFlow(t, "foo = 42", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenInteger, "42"},
+ {Position{1, 9}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = +42", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenInteger, "+42"},
+ {Position{1, 10}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = -42", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenInteger, "-42"},
+ {Position{1, 10}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = 4.2", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenFloat, "4.2"},
+ {Position{1, 10}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = +4.2", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenFloat, "+4.2"},
+ {Position{1, 11}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = -4.2", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenFloat, "-4.2"},
+ {Position{1, 11}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = 1_000", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenInteger, "1_000"},
+ {Position{1, 12}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = 5_349_221", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenInteger, "5_349_221"},
+ {Position{1, 16}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = 1_2_3_4_5", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenInteger, "1_2_3_4_5"},
+ {Position{1, 16}, tokenEOF, ""},
+ })
+
+ testFlow(t, "flt8 = 9_224_617.445_991_228_313", []token{
+ {Position{1, 1}, tokenKey, "flt8"},
+ {Position{1, 6}, tokenEqual, "="},
+ {Position{1, 8}, tokenFloat, "9_224_617.445_991_228_313"},
+ {Position{1, 33}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = +", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenError, "no digit in that number"},
+ })
+}
+
+func TestMultiline(t *testing.T) {
+ testFlow(t, "foo = 42\nbar=21", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 7}, tokenInteger, "42"},
+ {Position{2, 1}, tokenKey, "bar"},
+ {Position{2, 4}, tokenEqual, "="},
+ {Position{2, 5}, tokenInteger, "21"},
+ {Position{2, 7}, tokenEOF, ""},
+ })
+}
+
+func TestKeyEqualStringUnicodeEscape(t *testing.T) {
+ testFlow(t, `foo = "hello \u2665"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, "hello ♥"},
+ {Position{1, 21}, tokenEOF, ""},
+ })
+ testFlow(t, `foo = "hello \U000003B4"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, "hello δ"},
+ {Position{1, 25}, tokenEOF, ""},
+ })
+ testFlow(t, `foo = "\uabcd"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, "\uabcd"},
+ {Position{1, 15}, tokenEOF, ""},
+ })
+ testFlow(t, `foo = "\uABCD"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, "\uABCD"},
+ {Position{1, 15}, tokenEOF, ""},
+ })
+ testFlow(t, `foo = "\U000bcdef"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, "\U000bcdef"},
+ {Position{1, 19}, tokenEOF, ""},
+ })
+ testFlow(t, `foo = "\U000BCDEF"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, "\U000BCDEF"},
+ {Position{1, 19}, tokenEOF, ""},
+ })
+ testFlow(t, `foo = "\u2"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenError, "unfinished unicode escape"},
+ })
+ testFlow(t, `foo = "\U2"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenError, "unfinished unicode escape"},
+ })
+}
+
+func TestKeyEqualStringNoEscape(t *testing.T) {
+ testFlow(t, "foo = \"hello \u0002\"", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenError, "unescaped control character U+0002"},
+ })
+ testFlow(t, "foo = \"hello \u001F\"", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenError, "unescaped control character U+001F"},
+ })
+}
+
+func TestLiteralString(t *testing.T) {
+ testFlow(t, `foo = 'C:\Users\nodejs\templates'`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, `C:\Users\nodejs\templates`},
+ {Position{1, 34}, tokenEOF, ""},
+ })
+ testFlow(t, `foo = '\\ServerX\admin$\system32\'`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, `\\ServerX\admin$\system32\`},
+ {Position{1, 35}, tokenEOF, ""},
+ })
+ testFlow(t, `foo = 'Tom "Dubs" Preston-Werner'`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, `Tom "Dubs" Preston-Werner`},
+ {Position{1, 34}, tokenEOF, ""},
+ })
+ testFlow(t, `foo = '<\i\c*\s*>'`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, `<\i\c*\s*>`},
+ {Position{1, 19}, tokenEOF, ""},
+ })
+ testFlow(t, `foo = 'C:\Users\nodejs\unfinis`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenError, "unclosed string"},
+ })
+}
+
+func TestMultilineLiteralString(t *testing.T) {
+ testFlow(t, `foo = '''hello 'literal' world'''`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 10}, tokenString, `hello 'literal' world`},
+ {Position{1, 34}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = '''\nhello\n'literal'\nworld'''", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{2, 1}, tokenString, "hello\n'literal'\nworld"},
+ {Position{4, 9}, tokenEOF, ""},
+ })
+ testFlow(t, "foo = '''\r\nhello\r\n'literal'\r\nworld'''", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{2, 1}, tokenString, "hello\r\n'literal'\r\nworld"},
+ {Position{4, 9}, tokenEOF, ""},
+ })
+}
+
+func TestMultilineString(t *testing.T) {
+ testFlow(t, `foo = """hello "literal" world"""`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 10}, tokenString, `hello "literal" world`},
+ {Position{1, 34}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = \"\"\"\r\nhello\\\r\n\"literal\"\\\nworld\"\"\"", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{2, 1}, tokenString, "hello\"literal\"world"},
+ {Position{4, 9}, tokenEOF, ""},
+ })
+
+ testFlow(t, "foo = \"\"\"\\\n \\\n \\\n hello\\\nmultiline\\\nworld\"\"\"", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 10}, tokenString, "hellomultilineworld"},
+ {Position{6, 9}, tokenEOF, ""},
+ })
+
+ testFlow(t, "key2 = \"\"\"\nThe quick brown \\\n\n\n fox jumps over \\\n the lazy dog.\"\"\"", []token{
+ {Position{1, 1}, tokenKey, "key2"},
+ {Position{1, 6}, tokenEqual, "="},
+ {Position{2, 1}, tokenString, "The quick brown fox jumps over the lazy dog."},
+ {Position{6, 21}, tokenEOF, ""},
+ })
+
+ testFlow(t, "key2 = \"\"\"\\\n The quick brown \\\n fox jumps over \\\n the lazy dog.\\\n \"\"\"", []token{
+ {Position{1, 1}, tokenKey, "key2"},
+ {Position{1, 6}, tokenEqual, "="},
+ {Position{1, 11}, tokenString, "The quick brown fox jumps over the lazy dog."},
+ {Position{5, 11}, tokenEOF, ""},
+ })
+
+ testFlow(t, `key2 = "Roses are red\nViolets are blue"`, []token{
+ {Position{1, 1}, tokenKey, "key2"},
+ {Position{1, 6}, tokenEqual, "="},
+ {Position{1, 9}, tokenString, "Roses are red\nViolets are blue"},
+ {Position{1, 41}, tokenEOF, ""},
+ })
+
+ testFlow(t, "key2 = \"\"\"\nRoses are red\nViolets are blue\"\"\"", []token{
+ {Position{1, 1}, tokenKey, "key2"},
+ {Position{1, 6}, tokenEqual, "="},
+ {Position{2, 1}, tokenString, "Roses are red\nViolets are blue"},
+ {Position{3, 20}, tokenEOF, ""},
+ })
+}
+
+func TestUnicodeString(t *testing.T) {
+ testFlow(t, `foo = "hello ♥ world"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, "hello ♥ world"},
+ {Position{1, 22}, tokenEOF, ""},
+ })
+}
+func TestEscapeInString(t *testing.T) {
+ testFlow(t, `foo = "\b\f\/"`, []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenEqual, "="},
+ {Position{1, 8}, tokenString, "\b\f/"},
+ {Position{1, 15}, tokenEOF, ""},
+ })
+}
+
+func TestKeyGroupArray(t *testing.T) {
+ testFlow(t, "[[foo]]", []token{
+ {Position{1, 1}, tokenDoubleLeftBracket, "[["},
+ {Position{1, 3}, tokenKeyGroupArray, "foo"},
+ {Position{1, 6}, tokenDoubleRightBracket, "]]"},
+ {Position{1, 8}, tokenEOF, ""},
+ })
+}
+
+func TestQuotedKey(t *testing.T) {
+ testFlow(t, "\"a b\" = 42", []token{
+ {Position{1, 1}, tokenKey, "\"a b\""},
+ {Position{1, 7}, tokenEqual, "="},
+ {Position{1, 9}, tokenInteger, "42"},
+ {Position{1, 11}, tokenEOF, ""},
+ })
+}
+
+func TestKeyNewline(t *testing.T) {
+ testFlow(t, "a\n= 4", []token{
+ {Position{1, 1}, tokenError, "keys cannot contain new lines"},
+ })
+}
+
+func TestInvalidFloat(t *testing.T) {
+ testFlow(t, "a=7e1_", []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 2}, tokenEqual, "="},
+ {Position{1, 3}, tokenFloat, "7e1_"},
+ {Position{1, 7}, tokenEOF, ""},
+ })
+}
+
+func TestLexUnknownRvalue(t *testing.T) {
+ testFlow(t, `a = !b`, []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenError, "no value can start with !"},
+ })
+
+ testFlow(t, `a = \b`, []token{
+ {Position{1, 1}, tokenKey, "a"},
+ {Position{1, 3}, tokenEqual, "="},
+ {Position{1, 5}, tokenError, `no value can start with \`},
+ })
+}
diff --git a/vendor/github.com/pelletier/go-toml/match.go b/vendor/github.com/pelletier/go-toml/match.go
new file mode 100644
index 000000000..48b0f2a15
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/match.go
@@ -0,0 +1,234 @@
+package toml
+
+import (
+ "fmt"
+)
+
+// support function to set positions for tomlValues
+// NOTE: this is done to allow ctx.lastPosition to indicate the start of any
+// values returned by the query engines
+func tomlValueCheck(node interface{}, ctx *queryContext) interface{} {
+ switch castNode := node.(type) {
+ case *tomlValue:
+ ctx.lastPosition = castNode.position
+ return castNode.value
+ case []*TomlTree:
+ if len(castNode) > 0 {
+ ctx.lastPosition = castNode[0].position
+ }
+ return node
+ default:
+ return node
+ }
+}
+
+// base match
+type matchBase struct {
+ next pathFn
+}
+
+func (f *matchBase) setNext(next pathFn) {
+ f.next = next
+}
+
+// terminating functor - gathers results
+type terminatingFn struct {
+ // empty
+}
+
+func newTerminatingFn() *terminatingFn {
+ return &terminatingFn{}
+}
+
+func (f *terminatingFn) setNext(next pathFn) {
+ // do nothing
+}
+
+func (f *terminatingFn) call(node interface{}, ctx *queryContext) {
+ switch castNode := node.(type) {
+ case *TomlTree:
+ ctx.result.appendResult(node, castNode.position)
+ case *tomlValue:
+ ctx.result.appendResult(node, castNode.position)
+ default:
+ // use last position for scalars
+ ctx.result.appendResult(node, ctx.lastPosition)
+ }
+}
+
+// match single key
+type matchKeyFn struct {
+ matchBase
+ Name string
+}
+
+func newMatchKeyFn(name string) *matchKeyFn {
+ return &matchKeyFn{Name: name}
+}
+
+func (f *matchKeyFn) call(node interface{}, ctx *queryContext) {
+ if array, ok := node.([]*TomlTree); ok {
+ for _, tree := range array {
+ item := tree.values[f.Name]
+ if item != nil {
+ f.next.call(item, ctx)
+ }
+ }
+ } else if tree, ok := node.(*TomlTree); ok {
+ item := tree.values[f.Name]
+ if item != nil {
+ f.next.call(item, ctx)
+ }
+ }
+}
+
+// match single index
+type matchIndexFn struct {
+ matchBase
+ Idx int
+}
+
+func newMatchIndexFn(idx int) *matchIndexFn {
+ return &matchIndexFn{Idx: idx}
+}
+
+func (f *matchIndexFn) call(node interface{}, ctx *queryContext) {
+ if arr, ok := tomlValueCheck(node, ctx).([]interface{}); ok {
+ if f.Idx < len(arr) && f.Idx >= 0 {
+ f.next.call(arr[f.Idx], ctx)
+ }
+ }
+}
+
+// filter by slicing
+type matchSliceFn struct {
+ matchBase
+ Start, End, Step int
+}
+
+func newMatchSliceFn(start, end, step int) *matchSliceFn {
+ return &matchSliceFn{Start: start, End: end, Step: step}
+}
+
+func (f *matchSliceFn) call(node interface{}, ctx *queryContext) {
+ if arr, ok := tomlValueCheck(node, ctx).([]interface{}); ok {
+ // adjust indexes for negative values, reverse ordering
+ realStart, realEnd := f.Start, f.End
+ if realStart < 0 {
+ realStart = len(arr) + realStart
+ }
+ if realEnd < 0 {
+ realEnd = len(arr) + realEnd
+ }
+ if realEnd < realStart {
+ realEnd, realStart = realStart, realEnd // swap
+ }
+ // loop and gather
+ for idx := realStart; idx < realEnd; idx += f.Step {
+ f.next.call(arr[idx], ctx)
+ }
+ }
+}
+
+// match anything
+type matchAnyFn struct {
+ matchBase
+}
+
+func newMatchAnyFn() *matchAnyFn {
+ return &matchAnyFn{}
+}
+
+func (f *matchAnyFn) call(node interface{}, ctx *queryContext) {
+ if tree, ok := node.(*TomlTree); ok {
+ for _, v := range tree.values {
+ f.next.call(v, ctx)
+ }
+ }
+}
+
+// filter through union
+type matchUnionFn struct {
+ Union []pathFn
+}
+
+func (f *matchUnionFn) setNext(next pathFn) {
+ for _, fn := range f.Union {
+ fn.setNext(next)
+ }
+}
+
+func (f *matchUnionFn) call(node interface{}, ctx *queryContext) {
+ for _, fn := range f.Union {
+ fn.call(node, ctx)
+ }
+}
+
+// match every single last node in the tree
+type matchRecursiveFn struct {
+ matchBase
+}
+
+func newMatchRecursiveFn() *matchRecursiveFn {
+ return &matchRecursiveFn{}
+}
+
+func (f *matchRecursiveFn) call(node interface{}, ctx *queryContext) {
+ if tree, ok := node.(*TomlTree); ok {
+ var visit func(tree *TomlTree)
+ visit = func(tree *TomlTree) {
+ for _, v := range tree.values {
+ f.next.call(v, ctx)
+ switch node := v.(type) {
+ case *TomlTree:
+ visit(node)
+ case []*TomlTree:
+ for _, subtree := range node {
+ visit(subtree)
+ }
+ }
+ }
+ }
+ f.next.call(tree, ctx)
+ visit(tree)
+ }
+}
+
+// match based on an externally provided functional filter
+type matchFilterFn struct {
+ matchBase
+ Pos Position
+ Name string
+}
+
+func newMatchFilterFn(name string, pos Position) *matchFilterFn {
+ return &matchFilterFn{Name: name, Pos: pos}
+}
+
+func (f *matchFilterFn) call(node interface{}, ctx *queryContext) {
+ fn, ok := (*ctx.filters)[f.Name]
+ if !ok {
+ panic(fmt.Sprintf("%s: query context does not have filter '%s'",
+ f.Pos.String(), f.Name))
+ }
+ switch castNode := tomlValueCheck(node, ctx).(type) {
+ case *TomlTree:
+ for _, v := range castNode.values {
+ if tv, ok := v.(*tomlValue); ok {
+ if fn(tv.value) {
+ f.next.call(v, ctx)
+ }
+ } else {
+ if fn(v) {
+ f.next.call(v, ctx)
+ }
+ }
+ }
+ case []interface{}:
+ for _, v := range castNode {
+ if fn(v) {
+ f.next.call(v, ctx)
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/pelletier/go-toml/match_test.go b/vendor/github.com/pelletier/go-toml/match_test.go
new file mode 100644
index 000000000..b63654ad2
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/match_test.go
@@ -0,0 +1,201 @@
+package toml
+
+import (
+ "fmt"
+ "testing"
+)
+
+// dump path tree to a string
+func pathString(root pathFn) string {
+ result := fmt.Sprintf("%T:", root)
+ switch fn := root.(type) {
+ case *terminatingFn:
+ result += "{}"
+ case *matchKeyFn:
+ result += fmt.Sprintf("{%s}", fn.Name)
+ result += pathString(fn.next)
+ case *matchIndexFn:
+ result += fmt.Sprintf("{%d}", fn.Idx)
+ result += pathString(fn.next)
+ case *matchSliceFn:
+ result += fmt.Sprintf("{%d:%d:%d}",
+ fn.Start, fn.End, fn.Step)
+ result += pathString(fn.next)
+ case *matchAnyFn:
+ result += "{}"
+ result += pathString(fn.next)
+ case *matchUnionFn:
+ result += "{["
+ for _, v := range fn.Union {
+ result += pathString(v) + ", "
+ }
+ result += "]}"
+ case *matchRecursiveFn:
+ result += "{}"
+ result += pathString(fn.next)
+ case *matchFilterFn:
+ result += fmt.Sprintf("{%s}", fn.Name)
+ result += pathString(fn.next)
+ }
+ return result
+}
+
+func assertPathMatch(t *testing.T, path, ref *Query) bool {
+ pathStr := pathString(path.root)
+ refStr := pathString(ref.root)
+ if pathStr != refStr {
+ t.Errorf("paths do not match")
+ t.Log("test:", pathStr)
+ t.Log("ref: ", refStr)
+ return false
+ }
+ return true
+}
+
+func assertPath(t *testing.T, query string, ref *Query) {
+ path, _ := parseQuery(lexQuery(query))
+ assertPathMatch(t, path, ref)
+}
+
+func buildPath(parts ...pathFn) *Query {
+ query := newQuery()
+ for _, v := range parts {
+ query.appendPath(v)
+ }
+ return query
+}
+
+func TestPathRoot(t *testing.T) {
+ assertPath(t,
+ "$",
+ buildPath(
+ // empty
+ ))
+}
+
+func TestPathKey(t *testing.T) {
+ assertPath(t,
+ "$.foo",
+ buildPath(
+ newMatchKeyFn("foo"),
+ ))
+}
+
+func TestPathBracketKey(t *testing.T) {
+ assertPath(t,
+ "$[foo]",
+ buildPath(
+ newMatchKeyFn("foo"),
+ ))
+}
+
+func TestPathBracketStringKey(t *testing.T) {
+ assertPath(t,
+ "$['foo']",
+ buildPath(
+ newMatchKeyFn("foo"),
+ ))
+}
+
+func TestPathIndex(t *testing.T) {
+ assertPath(t,
+ "$[123]",
+ buildPath(
+ newMatchIndexFn(123),
+ ))
+}
+
+func TestPathSliceStart(t *testing.T) {
+ assertPath(t,
+ "$[123:]",
+ buildPath(
+ newMatchSliceFn(123, maxInt, 1),
+ ))
+}
+
+func TestPathSliceStartEnd(t *testing.T) {
+ assertPath(t,
+ "$[123:456]",
+ buildPath(
+ newMatchSliceFn(123, 456, 1),
+ ))
+}
+
+func TestPathSliceStartEndColon(t *testing.T) {
+ assertPath(t,
+ "$[123:456:]",
+ buildPath(
+ newMatchSliceFn(123, 456, 1),
+ ))
+}
+
+func TestPathSliceStartStep(t *testing.T) {
+ assertPath(t,
+ "$[123::7]",
+ buildPath(
+ newMatchSliceFn(123, maxInt, 7),
+ ))
+}
+
+func TestPathSliceEndStep(t *testing.T) {
+ assertPath(t,
+ "$[:456:7]",
+ buildPath(
+ newMatchSliceFn(0, 456, 7),
+ ))
+}
+
+func TestPathSliceStep(t *testing.T) {
+ assertPath(t,
+ "$[::7]",
+ buildPath(
+ newMatchSliceFn(0, maxInt, 7),
+ ))
+}
+
+func TestPathSliceAll(t *testing.T) {
+ assertPath(t,
+ "$[123:456:7]",
+ buildPath(
+ newMatchSliceFn(123, 456, 7),
+ ))
+}
+
+func TestPathAny(t *testing.T) {
+ assertPath(t,
+ "$.*",
+ buildPath(
+ newMatchAnyFn(),
+ ))
+}
+
+func TestPathUnion(t *testing.T) {
+ assertPath(t,
+ "$[foo, bar, baz]",
+ buildPath(
+ &matchUnionFn{[]pathFn{
+ newMatchKeyFn("foo"),
+ newMatchKeyFn("bar"),
+ newMatchKeyFn("baz"),
+ }},
+ ))
+}
+
+func TestPathRecurse(t *testing.T) {
+ assertPath(t,
+ "$..*",
+ buildPath(
+ newMatchRecursiveFn(),
+ ))
+}
+
+func TestPathFilterExpr(t *testing.T) {
+ assertPath(t,
+ "$[?('foo'),?(bar)]",
+ buildPath(
+ &matchUnionFn{[]pathFn{
+ newMatchFilterFn("foo", Position{}),
+ newMatchFilterFn("bar", Position{}),
+ }},
+ ))
+}
diff --git a/vendor/github.com/pelletier/go-toml/parser.go b/vendor/github.com/pelletier/go-toml/parser.go
new file mode 100644
index 000000000..20e90a3ed
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/parser.go
@@ -0,0 +1,393 @@
+// TOML Parser.
+
+package toml
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+)
+
+type tomlParser struct {
+ flow chan token
+ tree *TomlTree
+ tokensBuffer []token
+ currentTable []string
+ seenTableKeys []string
+}
+
+type tomlParserStateFn func() tomlParserStateFn
+
+// Formats and panics an error message based on a token
+func (p *tomlParser) raiseError(tok *token, msg string, args ...interface{}) {
+ panic(tok.Position.String() + ": " + fmt.Sprintf(msg, args...))
+}
+
+func (p *tomlParser) run() {
+ for state := p.parseStart; state != nil; {
+ state = state()
+ }
+}
+
+func (p *tomlParser) peek() *token {
+ if len(p.tokensBuffer) != 0 {
+ return &(p.tokensBuffer[0])
+ }
+
+ tok, ok := <-p.flow
+ if !ok {
+ return nil
+ }
+ p.tokensBuffer = append(p.tokensBuffer, tok)
+ return &tok
+}
+
+func (p *tomlParser) assume(typ tokenType) {
+ tok := p.getToken()
+ if tok == nil {
+ p.raiseError(tok, "was expecting token %s, but token stream is empty", tok)
+ }
+ if tok.typ != typ {
+ p.raiseError(tok, "was expecting token %s, but got %s instead", typ, tok)
+ }
+}
+
+func (p *tomlParser) getToken() *token {
+ if len(p.tokensBuffer) != 0 {
+ tok := p.tokensBuffer[0]
+ p.tokensBuffer = p.tokensBuffer[1:]
+ return &tok
+ }
+ tok, ok := <-p.flow
+ if !ok {
+ return nil
+ }
+ return &tok
+}
+
+func (p *tomlParser) parseStart() tomlParserStateFn {
+ tok := p.peek()
+
+ // end of stream, parsing is finished
+ if tok == nil {
+ return nil
+ }
+
+ switch tok.typ {
+ case tokenDoubleLeftBracket:
+ return p.parseGroupArray
+ case tokenLeftBracket:
+ return p.parseGroup
+ case tokenKey:
+ return p.parseAssign
+ case tokenEOF:
+ return nil
+ default:
+ p.raiseError(tok, "unexpected token")
+ }
+ return nil
+}
+
+func (p *tomlParser) parseGroupArray() tomlParserStateFn {
+ startToken := p.getToken() // discard the [[
+ key := p.getToken()
+ if key.typ != tokenKeyGroupArray {
+ p.raiseError(key, "unexpected token %s, was expecting a table array key", key)
+ }
+
+ // get or create table array element at the indicated part in the path
+ keys, err := parseKey(key.val)
+ if err != nil {
+ p.raiseError(key, "invalid table array key: %s", err)
+ }
+ p.tree.createSubTree(keys[:len(keys)-1], startToken.Position) // create parent entries
+ destTree := p.tree.GetPath(keys)
+ var array []*TomlTree
+ if destTree == nil {
+ array = make([]*TomlTree, 0)
+ } else if target, ok := destTree.([]*TomlTree); ok && target != nil {
+ array = destTree.([]*TomlTree)
+ } else {
+ p.raiseError(key, "key %s is already assigned and not of type table array", key)
+ }
+ p.currentTable = keys
+
+ // add a new tree to the end of the table array
+ newTree := newTomlTree()
+ newTree.position = startToken.Position
+ array = append(array, newTree)
+ p.tree.SetPath(p.currentTable, array)
+
+ // remove all keys that were children of this table array
+ prefix := key.val + "."
+ found := false
+ for ii := 0; ii < len(p.seenTableKeys); {
+ tableKey := p.seenTableKeys[ii]
+ if strings.HasPrefix(tableKey, prefix) {
+ p.seenTableKeys = append(p.seenTableKeys[:ii], p.seenTableKeys[ii+1:]...)
+ } else {
+ found = (tableKey == key.val)
+ ii++
+ }
+ }
+
+ // keep this key name from use by other kinds of assignments
+ if !found {
+ p.seenTableKeys = append(p.seenTableKeys, key.val)
+ }
+
+ // move to next parser state
+ p.assume(tokenDoubleRightBracket)
+ return p.parseStart
+}
+
+func (p *tomlParser) parseGroup() tomlParserStateFn {
+ startToken := p.getToken() // discard the [
+ key := p.getToken()
+ if key.typ != tokenKeyGroup {
+ p.raiseError(key, "unexpected token %s, was expecting a table key", key)
+ }
+ for _, item := range p.seenTableKeys {
+ if item == key.val {
+ p.raiseError(key, "duplicated tables")
+ }
+ }
+
+ p.seenTableKeys = append(p.seenTableKeys, key.val)
+ keys, err := parseKey(key.val)
+ if err != nil {
+ p.raiseError(key, "invalid table array key: %s", err)
+ }
+ if err := p.tree.createSubTree(keys, startToken.Position); err != nil {
+ p.raiseError(key, "%s", err)
+ }
+ p.assume(tokenRightBracket)
+ p.currentTable = keys
+ return p.parseStart
+}
+
+func (p *tomlParser) parseAssign() tomlParserStateFn {
+ key := p.getToken()
+ p.assume(tokenEqual)
+
+ value := p.parseRvalue()
+ var tableKey []string
+ if len(p.currentTable) > 0 {
+ tableKey = p.currentTable
+ } else {
+ tableKey = []string{}
+ }
+
+ // find the table to assign, looking out for arrays of tables
+ var targetNode *TomlTree
+ switch node := p.tree.GetPath(tableKey).(type) {
+ case []*TomlTree:
+ targetNode = node[len(node)-1]
+ case *TomlTree:
+ targetNode = node
+ default:
+ p.raiseError(key, "Unknown table type for path: %s",
+ strings.Join(tableKey, "."))
+ }
+
+ // assign value to the found table
+ keyVals, err := parseKey(key.val)
+ if err != nil {
+ p.raiseError(key, "%s", err)
+ }
+ if len(keyVals) != 1 {
+ p.raiseError(key, "Invalid key")
+ }
+ keyVal := keyVals[0]
+ localKey := []string{keyVal}
+ finalKey := append(tableKey, keyVal)
+ if targetNode.GetPath(localKey) != nil {
+ p.raiseError(key, "The following key was defined twice: %s",
+ strings.Join(finalKey, "."))
+ }
+ var toInsert interface{}
+
+ switch value.(type) {
+ case *TomlTree, []*TomlTree:
+ toInsert = value
+ default:
+ toInsert = &tomlValue{value, key.Position}
+ }
+ targetNode.values[keyVal] = toInsert
+ return p.parseStart
+}
+
+var numberUnderscoreInvalidRegexp *regexp.Regexp
+
+func cleanupNumberToken(value string) (string, error) {
+ if numberUnderscoreInvalidRegexp.MatchString(value) {
+ return "", errors.New("invalid use of _ in number")
+ }
+ cleanedVal := strings.Replace(value, "_", "", -1)
+ return cleanedVal, nil
+}
+
+func (p *tomlParser) parseRvalue() interface{} {
+ tok := p.getToken()
+ if tok == nil || tok.typ == tokenEOF {
+ p.raiseError(tok, "expecting a value")
+ }
+
+ switch tok.typ {
+ case tokenString:
+ return tok.val
+ case tokenTrue:
+ return true
+ case tokenFalse:
+ return false
+ case tokenInteger:
+ cleanedVal, err := cleanupNumberToken(tok.val)
+ if err != nil {
+ p.raiseError(tok, "%s", err)
+ }
+ val, err := strconv.ParseInt(cleanedVal, 10, 64)
+ if err != nil {
+ p.raiseError(tok, "%s", err)
+ }
+ return val
+ case tokenFloat:
+ cleanedVal, err := cleanupNumberToken(tok.val)
+ if err != nil {
+ p.raiseError(tok, "%s", err)
+ }
+ val, err := strconv.ParseFloat(cleanedVal, 64)
+ if err != nil {
+ p.raiseError(tok, "%s", err)
+ }
+ return val
+ case tokenDate:
+ val, err := time.ParseInLocation(time.RFC3339Nano, tok.val, time.UTC)
+ if err != nil {
+ p.raiseError(tok, "%s", err)
+ }
+ return val
+ case tokenLeftBracket:
+ return p.parseArray()
+ case tokenLeftCurlyBrace:
+ return p.parseInlineTable()
+ case tokenEqual:
+ p.raiseError(tok, "cannot have multiple equals for the same key")
+ case tokenError:
+ p.raiseError(tok, "%s", tok)
+ }
+
+ p.raiseError(tok, "never reached")
+
+ return nil
+}
+
+func tokenIsComma(t *token) bool {
+ return t != nil && t.typ == tokenComma
+}
+
+func (p *tomlParser) parseInlineTable() *TomlTree {
+ tree := newTomlTree()
+ var previous *token
+Loop:
+ for {
+ follow := p.peek()
+ if follow == nil || follow.typ == tokenEOF {
+ p.raiseError(follow, "unterminated inline table")
+ }
+ switch follow.typ {
+ case tokenRightCurlyBrace:
+ p.getToken()
+ break Loop
+ case tokenKey:
+ if !tokenIsComma(previous) && previous != nil {
+ p.raiseError(follow, "comma expected between fields in inline table")
+ }
+ key := p.getToken()
+ p.assume(tokenEqual)
+ value := p.parseRvalue()
+ tree.Set(key.val, value)
+ case tokenComma:
+ if previous == nil {
+ p.raiseError(follow, "inline table cannot start with a comma")
+ }
+ if tokenIsComma(previous) {
+ p.raiseError(follow, "need field between two commas in inline table")
+ }
+ p.getToken()
+ default:
+ p.raiseError(follow, "unexpected token type in inline table: %s", follow.typ.String())
+ }
+ previous = follow
+ }
+ if tokenIsComma(previous) {
+ p.raiseError(previous, "trailing comma at the end of inline table")
+ }
+ return tree
+}
+
+func (p *tomlParser) parseArray() interface{} {
+ var array []interface{}
+ arrayType := reflect.TypeOf(nil)
+ for {
+ follow := p.peek()
+ if follow == nil || follow.typ == tokenEOF {
+ p.raiseError(follow, "unterminated array")
+ }
+ if follow.typ == tokenRightBracket {
+ p.getToken()
+ break
+ }
+ val := p.parseRvalue()
+ if arrayType == nil {
+ arrayType = reflect.TypeOf(val)
+ }
+ if reflect.TypeOf(val) != arrayType {
+ p.raiseError(follow, "mixed types in array")
+ }
+ array = append(array, val)
+ follow = p.peek()
+ if follow == nil || follow.typ == tokenEOF {
+ p.raiseError(follow, "unterminated array")
+ }
+ if follow.typ != tokenRightBracket && follow.typ != tokenComma {
+ p.raiseError(follow, "missing comma")
+ }
+ if follow.typ == tokenComma {
+ p.getToken()
+ }
+ }
+ // An array of TomlTrees is actually an array of inline
+ // tables, which is a shorthand for a table array. If the
+ // array was not converted from []interface{} to []*TomlTree,
+ // the two notations would not be equivalent.
+ if arrayType == reflect.TypeOf(newTomlTree()) {
+ tomlArray := make([]*TomlTree, len(array))
+ for i, v := range array {
+ tomlArray[i] = v.(*TomlTree)
+ }
+ return tomlArray
+ }
+ return array
+}
+
+func parseToml(flow chan token) *TomlTree {
+ result := newTomlTree()
+ result.position = Position{1, 1}
+ parser := &tomlParser{
+ flow: flow,
+ tree: result,
+ tokensBuffer: make([]token, 0),
+ currentTable: make([]string, 0),
+ seenTableKeys: make([]string, 0),
+ }
+ parser.run()
+ return result
+}
+
+func init() {
+ numberUnderscoreInvalidRegexp = regexp.MustCompile(`([^\d]_|_[^\d]|_$|^_)`)
+}
diff --git a/vendor/github.com/pelletier/go-toml/parser_test.go b/vendor/github.com/pelletier/go-toml/parser_test.go
new file mode 100644
index 000000000..58aae203a
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/parser_test.go
@@ -0,0 +1,785 @@
+package toml
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/davecgh/go-spew/spew"
+)
+
+func assertSubTree(t *testing.T, path []string, tree *TomlTree, err error, ref map[string]interface{}) {
+ if err != nil {
+ t.Error("Non-nil error:", err.Error())
+ return
+ }
+ for k, v := range ref {
+ nextPath := append(path, k)
+ t.Log("asserting path", nextPath)
+ // NOTE: directly access key instead of resolve by path
+ // NOTE: see TestSpecialKV
+ switch node := tree.GetPath([]string{k}).(type) {
+ case []*TomlTree:
+ t.Log("\tcomparing key", nextPath, "by array iteration")
+ for idx, item := range node {
+ assertSubTree(t, nextPath, item, err, v.([]map[string]interface{})[idx])
+ }
+ case *TomlTree:
+ t.Log("\tcomparing key", nextPath, "by subtree assestion")
+ assertSubTree(t, nextPath, node, err, v.(map[string]interface{}))
+ default:
+ t.Log("\tcomparing key", nextPath, "by string representation because it's of type", reflect.TypeOf(node))
+ if fmt.Sprintf("%v", node) != fmt.Sprintf("%v", v) {
+ t.Errorf("was expecting %v at %v but got %v", v, k, node)
+ }
+ }
+ }
+}
+
+func assertTree(t *testing.T, tree *TomlTree, err error, ref map[string]interface{}) {
+ t.Log("Asserting tree:\n", spew.Sdump(tree))
+ assertSubTree(t, []string{}, tree, err, ref)
+ t.Log("Finished tree assertion.")
+}
+
+func TestCreateSubTree(t *testing.T) {
+ tree := newTomlTree()
+ tree.createSubTree([]string{"a", "b", "c"}, Position{})
+ tree.Set("a.b.c", 42)
+ if tree.Get("a.b.c") != 42 {
+ t.Fail()
+ }
+}
+
+func TestSimpleKV(t *testing.T) {
+ tree, err := Load("a = 42")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": int64(42),
+ })
+
+ tree, _ = Load("a = 42\nb = 21")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": int64(42),
+ "b": int64(21),
+ })
+}
+
+func TestNumberInKey(t *testing.T) {
+ tree, err := Load("hello2 = 42")
+ assertTree(t, tree, err, map[string]interface{}{
+ "hello2": int64(42),
+ })
+}
+
+func TestSimpleNumbers(t *testing.T) {
+ tree, err := Load("a = +42\nb = -21\nc = +4.2\nd = -2.1")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": int64(42),
+ "b": int64(-21),
+ "c": float64(4.2),
+ "d": float64(-2.1),
+ })
+}
+
+func TestNumbersWithUnderscores(t *testing.T) {
+ tree, err := Load("a = 1_000")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": int64(1000),
+ })
+
+ tree, err = Load("a = 5_349_221")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": int64(5349221),
+ })
+
+ tree, err = Load("a = 1_2_3_4_5")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": int64(12345),
+ })
+
+ tree, err = Load("flt8 = 9_224_617.445_991_228_313")
+ assertTree(t, tree, err, map[string]interface{}{
+ "flt8": float64(9224617.445991228313),
+ })
+
+ tree, err = Load("flt9 = 1e1_00")
+ assertTree(t, tree, err, map[string]interface{}{
+ "flt9": float64(1e100),
+ })
+}
+
+func TestFloatsWithExponents(t *testing.T) {
+ tree, err := Load("a = 5e+22\nb = 5E+22\nc = -5e+22\nd = -5e-22\ne = 6.626e-34")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": float64(5e+22),
+ "b": float64(5E+22),
+ "c": float64(-5e+22),
+ "d": float64(-5e-22),
+ "e": float64(6.626e-34),
+ })
+}
+
+func TestSimpleDate(t *testing.T) {
+ tree, err := Load("a = 1979-05-27T07:32:00Z")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
+ })
+}
+
+func TestDateOffset(t *testing.T) {
+ tree, err := Load("a = 1979-05-27T00:32:00-07:00")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": time.Date(1979, time.May, 27, 0, 32, 0, 0, time.FixedZone("", -7*60*60)),
+ })
+}
+
+func TestDateNano(t *testing.T) {
+ tree, err := Load("a = 1979-05-27T00:32:00.999999999-07:00")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": time.Date(1979, time.May, 27, 0, 32, 0, 999999999, time.FixedZone("", -7*60*60)),
+ })
+}
+
+func TestSimpleString(t *testing.T) {
+ tree, err := Load("a = \"hello world\"")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": "hello world",
+ })
+}
+
+func TestSpaceKey(t *testing.T) {
+ tree, err := Load("\"a b\" = \"hello world\"")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a b": "hello world",
+ })
+}
+
+func TestStringEscapables(t *testing.T) {
+ tree, err := Load("a = \"a \\n b\"")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": "a \n b",
+ })
+
+ tree, err = Load("a = \"a \\t b\"")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": "a \t b",
+ })
+
+ tree, err = Load("a = \"a \\r b\"")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": "a \r b",
+ })
+
+ tree, err = Load("a = \"a \\\\ b\"")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": "a \\ b",
+ })
+}
+
+func TestEmptyQuotedString(t *testing.T) {
+ tree, err := Load(`[""]
+"" = 1`)
+ assertTree(t, tree, err, map[string]interface{}{
+ "": map[string]interface{}{
+ "": int64(1),
+ },
+ })
+}
+
+func TestBools(t *testing.T) {
+ tree, err := Load("a = true\nb = false")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": true,
+ "b": false,
+ })
+}
+
+func TestNestedKeys(t *testing.T) {
+ tree, err := Load("[a.b.c]\nd = 42")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": map[string]interface{}{
+ "b": map[string]interface{}{
+ "c": map[string]interface{}{
+ "d": int64(42),
+ },
+ },
+ },
+ })
+}
+
+func TestNestedQuotedUnicodeKeys(t *testing.T) {
+ tree, err := Load("[ j . \"ʞ\" . l ]\nd = 42")
+ assertTree(t, tree, err, map[string]interface{}{
+ "j": map[string]interface{}{
+ "ʞ": map[string]interface{}{
+ "l": map[string]interface{}{
+ "d": int64(42),
+ },
+ },
+ },
+ })
+
+ tree, err = Load("[ g . h . i ]\nd = 42")
+ assertTree(t, tree, err, map[string]interface{}{
+ "g": map[string]interface{}{
+ "h": map[string]interface{}{
+ "i": map[string]interface{}{
+ "d": int64(42),
+ },
+ },
+ },
+ })
+
+ tree, err = Load("[ d.e.f ]\nk = 42")
+ assertTree(t, tree, err, map[string]interface{}{
+ "d": map[string]interface{}{
+ "e": map[string]interface{}{
+ "f": map[string]interface{}{
+ "k": int64(42),
+ },
+ },
+ },
+ })
+}
+
+func TestArrayOne(t *testing.T) {
+ tree, err := Load("a = [1]")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": []int64{int64(1)},
+ })
+}
+
+func TestArrayZero(t *testing.T) {
+ tree, err := Load("a = []")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": []interface{}{},
+ })
+}
+
+func TestArraySimple(t *testing.T) {
+ tree, err := Load("a = [42, 21, 10]")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": []int64{int64(42), int64(21), int64(10)},
+ })
+
+ tree, _ = Load("a = [42, 21, 10,]")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": []int64{int64(42), int64(21), int64(10)},
+ })
+}
+
+func TestArrayMultiline(t *testing.T) {
+ tree, err := Load("a = [42,\n21, 10,]")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": []int64{int64(42), int64(21), int64(10)},
+ })
+}
+
+func TestArrayNested(t *testing.T) {
+ tree, err := Load("a = [[42, 21], [10]]")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": [][]int64{{int64(42), int64(21)}, {int64(10)}},
+ })
+}
+
+func TestNestedArrayComment(t *testing.T) {
+ tree, err := Load(`
+someArray = [
+# does not work
+["entry1"]
+]`)
+ assertTree(t, tree, err, map[string]interface{}{
+ "someArray": [][]string{{"entry1"}},
+ })
+}
+
+func TestNestedEmptyArrays(t *testing.T) {
+ tree, err := Load("a = [[[]]]")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": [][][]interface{}{{{}}},
+ })
+}
+
+func TestArrayMixedTypes(t *testing.T) {
+ _, err := Load("a = [42, 16.0]")
+ if err.Error() != "(1, 10): mixed types in array" {
+ t.Error("Bad error message:", err.Error())
+ }
+
+ _, err = Load("a = [42, \"hello\"]")
+ if err.Error() != "(1, 11): mixed types in array" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestArrayNestedStrings(t *testing.T) {
+ tree, err := Load("data = [ [\"gamma\", \"delta\"], [\"Foo\"] ]")
+ assertTree(t, tree, err, map[string]interface{}{
+ "data": [][]string{{"gamma", "delta"}, {"Foo"}},
+ })
+}
+
+func TestParseUnknownRvalue(t *testing.T) {
+ _, err := Load("a = !bssss")
+ if err == nil {
+ t.Error("Expecting a parse error")
+ }
+
+ _, err = Load("a = /b")
+ if err == nil {
+ t.Error("Expecting a parse error")
+ }
+}
+
+func TestMissingValue(t *testing.T) {
+ _, err := Load("a = ")
+ if err.Error() != "(1, 5): expecting a value" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestUnterminatedArray(t *testing.T) {
+ _, err := Load("a = [1,")
+ if err.Error() != "(1, 8): unterminated array" {
+ t.Error("Bad error message:", err.Error())
+ }
+
+ _, err = Load("a = [1")
+ if err.Error() != "(1, 7): unterminated array" {
+ t.Error("Bad error message:", err.Error())
+ }
+
+ _, err = Load("a = [1 2")
+ if err.Error() != "(1, 8): missing comma" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestNewlinesInArrays(t *testing.T) {
+ tree, err := Load("a = [1,\n2,\n3]")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": []int64{int64(1), int64(2), int64(3)},
+ })
+}
+
+func TestArrayWithExtraComma(t *testing.T) {
+ tree, err := Load("a = [1,\n2,\n3,\n]")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": []int64{int64(1), int64(2), int64(3)},
+ })
+}
+
+func TestArrayWithExtraCommaComment(t *testing.T) {
+ tree, err := Load("a = [1, # wow\n2, # such items\n3, # so array\n]")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": []int64{int64(1), int64(2), int64(3)},
+ })
+}
+
+func TestSimpleInlineGroup(t *testing.T) {
+ tree, err := Load("key = {a = 42}")
+ assertTree(t, tree, err, map[string]interface{}{
+ "key": map[string]interface{}{
+ "a": int64(42),
+ },
+ })
+}
+
+func TestDoubleInlineGroup(t *testing.T) {
+ tree, err := Load("key = {a = 42, b = \"foo\"}")
+ assertTree(t, tree, err, map[string]interface{}{
+ "key": map[string]interface{}{
+ "a": int64(42),
+ "b": "foo",
+ },
+ })
+}
+
+func TestExampleInlineGroup(t *testing.T) {
+ tree, err := Load(`name = { first = "Tom", last = "Preston-Werner" }
+point = { x = 1, y = 2 }`)
+ assertTree(t, tree, err, map[string]interface{}{
+ "name": map[string]interface{}{
+ "first": "Tom",
+ "last": "Preston-Werner",
+ },
+ "point": map[string]interface{}{
+ "x": int64(1),
+ "y": int64(2),
+ },
+ })
+}
+
+func TestExampleInlineGroupInArray(t *testing.T) {
+ tree, err := Load(`points = [{ x = 1, y = 2 }]`)
+ assertTree(t, tree, err, map[string]interface{}{
+ "points": []map[string]interface{}{
+ {
+ "x": int64(1),
+ "y": int64(2),
+ },
+ },
+ })
+}
+
+func TestInlineTableUnterminated(t *testing.T) {
+ _, err := Load("foo = {")
+ if err.Error() != "(1, 8): unterminated inline table" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestInlineTableCommaExpected(t *testing.T) {
+ _, err := Load("foo = {hello = 53 test = foo}")
+ if err.Error() != "(1, 19): comma expected between fields in inline table" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestInlineTableCommaStart(t *testing.T) {
+ _, err := Load("foo = {, hello = 53}")
+ if err.Error() != "(1, 8): inline table cannot start with a comma" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestInlineTableDoubleComma(t *testing.T) {
+ _, err := Load("foo = {hello = 53,, foo = 17}")
+ if err.Error() != "(1, 19): need field between two commas in inline table" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestDuplicateGroups(t *testing.T) {
+ _, err := Load("[foo]\na=2\n[foo]b=3")
+ if err.Error() != "(3, 2): duplicated tables" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestDuplicateKeys(t *testing.T) {
+ _, err := Load("foo = 2\nfoo = 3")
+ if err.Error() != "(2, 1): The following key was defined twice: foo" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestEmptyIntermediateTable(t *testing.T) {
+ _, err := Load("[foo..bar]")
+ if err.Error() != "(1, 2): invalid table array key: empty table key" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestImplicitDeclarationBefore(t *testing.T) {
+ tree, err := Load("[a.b.c]\nanswer = 42\n[a]\nbetter = 43")
+ assertTree(t, tree, err, map[string]interface{}{
+ "a": map[string]interface{}{
+ "b": map[string]interface{}{
+ "c": map[string]interface{}{
+ "answer": int64(42),
+ },
+ },
+ "better": int64(43),
+ },
+ })
+}
+
+func TestFloatsWithoutLeadingZeros(t *testing.T) {
+ _, err := Load("a = .42")
+ if err.Error() != "(1, 5): cannot start float with a dot" {
+ t.Error("Bad error message:", err.Error())
+ }
+
+ _, err = Load("a = -.42")
+ if err.Error() != "(1, 5): cannot start float with a dot" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestMissingFile(t *testing.T) {
+ _, err := LoadFile("foo.toml")
+ if err.Error() != "open foo.toml: no such file or directory" &&
+ err.Error() != "open foo.toml: The system cannot find the file specified." {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestParseFile(t *testing.T) {
+ tree, err := LoadFile("example.toml")
+
+ assertTree(t, tree, err, map[string]interface{}{
+ "title": "TOML Example",
+ "owner": map[string]interface{}{
+ "name": "Tom Preston-Werner",
+ "organization": "GitHub",
+ "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.",
+ "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
+ },
+ "database": map[string]interface{}{
+ "server": "192.168.1.1",
+ "ports": []int64{8001, 8001, 8002},
+ "connection_max": 5000,
+ "enabled": true,
+ },
+ "servers": map[string]interface{}{
+ "alpha": map[string]interface{}{
+ "ip": "10.0.0.1",
+ "dc": "eqdc10",
+ },
+ "beta": map[string]interface{}{
+ "ip": "10.0.0.2",
+ "dc": "eqdc10",
+ },
+ },
+ "clients": map[string]interface{}{
+ "data": []interface{}{
+ []string{"gamma", "delta"},
+ []int64{1, 2},
+ },
+ },
+ })
+}
+
+func TestParseFileCRLF(t *testing.T) {
+ tree, err := LoadFile("example-crlf.toml")
+
+ assertTree(t, tree, err, map[string]interface{}{
+ "title": "TOML Example",
+ "owner": map[string]interface{}{
+ "name": "Tom Preston-Werner",
+ "organization": "GitHub",
+ "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.",
+ "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
+ },
+ "database": map[string]interface{}{
+ "server": "192.168.1.1",
+ "ports": []int64{8001, 8001, 8002},
+ "connection_max": 5000,
+ "enabled": true,
+ },
+ "servers": map[string]interface{}{
+ "alpha": map[string]interface{}{
+ "ip": "10.0.0.1",
+ "dc": "eqdc10",
+ },
+ "beta": map[string]interface{}{
+ "ip": "10.0.0.2",
+ "dc": "eqdc10",
+ },
+ },
+ "clients": map[string]interface{}{
+ "data": []interface{}{
+ []string{"gamma", "delta"},
+ []int64{1, 2},
+ },
+ },
+ })
+}
+
+func TestParseKeyGroupArray(t *testing.T) {
+ tree, err := Load("[[foo.bar]] a = 42\n[[foo.bar]] a = 69")
+ assertTree(t, tree, err, map[string]interface{}{
+ "foo": map[string]interface{}{
+ "bar": []map[string]interface{}{
+ {"a": int64(42)},
+ {"a": int64(69)},
+ },
+ },
+ })
+}
+
+func TestParseKeyGroupArrayUnfinished(t *testing.T) {
+ _, err := Load("[[foo.bar]\na = 42")
+ if err.Error() != "(1, 10): was expecting token [[, but got unclosed table array key instead" {
+ t.Error("Bad error message:", err.Error())
+ }
+
+ _, err = Load("[[foo.[bar]\na = 42")
+ if err.Error() != "(1, 3): unexpected token table array key cannot contain ']', was expecting a table array key" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestParseKeyGroupArrayQueryExample(t *testing.T) {
+ tree, err := Load(`
+ [[book]]
+ title = "The Stand"
+ author = "Stephen King"
+ [[book]]
+ title = "For Whom the Bell Tolls"
+ author = "Ernest Hemmingway"
+ [[book]]
+ title = "Neuromancer"
+ author = "William Gibson"
+ `)
+
+ assertTree(t, tree, err, map[string]interface{}{
+ "book": []map[string]interface{}{
+ {"title": "The Stand", "author": "Stephen King"},
+ {"title": "For Whom the Bell Tolls", "author": "Ernest Hemmingway"},
+ {"title": "Neuromancer", "author": "William Gibson"},
+ },
+ })
+}
+
+func TestParseKeyGroupArraySpec(t *testing.T) {
+ tree, err := Load("[[fruit]]\n name=\"apple\"\n [fruit.physical]\n color=\"red\"\n shape=\"round\"\n [[fruit]]\n name=\"banana\"")
+ assertTree(t, tree, err, map[string]interface{}{
+ "fruit": []map[string]interface{}{
+ {"name": "apple", "physical": map[string]interface{}{"color": "red", "shape": "round"}},
+ {"name": "banana"},
+ },
+ })
+}
+
+func TestTomlValueStringRepresentation(t *testing.T) {
+ for idx, item := range []struct {
+ Value interface{}
+ Expect string
+ }{
+ {int64(12345), "12345"},
+ {uint64(50), "50"},
+ {float64(123.45), "123.45"},
+ {bool(true), "true"},
+ {"hello world", "\"hello world\""},
+ {"\b\t\n\f\r\"\\", "\"\\b\\t\\n\\f\\r\\\"\\\\\""},
+ {"\x05", "\"\\u0005\""},
+ {time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
+ "1979-05-27T07:32:00Z"},
+ {[]interface{}{"gamma", "delta"},
+ "[\"gamma\",\"delta\"]"},
+ {nil, ""},
+ } {
+ result, err := tomlValueStringRepresentation(item.Value)
+ if err != nil {
+ t.Errorf("Test %d - unexpected error: %s", idx, err)
+ }
+ if result != item.Expect {
+ t.Errorf("Test %d - got '%s', expected '%s'", idx, result, item.Expect)
+ }
+ }
+}
+
+func TestToStringMapStringString(t *testing.T) {
+ tree, err := TreeFromMap(map[string]interface{}{"m": map[string]interface{}{"v": "abc"}})
+ if err != nil {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ want := "\n[m]\n v = \"abc\"\n"
+ got := tree.String()
+
+ if got != want {
+ t.Errorf("want:\n%q\ngot:\n%q", want, got)
+ }
+}
+
+func assertPosition(t *testing.T, text string, ref map[string]Position) {
+ tree, err := Load(text)
+ if err != nil {
+ t.Errorf("Error loading document text: `%v`", text)
+ t.Errorf("Error: %v", err)
+ }
+ for path, pos := range ref {
+ testPos := tree.GetPosition(path)
+ if testPos.Invalid() {
+ t.Errorf("Failed to query tree path or path has invalid position: %s", path)
+ } else if pos != testPos {
+ t.Errorf("Expected position %v, got %v instead", pos, testPos)
+ }
+ }
+}
+
+func TestDocumentPositions(t *testing.T) {
+ assertPosition(t,
+ "[foo]\nbar=42\nbaz=69",
+ map[string]Position{
+ "": {1, 1},
+ "foo": {1, 1},
+ "foo.bar": {2, 1},
+ "foo.baz": {3, 1},
+ })
+}
+
+func TestDocumentPositionsWithSpaces(t *testing.T) {
+ assertPosition(t,
+ " [foo]\n bar=42\n baz=69",
+ map[string]Position{
+ "": {1, 1},
+ "foo": {1, 3},
+ "foo.bar": {2, 3},
+ "foo.baz": {3, 3},
+ })
+}
+
+func TestDocumentPositionsWithGroupArray(t *testing.T) {
+ assertPosition(t,
+ "[[foo]]\nbar=42\nbaz=69",
+ map[string]Position{
+ "": {1, 1},
+ "foo": {1, 1},
+ "foo.bar": {2, 1},
+ "foo.baz": {3, 1},
+ })
+}
+
+func TestNestedTreePosition(t *testing.T) {
+ assertPosition(t,
+ "[foo.bar]\na=42\nb=69",
+ map[string]Position{
+ "": {1, 1},
+ "foo": {1, 1},
+ "foo.bar": {1, 1},
+ "foo.bar.a": {2, 1},
+ "foo.bar.b": {3, 1},
+ })
+}
+
+func TestInvalidGroupArray(t *testing.T) {
+ _, err := Load("[table#key]\nanswer = 42")
+ if err == nil {
+ t.Error("Should error")
+ }
+
+ _, err = Load("[foo.[bar]\na = 42")
+ if err.Error() != "(1, 2): unexpected token table key cannot contain ']', was expecting a table key" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestDoubleEqual(t *testing.T) {
+ _, err := Load("foo= = 2")
+ if err.Error() != "(1, 6): cannot have multiple equals for the same key" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestGroupArrayReassign(t *testing.T) {
+ _, err := Load("[hello]\n[[hello]]")
+ if err.Error() != "(2, 3): key \"hello\" is already assigned and not of type table array" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
+
+func TestInvalidFloatParsing(t *testing.T) {
+ _, err := Load("a=1e_2")
+ if err.Error() != "(1, 3): invalid use of _ in number" {
+ t.Error("Bad error message:", err.Error())
+ }
+
+ _, err = Load("a=1e2_")
+ if err.Error() != "(1, 3): invalid use of _ in number" {
+ t.Error("Bad error message:", err.Error())
+ }
+
+ _, err = Load("a=1__2")
+ if err.Error() != "(1, 3): invalid use of _ in number" {
+ t.Error("Bad error message:", err.Error())
+ }
+
+ _, err = Load("a=_1_2")
+ if err.Error() != "(1, 3): cannot start number with underscore" {
+ t.Error("Bad error message:", err.Error())
+ }
+}
diff --git a/vendor/github.com/pelletier/go-toml/position.go b/vendor/github.com/pelletier/go-toml/position.go
new file mode 100644
index 000000000..c17bff87b
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/position.go
@@ -0,0 +1,29 @@
+// Position support for go-toml
+
+package toml
+
+import (
+ "fmt"
+)
+
+// Position of a document element within a TOML document.
+//
+// Line and Col are both 1-indexed positions for the element's line number and
+// column number, respectively. Values of zero or less will cause Invalid(),
+// to return true.
+type Position struct {
+ Line int // line within the document
+ Col int // column within the line
+}
+
+// String representation of the position.
+// Displays 1-indexed line and column numbers.
+func (p Position) String() string {
+ return fmt.Sprintf("(%d, %d)", p.Line, p.Col)
+}
+
+// Invalid returns whether or not the position is valid (i.e. with negative or
+// null values)
+func (p Position) Invalid() bool {
+ return p.Line <= 0 || p.Col <= 0
+}
diff --git a/vendor/github.com/pelletier/go-toml/position_test.go b/vendor/github.com/pelletier/go-toml/position_test.go
new file mode 100644
index 000000000..63ad1afc8
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/position_test.go
@@ -0,0 +1,29 @@
+// Testing support for go-toml
+
+package toml
+
+import (
+ "testing"
+)
+
+func TestPositionString(t *testing.T) {
+ p := Position{123, 456}
+ expected := "(123, 456)"
+ value := p.String()
+
+ if value != expected {
+ t.Errorf("Expected %v, got %v instead", expected, value)
+ }
+}
+
+func TestInvalid(t *testing.T) {
+ for i, v := range []Position{
+ {0, 1234},
+ {1234, 0},
+ {0, 0},
+ } {
+ if !v.Invalid() {
+ t.Errorf("Position at %v is valid: %v", i, v)
+ }
+ }
+}
diff --git a/vendor/github.com/pelletier/go-toml/query.go b/vendor/github.com/pelletier/go-toml/query.go
new file mode 100644
index 000000000..307a1ecab
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/query.go
@@ -0,0 +1,153 @@
+package toml
+
+import (
+ "time"
+)
+
+// NodeFilterFn represents a user-defined filter function, for use with
+// Query.SetFilter().
+//
+// The return value of the function must indicate if 'node' is to be included
+// at this stage of the TOML path. Returning true will include the node, and
+// returning false will exclude it.
+//
+// NOTE: Care should be taken to write script callbacks such that they are safe
+// to use from multiple goroutines.
+type NodeFilterFn func(node interface{}) bool
+
+// QueryResult is the result of Executing a Query.
+type QueryResult struct {
+ items []interface{}
+ positions []Position
+}
+
+// appends a value/position pair to the result set.
+func (r *QueryResult) appendResult(node interface{}, pos Position) {
+ r.items = append(r.items, node)
+ r.positions = append(r.positions, pos)
+}
+
+// Values is a set of values within a QueryResult. The order of values is not
+// guaranteed to be in document order, and may be different each time a query is
+// executed.
+func (r QueryResult) Values() []interface{} {
+ values := make([]interface{}, len(r.items))
+ for i, v := range r.items {
+ o, ok := v.(*tomlValue)
+ if ok {
+ values[i] = o.value
+ } else {
+ values[i] = v
+ }
+ }
+ return values
+}
+
+// Positions is a set of positions for values within a QueryResult. Each index
+// in Positions() corresponds to the entry in Value() of the same index.
+func (r QueryResult) Positions() []Position {
+ return r.positions
+}
+
+// runtime context for executing query paths
+type queryContext struct {
+ result *QueryResult
+ filters *map[string]NodeFilterFn
+ lastPosition Position
+}
+
+// generic path functor interface
+type pathFn interface {
+ setNext(next pathFn)
+ call(node interface{}, ctx *queryContext)
+}
+
+// A Query is the representation of a compiled TOML path. A Query is safe
+// for concurrent use by multiple goroutines.
+type Query struct {
+ root pathFn
+ tail pathFn
+ filters *map[string]NodeFilterFn
+}
+
+func newQuery() *Query {
+ return &Query{
+ root: nil,
+ tail: nil,
+ filters: &defaultFilterFunctions,
+ }
+}
+
+func (q *Query) appendPath(next pathFn) {
+ if q.root == nil {
+ q.root = next
+ } else {
+ q.tail.setNext(next)
+ }
+ q.tail = next
+ next.setNext(newTerminatingFn()) // init the next functor
+}
+
+// CompileQuery compiles a TOML path expression. The returned Query can be used
+// to match elements within a TomlTree and its descendants.
+func CompileQuery(path string) (*Query, error) {
+ return parseQuery(lexQuery(path))
+}
+
+// Execute executes a query against a TomlTree, and returns the result of the query.
+func (q *Query) Execute(tree *TomlTree) *QueryResult {
+ result := &QueryResult{
+ items: []interface{}{},
+ positions: []Position{},
+ }
+ if q.root == nil {
+ result.appendResult(tree, tree.GetPosition(""))
+ } else {
+ ctx := &queryContext{
+ result: result,
+ filters: q.filters,
+ }
+ q.root.call(tree, ctx)
+ }
+ return result
+}
+
+// SetFilter sets a user-defined filter function. These may be used inside
+// "?(..)" query expressions to filter TOML document elements within a query.
+func (q *Query) SetFilter(name string, fn NodeFilterFn) {
+ if q.filters == &defaultFilterFunctions {
+ // clone the static table
+ q.filters = &map[string]NodeFilterFn{}
+ for k, v := range defaultFilterFunctions {
+ (*q.filters)[k] = v
+ }
+ }
+ (*q.filters)[name] = fn
+}
+
+var defaultFilterFunctions = map[string]NodeFilterFn{
+ "tree": func(node interface{}) bool {
+ _, ok := node.(*TomlTree)
+ return ok
+ },
+ "int": func(node interface{}) bool {
+ _, ok := node.(int64)
+ return ok
+ },
+ "float": func(node interface{}) bool {
+ _, ok := node.(float64)
+ return ok
+ },
+ "string": func(node interface{}) bool {
+ _, ok := node.(string)
+ return ok
+ },
+ "time": func(node interface{}) bool {
+ _, ok := node.(time.Time)
+ return ok
+ },
+ "bool": func(node interface{}) bool {
+ _, ok := node.(bool)
+ return ok
+ },
+}
diff --git a/vendor/github.com/pelletier/go-toml/query_test.go b/vendor/github.com/pelletier/go-toml/query_test.go
new file mode 100644
index 000000000..0d9f3832b
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/query_test.go
@@ -0,0 +1,70 @@
+package toml
+
+import (
+ "testing"
+)
+
+func assertArrayContainsInAnyOrder(t *testing.T, array []interface{}, objects ...interface{}) {
+ if len(array) != len(objects) {
+ t.Fatalf("array contains %d objects but %d are expected", len(array), len(objects))
+ }
+
+ for _, o := range objects {
+ found := false
+ for _, a := range array {
+ if a == o {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatal(o, "not found in array", array)
+ }
+ }
+}
+
+func TestQueryExample(t *testing.T) {
+ config, _ := Load(`
+ [[book]]
+ title = "The Stand"
+ author = "Stephen King"
+ [[book]]
+ title = "For Whom the Bell Tolls"
+ author = "Ernest Hemmingway"
+ [[book]]
+ title = "Neuromancer"
+ author = "William Gibson"
+ `)
+
+ authors, _ := config.Query("$.book.author")
+ names := authors.Values()
+ if len(names) != 3 {
+ t.Fatalf("query should return 3 names but returned %d", len(names))
+ }
+ assertArrayContainsInAnyOrder(t, names, "Stephen King", "Ernest Hemmingway", "William Gibson")
+}
+
+func TestQueryReadmeExample(t *testing.T) {
+ config, _ := Load(`
+[postgres]
+user = "pelletier"
+password = "mypassword"
+`)
+ results, _ := config.Query("$..[user,password]")
+ values := results.Values()
+ if len(values) != 2 {
+ t.Fatalf("query should return 2 values but returned %d", len(values))
+ }
+ assertArrayContainsInAnyOrder(t, values, "pelletier", "mypassword")
+}
+
+func TestQueryPathNotPresent(t *testing.T) {
+ config, _ := Load(`a = "hello"`)
+ results, err := config.Query("$.foo.bar")
+ if err != nil {
+ t.Fatalf("err should be nil. got %s instead", err)
+ }
+ if len(results.items) != 0 {
+ t.Fatalf("no items should be matched. %d matched instead", len(results.items))
+ }
+}
diff --git a/vendor/github.com/pelletier/go-toml/querylexer.go b/vendor/github.com/pelletier/go-toml/querylexer.go
new file mode 100644
index 000000000..960681d0f
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/querylexer.go
@@ -0,0 +1,356 @@
+// TOML JSONPath lexer.
+//
+// Written using the principles developed by Rob Pike in
+// http://www.youtube.com/watch?v=HxaD_trXwRE
+
+package toml
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+)
+
+// Lexer state function
+type queryLexStateFn func() queryLexStateFn
+
+// Lexer definition
+type queryLexer struct {
+ input string
+ start int
+ pos int
+ width int
+ tokens chan token
+ depth int
+ line int
+ col int
+ stringTerm string
+}
+
+func (l *queryLexer) run() {
+ for state := l.lexVoid; state != nil; {
+ state = state()
+ }
+ close(l.tokens)
+}
+
+func (l *queryLexer) nextStart() {
+ // iterate by runes (utf8 characters)
+ // search for newlines and advance line/col counts
+ for i := l.start; i < l.pos; {
+ r, width := utf8.DecodeRuneInString(l.input[i:])
+ if r == '\n' {
+ l.line++
+ l.col = 1
+ } else {
+ l.col++
+ }
+ i += width
+ }
+ // advance start position to next token
+ l.start = l.pos
+}
+
+func (l *queryLexer) emit(t tokenType) {
+ l.tokens <- token{
+ Position: Position{l.line, l.col},
+ typ: t,
+ val: l.input[l.start:l.pos],
+ }
+ l.nextStart()
+}
+
+func (l *queryLexer) emitWithValue(t tokenType, value string) {
+ l.tokens <- token{
+ Position: Position{l.line, l.col},
+ typ: t,
+ val: value,
+ }
+ l.nextStart()
+}
+
+func (l *queryLexer) next() rune {
+ if l.pos >= len(l.input) {
+ l.width = 0
+ return eof
+ }
+ var r rune
+ r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
+ l.pos += l.width
+ return r
+}
+
+func (l *queryLexer) ignore() {
+ l.nextStart()
+}
+
+func (l *queryLexer) backup() {
+ l.pos -= l.width
+}
+
+func (l *queryLexer) errorf(format string, args ...interface{}) queryLexStateFn {
+ l.tokens <- token{
+ Position: Position{l.line, l.col},
+ typ: tokenError,
+ val: fmt.Sprintf(format, args...),
+ }
+ return nil
+}
+
+func (l *queryLexer) peek() rune {
+ r := l.next()
+ l.backup()
+ return r
+}
+
+func (l *queryLexer) accept(valid string) bool {
+ if strings.ContainsRune(valid, l.next()) {
+ return true
+ }
+ l.backup()
+ return false
+}
+
+func (l *queryLexer) follow(next string) bool {
+ return strings.HasPrefix(l.input[l.pos:], next)
+}
+
+func (l *queryLexer) lexVoid() queryLexStateFn {
+ for {
+ next := l.peek()
+ switch next {
+ case '$':
+ l.pos++
+ l.emit(tokenDollar)
+ continue
+ case '.':
+ if l.follow("..") {
+ l.pos += 2
+ l.emit(tokenDotDot)
+ } else {
+ l.pos++
+ l.emit(tokenDot)
+ }
+ continue
+ case '[':
+ l.pos++
+ l.emit(tokenLeftBracket)
+ continue
+ case ']':
+ l.pos++
+ l.emit(tokenRightBracket)
+ continue
+ case ',':
+ l.pos++
+ l.emit(tokenComma)
+ continue
+ case '*':
+ l.pos++
+ l.emit(tokenStar)
+ continue
+ case '(':
+ l.pos++
+ l.emit(tokenLeftParen)
+ continue
+ case ')':
+ l.pos++
+ l.emit(tokenRightParen)
+ continue
+ case '?':
+ l.pos++
+ l.emit(tokenQuestion)
+ continue
+ case ':':
+ l.pos++
+ l.emit(tokenColon)
+ continue
+ case '\'':
+ l.ignore()
+ l.stringTerm = string(next)
+ return l.lexString
+ case '"':
+ l.ignore()
+ l.stringTerm = string(next)
+ return l.lexString
+ }
+
+ if isSpace(next) {
+ l.next()
+ l.ignore()
+ continue
+ }
+
+ if isAlphanumeric(next) {
+ return l.lexKey
+ }
+
+ if next == '+' || next == '-' || isDigit(next) {
+ return l.lexNumber
+ }
+
+ if l.next() == eof {
+ break
+ }
+
+ return l.errorf("unexpected char: '%v'", next)
+ }
+ l.emit(tokenEOF)
+ return nil
+}
+
+func (l *queryLexer) lexKey() queryLexStateFn {
+ for {
+ next := l.peek()
+ if !isAlphanumeric(next) {
+ l.emit(tokenKey)
+ return l.lexVoid
+ }
+
+ if l.next() == eof {
+ break
+ }
+ }
+ l.emit(tokenEOF)
+ return nil
+}
+
+func (l *queryLexer) lexString() queryLexStateFn {
+ l.pos++
+ l.ignore()
+ growingString := ""
+
+ for {
+ if l.follow(l.stringTerm) {
+ l.emitWithValue(tokenString, growingString)
+ l.pos++
+ l.ignore()
+ return l.lexVoid
+ }
+
+ if l.follow("\\\"") {
+ l.pos++
+ growingString += "\""
+ } else if l.follow("\\'") {
+ l.pos++
+ growingString += "'"
+ } else if l.follow("\\n") {
+ l.pos++
+ growingString += "\n"
+ } else if l.follow("\\b") {
+ l.pos++
+ growingString += "\b"
+ } else if l.follow("\\f") {
+ l.pos++
+ growingString += "\f"
+ } else if l.follow("\\/") {
+ l.pos++
+ growingString += "/"
+ } else if l.follow("\\t") {
+ l.pos++
+ growingString += "\t"
+ } else if l.follow("\\r") {
+ l.pos++
+ growingString += "\r"
+ } else if l.follow("\\\\") {
+ l.pos++
+ growingString += "\\"
+ } else if l.follow("\\u") {
+ l.pos += 2
+ code := ""
+ for i := 0; i < 4; i++ {
+ c := l.peek()
+ l.pos++
+ if !isHexDigit(c) {
+ return l.errorf("unfinished unicode escape")
+ }
+ code = code + string(c)
+ }
+ l.pos--
+ intcode, err := strconv.ParseInt(code, 16, 32)
+ if err != nil {
+ return l.errorf("invalid unicode escape: \\u" + code)
+ }
+ growingString += string(rune(intcode))
+ } else if l.follow("\\U") {
+ l.pos += 2
+ code := ""
+ for i := 0; i < 8; i++ {
+ c := l.peek()
+ l.pos++
+ if !isHexDigit(c) {
+ return l.errorf("unfinished unicode escape")
+ }
+ code = code + string(c)
+ }
+ l.pos--
+ intcode, err := strconv.ParseInt(code, 16, 32)
+ if err != nil {
+ return l.errorf("invalid unicode escape: \\u" + code)
+ }
+ growingString += string(rune(intcode))
+ } else if l.follow("\\") {
+ l.pos++
+ return l.errorf("invalid escape sequence: \\" + string(l.peek()))
+ } else {
+ growingString += string(l.peek())
+ }
+
+ if l.next() == eof {
+ break
+ }
+ }
+
+ return l.errorf("unclosed string")
+}
+
+func (l *queryLexer) lexNumber() queryLexStateFn {
+ l.ignore()
+ if !l.accept("+") {
+ l.accept("-")
+ }
+ pointSeen := false
+ digitSeen := false
+ for {
+ next := l.next()
+ if next == '.' {
+ if pointSeen {
+ return l.errorf("cannot have two dots in one float")
+ }
+ if !isDigit(l.peek()) {
+ return l.errorf("float cannot end with a dot")
+ }
+ pointSeen = true
+ } else if isDigit(next) {
+ digitSeen = true
+ } else {
+ l.backup()
+ break
+ }
+ if pointSeen && !digitSeen {
+ return l.errorf("cannot start float with a dot")
+ }
+ }
+
+ if !digitSeen {
+ return l.errorf("no digit in that number")
+ }
+ if pointSeen {
+ l.emit(tokenFloat)
+ } else {
+ l.emit(tokenInteger)
+ }
+ return l.lexVoid
+}
+
+// Entry point
+func lexQuery(input string) chan token {
+ l := &queryLexer{
+ input: input,
+ tokens: make(chan token),
+ line: 1,
+ col: 1,
+ }
+ go l.run()
+ return l.tokens
+}
diff --git a/vendor/github.com/pelletier/go-toml/querylexer_test.go b/vendor/github.com/pelletier/go-toml/querylexer_test.go
new file mode 100644
index 000000000..2d0803ff7
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/querylexer_test.go
@@ -0,0 +1,178 @@
+package toml
+
+import (
+ "testing"
+)
+
+func testQLFlow(t *testing.T, input string, expectedFlow []token) {
+ ch := lexQuery(input)
+ for idx, expected := range expectedFlow {
+ token := <-ch
+ if token != expected {
+ t.Log("While testing #", idx, ":", input)
+ t.Log("compared (got)", token, "to (expected)", expected)
+ t.Log("\tvalue:", token.val, "<->", expected.val)
+ t.Log("\tvalue as bytes:", []byte(token.val), "<->", []byte(expected.val))
+ t.Log("\ttype:", token.typ.String(), "<->", expected.typ.String())
+ t.Log("\tline:", token.Line, "<->", expected.Line)
+ t.Log("\tcolumn:", token.Col, "<->", expected.Col)
+ t.Log("compared", token, "to", expected)
+ t.FailNow()
+ }
+ }
+
+ tok, ok := <-ch
+ if ok {
+ t.Log("channel is not closed!")
+ t.Log(len(ch)+1, "tokens remaining:")
+
+ t.Log("token ->", tok)
+ for token := range ch {
+ t.Log("token ->", token)
+ }
+ t.FailNow()
+ }
+}
+
+func TestLexSpecialChars(t *testing.T) {
+ testQLFlow(t, " .$[]..()?*", []token{
+ {Position{1, 2}, tokenDot, "."},
+ {Position{1, 3}, tokenDollar, "$"},
+ {Position{1, 4}, tokenLeftBracket, "["},
+ {Position{1, 5}, tokenRightBracket, "]"},
+ {Position{1, 6}, tokenDotDot, ".."},
+ {Position{1, 8}, tokenLeftParen, "("},
+ {Position{1, 9}, tokenRightParen, ")"},
+ {Position{1, 10}, tokenQuestion, "?"},
+ {Position{1, 11}, tokenStar, "*"},
+ {Position{1, 12}, tokenEOF, ""},
+ })
+}
+
+func TestLexString(t *testing.T) {
+ testQLFlow(t, "'foo\n'", []token{
+ {Position{1, 2}, tokenString, "foo\n"},
+ {Position{2, 2}, tokenEOF, ""},
+ })
+}
+
+func TestLexDoubleString(t *testing.T) {
+ testQLFlow(t, `"bar"`, []token{
+ {Position{1, 2}, tokenString, "bar"},
+ {Position{1, 6}, tokenEOF, ""},
+ })
+}
+
+func TestLexStringEscapes(t *testing.T) {
+ testQLFlow(t, `"foo \" \' \b \f \/ \t \r \\ \u03A9 \U00012345 \n bar"`, []token{
+ {Position{1, 2}, tokenString, "foo \" ' \b \f / \t \r \\ \u03A9 \U00012345 \n bar"},
+ {Position{1, 55}, tokenEOF, ""},
+ })
+}
+
+func TestLexStringUnfinishedUnicode4(t *testing.T) {
+ testQLFlow(t, `"\u000"`, []token{
+ {Position{1, 2}, tokenError, "unfinished unicode escape"},
+ })
+}
+
+func TestLexStringUnfinishedUnicode8(t *testing.T) {
+ testQLFlow(t, `"\U0000"`, []token{
+ {Position{1, 2}, tokenError, "unfinished unicode escape"},
+ })
+}
+
+func TestLexStringInvalidEscape(t *testing.T) {
+ testQLFlow(t, `"\x"`, []token{
+ {Position{1, 2}, tokenError, "invalid escape sequence: \\x"},
+ })
+}
+
+func TestLexStringUnfinished(t *testing.T) {
+ testQLFlow(t, `"bar`, []token{
+ {Position{1, 2}, tokenError, "unclosed string"},
+ })
+}
+
+func TestLexKey(t *testing.T) {
+ testQLFlow(t, "foo", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 4}, tokenEOF, ""},
+ })
+}
+
+func TestLexRecurse(t *testing.T) {
+ testQLFlow(t, "$..*", []token{
+ {Position{1, 1}, tokenDollar, "$"},
+ {Position{1, 2}, tokenDotDot, ".."},
+ {Position{1, 4}, tokenStar, "*"},
+ {Position{1, 5}, tokenEOF, ""},
+ })
+}
+
+func TestLexBracketKey(t *testing.T) {
+ testQLFlow(t, "$[foo]", []token{
+ {Position{1, 1}, tokenDollar, "$"},
+ {Position{1, 2}, tokenLeftBracket, "["},
+ {Position{1, 3}, tokenKey, "foo"},
+ {Position{1, 6}, tokenRightBracket, "]"},
+ {Position{1, 7}, tokenEOF, ""},
+ })
+}
+
+func TestLexSpace(t *testing.T) {
+ testQLFlow(t, "foo bar baz", []token{
+ {Position{1, 1}, tokenKey, "foo"},
+ {Position{1, 5}, tokenKey, "bar"},
+ {Position{1, 9}, tokenKey, "baz"},
+ {Position{1, 12}, tokenEOF, ""},
+ })
+}
+
+func TestLexInteger(t *testing.T) {
+ testQLFlow(t, "100 +200 -300", []token{
+ {Position{1, 1}, tokenInteger, "100"},
+ {Position{1, 5}, tokenInteger, "+200"},
+ {Position{1, 10}, tokenInteger, "-300"},
+ {Position{1, 14}, tokenEOF, ""},
+ })
+}
+
+func TestLexFloat(t *testing.T) {
+ testQLFlow(t, "100.0 +200.0 -300.0", []token{
+ {Position{1, 1}, tokenFloat, "100.0"},
+ {Position{1, 7}, tokenFloat, "+200.0"},
+ {Position{1, 14}, tokenFloat, "-300.0"},
+ {Position{1, 20}, tokenEOF, ""},
+ })
+}
+
+func TestLexFloatWithMultipleDots(t *testing.T) {
+ testQLFlow(t, "4.2.", []token{
+ {Position{1, 1}, tokenError, "cannot have two dots in one float"},
+ })
+}
+
+func TestLexFloatLeadingDot(t *testing.T) {
+ testQLFlow(t, "+.1", []token{
+ {Position{1, 1}, tokenError, "cannot start float with a dot"},
+ })
+}
+
+func TestLexFloatWithTrailingDot(t *testing.T) {
+ testQLFlow(t, "42.", []token{
+ {Position{1, 1}, tokenError, "float cannot end with a dot"},
+ })
+}
+
+func TestLexNumberWithoutDigit(t *testing.T) {
+ testQLFlow(t, "+", []token{
+ {Position{1, 1}, tokenError, "no digit in that number"},
+ })
+}
+
+func TestLexUnknown(t *testing.T) {
+ testQLFlow(t, "^", []token{
+ {Position{1, 1}, tokenError, "unexpected char: '94'"},
+ })
+}
diff --git a/vendor/github.com/pelletier/go-toml/queryparser.go b/vendor/github.com/pelletier/go-toml/queryparser.go
new file mode 100644
index 000000000..1cbfc83b2
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/queryparser.go
@@ -0,0 +1,275 @@
+/*
+ Based on the "jsonpath" spec/concept.
+
+ http://goessner.net/articles/JsonPath/
+ https://code.google.com/p/json-path/
+*/
+
+package toml
+
+import (
+ "fmt"
+)
+
+const maxInt = int(^uint(0) >> 1)
+
+type queryParser struct {
+ flow chan token
+ tokensBuffer []token
+ query *Query
+ union []pathFn
+ err error
+}
+
+type queryParserStateFn func() queryParserStateFn
+
+// Formats and panics an error message based on a token
+func (p *queryParser) parseError(tok *token, msg string, args ...interface{}) queryParserStateFn {
+ p.err = fmt.Errorf(tok.Position.String()+": "+msg, args...)
+ return nil // trigger parse to end
+}
+
+func (p *queryParser) run() {
+ for state := p.parseStart; state != nil; {
+ state = state()
+ }
+}
+
+func (p *queryParser) backup(tok *token) {
+ p.tokensBuffer = append(p.tokensBuffer, *tok)
+}
+
+func (p *queryParser) peek() *token {
+ if len(p.tokensBuffer) != 0 {
+ return &(p.tokensBuffer[0])
+ }
+
+ tok, ok := <-p.flow
+ if !ok {
+ return nil
+ }
+ p.backup(&tok)
+ return &tok
+}
+
+func (p *queryParser) lookahead(types ...tokenType) bool {
+ result := true
+ buffer := []token{}
+
+ for _, typ := range types {
+ tok := p.getToken()
+ if tok == nil {
+ result = false
+ break
+ }
+ buffer = append(buffer, *tok)
+ if tok.typ != typ {
+ result = false
+ break
+ }
+ }
+ // add the tokens back to the buffer, and return
+ p.tokensBuffer = append(p.tokensBuffer, buffer...)
+ return result
+}
+
+func (p *queryParser) getToken() *token {
+ if len(p.tokensBuffer) != 0 {
+ tok := p.tokensBuffer[0]
+ p.tokensBuffer = p.tokensBuffer[1:]
+ return &tok
+ }
+ tok, ok := <-p.flow
+ if !ok {
+ return nil
+ }
+ return &tok
+}
+
+func (p *queryParser) parseStart() queryParserStateFn {
+ tok := p.getToken()
+
+ if tok == nil || tok.typ == tokenEOF {
+ return nil
+ }
+
+ if tok.typ != tokenDollar {
+ return p.parseError(tok, "Expected '$' at start of expression")
+ }
+
+ return p.parseMatchExpr
+}
+
+// handle '.' prefix, '[]', and '..'
+func (p *queryParser) parseMatchExpr() queryParserStateFn {
+ tok := p.getToken()
+ switch tok.typ {
+ case tokenDotDot:
+ p.query.appendPath(&matchRecursiveFn{})
+ // nested parse for '..'
+ tok := p.getToken()
+ switch tok.typ {
+ case tokenKey:
+ p.query.appendPath(newMatchKeyFn(tok.val))
+ return p.parseMatchExpr
+ case tokenLeftBracket:
+ return p.parseBracketExpr
+ case tokenStar:
+ // do nothing - the recursive predicate is enough
+ return p.parseMatchExpr
+ }
+
+ case tokenDot:
+ // nested parse for '.'
+ tok := p.getToken()
+ switch tok.typ {
+ case tokenKey:
+ p.query.appendPath(newMatchKeyFn(tok.val))
+ return p.parseMatchExpr
+ case tokenStar:
+ p.query.appendPath(&matchAnyFn{})
+ return p.parseMatchExpr
+ }
+
+ case tokenLeftBracket:
+ return p.parseBracketExpr
+
+ case tokenEOF:
+ return nil // allow EOF at this stage
+ }
+ return p.parseError(tok, "expected match expression")
+}
+
+func (p *queryParser) parseBracketExpr() queryParserStateFn {
+ if p.lookahead(tokenInteger, tokenColon) {
+ return p.parseSliceExpr
+ }
+ if p.peek().typ == tokenColon {
+ return p.parseSliceExpr
+ }
+ return p.parseUnionExpr
+}
+
+func (p *queryParser) parseUnionExpr() queryParserStateFn {
+ var tok *token
+
+ // this state can be traversed after some sub-expressions
+ // so be careful when setting up state in the parser
+ if p.union == nil {
+ p.union = []pathFn{}
+ }
+
+loop: // labeled loop for easy breaking
+ for {
+ if len(p.union) > 0 {
+ // parse delimiter or terminator
+ tok = p.getToken()
+ switch tok.typ {
+ case tokenComma:
+ // do nothing
+ case tokenRightBracket:
+ break loop
+ default:
+ return p.parseError(tok, "expected ',' or ']', not '%s'", tok.val)
+ }
+ }
+
+ // parse sub expression
+ tok = p.getToken()
+ switch tok.typ {
+ case tokenInteger:
+ p.union = append(p.union, newMatchIndexFn(tok.Int()))
+ case tokenKey:
+ p.union = append(p.union, newMatchKeyFn(tok.val))
+ case tokenString:
+ p.union = append(p.union, newMatchKeyFn(tok.val))
+ case tokenQuestion:
+ return p.parseFilterExpr
+ default:
+ return p.parseError(tok, "expected union sub expression, not '%s', %d", tok.val, len(p.union))
+ }
+ }
+
+ // if there is only one sub-expression, use that instead
+ if len(p.union) == 1 {
+ p.query.appendPath(p.union[0])
+ } else {
+ p.query.appendPath(&matchUnionFn{p.union})
+ }
+
+ p.union = nil // clear out state
+ return p.parseMatchExpr
+}
+
+func (p *queryParser) parseSliceExpr() queryParserStateFn {
+ // init slice to grab all elements
+ start, end, step := 0, maxInt, 1
+
+ // parse optional start
+ tok := p.getToken()
+ if tok.typ == tokenInteger {
+ start = tok.Int()
+ tok = p.getToken()
+ }
+ if tok.typ != tokenColon {
+ return p.parseError(tok, "expected ':'")
+ }
+
+ // parse optional end
+ tok = p.getToken()
+ if tok.typ == tokenInteger {
+ end = tok.Int()
+ tok = p.getToken()
+ }
+ if tok.typ == tokenRightBracket {
+ p.query.appendPath(newMatchSliceFn(start, end, step))
+ return p.parseMatchExpr
+ }
+ if tok.typ != tokenColon {
+ return p.parseError(tok, "expected ']' or ':'")
+ }
+
+ // parse optional step
+ tok = p.getToken()
+ if tok.typ == tokenInteger {
+ step = tok.Int()
+ if step < 0 {
+ return p.parseError(tok, "step must be a positive value")
+ }
+ tok = p.getToken()
+ }
+ if tok.typ != tokenRightBracket {
+ return p.parseError(tok, "expected ']'")
+ }
+
+ p.query.appendPath(newMatchSliceFn(start, end, step))
+ return p.parseMatchExpr
+}
+
+func (p *queryParser) parseFilterExpr() queryParserStateFn {
+ tok := p.getToken()
+ if tok.typ != tokenLeftParen {
+ return p.parseError(tok, "expected left-parenthesis for filter expression")
+ }
+ tok = p.getToken()
+ if tok.typ != tokenKey && tok.typ != tokenString {
+ return p.parseError(tok, "expected key or string for filter funciton name")
+ }
+ name := tok.val
+ tok = p.getToken()
+ if tok.typ != tokenRightParen {
+ return p.parseError(tok, "expected right-parenthesis for filter expression")
+ }
+ p.union = append(p.union, newMatchFilterFn(name, tok.Position))
+ return p.parseUnionExpr
+}
+
+func parseQuery(flow chan token) (*Query, error) {
+ parser := &queryParser{
+ flow: flow,
+ tokensBuffer: []token{},
+ query: newQuery(),
+ }
+ parser.run()
+ return parser.query, parser.err
+}
diff --git a/vendor/github.com/pelletier/go-toml/queryparser_test.go b/vendor/github.com/pelletier/go-toml/queryparser_test.go
new file mode 100644
index 000000000..b2b85cefd
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/queryparser_test.go
@@ -0,0 +1,483 @@
+package toml
+
+import (
+ "fmt"
+ "io/ioutil"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+)
+
+type queryTestNode struct {
+ value interface{}
+ position Position
+}
+
+func valueString(root interface{}) string {
+ result := "" //fmt.Sprintf("%T:", root)
+ switch node := root.(type) {
+ case *tomlValue:
+ return valueString(node.value)
+ case *QueryResult:
+ items := []string{}
+ for i, v := range node.Values() {
+ items = append(items, fmt.Sprintf("%s:%s",
+ node.Positions()[i].String(), valueString(v)))
+ }
+ sort.Strings(items)
+ result = "[" + strings.Join(items, ", ") + "]"
+ case queryTestNode:
+ result = fmt.Sprintf("%s:%s",
+ node.position.String(), valueString(node.value))
+ case []interface{}:
+ items := []string{}
+ for _, v := range node {
+ items = append(items, valueString(v))
+ }
+ sort.Strings(items)
+ result = "[" + strings.Join(items, ", ") + "]"
+ case *TomlTree:
+ // workaround for unreliable map key ordering
+ items := []string{}
+ for _, k := range node.Keys() {
+ v := node.GetPath([]string{k})
+ items = append(items, k+":"+valueString(v))
+ }
+ sort.Strings(items)
+ result = "{" + strings.Join(items, ", ") + "}"
+ case map[string]interface{}:
+ // workaround for unreliable map key ordering
+ items := []string{}
+ for k, v := range node {
+ items = append(items, k+":"+valueString(v))
+ }
+ sort.Strings(items)
+ result = "{" + strings.Join(items, ", ") + "}"
+ case int64:
+ result += fmt.Sprintf("%d", node)
+ case string:
+ result += "'" + node + "'"
+ case float64:
+ result += fmt.Sprintf("%f", node)
+ case bool:
+ result += fmt.Sprintf("%t", node)
+ case time.Time:
+ result += fmt.Sprintf("'%v'", node)
+ }
+ return result
+}
+
+func assertValue(t *testing.T, result, ref interface{}) {
+ pathStr := valueString(result)
+ refStr := valueString(ref)
+ if pathStr != refStr {
+ t.Errorf("values do not match")
+ t.Log("test:", pathStr)
+ t.Log("ref: ", refStr)
+ }
+}
+
+func assertQueryPositions(t *testing.T, toml, query string, ref []interface{}) {
+ tree, err := Load(toml)
+ if err != nil {
+ t.Errorf("Non-nil toml parse error: %v", err)
+ return
+ }
+ q, err := CompileQuery(query)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ results := q.Execute(tree)
+ assertValue(t, results, ref)
+}
+
+func TestQueryRoot(t *testing.T) {
+ assertQueryPositions(t,
+ "a = 42",
+ "$",
+ []interface{}{
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(42),
+ }, Position{1, 1},
+ },
+ })
+}
+
+func TestQueryKey(t *testing.T) {
+ assertQueryPositions(t,
+ "[foo]\na = 42",
+ "$.foo.a",
+ []interface{}{
+ queryTestNode{
+ int64(42), Position{2, 1},
+ },
+ })
+}
+
+func TestQueryKeyString(t *testing.T) {
+ assertQueryPositions(t,
+ "[foo]\na = 42",
+ "$.foo['a']",
+ []interface{}{
+ queryTestNode{
+ int64(42), Position{2, 1},
+ },
+ })
+}
+
+func TestQueryIndex(t *testing.T) {
+ assertQueryPositions(t,
+ "[foo]\na = [1,2,3,4,5,6,7,8,9,0]",
+ "$.foo.a[5]",
+ []interface{}{
+ queryTestNode{
+ int64(6), Position{2, 1},
+ },
+ })
+}
+
+func TestQuerySliceRange(t *testing.T) {
+ assertQueryPositions(t,
+ "[foo]\na = [1,2,3,4,5,6,7,8,9,0]",
+ "$.foo.a[0:5]",
+ []interface{}{
+ queryTestNode{
+ int64(1), Position{2, 1},
+ },
+ queryTestNode{
+ int64(2), Position{2, 1},
+ },
+ queryTestNode{
+ int64(3), Position{2, 1},
+ },
+ queryTestNode{
+ int64(4), Position{2, 1},
+ },
+ queryTestNode{
+ int64(5), Position{2, 1},
+ },
+ })
+}
+
+func TestQuerySliceStep(t *testing.T) {
+ assertQueryPositions(t,
+ "[foo]\na = [1,2,3,4,5,6,7,8,9,0]",
+ "$.foo.a[0:5:2]",
+ []interface{}{
+ queryTestNode{
+ int64(1), Position{2, 1},
+ },
+ queryTestNode{
+ int64(3), Position{2, 1},
+ },
+ queryTestNode{
+ int64(5), Position{2, 1},
+ },
+ })
+}
+
+func TestQueryAny(t *testing.T) {
+ assertQueryPositions(t,
+ "[foo.bar]\na=1\nb=2\n[foo.baz]\na=3\nb=4",
+ "$.foo.*",
+ []interface{}{
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(1),
+ "b": int64(2),
+ }, Position{1, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(3),
+ "b": int64(4),
+ }, Position{4, 1},
+ },
+ })
+}
+func TestQueryUnionSimple(t *testing.T) {
+ assertQueryPositions(t,
+ "[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6",
+ "$.*[bar,foo]",
+ []interface{}{
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(1),
+ "b": int64(2),
+ }, Position{1, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(3),
+ "b": int64(4),
+ }, Position{4, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(5),
+ "b": int64(6),
+ }, Position{7, 1},
+ },
+ })
+}
+
+func TestQueryRecursionAll(t *testing.T) {
+ assertQueryPositions(t,
+ "[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6",
+ "$..*",
+ []interface{}{
+ queryTestNode{
+ map[string]interface{}{
+ "foo": map[string]interface{}{
+ "bar": map[string]interface{}{
+ "a": int64(1),
+ "b": int64(2),
+ },
+ },
+ "baz": map[string]interface{}{
+ "foo": map[string]interface{}{
+ "a": int64(3),
+ "b": int64(4),
+ },
+ },
+ "gorf": map[string]interface{}{
+ "foo": map[string]interface{}{
+ "a": int64(5),
+ "b": int64(6),
+ },
+ },
+ }, Position{1, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "bar": map[string]interface{}{
+ "a": int64(1),
+ "b": int64(2),
+ },
+ }, Position{1, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(1),
+ "b": int64(2),
+ }, Position{1, 1},
+ },
+ queryTestNode{
+ int64(1), Position{2, 1},
+ },
+ queryTestNode{
+ int64(2), Position{3, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "foo": map[string]interface{}{
+ "a": int64(3),
+ "b": int64(4),
+ },
+ }, Position{4, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(3),
+ "b": int64(4),
+ }, Position{4, 1},
+ },
+ queryTestNode{
+ int64(3), Position{5, 1},
+ },
+ queryTestNode{
+ int64(4), Position{6, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "foo": map[string]interface{}{
+ "a": int64(5),
+ "b": int64(6),
+ },
+ }, Position{7, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(5),
+ "b": int64(6),
+ }, Position{7, 1},
+ },
+ queryTestNode{
+ int64(5), Position{8, 1},
+ },
+ queryTestNode{
+ int64(6), Position{9, 1},
+ },
+ })
+}
+
+func TestQueryRecursionUnionSimple(t *testing.T) {
+ assertQueryPositions(t,
+ "[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6",
+ "$..['foo','bar']",
+ []interface{}{
+ queryTestNode{
+ map[string]interface{}{
+ "bar": map[string]interface{}{
+ "a": int64(1),
+ "b": int64(2),
+ },
+ }, Position{1, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(3),
+ "b": int64(4),
+ }, Position{4, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(1),
+ "b": int64(2),
+ }, Position{1, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "a": int64(5),
+ "b": int64(6),
+ }, Position{7, 1},
+ },
+ })
+}
+
+func TestQueryFilterFn(t *testing.T) {
+ buff, err := ioutil.ReadFile("example.toml")
+ if err != nil {
+ t.Error(err)
+ return
+ }
+
+ assertQueryPositions(t, string(buff),
+ "$..[?(int)]",
+ []interface{}{
+ queryTestNode{
+ int64(8001), Position{13, 1},
+ },
+ queryTestNode{
+ int64(8001), Position{13, 1},
+ },
+ queryTestNode{
+ int64(8002), Position{13, 1},
+ },
+ queryTestNode{
+ int64(5000), Position{14, 1},
+ },
+ })
+
+ assertQueryPositions(t, string(buff),
+ "$..[?(string)]",
+ []interface{}{
+ queryTestNode{
+ "TOML Example", Position{3, 1},
+ },
+ queryTestNode{
+ "Tom Preston-Werner", Position{6, 1},
+ },
+ queryTestNode{
+ "GitHub", Position{7, 1},
+ },
+ queryTestNode{
+ "GitHub Cofounder & CEO\nLikes tater tots and beer.",
+ Position{8, 1},
+ },
+ queryTestNode{
+ "192.168.1.1", Position{12, 1},
+ },
+ queryTestNode{
+ "10.0.0.1", Position{21, 3},
+ },
+ queryTestNode{
+ "eqdc10", Position{22, 3},
+ },
+ queryTestNode{
+ "10.0.0.2", Position{25, 3},
+ },
+ queryTestNode{
+ "eqdc10", Position{26, 3},
+ },
+ })
+
+ assertQueryPositions(t, string(buff),
+ "$..[?(float)]",
+ []interface{}{
+ // no float values in document
+ })
+
+ tv, _ := time.Parse(time.RFC3339, "1979-05-27T07:32:00Z")
+ assertQueryPositions(t, string(buff),
+ "$..[?(tree)]",
+ []interface{}{
+ queryTestNode{
+ map[string]interface{}{
+ "name": "Tom Preston-Werner",
+ "organization": "GitHub",
+ "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.",
+ "dob": tv,
+ }, Position{5, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "server": "192.168.1.1",
+ "ports": []interface{}{int64(8001), int64(8001), int64(8002)},
+ "connection_max": int64(5000),
+ "enabled": true,
+ }, Position{11, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "alpha": map[string]interface{}{
+ "ip": "10.0.0.1",
+ "dc": "eqdc10",
+ },
+ "beta": map[string]interface{}{
+ "ip": "10.0.0.2",
+ "dc": "eqdc10",
+ },
+ }, Position{17, 1},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "ip": "10.0.0.1",
+ "dc": "eqdc10",
+ }, Position{20, 3},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "ip": "10.0.0.2",
+ "dc": "eqdc10",
+ }, Position{24, 3},
+ },
+ queryTestNode{
+ map[string]interface{}{
+ "data": []interface{}{
+ []interface{}{"gamma", "delta"},
+ []interface{}{int64(1), int64(2)},
+ },
+ }, Position{28, 1},
+ },
+ })
+
+ assertQueryPositions(t, string(buff),
+ "$..[?(time)]",
+ []interface{}{
+ queryTestNode{
+ tv, Position{9, 1},
+ },
+ })
+
+ assertQueryPositions(t, string(buff),
+ "$..[?(bool)]",
+ []interface{}{
+ queryTestNode{
+ true, Position{15, 1},
+ },
+ })
+}
diff --git a/vendor/github.com/pelletier/go-toml/test.sh b/vendor/github.com/pelletier/go-toml/test.sh
new file mode 100755
index 000000000..436d2fb6c
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/test.sh
@@ -0,0 +1,82 @@
+#!/bin/bash
+# fail out of the script if anything here fails
+set -e
+
+# set the path to the present working directory
+export GOPATH=`pwd`
+
+function git_clone() {
+ path=$1
+ branch=$2
+ version=$3
+ if [ ! -d "src/$path" ]; then
+ mkdir -p src/$path
+ git clone https://$path.git src/$path
+ fi
+ pushd src/$path
+ git checkout "$branch"
+ git reset --hard "$version"
+ popd
+}
+
+# Run go vet
+go vet ./...
+
+go get github.com/pelletier/go-buffruneio
+go get github.com/davecgh/go-spew/spew
+
+# get code for BurntSushi TOML validation
+# pinning all to 'HEAD' for version 0.3.x work (TODO: pin to commit hash when tests stabilize)
+git_clone github.com/BurntSushi/toml master HEAD
+git_clone github.com/BurntSushi/toml-test master HEAD #was: 0.2.0 HEAD
+
+# build the BurntSushi test application
+go build -o toml-test github.com/BurntSushi/toml-test
+
+# vendorize the current lib for testing
+# NOTE: this basically mocks an install without having to go back out to github for code
+mkdir -p src/github.com/pelletier/go-toml/cmd
+cp *.go *.toml src/github.com/pelletier/go-toml
+cp -R cmd/* src/github.com/pelletier/go-toml/cmd
+go build -o test_program_bin src/github.com/pelletier/go-toml/cmd/test_program.go
+
+# Run basic unit tests
+go test github.com/pelletier/go-toml -v -covermode=count -coverprofile=coverage.out
+go test github.com/pelletier/go-toml/cmd/tomljson
+
+# run the entire BurntSushi test suite
+if [[ $# -eq 0 ]] ; then
+ echo "Running all BurntSushi tests"
+ ./toml-test ./test_program_bin | tee test_out
+else
+ # run a specific test
+ test=$1
+ test_path='src/github.com/BurntSushi/toml-test/tests'
+ valid_test="$test_path/valid/$test"
+ invalid_test="$test_path/invalid/$test"
+
+ if [ -e "$valid_test.toml" ]; then
+ echo "Valid Test TOML for $test:"
+ echo "===="
+ cat "$valid_test.toml"
+
+ echo "Valid Test JSON for $test:"
+ echo "===="
+ cat "$valid_test.json"
+
+ echo "Go-TOML Output for $test:"
+ echo "===="
+ cat "$valid_test.toml" | ./test_program_bin
+ fi
+
+ if [ -e "$invalid_test.toml" ]; then
+ echo "Invalid Test TOML for $test:"
+ echo "===="
+ cat "$invalid_test.toml"
+
+ echo "Go-TOML Output for $test:"
+ echo "===="
+ echo "go-toml Output:"
+ cat "$invalid_test.toml" | ./test_program_bin
+ fi
+fi
diff --git a/vendor/github.com/pelletier/go-toml/token.go b/vendor/github.com/pelletier/go-toml/token.go
new file mode 100644
index 000000000..5581fe0bc
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/token.go
@@ -0,0 +1,140 @@
+package toml
+
+import (
+ "fmt"
+ "strconv"
+ "unicode"
+)
+
+// Define tokens
+type tokenType int
+
+const (
+ eof = -(iota + 1)
+)
+
+const (
+ tokenError tokenType = iota
+ tokenEOF
+ tokenComment
+ tokenKey
+ tokenString
+ tokenInteger
+ tokenTrue
+ tokenFalse
+ tokenFloat
+ tokenEqual
+ tokenLeftBracket
+ tokenRightBracket
+ tokenLeftCurlyBrace
+ tokenRightCurlyBrace
+ tokenLeftParen
+ tokenRightParen
+ tokenDoubleLeftBracket
+ tokenDoubleRightBracket
+ tokenDate
+ tokenKeyGroup
+ tokenKeyGroupArray
+ tokenComma
+ tokenColon
+ tokenDollar
+ tokenStar
+ tokenQuestion
+ tokenDot
+ tokenDotDot
+ tokenEOL
+)
+
+var tokenTypeNames = []string{
+ "Error",
+ "EOF",
+ "Comment",
+ "Key",
+ "String",
+ "Integer",
+ "True",
+ "False",
+ "Float",
+ "=",
+ "[",
+ "]",
+ "{",
+ "}",
+ "(",
+ ")",
+ "]]",
+ "[[",
+ "Date",
+ "KeyGroup",
+ "KeyGroupArray",
+ ",",
+ ":",
+ "$",
+ "*",
+ "?",
+ ".",
+ "..",
+ "EOL",
+}
+
+type token struct {
+ Position
+ typ tokenType
+ val string
+}
+
+func (tt tokenType) String() string {
+ idx := int(tt)
+ if idx < len(tokenTypeNames) {
+ return tokenTypeNames[idx]
+ }
+ return "Unknown"
+}
+
+func (t token) Int() int {
+ if result, err := strconv.Atoi(t.val); err != nil {
+ panic(err)
+ } else {
+ return result
+ }
+}
+
+func (t token) String() string {
+ switch t.typ {
+ case tokenEOF:
+ return "EOF"
+ case tokenError:
+ return t.val
+ }
+
+ return fmt.Sprintf("%q", t.val)
+}
+
+func isSpace(r rune) bool {
+ return r == ' ' || r == '\t'
+}
+
+func isAlphanumeric(r rune) bool {
+ return unicode.IsLetter(r) || r == '_'
+}
+
+func isKeyChar(r rune) bool {
+ // Keys start with the first character that isn't whitespace or [ and end
+ // with the last non-whitespace character before the equals sign. Keys
+ // cannot contain a # character."
+ return !(r == '\r' || r == '\n' || r == eof || r == '=')
+}
+
+func isKeyStartChar(r rune) bool {
+ return !(isSpace(r) || r == '\r' || r == '\n' || r == eof || r == '[')
+}
+
+func isDigit(r rune) bool {
+ return unicode.IsNumber(r)
+}
+
+func isHexDigit(r rune) bool {
+ return isDigit(r) ||
+ (r >= 'a' && r <= 'f') ||
+ (r >= 'A' && r <= 'F')
+}
diff --git a/vendor/github.com/pelletier/go-toml/token_test.go b/vendor/github.com/pelletier/go-toml/token_test.go
new file mode 100644
index 000000000..20b560d51
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/token_test.go
@@ -0,0 +1,67 @@
+package toml
+
+import "testing"
+
+func TestTokenStringer(t *testing.T) {
+ var tests = []struct {
+ tt tokenType
+ expect string
+ }{
+ {tokenError, "Error"},
+ {tokenEOF, "EOF"},
+ {tokenComment, "Comment"},
+ {tokenKey, "Key"},
+ {tokenString, "String"},
+ {tokenInteger, "Integer"},
+ {tokenTrue, "True"},
+ {tokenFalse, "False"},
+ {tokenFloat, "Float"},
+ {tokenEqual, "="},
+ {tokenLeftBracket, "["},
+ {tokenRightBracket, "]"},
+ {tokenLeftCurlyBrace, "{"},
+ {tokenRightCurlyBrace, "}"},
+ {tokenLeftParen, "("},
+ {tokenRightParen, ")"},
+ {tokenDoubleLeftBracket, "]]"},
+ {tokenDoubleRightBracket, "[["},
+ {tokenDate, "Date"},
+ {tokenKeyGroup, "KeyGroup"},
+ {tokenKeyGroupArray, "KeyGroupArray"},
+ {tokenComma, ","},
+ {tokenColon, ":"},
+ {tokenDollar, "$"},
+ {tokenStar, "*"},
+ {tokenQuestion, "?"},
+ {tokenDot, "."},
+ {tokenDotDot, ".."},
+ {tokenEOL, "EOL"},
+ {tokenEOL + 1, "Unknown"},
+ }
+
+ for i, test := range tests {
+ got := test.tt.String()
+ if got != test.expect {
+ t.Errorf("[%d] invalid string of token type; got %q, expected %q", i, got, test.expect)
+ }
+ }
+}
+
+func TestTokenString(t *testing.T) {
+ var tests = []struct {
+ tok token
+ expect string
+ }{
+ {token{Position{1, 1}, tokenEOF, ""}, "EOF"},
+ {token{Position{1, 1}, tokenError, "Δt"}, "Δt"},
+ {token{Position{1, 1}, tokenString, "bar"}, `"bar"`},
+ {token{Position{1, 1}, tokenString, "123456789012345"}, `"123456789012345"`},
+ }
+
+ for i, test := range tests {
+ got := test.tok.String()
+ if got != test.expect {
+ t.Errorf("[%d] invalid of string token; got %q, expected %q", i, got, test.expect)
+ }
+ }
+}
diff --git a/vendor/github.com/pelletier/go-toml/toml.go b/vendor/github.com/pelletier/go-toml/toml.go
new file mode 100644
index 000000000..1ba56a1c1
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/toml.go
@@ -0,0 +1,284 @@
+package toml
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "runtime"
+ "strings"
+)
+
+type tomlValue struct {
+ value interface{} // string, int64, uint64, float64, bool, time.Time, [] of any of this list
+ position Position
+}
+
+// TomlTree is the result of the parsing of a TOML file.
+type TomlTree struct {
+ values map[string]interface{} // string -> *tomlValue, *TomlTree, []*TomlTree
+ position Position
+}
+
+func newTomlTree() *TomlTree {
+ return &TomlTree{
+ values: make(map[string]interface{}),
+ position: Position{},
+ }
+}
+
+// TreeFromMap initializes a new TomlTree object using the given map.
+func TreeFromMap(m map[string]interface{}) (*TomlTree, error) {
+ result, err := toTree(m)
+ if err != nil {
+ return nil, err
+ }
+ return result.(*TomlTree), nil
+}
+
+// Has returns a boolean indicating if the given key exists.
+func (t *TomlTree) Has(key string) bool {
+ if key == "" {
+ return false
+ }
+ return t.HasPath(strings.Split(key, "."))
+}
+
+// HasPath returns true if the given path of keys exists, false otherwise.
+func (t *TomlTree) HasPath(keys []string) bool {
+ return t.GetPath(keys) != nil
+}
+
+// Keys returns the keys of the toplevel tree.
+// Warning: this is a costly operation.
+func (t *TomlTree) Keys() []string {
+ var keys []string
+ for k := range t.values {
+ keys = append(keys, k)
+ }
+ return keys
+}
+
+// Get the value at key in the TomlTree.
+// Key is a dot-separated path (e.g. a.b.c).
+// Returns nil if the path does not exist in the tree.
+// If keys is of length zero, the current tree is returned.
+func (t *TomlTree) Get(key string) interface{} {
+ if key == "" {
+ return t
+ }
+ comps, err := parseKey(key)
+ if err != nil {
+ return nil
+ }
+ return t.GetPath(comps)
+}
+
+// GetPath returns the element in the tree indicated by 'keys'.
+// If keys is of length zero, the current tree is returned.
+func (t *TomlTree) GetPath(keys []string) interface{} {
+ if len(keys) == 0 {
+ return t
+ }
+ subtree := t
+ for _, intermediateKey := range keys[:len(keys)-1] {
+ value, exists := subtree.values[intermediateKey]
+ if !exists {
+ return nil
+ }
+ switch node := value.(type) {
+ case *TomlTree:
+ subtree = node
+ case []*TomlTree:
+ // go to most recent element
+ if len(node) == 0 {
+ return nil
+ }
+ subtree = node[len(node)-1]
+ default:
+ return nil // cannot navigate through other node types
+ }
+ }
+ // branch based on final node type
+ switch node := subtree.values[keys[len(keys)-1]].(type) {
+ case *tomlValue:
+ return node.value
+ default:
+ return node
+ }
+}
+
+// GetPosition returns the position of the given key.
+func (t *TomlTree) GetPosition(key string) Position {
+ if key == "" {
+ return t.position
+ }
+ return t.GetPositionPath(strings.Split(key, "."))
+}
+
+// GetPositionPath returns the element in the tree indicated by 'keys'.
+// If keys is of length zero, the current tree is returned.
+func (t *TomlTree) GetPositionPath(keys []string) Position {
+ if len(keys) == 0 {
+ return t.position
+ }
+ subtree := t
+ for _, intermediateKey := range keys[:len(keys)-1] {
+ value, exists := subtree.values[intermediateKey]
+ if !exists {
+ return Position{0, 0}
+ }
+ switch node := value.(type) {
+ case *TomlTree:
+ subtree = node
+ case []*TomlTree:
+ // go to most recent element
+ if len(node) == 0 {
+ return Position{0, 0}
+ }
+ subtree = node[len(node)-1]
+ default:
+ return Position{0, 0}
+ }
+ }
+ // branch based on final node type
+ switch node := subtree.values[keys[len(keys)-1]].(type) {
+ case *tomlValue:
+ return node.position
+ case *TomlTree:
+ return node.position
+ case []*TomlTree:
+ // go to most recent element
+ if len(node) == 0 {
+ return Position{0, 0}
+ }
+ return node[len(node)-1].position
+ default:
+ return Position{0, 0}
+ }
+}
+
+// GetDefault works like Get but with a default value
+func (t *TomlTree) GetDefault(key string, def interface{}) interface{} {
+ val := t.Get(key)
+ if val == nil {
+ return def
+ }
+ return val
+}
+
+// Set an element in the tree.
+// Key is a dot-separated path (e.g. a.b.c).
+// Creates all necessary intermediates trees, if needed.
+func (t *TomlTree) Set(key string, value interface{}) {
+ t.SetPath(strings.Split(key, "."), value)
+}
+
+// SetPath sets an element in the tree.
+// Keys is an array of path elements (e.g. {"a","b","c"}).
+// Creates all necessary intermediates trees, if needed.
+func (t *TomlTree) SetPath(keys []string, value interface{}) {
+ subtree := t
+ for _, intermediateKey := range keys[:len(keys)-1] {
+ nextTree, exists := subtree.values[intermediateKey]
+ if !exists {
+ nextTree = newTomlTree()
+ subtree.values[intermediateKey] = nextTree // add new element here
+ }
+ switch node := nextTree.(type) {
+ case *TomlTree:
+ subtree = node
+ case []*TomlTree:
+ // go to most recent element
+ if len(node) == 0 {
+ // create element if it does not exist
+ subtree.values[intermediateKey] = append(node, newTomlTree())
+ }
+ subtree = node[len(node)-1]
+ }
+ }
+
+ var toInsert interface{}
+
+ switch value.(type) {
+ case *TomlTree:
+ toInsert = value
+ case []*TomlTree:
+ toInsert = value
+ case *tomlValue:
+ toInsert = value
+ default:
+ toInsert = &tomlValue{value: value}
+ }
+
+ subtree.values[keys[len(keys)-1]] = toInsert
+}
+
+// createSubTree takes a tree and a key and create the necessary intermediate
+// subtrees to create a subtree at that point. In-place.
+//
+// e.g. passing a.b.c will create (assuming tree is empty) tree[a], tree[a][b]
+// and tree[a][b][c]
+//
+// Returns nil on success, error object on failure
+func (t *TomlTree) createSubTree(keys []string, pos Position) error {
+ subtree := t
+ for _, intermediateKey := range keys {
+ nextTree, exists := subtree.values[intermediateKey]
+ if !exists {
+ tree := newTomlTree()
+ tree.position = pos
+ subtree.values[intermediateKey] = tree
+ nextTree = tree
+ }
+
+ switch node := nextTree.(type) {
+ case []*TomlTree:
+ subtree = node[len(node)-1]
+ case *TomlTree:
+ subtree = node
+ default:
+ return fmt.Errorf("unknown type for path %s (%s): %T (%#v)",
+ strings.Join(keys, "."), intermediateKey, nextTree, nextTree)
+ }
+ }
+ return nil
+}
+
+// Query compiles and executes a query on a tree and returns the query result.
+func (t *TomlTree) Query(query string) (*QueryResult, error) {
+ q, err := CompileQuery(query)
+ if err != nil {
+ return nil, err
+ }
+ return q.Execute(t), nil
+}
+
+// LoadReader creates a TomlTree from any io.Reader.
+func LoadReader(reader io.Reader) (tree *TomlTree, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ if _, ok := r.(runtime.Error); ok {
+ panic(r)
+ }
+ err = errors.New(r.(string))
+ }
+ }()
+ tree = parseToml(lexToml(reader))
+ return
+}
+
+// Load creates a TomlTree from a string.
+func Load(content string) (tree *TomlTree, err error) {
+ return LoadReader(strings.NewReader(content))
+}
+
+// LoadFile creates a TomlTree from a file.
+func LoadFile(path string) (tree *TomlTree, err error) {
+ file, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ return LoadReader(file)
+}
diff --git a/vendor/github.com/pelletier/go-toml/toml_test.go b/vendor/github.com/pelletier/go-toml/toml_test.go
new file mode 100644
index 000000000..7c7f9eff9
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/toml_test.go
@@ -0,0 +1,131 @@
+// Testing support for go-toml
+
+package toml
+
+import (
+ "testing"
+)
+
+func TestTomlHas(t *testing.T) {
+ tree, _ := Load(`
+ [test]
+ key = "value"
+ `)
+
+ if !tree.Has("test.key") {
+ t.Errorf("Has - expected test.key to exists")
+ }
+
+ if tree.Has("") {
+ t.Errorf("Should return false if the key is not provided")
+ }
+}
+
+func TestTomlGet(t *testing.T) {
+ tree, _ := Load(`
+ [test]
+ key = "value"
+ `)
+
+ if tree.Get("") != tree {
+ t.Errorf("Get should return the tree itself when given an empty path")
+ }
+
+ if tree.Get("test.key") != "value" {
+ t.Errorf("Get should return the value")
+ }
+ if tree.Get(`\`) != nil {
+ t.Errorf("should return nil when the key is malformed")
+ }
+}
+
+func TestTomlGetDefault(t *testing.T) {
+ tree, _ := Load(`
+ [test]
+ key = "value"
+ `)
+
+ if tree.GetDefault("", "hello") != tree {
+ t.Error("GetDefault should return the tree itself when given an empty path")
+ }
+
+ if tree.GetDefault("test.key", "hello") != "value" {
+ t.Error("Get should return the value")
+ }
+
+ if tree.GetDefault("whatever", "hello") != "hello" {
+ t.Error("GetDefault should return the default value if the key does not exist")
+ }
+}
+
+func TestTomlHasPath(t *testing.T) {
+ tree, _ := Load(`
+ [test]
+ key = "value"
+ `)
+
+ if !tree.HasPath([]string{"test", "key"}) {
+ t.Errorf("HasPath - expected test.key to exists")
+ }
+}
+
+func TestTomlGetPath(t *testing.T) {
+ node := newTomlTree()
+ //TODO: set other node data
+
+ for idx, item := range []struct {
+ Path []string
+ Expected *TomlTree
+ }{
+ { // empty path test
+ []string{},
+ node,
+ },
+ } {
+ result := node.GetPath(item.Path)
+ if result != item.Expected {
+ t.Errorf("GetPath[%d] %v - expected %v, got %v instead.", idx, item.Path, item.Expected, result)
+ }
+ }
+
+ tree, _ := Load("[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6")
+ if tree.GetPath([]string{"whatever"}) != nil {
+ t.Error("GetPath should return nil when the key does not exist")
+ }
+}
+
+func TestTomlQuery(t *testing.T) {
+ tree, err := Load("[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6")
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ result, err := tree.Query("$.foo.bar")
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ values := result.Values()
+ if len(values) != 1 {
+ t.Errorf("Expected resultset of 1, got %d instead: %v", len(values), values)
+ }
+
+ if tt, ok := values[0].(*TomlTree); !ok {
+ t.Errorf("Expected type of TomlTree: %T", values[0])
+ } else if tt.Get("a") != int64(1) {
+ t.Errorf("Expected 'a' with a value 1: %v", tt.Get("a"))
+ } else if tt.Get("b") != int64(2) {
+ t.Errorf("Expected 'b' with a value 2: %v", tt.Get("b"))
+ }
+}
+
+func TestTomlFromMap(t *testing.T) {
+ simpleMap := map[string]interface{}{"hello": 42}
+ tree, err := TreeFromMap(simpleMap)
+ if err != nil {
+ t.Fatal("unexpected error:", err)
+ }
+ if tree.Get("hello") != int64(42) {
+ t.Fatal("hello should be 42, not", tree.Get("hello"))
+ }
+}
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_create.go b/vendor/github.com/pelletier/go-toml/tomltree_create.go
new file mode 100644
index 000000000..c6054f358
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/tomltree_create.go
@@ -0,0 +1,135 @@
+package toml
+
+import (
+ "fmt"
+ "reflect"
+ "time"
+)
+
+// supported values:
+// string, bool, int64, uint64, float64, time.Time, int, int8, int16, int32, uint, uint8, uint16, uint32, float32
+
+var kindToTypeMapping = map[reflect.Kind]reflect.Type{
+ reflect.Bool: reflect.TypeOf(true),
+ reflect.String: reflect.TypeOf(""),
+ reflect.Float32: reflect.TypeOf(float64(1)),
+ reflect.Float64: reflect.TypeOf(float64(1)),
+ reflect.Int: reflect.TypeOf(int64(1)),
+ reflect.Int8: reflect.TypeOf(int64(1)),
+ reflect.Int16: reflect.TypeOf(int64(1)),
+ reflect.Int32: reflect.TypeOf(int64(1)),
+ reflect.Int64: reflect.TypeOf(int64(1)),
+ reflect.Uint: reflect.TypeOf(uint64(1)),
+ reflect.Uint8: reflect.TypeOf(uint64(1)),
+ reflect.Uint16: reflect.TypeOf(uint64(1)),
+ reflect.Uint32: reflect.TypeOf(uint64(1)),
+ reflect.Uint64: reflect.TypeOf(uint64(1)),
+}
+
+func simpleValueCoercion(object interface{}) (interface{}, error) {
+ switch original := object.(type) {
+ case string, bool, int64, uint64, float64, time.Time:
+ return original, nil
+ case int:
+ return int64(original), nil
+ case int8:
+ return int64(original), nil
+ case int16:
+ return int64(original), nil
+ case int32:
+ return int64(original), nil
+ case uint:
+ return uint64(original), nil
+ case uint8:
+ return uint64(original), nil
+ case uint16:
+ return uint64(original), nil
+ case uint32:
+ return uint64(original), nil
+ case float32:
+ return float64(original), nil
+ case fmt.Stringer:
+ return original.String(), nil
+ default:
+ return nil, fmt.Errorf("cannot convert type %T to TomlTree", object)
+ }
+}
+
+func sliceToTree(object interface{}) (interface{}, error) {
+ // arrays are a bit tricky, since they can represent either a
+ // collection of simple values, which is represented by one
+ // *tomlValue, or an array of tables, which is represented by an
+ // array of *TomlTree.
+
+ // holding the assumption that this function is called from toTree only when value.Kind() is Array or Slice
+ value := reflect.ValueOf(object)
+ insideType := value.Type().Elem()
+ length := value.Len()
+ if length > 0 {
+ insideType = reflect.ValueOf(value.Index(0).Interface()).Type()
+ }
+ if insideType.Kind() == reflect.Map {
+ // this is considered as an array of tables
+ tablesArray := make([]*TomlTree, 0, length)
+ for i := 0; i < length; i++ {
+ table := value.Index(i)
+ tree, err := toTree(table.Interface())
+ if err != nil {
+ return nil, err
+ }
+ tablesArray = append(tablesArray, tree.(*TomlTree))
+ }
+ return tablesArray, nil
+ }
+
+ sliceType := kindToTypeMapping[insideType.Kind()]
+ if sliceType == nil {
+ sliceType = insideType
+ }
+
+ arrayValue := reflect.MakeSlice(reflect.SliceOf(sliceType), 0, length)
+
+ for i := 0; i < length; i++ {
+ val := value.Index(i).Interface()
+ simpleValue, err := simpleValueCoercion(val)
+ if err != nil {
+ return nil, err
+ }
+ arrayValue = reflect.Append(arrayValue, reflect.ValueOf(simpleValue))
+ }
+ return &tomlValue{arrayValue.Interface(), Position{}}, nil
+}
+
+func toTree(object interface{}) (interface{}, error) {
+ value := reflect.ValueOf(object)
+
+ if value.Kind() == reflect.Map {
+ values := map[string]interface{}{}
+ keys := value.MapKeys()
+ for _, key := range keys {
+ if key.Kind() != reflect.String {
+ if _, ok := key.Interface().(string); !ok {
+ return nil, fmt.Errorf("map key needs to be a string, not %T (%v)", key.Interface(), key.Kind())
+ }
+ }
+
+ v := value.MapIndex(key)
+ newValue, err := toTree(v.Interface())
+ if err != nil {
+ return nil, err
+ }
+ values[key.String()] = newValue
+ }
+ return &TomlTree{values, Position{}}, nil
+ }
+
+ if value.Kind() == reflect.Array || value.Kind() == reflect.Slice {
+ return sliceToTree(object)
+ }
+
+ simpleValue, err := simpleValueCoercion(object)
+ if err != nil {
+ return nil, err
+ }
+ return &tomlValue{simpleValue, Position{}}, nil
+}
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_create_test.go b/vendor/github.com/pelletier/go-toml/tomltree_create_test.go
new file mode 100644
index 000000000..6c1496835
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/tomltree_create_test.go
@@ -0,0 +1,126 @@
+package toml
+
+import (
+ "testing"
+ "time"
+ "strconv"
+)
+
+type customString string
+
+type stringer struct{}
+
+func (s stringer) String() string {
+ return "stringer"
+}
+
+func validate(t *testing.T, path string, object interface{}) {
+ switch o := object.(type) {
+ case *TomlTree:
+ for key, tree := range o.values {
+ validate(t, path+"."+key, tree)
+ }
+ case []*TomlTree:
+ for index, tree := range o {
+ validate(t, path+"."+strconv.Itoa(index), tree)
+ }
+ case *tomlValue:
+ switch o.value.(type) {
+ case int64, uint64, bool, string, float64, time.Time,
+ []int64, []uint64, []bool, []string, []float64, []time.Time:
+ default:
+ t.Fatalf("tomlValue at key %s containing incorrect type %T", path, o.value)
+ }
+ default:
+ t.Fatalf("value at key %s is of incorrect type %T", path, object)
+ }
+ t.Logf("validation ok %s as %T", path, object)
+}
+
+func validateTree(t *testing.T, tree *TomlTree) {
+ validate(t, "", tree)
+}
+
+func TestTomlTreeCreateToTree(t *testing.T) {
+ data := map[string]interface{}{
+ "a_string": "bar",
+ "an_int": 42,
+ "time": time.Now(),
+ "int8": int8(2),
+ "int16": int16(2),
+ "int32": int32(2),
+ "uint8": uint8(2),
+ "uint16": uint16(2),
+ "uint32": uint32(2),
+ "float32": float32(2),
+ "a_bool": false,
+ "stringer": stringer{},
+ "nested": map[string]interface{}{
+ "foo": "bar",
+ },
+ "array": []string{"a", "b", "c"},
+ "array_uint": []uint{uint(1), uint(2)},
+ "array_table": []map[string]interface{}{map[string]interface{}{"sub_map": 52}},
+ "array_times": []time.Time{time.Now(), time.Now()},
+ "map_times": map[string]time.Time{"now": time.Now()},
+ "custom_string_map_key": map[customString]interface{}{customString("custom"): "custom"},
+ }
+ tree, err := TreeFromMap(data)
+ if err != nil {
+ t.Fatal("unexpected error:", err)
+ }
+ validateTree(t, tree)
+}
+
+func TestTomlTreeCreateToTreeInvalidLeafType(t *testing.T) {
+ _, err := TreeFromMap(map[string]interface{}{"foo": t})
+ expected := "cannot convert type *testing.T to TomlTree"
+ if err.Error() != expected {
+ t.Fatalf("expected error %s, got %s", expected, err.Error())
+ }
+}
+
+func TestTomlTreeCreateToTreeInvalidMapKeyType(t *testing.T) {
+ _, err := TreeFromMap(map[string]interface{}{"foo": map[int]interface{}{2: 1}})
+ expected := "map key needs to be a string, not int (int)"
+ if err.Error() != expected {
+ t.Fatalf("expected error %s, got %s", expected, err.Error())
+ }
+}
+
+func TestTomlTreeCreateToTreeInvalidArrayMemberType(t *testing.T) {
+ _, err := TreeFromMap(map[string]interface{}{"foo": []*testing.T{t}})
+ expected := "cannot convert type *testing.T to TomlTree"
+ if err.Error() != expected {
+ t.Fatalf("expected error %s, got %s", expected, err.Error())
+ }
+}
+
+func TestTomlTreeCreateToTreeInvalidTableGroupType(t *testing.T) {
+ _, err := TreeFromMap(map[string]interface{}{"foo": []map[string]interface{}{map[string]interface{}{"hello": t}}})
+ expected := "cannot convert type *testing.T to TomlTree"
+ if err.Error() != expected {
+ t.Fatalf("expected error %s, got %s", expected, err.Error())
+ }
+}
+
+func TestRoundTripArrayOfTables(t *testing.T) {
+ orig := "\n[[stuff]]\n name = \"foo\"\n things = [\"a\",\"b\"]\n"
+ tree, err := Load(orig)
+ if err != nil {
+ t.Fatalf("unexpected error: %s", err)
+ }
+
+ m := tree.ToMap()
+
+ tree, err = TreeFromMap(m)
+ if err != nil {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ want := orig
+ got := tree.String()
+
+ if got != want {
+ t.Errorf("want:\n%s\ngot:\n%s", want, got)
+ }
+}
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_write.go b/vendor/github.com/pelletier/go-toml/tomltree_write.go
new file mode 100644
index 000000000..89c3c4229
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/tomltree_write.go
@@ -0,0 +1,214 @@
+package toml
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+ "reflect"
+)
+
+// encodes a string to a TOML-compliant string value
+func encodeTomlString(value string) string {
+ result := ""
+ for _, rr := range value {
+ switch rr {
+ case '\b':
+ result += "\\b"
+ case '\t':
+ result += "\\t"
+ case '\n':
+ result += "\\n"
+ case '\f':
+ result += "\\f"
+ case '\r':
+ result += "\\r"
+ case '"':
+ result += "\\\""
+ case '\\':
+ result += "\\\\"
+ default:
+ intRr := uint16(rr)
+ if intRr < 0x001F {
+ result += fmt.Sprintf("\\u%0.4X", intRr)
+ } else {
+ result += string(rr)
+ }
+ }
+ }
+ return result
+}
+
+func tomlValueStringRepresentation(v interface{}) (string, error) {
+ switch value := v.(type) {
+ case uint64:
+ return strconv.FormatUint(value, 10), nil
+ case int64:
+ return strconv.FormatInt(value, 10), nil
+ case float64:
+ return strconv.FormatFloat(value, 'f', -1, 32), nil
+ case string:
+ return "\"" + encodeTomlString(value) + "\"", nil
+ case bool:
+ if value {
+ return "true", nil
+ }
+ return "false", nil
+ case time.Time:
+ return value.Format(time.RFC3339), nil
+ case nil:
+ return "", nil
+ }
+
+ rv := reflect.ValueOf(v)
+
+ if rv.Kind() == reflect.Slice {
+ values := []string{}
+ for i := 0; i < rv.Len(); i++ {
+ item := rv.Index(i).Interface()
+ itemRepr, err := tomlValueStringRepresentation(item)
+ if err != nil {
+ return "", err
+ }
+ values = append(values, itemRepr)
+ }
+ return "[" + strings.Join(values, ",") + "]", nil
+ }
+ return "", fmt.Errorf("unsupported value type %T: %v", v, v)
+}
+
+func (t *TomlTree) writeTo(w io.Writer, indent, keyspace string, bytesCount int64) (int64, error) {
+ simpleValuesKeys := make([]string, 0)
+ complexValuesKeys := make([]string, 0)
+
+ for k := range t.values {
+ v := t.values[k]
+ switch v.(type) {
+ case *TomlTree, []*TomlTree:
+ complexValuesKeys = append(complexValuesKeys, k)
+ default:
+ simpleValuesKeys = append(simpleValuesKeys, k)
+ }
+ }
+
+ sort.Strings(simpleValuesKeys)
+ sort.Strings(complexValuesKeys)
+
+ for _, k := range simpleValuesKeys {
+ v, ok := t.values[k].(*tomlValue)
+ if !ok {
+ return bytesCount, fmt.Errorf("invalid value type at %s: %T", k, t.values[k])
+ }
+
+ repr, err := tomlValueStringRepresentation(v.value)
+ if err != nil {
+ return bytesCount, err
+ }
+
+ kvRepr := fmt.Sprintf("%s%s = %s\n", indent, k, repr)
+ writtenBytesCount, err := w.Write([]byte(kvRepr))
+ bytesCount += int64(writtenBytesCount)
+ if err != nil {
+ return bytesCount, err
+ }
+ }
+
+ for _, k := range complexValuesKeys {
+ v := t.values[k]
+
+ combinedKey := k
+ if keyspace != "" {
+ combinedKey = keyspace + "." + combinedKey
+ }
+
+ switch node := v.(type) {
+ // node has to be of those two types given how keys are sorted above
+ case *TomlTree:
+ tableName := fmt.Sprintf("\n%s[%s]\n", indent, combinedKey)
+ writtenBytesCount, err := w.Write([]byte(tableName))
+ bytesCount += int64(writtenBytesCount)
+ if err != nil {
+ return bytesCount, err
+ }
+ bytesCount, err = node.writeTo(w, indent+" ", combinedKey, bytesCount)
+ if err != nil {
+ return bytesCount, err
+ }
+ case []*TomlTree:
+ for _, subTree := range node {
+ if len(subTree.values) > 0 {
+ tableArrayName := fmt.Sprintf("\n%s[[%s]]\n", indent, combinedKey)
+ writtenBytesCount, err := w.Write([]byte(tableArrayName))
+ bytesCount += int64(writtenBytesCount)
+ if err != nil {
+ return bytesCount, err
+ }
+
+ bytesCount, err = subTree.writeTo(w, indent+" ", combinedKey, bytesCount)
+ if err != nil {
+ return bytesCount, err
+ }
+ }
+ }
+ }
+ }
+
+ return bytesCount, nil
+}
+
+// WriteTo encode the TomlTree as Toml and writes it to the writer w.
+// Returns the number of bytes written in case of success, or an error if anything happened.
+func (t *TomlTree) WriteTo(w io.Writer) (int64, error) {
+ return t.writeTo(w, "", "", 0)
+}
+
+// ToTomlString generates a human-readable representation of the current tree.
+// Output spans multiple lines, and is suitable for ingest by a TOML parser.
+// If the conversion cannot be performed, ToString returns a non-nil error.
+func (t *TomlTree) ToTomlString() (string, error) {
+ var buf bytes.Buffer
+ _, err := t.WriteTo(&buf)
+ if err != nil {
+ return "", err
+ }
+ return buf.String(), nil
+}
+
+// String generates a human-readable representation of the current tree.
+// Alias of ToString. Present to implement the fmt.Stringer interface.
+func (t *TomlTree) String() string {
+ result, _ := t.ToTomlString()
+ return result
+}
+
+// ToMap recursively generates a representation of the tree using Go built-in structures.
+// The following types are used:
+// * uint64
+// * int64
+// * bool
+// * string
+// * time.Time
+// * map[string]interface{} (where interface{} is any of this list)
+// * []interface{} (where interface{} is any of this list)
+func (t *TomlTree) ToMap() map[string]interface{} {
+ result := map[string]interface{}{}
+
+ for k, v := range t.values {
+ switch node := v.(type) {
+ case []*TomlTree:
+ var array []interface{}
+ for _, item := range node {
+ array = append(array, item.ToMap())
+ }
+ result[k] = array
+ case *TomlTree:
+ result[k] = node.ToMap()
+ case *tomlValue:
+ result[k] = node.value
+ }
+ }
+ return result
+}
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_write_test.go b/vendor/github.com/pelletier/go-toml/tomltree_write_test.go
new file mode 100644
index 000000000..b5ad8db7c
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/tomltree_write_test.go
@@ -0,0 +1,271 @@
+package toml
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+type failingWriter struct {
+ failAt int
+ written int
+ buffer bytes.Buffer
+}
+
+func (f failingWriter) Write(p []byte) (n int, err error) {
+ count := len(p)
+ toWrite := f.failAt - count + f.written
+ if toWrite < 0 {
+ toWrite = 0
+ }
+ if toWrite > count {
+ f.written += count
+ f.buffer.WriteString(string(p))
+ return count, nil
+ }
+
+ f.buffer.WriteString(string(p[:toWrite]))
+ f.written = f.failAt
+ return f.written, fmt.Errorf("failingWriter failed after writting %d bytes", f.written)
+}
+
+func assertErrorString(t *testing.T, expected string, err error) {
+ expectedErr := errors.New(expected)
+ if err.Error() != expectedErr.Error() {
+ t.Errorf("expecting error %s, but got %s instead", expected, err)
+ }
+}
+
+func TestTomlTreeWriteToTomlString(t *testing.T) {
+ toml, err := Load(`name = { first = "Tom", last = "Preston-Werner" }
+points = { x = 1, y = 2 }`)
+
+ if err != nil {
+ t.Fatal("Unexpected error:", err)
+ }
+
+ tomlString, _ := toml.ToTomlString()
+ reparsedTree, err := Load(tomlString)
+
+ assertTree(t, reparsedTree, err, map[string]interface{}{
+ "name": map[string]interface{}{
+ "first": "Tom",
+ "last": "Preston-Werner",
+ },
+ "points": map[string]interface{}{
+ "x": int64(1),
+ "y": int64(2),
+ },
+ })
+}
+
+func TestTomlTreeWriteToTomlStringSimple(t *testing.T) {
+ tree, err := Load("[foo]\n\n[[foo.bar]]\na = 42\n\n[[foo.bar]]\na = 69\n")
+ if err != nil {
+ t.Errorf("Test failed to parse: %v", err)
+ return
+ }
+ result, err := tree.ToTomlString()
+ if err != nil {
+ t.Errorf("Unexpected error: %s", err)
+ }
+ expected := "\n[foo]\n\n [[foo.bar]]\n a = 42\n\n [[foo.bar]]\n a = 69\n"
+ if result != expected {
+ t.Errorf("Expected got '%s', expected '%s'", result, expected)
+ }
+}
+
+func TestTomlTreeWriteToTomlStringKeysOrders(t *testing.T) {
+ for i := 0; i < 100; i++ {
+ tree, _ := Load(`
+ foobar = true
+ bar = "baz"
+ foo = 1
+ [qux]
+ foo = 1
+ bar = "baz2"`)
+
+ stringRepr, _ := tree.ToTomlString()
+
+ t.Log("Intermediate string representation:")
+ t.Log(stringRepr)
+
+ r := strings.NewReader(stringRepr)
+ toml, err := LoadReader(r)
+
+ if err != nil {
+ t.Fatal("Unexpected error:", err)
+ }
+
+ assertTree(t, toml, err, map[string]interface{}{
+ "foobar": true,
+ "bar": "baz",
+ "foo": 1,
+ "qux": map[string]interface{}{
+ "foo": 1,
+ "bar": "baz2",
+ },
+ })
+ }
+}
+
+func testMaps(t *testing.T, actual, expected map[string]interface{}) {
+ if !reflect.DeepEqual(actual, expected) {
+ t.Fatal("trees aren't equal.\n", "Expected:\n", expected, "\nActual:\n", actual)
+ }
+}
+
+func TestTomlTreeWriteToMapSimple(t *testing.T) {
+ tree, _ := Load("a = 42\nb = 17")
+
+ expected := map[string]interface{}{
+ "a": int64(42),
+ "b": int64(17),
+ }
+
+ testMaps(t, tree.ToMap(), expected)
+}
+
+func TestTomlTreeWriteToInvalidTreeSimpleValue(t *testing.T) {
+ tree := TomlTree{values: map[string]interface{}{"foo": int8(1)}}
+ _, err := tree.ToTomlString()
+ assertErrorString(t, "invalid value type at foo: int8", err)
+}
+
+func TestTomlTreeWriteToInvalidTreeTomlValue(t *testing.T) {
+ tree := TomlTree{values: map[string]interface{}{"foo": &tomlValue{int8(1), Position{}}}}
+ _, err := tree.ToTomlString()
+ assertErrorString(t, "unsupported value type int8: 1", err)
+}
+
+func TestTomlTreeWriteToInvalidTreeTomlValueArray(t *testing.T) {
+ tree := TomlTree{values: map[string]interface{}{"foo": &tomlValue{[]interface{}{int8(1)}, Position{}}}}
+ _, err := tree.ToTomlString()
+ assertErrorString(t, "unsupported value type int8: 1", err)
+}
+
+func TestTomlTreeWriteToFailingWriterInSimpleValue(t *testing.T) {
+ toml, _ := Load(`a = 2`)
+ writer := failingWriter{failAt: 0, written: 0}
+ _, err := toml.WriteTo(writer)
+ assertErrorString(t, "failingWriter failed after writting 0 bytes", err)
+}
+
+func TestTomlTreeWriteToFailingWriterInTable(t *testing.T) {
+ toml, _ := Load(`
+[b]
+a = 2`)
+ writer := failingWriter{failAt: 2, written: 0}
+ _, err := toml.WriteTo(writer)
+ assertErrorString(t, "failingWriter failed after writting 2 bytes", err)
+
+ writer = failingWriter{failAt: 13, written: 0}
+ _, err = toml.WriteTo(writer)
+ assertErrorString(t, "failingWriter failed after writting 13 bytes", err)
+}
+
+func TestTomlTreeWriteToFailingWriterInArray(t *testing.T) {
+ toml, _ := Load(`
+[[b]]
+a = 2`)
+ writer := failingWriter{failAt: 2, written: 0}
+ _, err := toml.WriteTo(writer)
+ assertErrorString(t, "failingWriter failed after writting 2 bytes", err)
+
+ writer = failingWriter{failAt: 15, written: 0}
+ _, err = toml.WriteTo(writer)
+ assertErrorString(t, "failingWriter failed after writting 15 bytes", err)
+}
+
+func TestTomlTreeWriteToMapExampleFile(t *testing.T) {
+ tree, _ := LoadFile("example.toml")
+ expected := map[string]interface{}{
+ "title": "TOML Example",
+ "owner": map[string]interface{}{
+ "name": "Tom Preston-Werner",
+ "organization": "GitHub",
+ "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.",
+ "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
+ },
+ "database": map[string]interface{}{
+ "server": "192.168.1.1",
+ "ports": []interface{}{int64(8001), int64(8001), int64(8002)},
+ "connection_max": int64(5000),
+ "enabled": true,
+ },
+ "servers": map[string]interface{}{
+ "alpha": map[string]interface{}{
+ "ip": "10.0.0.1",
+ "dc": "eqdc10",
+ },
+ "beta": map[string]interface{}{
+ "ip": "10.0.0.2",
+ "dc": "eqdc10",
+ },
+ },
+ "clients": map[string]interface{}{
+ "data": []interface{}{
+ []interface{}{"gamma", "delta"},
+ []interface{}{int64(1), int64(2)},
+ },
+ },
+ }
+ testMaps(t, tree.ToMap(), expected)
+}
+
+func TestTomlTreeWriteToMapWithTablesInMultipleChunks(t *testing.T) {
+ tree, _ := Load(`
+ [[menu.main]]
+ a = "menu 1"
+ b = "menu 2"
+ [[menu.main]]
+ c = "menu 3"
+ d = "menu 4"`)
+ expected := map[string]interface{}{
+ "menu": map[string]interface{}{
+ "main": []interface{}{
+ map[string]interface{}{"a": "menu 1", "b": "menu 2"},
+ map[string]interface{}{"c": "menu 3", "d": "menu 4"},
+ },
+ },
+ }
+ treeMap := tree.ToMap()
+
+ testMaps(t, treeMap, expected)
+}
+
+func TestTomlTreeWriteToMapWithArrayOfInlineTables(t *testing.T) {
+ tree, _ := Load(`
+ [params]
+ language_tabs = [
+ { key = "shell", name = "Shell" },
+ { key = "ruby", name = "Ruby" },
+ { key = "python", name = "Python" }
+ ]`)
+
+ expected := map[string]interface{}{
+ "params": map[string]interface{}{
+ "language_tabs": []interface{}{
+ map[string]interface{}{
+ "key": "shell",
+ "name": "Shell",
+ },
+ map[string]interface{}{
+ "key": "ruby",
+ "name": "Ruby",
+ },
+ map[string]interface{}{
+ "key": "python",
+ "name": "Python",
+ },
+ },
+ },
+ }
+
+ treeMap := tree.ToMap()
+ testMaps(t, treeMap, expected)
+}
diff --git a/vendor/github.com/spf13/afero/.travis.yml b/vendor/github.com/spf13/afero/.travis.yml
new file mode 100644
index 000000000..6c296d293
--- /dev/null
+++ b/vendor/github.com/spf13/afero/.travis.yml
@@ -0,0 +1,20 @@
+sudo: false
+language: go
+
+go:
+ - 1.7.5
+ - 1.8
+ - tip
+
+os:
+ - linux
+ - osx
+
+matrix:
+ allow_failures:
+ - go: tip
+ fast_finish: true
+
+script:
+ - go test -v ./...
+ - go build
diff --git a/vendor/github.com/spf13/afero/LICENSE.txt b/vendor/github.com/spf13/afero/LICENSE.txt
new file mode 100644
index 000000000..298f0e266
--- /dev/null
+++ b/vendor/github.com/spf13/afero/LICENSE.txt
@@ -0,0 +1,174 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
diff --git a/vendor/github.com/spf13/afero/README.md b/vendor/github.com/spf13/afero/README.md
new file mode 100644
index 000000000..d9e332730
--- /dev/null
+++ b/vendor/github.com/spf13/afero/README.md
@@ -0,0 +1,449 @@
+![afero logo-sm](https://cloud.githubusercontent.com/assets/173412/11490338/d50e16dc-97a5-11e5-8b12-019a300d0fcb.png)
+
+A FileSystem Abstraction System for Go
+
+[![Build Status](https://travis-ci.org/spf13/afero.svg)](https://travis-ci.org/spf13/afero) [![Build status](https://ci.appveyor.com/api/projects/status/github/spf13/afero?branch=master&svg=true)](https://ci.appveyor.com/project/spf13/afero) [![GoDoc](https://godoc.org/github.com/spf13/afero?status.svg)](https://godoc.org/github.com/spf13/afero) [![Join the chat at https://gitter.im/spf13/afero](https://badges.gitter.im/Dev%20Chat.svg)](https://gitter.im/spf13/afero?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+
+# Overview
+
+Afero is an filesystem framework providing a simple, uniform and universal API
+interacting with any filesystem, as an abstraction layer providing interfaces,
+types and methods. Afero has an exceptionally clean interface and simple design
+without needless constructors or initialization methods.
+
+Afero is also a library providing a base set of interoperable backend
+filesystems that make it easy to work with afero while retaining all the power
+and benefit of the os and ioutil packages.
+
+Afero provides significant improvements over using the os package alone, most
+notably the ability to create mock and testing filesystems without relying on the disk.
+
+It is suitable for use in a any situation where you would consider using the OS
+package as it provides an additional abstraction that makes it easy to use a
+memory backed file system during testing. It also adds support for the http
+filesystem for full interoperability.
+
+
+## Afero Features
+
+* A single consistent API for accessing a variety of filesystems
+* Interoperation between a variety of file system types
+* A set of interfaces to encourage and enforce interoperability between backends
+* An atomic cross platform memory backed file system
+* Support for compositional (union) file systems by combining multiple file systems acting as one
+* Specialized backends which modify existing filesystems (Read Only, Regexp filtered)
+* A set of utility functions ported from io, ioutil & hugo to be afero aware
+
+
+# Using Afero
+
+Afero is easy to use and easier to adopt.
+
+A few different ways you could use Afero:
+
+* Use the interfaces alone to define you own file system.
+* Wrap for the OS packages.
+* Define different filesystems for different parts of your application.
+* Use Afero for mock filesystems while testing
+
+## Step 1: Install Afero
+
+First use go get to install the latest version of the library.
+
+ $ go get github.com/spf13/afero
+
+Next include Afero in your application.
+```go
+import "github.com/spf13/afero"
+```
+
+## Step 2: Declare a backend
+
+First define a package variable and set it to a pointer to a filesystem.
+```go
+var AppFs afero.Fs = afero.NewMemMapFs()
+
+or
+
+var AppFs afero.Fs = afero.NewOsFs()
+```
+It is important to note that if you repeat the composite literal you
+will be using a completely new and isolated filesystem. In the case of
+OsFs it will still use the same underlying filesystem but will reduce
+the ability to drop in other filesystems as desired.
+
+## Step 3: Use it like you would the OS package
+
+Throughout your application use any function and method like you normally
+would.
+
+So if my application before had:
+```go
+os.Open('/tmp/foo')
+```
+We would replace it with a call to `AppFs.Open('/tmp/foo')`.
+
+`AppFs` being the variable we defined above.
+
+
+## List of all available functions
+
+File System Methods Available:
+```go
+Chmod(name string, mode os.FileMode) : error
+Chtimes(name string, atime time.Time, mtime time.Time) : error
+Create(name string) : File, error
+Mkdir(name string, perm os.FileMode) : error
+MkdirAll(path string, perm os.FileMode) : error
+Name() : string
+Open(name string) : File, error
+OpenFile(name string, flag int, perm os.FileMode) : File, error
+Remove(name string) : error
+RemoveAll(path string) : error
+Rename(oldname, newname string) : error
+Stat(name string) : os.FileInfo, error
+```
+File Interfaces and Methods Available:
+```go
+io.Closer
+io.Reader
+io.ReaderAt
+io.Seeker
+io.Writer
+io.WriterAt
+
+Name() : string
+Readdir(count int) : []os.FileInfo, error
+Readdirnames(n int) : []string, error
+Stat() : os.FileInfo, error
+Sync() : error
+Truncate(size int64) : error
+WriteString(s string) : ret int, err error
+```
+In some applications it may make sense to define a new package that
+simply exports the file system variable for easy access from anywhere.
+
+## Using Afero's utility functions
+
+Afero provides a set of functions to make it easier to use the underlying file systems.
+These functions have been primarily ported from io & ioutil with some developed for Hugo.
+
+The afero utilities support all afero compatible backends.
+
+The list of utilities includes:
+
+```go
+DirExists(path string) (bool, error)
+Exists(path string) (bool, error)
+FileContainsBytes(filename string, subslice []byte) (bool, error)
+GetTempDir(subPath string) string
+IsDir(path string) (bool, error)
+IsEmpty(path string) (bool, error)
+ReadDir(dirname string) ([]os.FileInfo, error)
+ReadFile(filename string) ([]byte, error)
+SafeWriteReader(path string, r io.Reader) (err error)
+TempDir(dir, prefix string) (name string, err error)
+TempFile(dir, prefix string) (f File, err error)
+Walk(root string, walkFn filepath.WalkFunc) error
+WriteFile(filename string, data []byte, perm os.FileMode) error
+WriteReader(path string, r io.Reader) (err error)
+```
+For a complete list see [Afero's GoDoc](https://godoc.org/github.com/spf13/afero)
+
+They are available under two different approaches to use. You can either call
+them directly where the first parameter of each function will be the file
+system, or you can declare a new `Afero`, a custom type used to bind these
+functions as methods to a given filesystem.
+
+### Calling utilities directly
+
+```go
+fs := new(afero.MemMapFs)
+f, err := afero.TempFile(fs,"", "ioutil-test")
+
+```
+
+### Calling via Afero
+
+```go
+fs := afero.NewMemMapFs
+afs := &Afero{Fs: fs}
+f, err := afs.TempFile("", "ioutil-test")
+```
+
+## Using Afero for Testing
+
+There is a large benefit to using a mock filesystem for testing. It has a
+completely blank state every time it is initialized and can be easily
+reproducible regardless of OS. You could create files to your heart’s content
+and the file access would be fast while also saving you from all the annoying
+issues with deleting temporary files, Windows file locking, etc. The MemMapFs
+backend is perfect for testing.
+
+* Much faster than performing I/O operations on disk
+* Avoid security issues and permissions
+* Far more control. 'rm -rf /' with confidence
+* Test setup is far more easier to do
+* No test cleanup needed
+
+One way to accomplish this is to define a variable as mentioned above.
+In your application this will be set to afero.NewOsFs() during testing you
+can set it to afero.NewMemMapFs().
+
+It wouldn't be uncommon to have each test initialize a blank slate memory
+backend. To do this I would define my `appFS = afero.NewOsFs()` somewhere
+appropriate in my application code. This approach ensures that Tests are order
+independent, with no test relying on the state left by an earlier test.
+
+Then in my tests I would initialize a new MemMapFs for each test:
+```go
+func TestExist(t *testing.T) {
+ appFS := afero.NewMemMapFs()
+ // create test files and directories
+ appFS.MkdirAll("src/a", 0755)
+ afero.WriteFile(appFS, "src/a/b", []byte("file b"), 0644)
+ afero.WriteFile(appFS, "src/c", []byte("file c"), 0644)
+ name := "src/c"
+ _, err := appFS.Stat(name)
+ if os.IsNotExist(err) {
+ t.Errorf("file \"%s\" does not exist.\n", name)
+ }
+}
+```
+
+# Available Backends
+
+## Operating System Native
+
+### OsFs
+
+The first is simply a wrapper around the native OS calls. This makes it
+very easy to use as all of the calls are the same as the existing OS
+calls. It also makes it trivial to have your code use the OS during
+operation and a mock filesystem during testing or as needed.
+
+```go
+appfs := afero.NewOsFs()
+appfs.MkdirAll("src/a", 0755))
+```
+
+## Memory Backed Storage
+
+### MemMapFs
+
+Afero also provides a fully atomic memory backed filesystem perfect for use in
+mocking and to speed up unnecessary disk io when persistence isn’t
+necessary. It is fully concurrent and will work within go routines
+safely.
+
+```go
+mm := afero.NewMemMapFs()
+mm.MkdirAll("src/a", 0755))
+```
+
+#### InMemoryFile
+
+As part of MemMapFs, Afero also provides an atomic, fully concurrent memory
+backed file implementation. This can be used in other memory backed file
+systems with ease. Plans are to add a radix tree memory stored file
+system using InMemoryFile.
+
+## Network Interfaces
+
+### SftpFs
+
+Afero has experimental support for secure file transfer protocol (sftp). Which can
+be used to perform file operations over a encrypted channel.
+
+## Filtering Backends
+
+### BasePathFs
+
+The BasePathFs restricts all operations to a given path within an Fs.
+The given file name to the operations on this Fs will be prepended with
+the base path before calling the source Fs.
+
+```go
+bp := afero.NewBasePathFs(afero.NewOsFs(), "/base/path")
+```
+
+### ReadOnlyFs
+
+A thin wrapper around the source Fs providing a read only view.
+
+```go
+fs := afero.NewReadOnlyFs(afero.NewOsFs())
+_, err := fs.Create("/file.txt")
+// err = syscall.EPERM
+```
+
+# RegexpFs
+
+A filtered view on file names, any file NOT matching
+the passed regexp will be treated as non-existing.
+Files not matching the regexp provided will not be created.
+Directories are not filtered.
+
+```go
+fs := afero.NewRegexpFs(afero.NewMemMapFs(), regexp.MustCompile(`\.txt$`))
+_, err := fs.Create("/file.html")
+// err = syscall.ENOENT
+```
+
+### HttpFs
+
+Afero provides an http compatible backend which can wrap any of the existing
+backends.
+
+The Http package requires a slightly specific version of Open which
+returns an http.File type.
+
+Afero provides an httpFs file system which satisfies this requirement.
+Any Afero FileSystem can be used as an httpFs.
+
+```go
+httpFs := afero.NewHttpFs(<ExistingFS>)
+fileserver := http.FileServer(httpFs.Dir(<PATH>)))
+http.Handle("/", fileserver)
+```
+
+## Composite Backends
+
+Afero provides the ability have two filesystems (or more) act as a single
+file system.
+
+### CacheOnReadFs
+
+The CacheOnReadFs will lazily make copies of any accessed files from the base
+layer into the overlay. Subsequent reads will be pulled from the overlay
+directly permitting the request is within the cache duration of when it was
+created in the overlay.
+
+If the base filesystem is writeable, any changes to files will be
+done first to the base, then to the overlay layer. Write calls to open file
+handles like `Write()` or `Truncate()` to the overlay first.
+
+To writing files to the overlay only, you can use the overlay Fs directly (not
+via the union Fs).
+
+Cache files in the layer for the given time.Duration, a cache duration of 0
+means "forever" meaning the file will not be re-requested from the base ever.
+
+A read-only base will make the overlay also read-only but still copy files
+from the base to the overlay when they're not present (or outdated) in the
+caching layer.
+
+```go
+base := afero.NewOsFs()
+layer := afero.NewMemMapFs()
+ufs := afero.NewCacheOnReadFs(base, layer, 100 * time.Second)
+```
+
+### CopyOnWriteFs()
+
+The CopyOnWriteFs is a read only base file system with a potentially
+writeable layer on top.
+
+Read operations will first look in the overlay and if not found there, will
+serve the file from the base.
+
+Changes to the file system will only be made in the overlay.
+
+Any attempt to modify a file found only in the base will copy the file to the
+overlay layer before modification (including opening a file with a writable
+handle).
+
+Removing and Renaming files present only in the base layer is not currently
+permitted. If a file is present in the base layer and the overlay, only the
+overlay will be removed/renamed.
+
+```go
+ base := afero.NewOsFs()
+ roBase := afero.NewReadOnlyFs(base)
+ ufs := afero.NewCopyOnWriteFs(roBase, afero.NewMemMapFs())
+
+ fh, _ = ufs.Create("/home/test/file2.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+```
+
+In this example all write operations will only occur in memory (MemMapFs)
+leaving the base filesystem (OsFs) untouched.
+
+
+## Desired/possible backends
+
+The following is a short list of possible backends we hope someone will
+implement:
+
+* SSH
+* ZIP
+* TAR
+* S3
+
+# About the project
+
+## What's in the name
+
+Afero comes from the latin roots Ad-Facere.
+
+**"Ad"** is a prefix meaning "to".
+
+**"Facere"** is a form of the root "faciō" making "make or do".
+
+The literal meaning of afero is "to make" or "to do" which seems very fitting
+for a library that allows one to make files and directories and do things with them.
+
+The English word that shares the same roots as Afero is "affair". Affair shares
+the same concept but as a noun it means "something that is made or done" or "an
+object of a particular type".
+
+It's also nice that unlike some of my other libraries (hugo, cobra, viper) it
+Googles very well.
+
+## Release Notes
+
+* **0.10.0** 2015.12.10
+ * Full compatibility with Windows
+ * Introduction of afero utilities
+ * Test suite rewritten to work cross platform
+ * Normalize paths for MemMapFs
+ * Adding Sync to the file interface
+ * **Breaking Change** Walk and ReadDir have changed parameter order
+ * Moving types used by MemMapFs to a subpackage
+ * General bugfixes and improvements
+* **0.9.0** 2015.11.05
+ * New Walk function similar to filepath.Walk
+ * MemMapFs.OpenFile handles O_CREATE, O_APPEND, O_TRUNC
+ * MemMapFs.Remove now really deletes the file
+ * InMemoryFile.Readdir and Readdirnames work correctly
+ * InMemoryFile functions lock it for concurrent access
+ * Test suite improvements
+* **0.8.0** 2014.10.28
+ * First public version
+ * Interfaces feel ready for people to build using
+ * Interfaces satisfy all known uses
+ * MemMapFs passes the majority of the OS test suite
+ * OsFs passes the majority of the OS test suite
+
+## Contributing
+
+1. Fork it
+2. Create your feature branch (`git checkout -b my-new-feature`)
+3. Commit your changes (`git commit -am 'Add some feature'`)
+4. Push to the branch (`git push origin my-new-feature`)
+5. Create new Pull Request
+
+## Contributors
+
+Names in no particular order:
+
+* [spf13](https://github.com/spf13)
+* [jaqx0r](https://github.com/jaqx0r)
+* [mbertschler](https://github.com/mbertschler)
+* [xor-gate](https://github.com/xor-gate)
+
+## License
+
+Afero is released under the Apache 2.0 license. See
+[LICENSE.txt](https://github.com/spf13/afero/blob/master/LICENSE.txt)
diff --git a/vendor/github.com/spf13/afero/afero.go b/vendor/github.com/spf13/afero/afero.go
new file mode 100644
index 000000000..f5b5e127c
--- /dev/null
+++ b/vendor/github.com/spf13/afero/afero.go
@@ -0,0 +1,108 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+// Copyright 2013 tsuru authors. All rights reserved.
+//
+// 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.
+
+// Package afero provides types and methods for interacting with the filesystem,
+// as an abstraction layer.
+
+// Afero also provides a few implementations that are mostly interoperable. One that
+// uses the operating system filesystem, one that uses memory to store files
+// (cross platform) and an interface that should be implemented if you want to
+// provide your own filesystem.
+
+package afero
+
+import (
+ "errors"
+ "io"
+ "os"
+ "time"
+)
+
+type Afero struct {
+ Fs
+}
+
+// File represents a file in the filesystem.
+type File interface {
+ io.Closer
+ io.Reader
+ io.ReaderAt
+ io.Seeker
+ io.Writer
+ io.WriterAt
+
+ Name() string
+ Readdir(count int) ([]os.FileInfo, error)
+ Readdirnames(n int) ([]string, error)
+ Stat() (os.FileInfo, error)
+ Sync() error
+ Truncate(size int64) error
+ WriteString(s string) (ret int, err error)
+}
+
+// Fs is the filesystem interface.
+//
+// Any simulated or real filesystem should implement this interface.
+type Fs interface {
+ // Create creates a file in the filesystem, returning the file and an
+ // error, if any happens.
+ Create(name string) (File, error)
+
+ // Mkdir creates a directory in the filesystem, return an error if any
+ // happens.
+ Mkdir(name string, perm os.FileMode) error
+
+ // MkdirAll creates a directory path and all parents that does not exist
+ // yet.
+ MkdirAll(path string, perm os.FileMode) error
+
+ // Open opens a file, returning it or an error, if any happens.
+ Open(name string) (File, error)
+
+ // OpenFile opens a file using the given flags and the given mode.
+ OpenFile(name string, flag int, perm os.FileMode) (File, error)
+
+ // Remove removes a file identified by name, returning an error, if any
+ // happens.
+ Remove(name string) error
+
+ // RemoveAll removes a directory path and any children it contains. It
+ // does not fail if the path does not exist (return nil).
+ RemoveAll(path string) error
+
+ // Rename renames a file.
+ Rename(oldname, newname string) error
+
+ // Stat returns a FileInfo describing the named file, or an error, if any
+ // happens.
+ Stat(name string) (os.FileInfo, error)
+
+ // The name of this FileSystem
+ Name() string
+
+ //Chmod changes the mode of the named file to mode.
+ Chmod(name string, mode os.FileMode) error
+
+ //Chtimes changes the access and modification times of the named file
+ Chtimes(name string, atime time.Time, mtime time.Time) error
+}
+
+var (
+ ErrFileClosed = errors.New("File is closed")
+ ErrOutOfRange = errors.New("Out of range")
+ ErrTooLarge = errors.New("Too large")
+ ErrFileNotFound = os.ErrNotExist
+ ErrFileExists = os.ErrExist
+ ErrDestinationExists = os.ErrExist
+)
diff --git a/vendor/github.com/spf13/afero/afero_test.go b/vendor/github.com/spf13/afero/afero_test.go
new file mode 100644
index 000000000..526afa975
--- /dev/null
+++ b/vendor/github.com/spf13/afero/afero_test.go
@@ -0,0 +1,699 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+// Copyright 2009 The Go Authors. All rights reserved.
+//
+// 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.
+
+package afero
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "syscall"
+ "testing"
+)
+
+var testName = "test.txt"
+var Fss = []Fs{&MemMapFs{}, &OsFs{}}
+
+var testRegistry map[Fs][]string = make(map[Fs][]string)
+
+func testDir(fs Fs) string {
+ name, err := TempDir(fs, "", "afero")
+ if err != nil {
+ panic(fmt.Sprint("unable to work with test dir", err))
+ }
+ testRegistry[fs] = append(testRegistry[fs], name)
+
+ return name
+}
+
+func tmpFile(fs Fs) File {
+ x, err := TempFile(fs, "", "afero")
+
+ if err != nil {
+ panic(fmt.Sprint("unable to work with temp file", err))
+ }
+
+ testRegistry[fs] = append(testRegistry[fs], x.Name())
+
+ return x
+}
+
+//Read with length 0 should not return EOF.
+func TestRead0(t *testing.T) {
+ for _, fs := range Fss {
+ f := tmpFile(fs)
+ defer f.Close()
+ f.WriteString("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
+
+ var b []byte
+ // b := make([]byte, 0)
+ n, err := f.Read(b)
+ if n != 0 || err != nil {
+ t.Errorf("%v: Read(0) = %d, %v, want 0, nil", fs.Name(), n, err)
+ }
+ f.Seek(0, 0)
+ b = make([]byte, 100)
+ n, err = f.Read(b)
+ if n <= 0 || err != nil {
+ t.Errorf("%v: Read(100) = %d, %v, want >0, nil", fs.Name(), n, err)
+ }
+ }
+}
+
+func TestOpenFile(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for _, fs := range Fss {
+ tmp := testDir(fs)
+ path := filepath.Join(tmp, testName)
+
+ f, err := fs.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
+ if err != nil {
+ t.Error(fs.Name(), "OpenFile (O_CREATE) failed:", err)
+ continue
+ }
+ io.WriteString(f, "initial")
+ f.Close()
+
+ f, err = fs.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0600)
+ if err != nil {
+ t.Error(fs.Name(), "OpenFile (O_APPEND) failed:", err)
+ continue
+ }
+ io.WriteString(f, "|append")
+ f.Close()
+
+ f, err = fs.OpenFile(path, os.O_RDONLY, 0600)
+ contents, _ := ioutil.ReadAll(f)
+ expectedContents := "initial|append"
+ if string(contents) != expectedContents {
+ t.Errorf("%v: appending, expected '%v', got: '%v'", fs.Name(), expectedContents, string(contents))
+ }
+ f.Close()
+
+ f, err = fs.OpenFile(path, os.O_RDWR|os.O_TRUNC, 0600)
+ if err != nil {
+ t.Error(fs.Name(), "OpenFile (O_TRUNC) failed:", err)
+ continue
+ }
+ contents, _ = ioutil.ReadAll(f)
+ if string(contents) != "" {
+ t.Errorf("%v: expected truncated file, got: '%v'", fs.Name(), string(contents))
+ }
+ f.Close()
+ }
+}
+
+func TestCreate(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for _, fs := range Fss {
+ tmp := testDir(fs)
+ path := filepath.Join(tmp, testName)
+
+ f, err := fs.Create(path)
+ if err != nil {
+ t.Error(fs.Name(), "Create failed:", err)
+ f.Close()
+ continue
+ }
+ io.WriteString(f, "initial")
+ f.Close()
+
+ f, err = fs.Create(path)
+ if err != nil {
+ t.Error(fs.Name(), "Create failed:", err)
+ f.Close()
+ continue
+ }
+ secondContent := "second create"
+ io.WriteString(f, secondContent)
+ f.Close()
+
+ f, err = fs.Open(path)
+ if err != nil {
+ t.Error(fs.Name(), "Open failed:", err)
+ f.Close()
+ continue
+ }
+ buf, err := ReadAll(f)
+ if err != nil {
+ t.Error(fs.Name(), "ReadAll failed:", err)
+ f.Close()
+ continue
+ }
+ if string(buf) != secondContent {
+ t.Error(fs.Name(), "Content should be", "\""+secondContent+"\" but is \""+string(buf)+"\"")
+ f.Close()
+ continue
+ }
+ f.Close()
+ }
+}
+
+func TestMemFileRead(t *testing.T) {
+ f := tmpFile(new(MemMapFs))
+ // f := MemFileCreate("testfile")
+ f.WriteString("abcd")
+ f.Seek(0, 0)
+ b := make([]byte, 8)
+ n, err := f.Read(b)
+ if n != 4 {
+ t.Errorf("didn't read all bytes: %v %v %v", n, err, b)
+ }
+ if err != nil {
+ t.Errorf("err is not nil: %v %v %v", n, err, b)
+ }
+ n, err = f.Read(b)
+ if n != 0 {
+ t.Errorf("read more bytes: %v %v %v", n, err, b)
+ }
+ if err != io.EOF {
+ t.Errorf("error is not EOF: %v %v %v", n, err, b)
+ }
+}
+
+func TestRename(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for _, fs := range Fss {
+ tDir := testDir(fs)
+ from := filepath.Join(tDir, "/renamefrom")
+ to := filepath.Join(tDir, "/renameto")
+ exists := filepath.Join(tDir, "/renameexists")
+ file, err := fs.Create(from)
+ if err != nil {
+ t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
+ }
+ if err = file.Close(); err != nil {
+ t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
+ }
+ file, err = fs.Create(exists)
+ if err != nil {
+ t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
+ }
+ if err = file.Close(); err != nil {
+ t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
+ }
+ err = fs.Rename(from, to)
+ if err != nil {
+ t.Fatalf("%s: rename %q, %q failed: %v", fs.Name(), to, from, err)
+ }
+ file, err = fs.Create(from)
+ if err != nil {
+ t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
+ }
+ if err = file.Close(); err != nil {
+ t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
+ }
+ err = fs.Rename(from, exists)
+ if err != nil {
+ t.Errorf("%s: rename %q, %q failed: %v", fs.Name(), exists, from, err)
+ }
+ names, err := readDirNames(fs, tDir)
+ if err != nil {
+ t.Errorf("%s: readDirNames error: %v", fs.Name(), err)
+ }
+ found := false
+ for _, e := range names {
+ if e == "renamefrom" {
+ t.Error("File is still called renamefrom")
+ }
+ if e == "renameto" {
+ found = true
+ }
+ }
+ if !found {
+ t.Error("File was not renamed to renameto")
+ }
+
+ _, err = fs.Stat(to)
+ if err != nil {
+ t.Errorf("%s: stat %q failed: %v", fs.Name(), to, err)
+ }
+ }
+}
+
+func TestRemove(t *testing.T) {
+ for _, fs := range Fss {
+
+ x, err := TempFile(fs, "", "afero")
+ if err != nil {
+ t.Error(fmt.Sprint("unable to work with temp file", err))
+ }
+
+ path := x.Name()
+ x.Close()
+
+ tDir := filepath.Dir(path)
+
+ err = fs.Remove(path)
+ if err != nil {
+ t.Errorf("%v: Remove() failed: %v", fs.Name(), err)
+ continue
+ }
+
+ _, err = fs.Stat(path)
+ if !os.IsNotExist(err) {
+ t.Errorf("%v: Remove() didn't remove file", fs.Name())
+ continue
+ }
+
+ // Deleting non-existent file should raise error
+ err = fs.Remove(path)
+ if !os.IsNotExist(err) {
+ t.Errorf("%v: Remove() didn't raise error for non-existent file", fs.Name())
+ }
+
+ f, err := fs.Open(tDir)
+ if err != nil {
+ t.Error("TestDir should still exist:", err)
+ }
+
+ names, err := f.Readdirnames(-1)
+ if err != nil {
+ t.Error("Readdirnames failed:", err)
+ }
+
+ for _, e := range names {
+ if e == testName {
+ t.Error("File was not removed from parent directory")
+ }
+ }
+ }
+}
+
+func TestTruncate(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for _, fs := range Fss {
+ f := tmpFile(fs)
+ defer f.Close()
+
+ checkSize(t, f, 0)
+ f.Write([]byte("hello, world\n"))
+ checkSize(t, f, 13)
+ f.Truncate(10)
+ checkSize(t, f, 10)
+ f.Truncate(1024)
+ checkSize(t, f, 1024)
+ f.Truncate(0)
+ checkSize(t, f, 0)
+ _, err := f.Write([]byte("surprise!"))
+ if err == nil {
+ checkSize(t, f, 13+9) // wrote at offset past where hello, world was.
+ }
+ }
+}
+
+func TestSeek(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for _, fs := range Fss {
+ f := tmpFile(fs)
+ defer f.Close()
+
+ const data = "hello, world\n"
+ io.WriteString(f, data)
+
+ type test struct {
+ in int64
+ whence int
+ out int64
+ }
+ var tests = []test{
+ {0, 1, int64(len(data))},
+ {0, 0, 0},
+ {5, 0, 5},
+ {0, 2, int64(len(data))},
+ {0, 0, 0},
+ {-1, 2, int64(len(data)) - 1},
+ {1 << 33, 0, 1 << 33},
+ {1 << 33, 2, 1<<33 + int64(len(data))},
+ }
+ for i, tt := range tests {
+ off, err := f.Seek(tt.in, tt.whence)
+ if off != tt.out || err != nil {
+ if e, ok := err.(*os.PathError); ok && e.Err == syscall.EINVAL && tt.out > 1<<32 {
+ // Reiserfs rejects the big seeks.
+ // http://code.google.com/p/go/issues/detail?id=91
+ break
+ }
+ t.Errorf("#%d: Seek(%v, %v) = %v, %v want %v, nil", i, tt.in, tt.whence, off, err, tt.out)
+ }
+ }
+ }
+}
+
+func TestReadAt(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for _, fs := range Fss {
+ f := tmpFile(fs)
+ defer f.Close()
+
+ const data = "hello, world\n"
+ io.WriteString(f, data)
+
+ b := make([]byte, 5)
+ n, err := f.ReadAt(b, 7)
+ if err != nil || n != len(b) {
+ t.Fatalf("ReadAt 7: %d, %v", n, err)
+ }
+ if string(b) != "world" {
+ t.Fatalf("ReadAt 7: have %q want %q", string(b), "world")
+ }
+ }
+}
+
+func TestWriteAt(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for _, fs := range Fss {
+ f := tmpFile(fs)
+ defer f.Close()
+
+ const data = "hello, world\n"
+ io.WriteString(f, data)
+
+ n, err := f.WriteAt([]byte("WORLD"), 7)
+ if err != nil || n != 5 {
+ t.Fatalf("WriteAt 7: %d, %v", n, err)
+ }
+
+ f2, err := fs.Open(f.Name())
+ if err != nil {
+ t.Fatalf("%v: ReadFile %s: %v", fs.Name(), f.Name(), err)
+ }
+ defer f2.Close()
+ buf := new(bytes.Buffer)
+ buf.ReadFrom(f2)
+ b := buf.Bytes()
+ if string(b) != "hello, WORLD\n" {
+ t.Fatalf("after write: have %q want %q", string(b), "hello, WORLD\n")
+ }
+
+ }
+}
+
+func setupTestDir(t *testing.T, fs Fs) string {
+ path := testDir(fs)
+ return setupTestFiles(t, fs, path)
+}
+
+func setupTestDirRoot(t *testing.T, fs Fs) string {
+ path := testDir(fs)
+ setupTestFiles(t, fs, path)
+ return path
+}
+
+func setupTestDirReusePath(t *testing.T, fs Fs, path string) string {
+ testRegistry[fs] = append(testRegistry[fs], path)
+ return setupTestFiles(t, fs, path)
+}
+
+func setupTestFiles(t *testing.T, fs Fs, path string) string {
+ testSubDir := filepath.Join(path, "more", "subdirectories", "for", "testing", "we")
+ err := fs.MkdirAll(testSubDir, 0700)
+ if err != nil && !os.IsExist(err) {
+ t.Fatal(err)
+ }
+
+ f, err := fs.Create(filepath.Join(testSubDir, "testfile1"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.WriteString("Testfile 1 content")
+ f.Close()
+
+ f, err = fs.Create(filepath.Join(testSubDir, "testfile2"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.WriteString("Testfile 2 content")
+ f.Close()
+
+ f, err = fs.Create(filepath.Join(testSubDir, "testfile3"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.WriteString("Testfile 3 content")
+ f.Close()
+
+ f, err = fs.Create(filepath.Join(testSubDir, "testfile4"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.WriteString("Testfile 4 content")
+ f.Close()
+ return testSubDir
+}
+
+func TestReaddirnames(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for _, fs := range Fss {
+ testSubDir := setupTestDir(t, fs)
+ tDir := filepath.Dir(testSubDir)
+
+ root, err := fs.Open(tDir)
+ if err != nil {
+ t.Fatal(fs.Name(), tDir, err)
+ }
+ defer root.Close()
+
+ namesRoot, err := root.Readdirnames(-1)
+ if err != nil {
+ t.Fatal(fs.Name(), namesRoot, err)
+ }
+
+ sub, err := fs.Open(testSubDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer sub.Close()
+
+ namesSub, err := sub.Readdirnames(-1)
+ if err != nil {
+ t.Fatal(fs.Name(), namesSub, err)
+ }
+
+ findNames(fs, t, tDir, testSubDir, namesRoot, namesSub)
+ }
+}
+
+func TestReaddirSimple(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for _, fs := range Fss {
+ testSubDir := setupTestDir(t, fs)
+ tDir := filepath.Dir(testSubDir)
+
+ root, err := fs.Open(tDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer root.Close()
+
+ rootInfo, err := root.Readdir(1)
+ if err != nil {
+ t.Log(myFileInfo(rootInfo))
+ t.Error(err)
+ }
+
+ rootInfo, err = root.Readdir(5)
+ if err != io.EOF {
+ t.Log(myFileInfo(rootInfo))
+ t.Error(err)
+ }
+
+ sub, err := fs.Open(testSubDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer sub.Close()
+
+ subInfo, err := sub.Readdir(5)
+ if err != nil {
+ t.Log(myFileInfo(subInfo))
+ t.Error(err)
+ }
+ }
+}
+
+func TestReaddir(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for num := 0; num < 6; num++ {
+ outputs := make([]string, len(Fss))
+ infos := make([]string, len(Fss))
+ for i, fs := range Fss {
+ testSubDir := setupTestDir(t, fs)
+ //tDir := filepath.Dir(testSubDir)
+ root, err := fs.Open(testSubDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer root.Close()
+
+ for j := 0; j < 6; j++ {
+ info, err := root.Readdir(num)
+ outputs[i] += fmt.Sprintf("%v Error: %v\n", myFileInfo(info), err)
+ infos[i] += fmt.Sprintln(len(info), err)
+ }
+ }
+
+ fail := false
+ for i, o := range infos {
+ if i == 0 {
+ continue
+ }
+ if o != infos[i-1] {
+ fail = true
+ break
+ }
+ }
+ if fail {
+ t.Log("Readdir outputs not equal for Readdir(", num, ")")
+ for i, o := range outputs {
+ t.Log(Fss[i].Name())
+ t.Log(o)
+ }
+ t.Fail()
+ }
+ }
+}
+
+type myFileInfo []os.FileInfo
+
+func (m myFileInfo) String() string {
+ out := "Fileinfos:\n"
+ for _, e := range m {
+ out += " " + e.Name() + "\n"
+ }
+ return out
+}
+
+func TestReaddirAll(t *testing.T) {
+ defer removeAllTestFiles(t)
+ for _, fs := range Fss {
+ testSubDir := setupTestDir(t, fs)
+ tDir := filepath.Dir(testSubDir)
+
+ root, err := fs.Open(tDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer root.Close()
+
+ rootInfo, err := root.Readdir(-1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var namesRoot = []string{}
+ for _, e := range rootInfo {
+ namesRoot = append(namesRoot, e.Name())
+ }
+
+ sub, err := fs.Open(testSubDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer sub.Close()
+
+ subInfo, err := sub.Readdir(-1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var namesSub = []string{}
+ for _, e := range subInfo {
+ namesSub = append(namesSub, e.Name())
+ }
+
+ findNames(fs, t, tDir, testSubDir, namesRoot, namesSub)
+ }
+}
+
+func findNames(fs Fs, t *testing.T, tDir, testSubDir string, root, sub []string) {
+ var foundRoot bool
+ for _, e := range root {
+ f, err := fs.Open(filepath.Join(tDir, e))
+ if err != nil {
+ t.Error("Open", filepath.Join(tDir, e), ":", err)
+ }
+ defer f.Close()
+
+ if equal(e, "we") {
+ foundRoot = true
+ }
+ }
+ if !foundRoot {
+ t.Logf("Names root: %v", root)
+ t.Logf("Names sub: %v", sub)
+ t.Error("Didn't find subdirectory we")
+ }
+
+ var found1, found2 bool
+ for _, e := range sub {
+ f, err := fs.Open(filepath.Join(testSubDir, e))
+ if err != nil {
+ t.Error("Open", filepath.Join(testSubDir, e), ":", err)
+ }
+ defer f.Close()
+
+ if equal(e, "testfile1") {
+ found1 = true
+ }
+ if equal(e, "testfile2") {
+ found2 = true
+ }
+ }
+
+ if !found1 {
+ t.Logf("Names root: %v", root)
+ t.Logf("Names sub: %v", sub)
+ t.Error("Didn't find testfile1")
+ }
+ if !found2 {
+ t.Logf("Names root: %v", root)
+ t.Logf("Names sub: %v", sub)
+ t.Error("Didn't find testfile2")
+ }
+}
+
+func removeAllTestFiles(t *testing.T) {
+ for fs, list := range testRegistry {
+ for _, path := range list {
+ if err := fs.RemoveAll(path); err != nil {
+ t.Error(fs.Name(), err)
+ }
+ }
+ }
+ testRegistry = make(map[Fs][]string)
+}
+
+func equal(name1, name2 string) (r bool) {
+ switch runtime.GOOS {
+ case "windows":
+ r = strings.ToLower(name1) == strings.ToLower(name2)
+ default:
+ r = name1 == name2
+ }
+ return
+}
+
+func checkSize(t *testing.T, f File, size int64) {
+ dir, err := f.Stat()
+ if err != nil {
+ t.Fatalf("Stat %q (looking for size %d): %s", f.Name(), size, err)
+ }
+ if dir.Size() != size {
+ t.Errorf("Stat %q: size %d want %d", f.Name(), dir.Size(), size)
+ }
+}
diff --git a/vendor/github.com/spf13/afero/appveyor.yml b/vendor/github.com/spf13/afero/appveyor.yml
new file mode 100644
index 000000000..006f31534
--- /dev/null
+++ b/vendor/github.com/spf13/afero/appveyor.yml
@@ -0,0 +1,15 @@
+version: '{build}'
+clone_folder: C:\gopath\src\github.com\spf13\afero
+environment:
+ GOPATH: C:\gopath
+build_script:
+- cmd: >-
+ go version
+
+ go env
+
+ go get -v github.com/spf13/afero/...
+
+ go build github.com/spf13/afero
+test_script:
+- cmd: go test -v github.com/spf13/afero
diff --git a/vendor/github.com/spf13/afero/basepath.go b/vendor/github.com/spf13/afero/basepath.go
new file mode 100644
index 000000000..5e4fc2ec0
--- /dev/null
+++ b/vendor/github.com/spf13/afero/basepath.go
@@ -0,0 +1,145 @@
+package afero
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+)
+
+// The BasePathFs restricts all operations to a given path within an Fs.
+// The given file name to the operations on this Fs will be prepended with
+// the base path before calling the base Fs.
+// Any file name (after filepath.Clean()) outside this base path will be
+// treated as non existing file.
+//
+// Note that it does not clean the error messages on return, so you may
+// reveal the real path on errors.
+type BasePathFs struct {
+ source Fs
+ path string
+}
+
+func NewBasePathFs(source Fs, path string) Fs {
+ return &BasePathFs{source: source, path: path}
+}
+
+// on a file outside the base path it returns the given file name and an error,
+// else the given file with the base path prepended
+func (b *BasePathFs) RealPath(name string) (path string, err error) {
+ if err := validateBasePathName(name); err != nil {
+ return "", err
+ }
+
+ bpath := filepath.Clean(b.path)
+ path = filepath.Clean(filepath.Join(bpath, name))
+ if !strings.HasPrefix(path, bpath) {
+ return name, os.ErrNotExist
+ }
+
+ return path, nil
+}
+
+func validateBasePathName(name string) error {
+ if runtime.GOOS != "windows" {
+ // Not much to do here;
+ // the virtual file paths all look absolute on *nix.
+ return nil
+ }
+
+ // On Windows a common mistake would be to provide an absolute OS path
+ // We could strip out the base part, but that would not be very portable.
+ if filepath.IsAbs(name) {
+ return &os.PathError{Op: "realPath", Path: name, Err: errors.New("got a real OS path instead of a virtual")}
+ }
+
+ return nil
+}
+
+func (b *BasePathFs) Chtimes(name string, atime, mtime time.Time) (err error) {
+ if name, err = b.RealPath(name); err != nil {
+ return &os.PathError{Op: "chtimes", Path: name, Err: err}
+ }
+ return b.source.Chtimes(name, atime, mtime)
+}
+
+func (b *BasePathFs) Chmod(name string, mode os.FileMode) (err error) {
+ if name, err = b.RealPath(name); err != nil {
+ return &os.PathError{Op: "chmod", Path: name, Err: err}
+ }
+ return b.source.Chmod(name, mode)
+}
+
+func (b *BasePathFs) Name() string {
+ return "BasePathFs"
+}
+
+func (b *BasePathFs) Stat(name string) (fi os.FileInfo, err error) {
+ if name, err = b.RealPath(name); err != nil {
+ return nil, &os.PathError{Op: "stat", Path: name, Err: err}
+ }
+ return b.source.Stat(name)
+}
+
+func (b *BasePathFs) Rename(oldname, newname string) (err error) {
+ if oldname, err = b.RealPath(oldname); err != nil {
+ return &os.PathError{Op: "rename", Path: oldname, Err: err}
+ }
+ if newname, err = b.RealPath(newname); err != nil {
+ return &os.PathError{Op: "rename", Path: newname, Err: err}
+ }
+ return b.source.Rename(oldname, newname)
+}
+
+func (b *BasePathFs) RemoveAll(name string) (err error) {
+ if name, err = b.RealPath(name); err != nil {
+ return &os.PathError{Op: "remove_all", Path: name, Err: err}
+ }
+ return b.source.RemoveAll(name)
+}
+
+func (b *BasePathFs) Remove(name string) (err error) {
+ if name, err = b.RealPath(name); err != nil {
+ return &os.PathError{Op: "remove", Path: name, Err: err}
+ }
+ return b.source.Remove(name)
+}
+
+func (b *BasePathFs) OpenFile(name string, flag int, mode os.FileMode) (f File, err error) {
+ if name, err = b.RealPath(name); err != nil {
+ return nil, &os.PathError{Op: "openfile", Path: name, Err: err}
+ }
+ return b.source.OpenFile(name, flag, mode)
+}
+
+func (b *BasePathFs) Open(name string) (f File, err error) {
+ if name, err = b.RealPath(name); err != nil {
+ return nil, &os.PathError{Op: "open", Path: name, Err: err}
+ }
+ return b.source.Open(name)
+}
+
+func (b *BasePathFs) Mkdir(name string, mode os.FileMode) (err error) {
+ if name, err = b.RealPath(name); err != nil {
+ return &os.PathError{Op: "mkdir", Path: name, Err: err}
+ }
+ return b.source.Mkdir(name, mode)
+}
+
+func (b *BasePathFs) MkdirAll(name string, mode os.FileMode) (err error) {
+ if name, err = b.RealPath(name); err != nil {
+ return &os.PathError{Op: "mkdir", Path: name, Err: err}
+ }
+ return b.source.MkdirAll(name, mode)
+}
+
+func (b *BasePathFs) Create(name string) (f File, err error) {
+ if name, err = b.RealPath(name); err != nil {
+ return nil, &os.PathError{Op: "create", Path: name, Err: err}
+ }
+ return b.source.Create(name)
+}
+
+// vim: ts=4 sw=4 noexpandtab nolist syn=go
diff --git a/vendor/github.com/spf13/afero/basepath_test.go b/vendor/github.com/spf13/afero/basepath_test.go
new file mode 100644
index 000000000..abc22b9f6
--- /dev/null
+++ b/vendor/github.com/spf13/afero/basepath_test.go
@@ -0,0 +1,142 @@
+package afero
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+ "testing"
+)
+
+func TestBasePath(t *testing.T) {
+ baseFs := &MemMapFs{}
+ baseFs.MkdirAll("/base/path/tmp", 0777)
+ bp := NewBasePathFs(baseFs, "/base/path")
+
+ if _, err := bp.Create("/tmp/foo"); err != nil {
+ t.Errorf("Failed to set real path")
+ }
+
+ if fh, err := bp.Create("../tmp/bar"); err == nil {
+ t.Errorf("succeeded in creating %s ...", fh.Name())
+ }
+}
+
+func TestBasePathRoot(t *testing.T) {
+ baseFs := &MemMapFs{}
+ baseFs.MkdirAll("/base/path/foo/baz", 0777)
+ baseFs.MkdirAll("/base/path/boo/", 0777)
+ bp := NewBasePathFs(baseFs, "/base/path")
+
+ rd, err := ReadDir(bp, string(os.PathSeparator))
+
+ if len(rd) != 2 {
+ t.Errorf("base path doesn't respect root")
+ }
+
+ if err != nil {
+ t.Error(err)
+ }
+}
+
+func TestRealPath(t *testing.T) {
+ fs := NewOsFs()
+ baseDir, err := TempDir(fs, "", "base")
+ if err != nil {
+ t.Fatal("error creating tempDir", err)
+ }
+ defer fs.RemoveAll(baseDir)
+ anotherDir, err := TempDir(fs, "", "another")
+ if err != nil {
+ t.Fatal("error creating tempDir", err)
+ }
+ defer fs.RemoveAll(anotherDir)
+
+ bp := NewBasePathFs(fs, baseDir).(*BasePathFs)
+
+ subDir := filepath.Join(baseDir, "s1")
+
+ realPath, err := bp.RealPath("/s1")
+
+ if err != nil {
+ t.Errorf("Got error %s", err)
+ }
+
+ if realPath != subDir {
+ t.Errorf("Expected \n%s got \n%s", subDir, realPath)
+ }
+
+ if runtime.GOOS == "windows" {
+ _, err = bp.RealPath(anotherDir)
+
+ if err == nil {
+ t.Errorf("Expected error")
+ }
+
+ } else {
+ // on *nix we have no way of just looking at the path and tell that anotherDir
+ // is not inside the base file system.
+ // The user will receive an os.ErrNotExist later.
+ surrealPath, err := bp.RealPath(anotherDir)
+
+ if err != nil {
+ t.Errorf("Got error %s", err)
+ }
+
+ excpected := filepath.Join(baseDir, anotherDir)
+
+ if surrealPath != excpected {
+ t.Errorf("Expected \n%s got \n%s", excpected, surrealPath)
+ }
+ }
+
+}
+
+func TestNestedBasePaths(t *testing.T) {
+ type dirSpec struct {
+ Dir1, Dir2, Dir3 string
+ }
+ dirSpecs := []dirSpec{
+ dirSpec{Dir1: "/", Dir2: "/", Dir3: "/"},
+ dirSpec{Dir1: "/", Dir2: "/path2", Dir3: "/"},
+ dirSpec{Dir1: "/path1/dir", Dir2: "/path2/dir/", Dir3: "/path3/dir"},
+ dirSpec{Dir1: "C:/path1", Dir2: "path2/dir", Dir3: "/path3/dir/"},
+ }
+
+ for _, ds := range dirSpecs {
+ memFs := NewMemMapFs()
+ level1Fs := NewBasePathFs(memFs, ds.Dir1)
+ level2Fs := NewBasePathFs(level1Fs, ds.Dir2)
+ level3Fs := NewBasePathFs(level2Fs, ds.Dir3)
+
+ type spec struct {
+ BaseFs Fs
+ FileName string
+ }
+ specs := []spec{
+ spec{BaseFs: level3Fs, FileName: "f.txt"},
+ spec{BaseFs: level2Fs, FileName: "f.txt"},
+ spec{BaseFs: level1Fs, FileName: "f.txt"},
+ }
+
+ for _, s := range specs {
+ if err := s.BaseFs.MkdirAll(s.FileName, 0755); err != nil {
+ t.Errorf("Got error %s", err.Error())
+ }
+ if _, err := s.BaseFs.Stat(s.FileName); err != nil {
+ t.Errorf("Got error %s", err.Error())
+ }
+
+ if s.BaseFs == level3Fs {
+ pathToExist := filepath.Join(ds.Dir3, s.FileName)
+ if _, err := level2Fs.Stat(pathToExist); err != nil {
+ t.Errorf("Got error %s (path %s)", err.Error(), pathToExist)
+ }
+ } else if s.BaseFs == level2Fs {
+ pathToExist := filepath.Join(ds.Dir2, ds.Dir3, s.FileName)
+ if _, err := level1Fs.Stat(pathToExist); err != nil {
+ t.Errorf("Got error %s (path %s)", err.Error(), pathToExist)
+ }
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/spf13/afero/cacheOnReadFs.go b/vendor/github.com/spf13/afero/cacheOnReadFs.go
new file mode 100644
index 000000000..e54a4f8b4
--- /dev/null
+++ b/vendor/github.com/spf13/afero/cacheOnReadFs.go
@@ -0,0 +1,295 @@
+package afero
+
+import (
+ "os"
+ "syscall"
+ "time"
+)
+
+// If the cache duration is 0, cache time will be unlimited, i.e. once
+// a file is in the layer, the base will never be read again for this file.
+//
+// For cache times greater than 0, the modification time of a file is
+// checked. Note that a lot of file system implementations only allow a
+// resolution of a second for timestamps... or as the godoc for os.Chtimes()
+// states: "The underlying filesystem may truncate or round the values to a
+// less precise time unit."
+//
+// This caching union will forward all write calls also to the base file
+// system first. To prevent writing to the base Fs, wrap it in a read-only
+// filter - Note: this will also make the overlay read-only, for writing files
+// in the overlay, use the overlay Fs directly, not via the union Fs.
+type CacheOnReadFs struct {
+ base Fs
+ layer Fs
+ cacheTime time.Duration
+}
+
+func NewCacheOnReadFs(base Fs, layer Fs, cacheTime time.Duration) Fs {
+ return &CacheOnReadFs{base: base, layer: layer, cacheTime: cacheTime}
+}
+
+type cacheState int
+
+const (
+ // not present in the overlay, unknown if it exists in the base:
+ cacheMiss cacheState = iota
+ // present in the overlay and in base, base file is newer:
+ cacheStale
+ // present in the overlay - with cache time == 0 it may exist in the base,
+ // with cacheTime > 0 it exists in the base and is same age or newer in the
+ // overlay
+ cacheHit
+ // happens if someone writes directly to the overlay without
+ // going through this union
+ cacheLocal
+)
+
+func (u *CacheOnReadFs) cacheStatus(name string) (state cacheState, fi os.FileInfo, err error) {
+ var lfi, bfi os.FileInfo
+ lfi, err = u.layer.Stat(name)
+ if err == nil {
+ if u.cacheTime == 0 {
+ return cacheHit, lfi, nil
+ }
+ if lfi.ModTime().Add(u.cacheTime).Before(time.Now()) {
+ bfi, err = u.base.Stat(name)
+ if err != nil {
+ return cacheLocal, lfi, nil
+ }
+ if bfi.ModTime().After(lfi.ModTime()) {
+ return cacheStale, bfi, nil
+ }
+ }
+ return cacheHit, lfi, nil
+ }
+
+ if err == syscall.ENOENT {
+ return cacheMiss, nil, nil
+ }
+ var ok bool
+ if err, ok = err.(*os.PathError); ok {
+ if err == os.ErrNotExist {
+ return cacheMiss, nil, nil
+ }
+ }
+ return cacheMiss, nil, err
+}
+
+func (u *CacheOnReadFs) copyToLayer(name string) error {
+ return copyToLayer(u.base, u.layer, name)
+}
+
+func (u *CacheOnReadFs) Chtimes(name string, atime, mtime time.Time) error {
+ st, _, err := u.cacheStatus(name)
+ if err != nil {
+ return err
+ }
+ switch st {
+ case cacheLocal:
+ case cacheHit:
+ err = u.base.Chtimes(name, atime, mtime)
+ case cacheStale, cacheMiss:
+ if err := u.copyToLayer(name); err != nil {
+ return err
+ }
+ err = u.base.Chtimes(name, atime, mtime)
+ }
+ if err != nil {
+ return err
+ }
+ return u.layer.Chtimes(name, atime, mtime)
+}
+
+func (u *CacheOnReadFs) Chmod(name string, mode os.FileMode) error {
+ st, _, err := u.cacheStatus(name)
+ if err != nil {
+ return err
+ }
+ switch st {
+ case cacheLocal:
+ case cacheHit:
+ err = u.base.Chmod(name, mode)
+ case cacheStale, cacheMiss:
+ if err := u.copyToLayer(name); err != nil {
+ return err
+ }
+ err = u.base.Chmod(name, mode)
+ }
+ if err != nil {
+ return err
+ }
+ return u.layer.Chmod(name, mode)
+}
+
+func (u *CacheOnReadFs) Stat(name string) (os.FileInfo, error) {
+ st, fi, err := u.cacheStatus(name)
+ if err != nil {
+ return nil, err
+ }
+ switch st {
+ case cacheMiss:
+ return u.base.Stat(name)
+ default: // cacheStale has base, cacheHit and cacheLocal the layer os.FileInfo
+ return fi, nil
+ }
+}
+
+func (u *CacheOnReadFs) Rename(oldname, newname string) error {
+ st, _, err := u.cacheStatus(oldname)
+ if err != nil {
+ return err
+ }
+ switch st {
+ case cacheLocal:
+ case cacheHit:
+ err = u.base.Rename(oldname, newname)
+ case cacheStale, cacheMiss:
+ if err := u.copyToLayer(oldname); err != nil {
+ return err
+ }
+ err = u.base.Rename(oldname, newname)
+ }
+ if err != nil {
+ return err
+ }
+ return u.layer.Rename(oldname, newname)
+}
+
+func (u *CacheOnReadFs) Remove(name string) error {
+ st, _, err := u.cacheStatus(name)
+ if err != nil {
+ return err
+ }
+ switch st {
+ case cacheLocal:
+ case cacheHit, cacheStale, cacheMiss:
+ err = u.base.Remove(name)
+ }
+ if err != nil {
+ return err
+ }
+ return u.layer.Remove(name)
+}
+
+func (u *CacheOnReadFs) RemoveAll(name string) error {
+ st, _, err := u.cacheStatus(name)
+ if err != nil {
+ return err
+ }
+ switch st {
+ case cacheLocal:
+ case cacheHit, cacheStale, cacheMiss:
+ err = u.base.RemoveAll(name)
+ }
+ if err != nil {
+ return err
+ }
+ return u.layer.RemoveAll(name)
+}
+
+func (u *CacheOnReadFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
+ st, _, err := u.cacheStatus(name)
+ if err != nil {
+ return nil, err
+ }
+ switch st {
+ case cacheLocal, cacheHit:
+ default:
+ if err := u.copyToLayer(name); err != nil {
+ return nil, err
+ }
+ }
+ if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
+ bfi, err := u.base.OpenFile(name, flag, perm)
+ if err != nil {
+ return nil, err
+ }
+ lfi, err := u.layer.OpenFile(name, flag, perm)
+ if err != nil {
+ bfi.Close() // oops, what if O_TRUNC was set and file opening in the layer failed...?
+ return nil, err
+ }
+ return &UnionFile{base: bfi, layer: lfi}, nil
+ }
+ return u.layer.OpenFile(name, flag, perm)
+}
+
+func (u *CacheOnReadFs) Open(name string) (File, error) {
+ st, fi, err := u.cacheStatus(name)
+ if err != nil {
+ return nil, err
+ }
+
+ switch st {
+ case cacheLocal:
+ return u.layer.Open(name)
+
+ case cacheMiss:
+ bfi, err := u.base.Stat(name)
+ if err != nil {
+ return nil, err
+ }
+ if bfi.IsDir() {
+ return u.base.Open(name)
+ }
+ if err := u.copyToLayer(name); err != nil {
+ return nil, err
+ }
+ return u.layer.Open(name)
+
+ case cacheStale:
+ if !fi.IsDir() {
+ if err := u.copyToLayer(name); err != nil {
+ return nil, err
+ }
+ return u.layer.Open(name)
+ }
+ case cacheHit:
+ if !fi.IsDir() {
+ return u.layer.Open(name)
+ }
+ }
+ // the dirs from cacheHit, cacheStale fall down here:
+ bfile, _ := u.base.Open(name)
+ lfile, err := u.layer.Open(name)
+ if err != nil && bfile == nil {
+ return nil, err
+ }
+ return &UnionFile{base: bfile, layer: lfile}, nil
+}
+
+func (u *CacheOnReadFs) Mkdir(name string, perm os.FileMode) error {
+ err := u.base.Mkdir(name, perm)
+ if err != nil {
+ return err
+ }
+ return u.layer.MkdirAll(name, perm) // yes, MkdirAll... we cannot assume it exists in the cache
+}
+
+func (u *CacheOnReadFs) Name() string {
+ return "CacheOnReadFs"
+}
+
+func (u *CacheOnReadFs) MkdirAll(name string, perm os.FileMode) error {
+ err := u.base.MkdirAll(name, perm)
+ if err != nil {
+ return err
+ }
+ return u.layer.MkdirAll(name, perm)
+}
+
+func (u *CacheOnReadFs) Create(name string) (File, error) {
+ bfh, err := u.base.Create(name)
+ if err != nil {
+ return nil, err
+ }
+ lfh, err := u.layer.Create(name)
+ if err != nil {
+ // oops, see comment about OS_TRUNC above, should we remove? then we have to
+ // remember if the file did not exist before
+ bfh.Close()
+ return nil, err
+ }
+ return &UnionFile{base: bfh, layer: lfh}, nil
+}
diff --git a/vendor/github.com/spf13/afero/composite_test.go b/vendor/github.com/spf13/afero/composite_test.go
new file mode 100644
index 000000000..e8ac1a818
--- /dev/null
+++ b/vendor/github.com/spf13/afero/composite_test.go
@@ -0,0 +1,368 @@
+package afero
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "testing"
+ "time"
+)
+
+var tempDirs []string
+
+func NewTempOsBaseFs(t *testing.T) Fs {
+ name, err := TempDir(NewOsFs(), "", "")
+ if err != nil {
+ t.Error("error creating tempDir", err)
+ }
+
+ tempDirs = append(tempDirs, name)
+
+ return NewBasePathFs(NewOsFs(), name)
+}
+
+func CleanupTempDirs(t *testing.T) {
+ osfs := NewOsFs()
+ type ev struct {
+ path string
+ e error
+ }
+
+ errs := []ev{}
+
+ for _, x := range tempDirs {
+ err := osfs.RemoveAll(x)
+ if err != nil {
+ errs = append(errs, ev{path: x, e: err})
+ }
+ }
+
+ for _, e := range errs {
+ fmt.Println("error removing tempDir", e.path, e.e)
+ }
+
+ if len(errs) > 0 {
+ t.Error("error cleaning up tempDirs")
+ }
+ tempDirs = []string{}
+}
+
+func TestUnionCreateExisting(t *testing.T) {
+ base := &MemMapFs{}
+ roBase := &ReadOnlyFs{source: base}
+
+ ufs := NewCopyOnWriteFs(roBase, &MemMapFs{})
+
+ base.MkdirAll("/home/test", 0777)
+ fh, _ := base.Create("/home/test/file.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ fh, err := ufs.OpenFile("/home/test/file.txt", os.O_RDWR, 0666)
+ if err != nil {
+ t.Errorf("Failed to open file r/w: %s", err)
+ }
+
+ _, err = fh.Write([]byte("####"))
+ if err != nil {
+ t.Errorf("Failed to write file: %s", err)
+ }
+ fh.Seek(0, 0)
+ data, err := ioutil.ReadAll(fh)
+ if err != nil {
+ t.Errorf("Failed to read file: %s", err)
+ }
+ if string(data) != "#### is a test" {
+ t.Errorf("Got wrong data")
+ }
+ fh.Close()
+
+ fh, _ = base.Open("/home/test/file.txt")
+ data, err = ioutil.ReadAll(fh)
+ if string(data) != "This is a test" {
+ t.Errorf("Got wrong data in base file")
+ }
+ fh.Close()
+
+ fh, err = ufs.Create("/home/test/file.txt")
+ switch err {
+ case nil:
+ if fi, _ := fh.Stat(); fi.Size() != 0 {
+ t.Errorf("Create did not truncate file")
+ }
+ fh.Close()
+ default:
+ t.Errorf("Create failed on existing file")
+ }
+
+}
+
+func TestUnionMergeReaddir(t *testing.T) {
+ base := &MemMapFs{}
+ roBase := &ReadOnlyFs{source: base}
+
+ ufs := &CopyOnWriteFs{base: roBase, layer: &MemMapFs{}}
+
+ base.MkdirAll("/home/test", 0777)
+ fh, _ := base.Create("/home/test/file.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ fh, _ = ufs.Create("/home/test/file2.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ fh, _ = ufs.Open("/home/test")
+ files, err := fh.Readdirnames(-1)
+ if err != nil {
+ t.Errorf("Readdirnames failed")
+ }
+ if len(files) != 2 {
+ t.Errorf("Got wrong number of files: %v", files)
+ }
+}
+
+func TestExistingDirectoryCollisionReaddir(t *testing.T) {
+ base := &MemMapFs{}
+ roBase := &ReadOnlyFs{source: base}
+ overlay := &MemMapFs{}
+
+ ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
+
+ base.MkdirAll("/home/test", 0777)
+ fh, _ := base.Create("/home/test/file.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ overlay.MkdirAll("home/test", 0777)
+ fh, _ = overlay.Create("/home/test/file2.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ fh, _ = ufs.Create("/home/test/file3.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ fh, _ = ufs.Open("/home/test")
+ files, err := fh.Readdirnames(-1)
+ if err != nil {
+ t.Errorf("Readdirnames failed")
+ }
+ if len(files) != 3 {
+ t.Errorf("Got wrong number of files in union: %v", files)
+ }
+
+ fh, _ = overlay.Open("/home/test")
+ files, err = fh.Readdirnames(-1)
+ if err != nil {
+ t.Errorf("Readdirnames failed")
+ }
+ if len(files) != 2 {
+ t.Errorf("Got wrong number of files in overlay: %v", files)
+ }
+}
+
+func TestNestedDirBaseReaddir(t *testing.T) {
+ base := &MemMapFs{}
+ roBase := &ReadOnlyFs{source: base}
+ overlay := &MemMapFs{}
+
+ ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
+
+ base.MkdirAll("/home/test/foo/bar", 0777)
+ fh, _ := base.Create("/home/test/file.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ fh, _ = base.Create("/home/test/foo/file2.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+ fh, _ = base.Create("/home/test/foo/bar/file3.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ overlay.MkdirAll("/", 0777)
+
+ // Opening something only in the base
+ fh, _ = ufs.Open("/home/test/foo")
+ list, err := fh.Readdir(-1)
+ if err != nil {
+ t.Errorf("Readdir failed %s", err)
+ }
+ if len(list) != 2 {
+ for _, x := range list {
+ fmt.Println(x.Name())
+ }
+ t.Errorf("Got wrong number of files in union: %v", len(list))
+ }
+}
+
+func TestNestedDirOverlayReaddir(t *testing.T) {
+ base := &MemMapFs{}
+ roBase := &ReadOnlyFs{source: base}
+ overlay := &MemMapFs{}
+
+ ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
+
+ base.MkdirAll("/", 0777)
+ overlay.MkdirAll("/home/test/foo/bar", 0777)
+ fh, _ := overlay.Create("/home/test/file.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+ fh, _ = overlay.Create("/home/test/foo/file2.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+ fh, _ = overlay.Create("/home/test/foo/bar/file3.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ // Opening nested dir only in the overlay
+ fh, _ = ufs.Open("/home/test/foo")
+ list, err := fh.Readdir(-1)
+ if err != nil {
+ t.Errorf("Readdir failed %s", err)
+ }
+ if len(list) != 2 {
+ for _, x := range list {
+ fmt.Println(x.Name())
+ }
+ t.Errorf("Got wrong number of files in union: %v", len(list))
+ }
+}
+
+func TestNestedDirOverlayOsFsReaddir(t *testing.T) {
+ defer CleanupTempDirs(t)
+ base := NewTempOsBaseFs(t)
+ roBase := &ReadOnlyFs{source: base}
+ overlay := NewTempOsBaseFs(t)
+
+ ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
+
+ base.MkdirAll("/", 0777)
+ overlay.MkdirAll("/home/test/foo/bar", 0777)
+ fh, _ := overlay.Create("/home/test/file.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+ fh, _ = overlay.Create("/home/test/foo/file2.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+ fh, _ = overlay.Create("/home/test/foo/bar/file3.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ // Opening nested dir only in the overlay
+ fh, _ = ufs.Open("/home/test/foo")
+ list, err := fh.Readdir(-1)
+ fh.Close()
+ if err != nil {
+ t.Errorf("Readdir failed %s", err)
+ }
+ if len(list) != 2 {
+ for _, x := range list {
+ fmt.Println(x.Name())
+ }
+ t.Errorf("Got wrong number of files in union: %v", len(list))
+ }
+}
+
+func TestCopyOnWriteFsWithOsFs(t *testing.T) {
+ defer CleanupTempDirs(t)
+ base := NewTempOsBaseFs(t)
+ roBase := &ReadOnlyFs{source: base}
+ overlay := NewTempOsBaseFs(t)
+
+ ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
+
+ base.MkdirAll("/home/test", 0777)
+ fh, _ := base.Create("/home/test/file.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ overlay.MkdirAll("home/test", 0777)
+ fh, _ = overlay.Create("/home/test/file2.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ fh, _ = ufs.Create("/home/test/file3.txt")
+ fh.WriteString("This is a test")
+ fh.Close()
+
+ fh, _ = ufs.Open("/home/test")
+ files, err := fh.Readdirnames(-1)
+ fh.Close()
+ if err != nil {
+ t.Errorf("Readdirnames failed")
+ }
+ if len(files) != 3 {
+ t.Errorf("Got wrong number of files in union: %v", files)
+ }
+
+ fh, _ = overlay.Open("/home/test")
+ files, err = fh.Readdirnames(-1)
+ fh.Close()
+ if err != nil {
+ t.Errorf("Readdirnames failed")
+ }
+ if len(files) != 2 {
+ t.Errorf("Got wrong number of files in overlay: %v", files)
+ }
+}
+
+func TestUnionCacheWrite(t *testing.T) {
+ base := &MemMapFs{}
+ layer := &MemMapFs{}
+
+ ufs := NewCacheOnReadFs(base, layer, 0)
+
+ base.Mkdir("/data", 0777)
+
+ fh, err := ufs.Create("/data/file.txt")
+ if err != nil {
+ t.Errorf("Failed to create file")
+ }
+ _, err = fh.Write([]byte("This is a test"))
+ if err != nil {
+ t.Errorf("Failed to write file")
+ }
+
+ fh.Seek(0, os.SEEK_SET)
+ buf := make([]byte, 4)
+ _, err = fh.Read(buf)
+ fh.Write([]byte(" IS A"))
+ fh.Close()
+
+ baseData, _ := ReadFile(base, "/data/file.txt")
+ layerData, _ := ReadFile(layer, "/data/file.txt")
+ if string(baseData) != string(layerData) {
+ t.Errorf("Different data: %s <=> %s", baseData, layerData)
+ }
+}
+
+func TestUnionCacheExpire(t *testing.T) {
+ base := &MemMapFs{}
+ layer := &MemMapFs{}
+ ufs := &CacheOnReadFs{base: base, layer: layer, cacheTime: 1 * time.Second}
+
+ base.Mkdir("/data", 0777)
+
+ fh, err := ufs.Create("/data/file.txt")
+ if err != nil {
+ t.Errorf("Failed to create file")
+ }
+ _, err = fh.Write([]byte("This is a test"))
+ if err != nil {
+ t.Errorf("Failed to write file")
+ }
+ fh.Close()
+
+ fh, _ = base.Create("/data/file.txt")
+ // sleep some time, so we really get a different time.Now() on write...
+ time.Sleep(2 * time.Second)
+ fh.WriteString("Another test")
+ fh.Close()
+
+ data, _ := ReadFile(ufs, "/data/file.txt")
+ if string(data) != "Another test" {
+ t.Errorf("cache time failed: <%s>", data)
+ }
+}
diff --git a/vendor/github.com/spf13/afero/const_bsds.go b/vendor/github.com/spf13/afero/const_bsds.go
new file mode 100644
index 000000000..5728243d9
--- /dev/null
+++ b/vendor/github.com/spf13/afero/const_bsds.go
@@ -0,0 +1,22 @@
+// Copyright © 2016 Steve Francia <spf@spf13.com>.
+//
+// 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.
+
+// +build darwin openbsd freebsd netbsd dragonfly
+
+package afero
+
+import (
+ "syscall"
+)
+
+const BADFD = syscall.EBADF
diff --git a/vendor/github.com/spf13/afero/const_win_unix.go b/vendor/github.com/spf13/afero/const_win_unix.go
new file mode 100644
index 000000000..968fc2783
--- /dev/null
+++ b/vendor/github.com/spf13/afero/const_win_unix.go
@@ -0,0 +1,25 @@
+// Copyright © 2016 Steve Francia <spf@spf13.com>.
+//
+// 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.
+// +build !darwin
+// +build !openbsd
+// +build !freebsd
+// +build !dragonfly
+// +build !netbsd
+
+package afero
+
+import (
+ "syscall"
+)
+
+const BADFD = syscall.EBADFD
diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs.go b/vendor/github.com/spf13/afero/copyOnWriteFs.go
new file mode 100644
index 000000000..ed692ae95
--- /dev/null
+++ b/vendor/github.com/spf13/afero/copyOnWriteFs.go
@@ -0,0 +1,253 @@
+package afero
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "syscall"
+ "time"
+)
+
+// The CopyOnWriteFs is a union filesystem: a read only base file system with
+// a possibly writeable layer on top. Changes to the file system will only
+// be made in the overlay: Changing an existing file in the base layer which
+// is not present in the overlay will copy the file to the overlay ("changing"
+// includes also calls to e.g. Chtimes() and Chmod()).
+//
+// Reading directories is currently only supported via Open(), not OpenFile().
+type CopyOnWriteFs struct {
+ base Fs
+ layer Fs
+}
+
+func NewCopyOnWriteFs(base Fs, layer Fs) Fs {
+ return &CopyOnWriteFs{base: base, layer: layer}
+}
+
+// Returns true if the file is not in the overlay
+func (u *CopyOnWriteFs) isBaseFile(name string) (bool, error) {
+ if _, err := u.layer.Stat(name); err == nil {
+ return false, nil
+ }
+ _, err := u.base.Stat(name)
+ if err != nil {
+ if oerr, ok := err.(*os.PathError); ok {
+ if oerr.Err == os.ErrNotExist || oerr.Err == syscall.ENOENT || oerr.Err == syscall.ENOTDIR {
+ return false, nil
+ }
+ }
+ if err == syscall.ENOENT {
+ return false, nil
+ }
+ }
+ return true, err
+}
+
+func (u *CopyOnWriteFs) copyToLayer(name string) error {
+ return copyToLayer(u.base, u.layer, name)
+}
+
+func (u *CopyOnWriteFs) Chtimes(name string, atime, mtime time.Time) error {
+ b, err := u.isBaseFile(name)
+ if err != nil {
+ return err
+ }
+ if b {
+ if err := u.copyToLayer(name); err != nil {
+ return err
+ }
+ }
+ return u.layer.Chtimes(name, atime, mtime)
+}
+
+func (u *CopyOnWriteFs) Chmod(name string, mode os.FileMode) error {
+ b, err := u.isBaseFile(name)
+ if err != nil {
+ return err
+ }
+ if b {
+ if err := u.copyToLayer(name); err != nil {
+ return err
+ }
+ }
+ return u.layer.Chmod(name, mode)
+}
+
+func (u *CopyOnWriteFs) Stat(name string) (os.FileInfo, error) {
+ fi, err := u.layer.Stat(name)
+ if err != nil {
+ origErr := err
+ if e, ok := err.(*os.PathError); ok {
+ err = e.Err
+ }
+ if err == syscall.ENOENT || err == syscall.ENOTDIR {
+ return u.base.Stat(name)
+ }
+ return nil, origErr
+ }
+ return fi, nil
+}
+
+// Renaming files present only in the base layer is not permitted
+func (u *CopyOnWriteFs) Rename(oldname, newname string) error {
+ b, err := u.isBaseFile(oldname)
+ if err != nil {
+ return err
+ }
+ if b {
+ return syscall.EPERM
+ }
+ return u.layer.Rename(oldname, newname)
+}
+
+// Removing files present only in the base layer is not permitted. If
+// a file is present in the base layer and the overlay, only the overlay
+// will be removed.
+func (u *CopyOnWriteFs) Remove(name string) error {
+ err := u.layer.Remove(name)
+ switch err {
+ case syscall.ENOENT:
+ _, err = u.base.Stat(name)
+ if err == nil {
+ return syscall.EPERM
+ }
+ return syscall.ENOENT
+ default:
+ return err
+ }
+}
+
+func (u *CopyOnWriteFs) RemoveAll(name string) error {
+ err := u.layer.RemoveAll(name)
+ switch err {
+ case syscall.ENOENT:
+ _, err = u.base.Stat(name)
+ if err == nil {
+ return syscall.EPERM
+ }
+ return syscall.ENOENT
+ default:
+ return err
+ }
+}
+
+func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
+ b, err := u.isBaseFile(name)
+ if err != nil {
+ return nil, err
+ }
+
+ if flag&(os.O_WRONLY|os.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
+ if b {
+ if err = u.copyToLayer(name); err != nil {
+ return nil, err
+ }
+ return u.layer.OpenFile(name, flag, perm)
+ }
+
+ dir := filepath.Dir(name)
+ isaDir, err := IsDir(u.base, dir)
+ if err != nil && !os.IsNotExist(err) {
+ return nil, err
+ }
+ if isaDir {
+ if err = u.layer.MkdirAll(dir, 0777); err != nil {
+ return nil, err
+ }
+ return u.layer.OpenFile(name, flag, perm)
+ }
+
+ isaDir, err = IsDir(u.layer, dir)
+ if err != nil {
+ return nil, err
+ }
+ if isaDir {
+ return u.layer.OpenFile(name, flag, perm)
+ }
+
+ return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOTDIR} // ...or os.ErrNotExist?
+ }
+ if b {
+ return u.base.OpenFile(name, flag, perm)
+ }
+ return u.layer.OpenFile(name, flag, perm)
+}
+
+// This function handles the 9 different possibilities caused
+// by the union which are the intersection of the following...
+// layer: doesn't exist, exists as a file, and exists as a directory
+// base: doesn't exist, exists as a file, and exists as a directory
+func (u *CopyOnWriteFs) Open(name string) (File, error) {
+ // Since the overlay overrides the base we check that first
+ b, err := u.isBaseFile(name)
+ if err != nil {
+ return nil, err
+ }
+
+ // If overlay doesn't exist, return the base (base state irrelevant)
+ if b {
+ return u.base.Open(name)
+ }
+
+ // If overlay is a file, return it (base state irrelevant)
+ dir, err := IsDir(u.layer, name)
+ if err != nil {
+ return nil, err
+ }
+ if !dir {
+ return u.layer.Open(name)
+ }
+
+ // Overlay is a directory, base state now matters.
+ // Base state has 3 states to check but 2 outcomes:
+ // A. It's a file or non-readable in the base (return just the overlay)
+ // B. It's an accessible directory in the base (return a UnionFile)
+
+ // If base is file or nonreadable, return overlay
+ dir, err = IsDir(u.base, name)
+ if !dir || err != nil {
+ return u.layer.Open(name)
+ }
+
+ // Both base & layer are directories
+ // Return union file (if opens are without error)
+ bfile, bErr := u.base.Open(name)
+ lfile, lErr := u.layer.Open(name)
+
+ // If either have errors at this point something is very wrong. Return nil and the errors
+ if bErr != nil || lErr != nil {
+ return nil, fmt.Errorf("BaseErr: %v\nOverlayErr: %v", bErr, lErr)
+ }
+
+ return &UnionFile{base: bfile, layer: lfile}, nil
+}
+
+func (u *CopyOnWriteFs) Mkdir(name string, perm os.FileMode) error {
+ dir, err := IsDir(u.base, name)
+ if err != nil {
+ return u.layer.MkdirAll(name, perm)
+ }
+ if dir {
+ return syscall.EEXIST
+ }
+ return u.layer.MkdirAll(name, perm)
+}
+
+func (u *CopyOnWriteFs) Name() string {
+ return "CopyOnWriteFs"
+}
+
+func (u *CopyOnWriteFs) MkdirAll(name string, perm os.FileMode) error {
+ dir, err := IsDir(u.base, name)
+ if err != nil {
+ return u.layer.MkdirAll(name, perm)
+ }
+ if dir {
+ return syscall.EEXIST
+ }
+ return u.layer.MkdirAll(name, perm)
+}
+
+func (u *CopyOnWriteFs) Create(name string) (File, error) {
+ return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666)
+}
diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs_test.go b/vendor/github.com/spf13/afero/copyOnWriteFs_test.go
new file mode 100644
index 000000000..2a00fab72
--- /dev/null
+++ b/vendor/github.com/spf13/afero/copyOnWriteFs_test.go
@@ -0,0 +1,23 @@
+package afero
+
+import "testing"
+
+func TestCopyOnWrite(t *testing.T) {
+ var fs Fs
+ var err error
+ base := NewOsFs()
+ roBase := NewReadOnlyFs(base)
+ ufs := NewCopyOnWriteFs(roBase, NewMemMapFs())
+ fs = ufs
+ err = fs.MkdirAll("nonexistent/directory/", 0744)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ _, err = fs.Create("nonexistent/directory/newfile")
+ if err != nil {
+ t.Error(err)
+ return
+ }
+
+}
diff --git a/vendor/github.com/spf13/afero/httpFs.go b/vendor/github.com/spf13/afero/httpFs.go
new file mode 100644
index 000000000..c42193688
--- /dev/null
+++ b/vendor/github.com/spf13/afero/httpFs.go
@@ -0,0 +1,110 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+//
+// 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.
+
+package afero
+
+import (
+ "errors"
+ "net/http"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+type httpDir struct {
+ basePath string
+ fs HttpFs
+}
+
+func (d httpDir) Open(name string) (http.File, error) {
+ if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
+ strings.Contains(name, "\x00") {
+ return nil, errors.New("http: invalid character in file path")
+ }
+ dir := string(d.basePath)
+ if dir == "" {
+ dir = "."
+ }
+
+ f, err := d.fs.Open(filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))))
+ if err != nil {
+ return nil, err
+ }
+ return f, nil
+}
+
+type HttpFs struct {
+ source Fs
+}
+
+func NewHttpFs(source Fs) *HttpFs {
+ return &HttpFs{source: source}
+}
+
+func (h HttpFs) Dir(s string) *httpDir {
+ return &httpDir{basePath: s, fs: h}
+}
+
+func (h HttpFs) Name() string { return "h HttpFs" }
+
+func (h HttpFs) Create(name string) (File, error) {
+ return h.source.Create(name)
+}
+
+func (h HttpFs) Chmod(name string, mode os.FileMode) error {
+ return h.source.Chmod(name, mode)
+}
+
+func (h HttpFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
+ return h.source.Chtimes(name, atime, mtime)
+}
+
+func (h HttpFs) Mkdir(name string, perm os.FileMode) error {
+ return h.source.Mkdir(name, perm)
+}
+
+func (h HttpFs) MkdirAll(path string, perm os.FileMode) error {
+ return h.source.MkdirAll(path, perm)
+}
+
+func (h HttpFs) Open(name string) (http.File, error) {
+ f, err := h.source.Open(name)
+ if err == nil {
+ if httpfile, ok := f.(http.File); ok {
+ return httpfile, nil
+ }
+ }
+ return nil, err
+}
+
+func (h HttpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
+ return h.source.OpenFile(name, flag, perm)
+}
+
+func (h HttpFs) Remove(name string) error {
+ return h.source.Remove(name)
+}
+
+func (h HttpFs) RemoveAll(path string) error {
+ return h.source.RemoveAll(path)
+}
+
+func (h HttpFs) Rename(oldname, newname string) error {
+ return h.source.Rename(oldname, newname)
+}
+
+func (h HttpFs) Stat(name string) (os.FileInfo, error) {
+ return h.source.Stat(name)
+}
diff --git a/vendor/github.com/spf13/afero/ioutil.go b/vendor/github.com/spf13/afero/ioutil.go
new file mode 100644
index 000000000..5c3a3d8ff
--- /dev/null
+++ b/vendor/github.com/spf13/afero/ioutil.go
@@ -0,0 +1,230 @@
+// Copyright ©2015 The Go Authors
+// Copyright ©2015 Steve Francia <spf@spf13.com>
+//
+// 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.
+
+package afero
+
+import (
+ "bytes"
+ "io"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "sync"
+ "time"
+)
+
+// byName implements sort.Interface.
+type byName []os.FileInfo
+
+func (f byName) Len() int { return len(f) }
+func (f byName) Less(i, j int) bool { return f[i].Name() < f[j].Name() }
+func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
+
+// ReadDir reads the directory named by dirname and returns
+// a list of sorted directory entries.
+func (a Afero) ReadDir(dirname string) ([]os.FileInfo, error) {
+ return ReadDir(a.Fs, dirname)
+}
+
+func ReadDir(fs Fs, dirname string) ([]os.FileInfo, error) {
+ f, err := fs.Open(dirname)
+ if err != nil {
+ return nil, err
+ }
+ list, err := f.Readdir(-1)
+ f.Close()
+ if err != nil {
+ return nil, err
+ }
+ sort.Sort(byName(list))
+ return list, nil
+}
+
+// ReadFile reads the file named by filename and returns the contents.
+// A successful call returns err == nil, not err == EOF. Because ReadFile
+// reads the whole file, it does not treat an EOF from Read as an error
+// to be reported.
+func (a Afero) ReadFile(filename string) ([]byte, error) {
+ return ReadFile(a.Fs, filename)
+}
+
+func ReadFile(fs Fs, filename string) ([]byte, error) {
+ f, err := fs.Open(filename)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ // It's a good but not certain bet that FileInfo will tell us exactly how much to
+ // read, so let's try it but be prepared for the answer to be wrong.
+ var n int64
+
+ if fi, err := f.Stat(); err == nil {
+ // Don't preallocate a huge buffer, just in case.
+ if size := fi.Size(); size < 1e9 {
+ n = size
+ }
+ }
+ // As initial capacity for readAll, use n + a little extra in case Size is zero,
+ // and to avoid another allocation after Read has filled the buffer. The readAll
+ // call will read into its allocated internal buffer cheaply. If the size was
+ // wrong, we'll either waste some space off the end or reallocate as needed, but
+ // in the overwhelmingly common case we'll get it just right.
+ return readAll(f, n+bytes.MinRead)
+}
+
+// readAll reads from r until an error or EOF and returns the data it read
+// from the internal buffer allocated with a specified capacity.
+func readAll(r io.Reader, capacity int64) (b []byte, err error) {
+ buf := bytes.NewBuffer(make([]byte, 0, capacity))
+ // If the buffer overflows, we will get bytes.ErrTooLarge.
+ // Return that as an error. Any other panic remains.
+ defer func() {
+ e := recover()
+ if e == nil {
+ return
+ }
+ if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
+ err = panicErr
+ } else {
+ panic(e)
+ }
+ }()
+ _, err = buf.ReadFrom(r)
+ return buf.Bytes(), err
+}
+
+// ReadAll reads from r until an error or EOF and returns the data it read.
+// A successful call returns err == nil, not err == EOF. Because ReadAll is
+// defined to read from src until EOF, it does not treat an EOF from Read
+// as an error to be reported.
+func ReadAll(r io.Reader) ([]byte, error) {
+ return readAll(r, bytes.MinRead)
+}
+
+// WriteFile writes data to a file named by filename.
+// If the file does not exist, WriteFile creates it with permissions perm;
+// otherwise WriteFile truncates it before writing.
+func (a Afero) WriteFile(filename string, data []byte, perm os.FileMode) error {
+ return WriteFile(a.Fs, filename, data, perm)
+}
+
+func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error {
+ f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
+ if err != nil {
+ return err
+ }
+ n, err := f.Write(data)
+ if err == nil && n < len(data) {
+ err = io.ErrShortWrite
+ }
+ if err1 := f.Close(); err == nil {
+ err = err1
+ }
+ return err
+}
+
+// Random number state.
+// We generate random temporary file names so that there's a good
+// chance the file doesn't exist yet - keeps the number of tries in
+// TempFile to a minimum.
+var rand uint32
+var randmu sync.Mutex
+
+func reseed() uint32 {
+ return uint32(time.Now().UnixNano() + int64(os.Getpid()))
+}
+
+func nextSuffix() string {
+ randmu.Lock()
+ r := rand
+ if r == 0 {
+ r = reseed()
+ }
+ r = r*1664525 + 1013904223 // constants from Numerical Recipes
+ rand = r
+ randmu.Unlock()
+ return strconv.Itoa(int(1e9 + r%1e9))[1:]
+}
+
+// TempFile creates a new temporary file in the directory dir
+// with a name beginning with prefix, opens the file for reading
+// and writing, and returns the resulting *File.
+// If dir is the empty string, TempFile uses the default directory
+// for temporary files (see os.TempDir).
+// Multiple programs calling TempFile simultaneously
+// will not choose the same file. The caller can use f.Name()
+// to find the pathname of the file. It is the caller's responsibility
+// to remove the file when no longer needed.
+func (a Afero) TempFile(dir, prefix string) (f File, err error) {
+ return TempFile(a.Fs, dir, prefix)
+}
+
+func TempFile(fs Fs, dir, prefix string) (f File, err error) {
+ if dir == "" {
+ dir = os.TempDir()
+ }
+
+ nconflict := 0
+ for i := 0; i < 10000; i++ {
+ name := filepath.Join(dir, prefix+nextSuffix())
+ f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
+ if os.IsExist(err) {
+ if nconflict++; nconflict > 10 {
+ randmu.Lock()
+ rand = reseed()
+ randmu.Unlock()
+ }
+ continue
+ }
+ break
+ }
+ return
+}
+
+// TempDir creates a new temporary directory in the directory dir
+// with a name beginning with prefix and returns the path of the
+// new directory. If dir is the empty string, TempDir uses the
+// default directory for temporary files (see os.TempDir).
+// Multiple programs calling TempDir simultaneously
+// will not choose the same directory. It is the caller's responsibility
+// to remove the directory when no longer needed.
+func (a Afero) TempDir(dir, prefix string) (name string, err error) {
+ return TempDir(a.Fs, dir, prefix)
+}
+func TempDir(fs Fs, dir, prefix string) (name string, err error) {
+ if dir == "" {
+ dir = os.TempDir()
+ }
+
+ nconflict := 0
+ for i := 0; i < 10000; i++ {
+ try := filepath.Join(dir, prefix+nextSuffix())
+ err = fs.Mkdir(try, 0700)
+ if os.IsExist(err) {
+ if nconflict++; nconflict > 10 {
+ randmu.Lock()
+ rand = reseed()
+ randmu.Unlock()
+ }
+ continue
+ }
+ if err == nil {
+ name = try
+ }
+ break
+ }
+ return
+}
diff --git a/vendor/github.com/spf13/afero/ioutil_test.go b/vendor/github.com/spf13/afero/ioutil_test.go
new file mode 100644
index 000000000..e7c9f0698
--- /dev/null
+++ b/vendor/github.com/spf13/afero/ioutil_test.go
@@ -0,0 +1,112 @@
+// ©2015 The Go Authors
+// Copyright ©2015 Steve Francia <spf@spf13.com>
+//
+// 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.
+
+package afero
+
+import "testing"
+
+func checkSizePath(t *testing.T, path string, size int64) {
+ dir, err := testFS.Stat(path)
+ if err != nil {
+ t.Fatalf("Stat %q (looking for size %d): %s", path, size, err)
+ }
+ if dir.Size() != size {
+ t.Errorf("Stat %q: size %d want %d", path, dir.Size(), size)
+ }
+}
+
+func TestReadFile(t *testing.T) {
+ testFS = &MemMapFs{}
+ fsutil := &Afero{Fs: testFS}
+
+ testFS.Create("this_exists.go")
+ filename := "rumpelstilzchen"
+ contents, err := fsutil.ReadFile(filename)
+ if err == nil {
+ t.Fatalf("ReadFile %s: error expected, none found", filename)
+ }
+
+ filename = "this_exists.go"
+ contents, err = fsutil.ReadFile(filename)
+ if err != nil {
+ t.Fatalf("ReadFile %s: %v", filename, err)
+ }
+
+ checkSizePath(t, filename, int64(len(contents)))
+}
+
+func TestWriteFile(t *testing.T) {
+ testFS = &MemMapFs{}
+ fsutil := &Afero{Fs: testFS}
+ f, err := fsutil.TempFile("", "ioutil-test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ filename := f.Name()
+ data := "Programming today is a race between software engineers striving to " +
+ "build bigger and better idiot-proof programs, and the Universe trying " +
+ "to produce bigger and better idiots. So far, the Universe is winning."
+
+ if err := fsutil.WriteFile(filename, []byte(data), 0644); err != nil {
+ t.Fatalf("WriteFile %s: %v", filename, err)
+ }
+
+ contents, err := fsutil.ReadFile(filename)
+ if err != nil {
+ t.Fatalf("ReadFile %s: %v", filename, err)
+ }
+
+ if string(contents) != data {
+ t.Fatalf("contents = %q\nexpected = %q", string(contents), data)
+ }
+
+ // cleanup
+ f.Close()
+ testFS.Remove(filename) // ignore error
+}
+
+func TestReadDir(t *testing.T) {
+ testFS = &MemMapFs{}
+ testFS.Mkdir("/i-am-a-dir", 0777)
+ testFS.Create("/this_exists.go")
+ dirname := "rumpelstilzchen"
+ _, err := ReadDir(testFS, dirname)
+ if err == nil {
+ t.Fatalf("ReadDir %s: error expected, none found", dirname)
+ }
+
+ dirname = ".."
+ list, err := ReadDir(testFS, dirname)
+ if err != nil {
+ t.Fatalf("ReadDir %s: %v", dirname, err)
+ }
+
+ foundFile := false
+ foundSubDir := false
+ for _, dir := range list {
+ switch {
+ case !dir.IsDir() && dir.Name() == "this_exists.go":
+ foundFile = true
+ case dir.IsDir() && dir.Name() == "i-am-a-dir":
+ foundSubDir = true
+ }
+ }
+ if !foundFile {
+ t.Fatalf("ReadDir %s: this_exists.go file not found", dirname)
+ }
+ if !foundSubDir {
+ t.Fatalf("ReadDir %s: i-am-a-dir directory not found", dirname)
+ }
+}
diff --git a/vendor/github.com/spf13/afero/mem/dir.go b/vendor/github.com/spf13/afero/mem/dir.go
new file mode 100644
index 000000000..e104013f4
--- /dev/null
+++ b/vendor/github.com/spf13/afero/mem/dir.go
@@ -0,0 +1,37 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+//
+// 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.
+
+package mem
+
+type Dir interface {
+ Len() int
+ Names() []string
+ Files() []*FileData
+ Add(*FileData)
+ Remove(*FileData)
+}
+
+func RemoveFromMemDir(dir *FileData, f *FileData) {
+ dir.memDir.Remove(f)
+}
+
+func AddToMemDir(dir *FileData, f *FileData) {
+ dir.memDir.Add(f)
+}
+
+func InitializeDir(d *FileData) {
+ if d.memDir == nil {
+ d.dir = true
+ d.memDir = &DirMap{}
+ }
+}
diff --git a/vendor/github.com/spf13/afero/mem/dirmap.go b/vendor/github.com/spf13/afero/mem/dirmap.go
new file mode 100644
index 000000000..03a57ee5b
--- /dev/null
+++ b/vendor/github.com/spf13/afero/mem/dirmap.go
@@ -0,0 +1,43 @@
+// Copyright © 2015 Steve Francia <spf@spf13.com>.
+//
+// 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.
+
+package mem
+
+import "sort"
+
+type DirMap map[string]*FileData
+
+func (m DirMap) Len() int { return len(m) }
+func (m DirMap) Add(f *FileData) { m[f.name] = f }
+func (m DirMap) Remove(f *FileData) { delete(m, f.name) }
+func (m DirMap) Files() (files []*FileData) {
+ for _, f := range m {
+ files = append(files, f)
+ }
+ sort.Sort(filesSorter(files))
+ return files
+}
+
+// implement sort.Interface for []*FileData
+type filesSorter []*FileData
+
+func (s filesSorter) Len() int { return len(s) }
+func (s filesSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+func (s filesSorter) Less(i, j int) bool { return s[i].name < s[j].name }
+
+func (m DirMap) Names() (names []string) {
+ for x := range m {
+ names = append(names, x)
+ }
+ return names
+}
diff --git a/vendor/github.com/spf13/afero/mem/file.go b/vendor/github.com/spf13/afero/mem/file.go
new file mode 100644
index 000000000..e41e0123d
--- /dev/null
+++ b/vendor/github.com/spf13/afero/mem/file.go
@@ -0,0 +1,285 @@
+// Copyright © 2015 Steve Francia <spf@spf13.com>.
+// Copyright 2013 tsuru authors. All rights reserved.
+//
+// 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.
+
+package mem
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "sync"
+ "sync/atomic"
+)
+
+import "time"
+
+const FilePathSeparator = string(filepath.Separator)
+
+type File struct {
+ // atomic requires 64-bit alignment for struct field access
+ at int64
+ readDirCount int64
+ closed bool
+ readOnly bool
+ fileData *FileData
+}
+
+func NewFileHandle(data *FileData) *File {
+ return &File{fileData: data}
+}
+
+func NewReadOnlyFileHandle(data *FileData) *File {
+ return &File{fileData: data, readOnly: true}
+}
+
+func (f File) Data() *FileData {
+ return f.fileData
+}
+
+type FileData struct {
+ sync.Mutex
+ name string
+ data []byte
+ memDir Dir
+ dir bool
+ mode os.FileMode
+ modtime time.Time
+}
+
+func (d *FileData) Name() string {
+ d.Lock()
+ defer d.Unlock()
+ return d.name
+}
+
+func CreateFile(name string) *FileData {
+ return &FileData{name: name, mode: os.ModeTemporary, modtime: time.Now()}
+}
+
+func CreateDir(name string) *FileData {
+ return &FileData{name: name, memDir: &DirMap{}, dir: true}
+}
+
+func ChangeFileName(f *FileData, newname string) {
+ f.name = newname
+}
+
+func SetMode(f *FileData, mode os.FileMode) {
+ f.mode = mode
+}
+
+func SetModTime(f *FileData, mtime time.Time) {
+ f.modtime = mtime
+}
+
+func GetFileInfo(f *FileData) *FileInfo {
+ return &FileInfo{f}
+}
+
+func (f *File) Open() error {
+ atomic.StoreInt64(&f.at, 0)
+ atomic.StoreInt64(&f.readDirCount, 0)
+ f.fileData.Lock()
+ f.closed = false
+ f.fileData.Unlock()
+ return nil
+}
+
+func (f *File) Close() error {
+ f.fileData.Lock()
+ f.closed = true
+ if !f.readOnly {
+ SetModTime(f.fileData, time.Now())
+ }
+ f.fileData.Unlock()
+ return nil
+}
+
+func (f *File) Name() string {
+ return f.fileData.Name()
+}
+
+func (f *File) Stat() (os.FileInfo, error) {
+ return &FileInfo{f.fileData}, nil
+}
+
+func (f *File) Sync() error {
+ return nil
+}
+
+func (f *File) Readdir(count int) (res []os.FileInfo, err error) {
+ var outLength int64
+
+ f.fileData.Lock()
+ files := f.fileData.memDir.Files()[f.readDirCount:]
+ if count > 0 {
+ if len(files) < count {
+ outLength = int64(len(files))
+ } else {
+ outLength = int64(count)
+ }
+ if len(files) == 0 {
+ err = io.EOF
+ }
+ } else {
+ outLength = int64(len(files))
+ }
+ f.readDirCount += outLength
+ f.fileData.Unlock()
+
+ res = make([]os.FileInfo, outLength)
+ for i := range res {
+ res[i] = &FileInfo{files[i]}
+ }
+
+ return res, err
+}
+
+func (f *File) Readdirnames(n int) (names []string, err error) {
+ fi, err := f.Readdir(n)
+ names = make([]string, len(fi))
+ for i, f := range fi {
+ _, names[i] = filepath.Split(f.Name())
+ }
+ return names, err
+}
+
+func (f *File) Read(b []byte) (n int, err error) {
+ f.fileData.Lock()
+ defer f.fileData.Unlock()
+ if f.closed == true {
+ return 0, ErrFileClosed
+ }
+ if len(b) > 0 && int(f.at) == len(f.fileData.data) {
+ return 0, io.EOF
+ }
+ if len(f.fileData.data)-int(f.at) >= len(b) {
+ n = len(b)
+ } else {
+ n = len(f.fileData.data) - int(f.at)
+ }
+ copy(b, f.fileData.data[f.at:f.at+int64(n)])
+ atomic.AddInt64(&f.at, int64(n))
+ return
+}
+
+func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
+ atomic.StoreInt64(&f.at, off)
+ return f.Read(b)
+}
+
+func (f *File) Truncate(size int64) error {
+ if f.closed == true {
+ return ErrFileClosed
+ }
+ if f.readOnly {
+ return &os.PathError{Op: "truncate", Path: f.fileData.name, Err: errors.New("file handle is read only")}
+ }
+ if size < 0 {
+ return ErrOutOfRange
+ }
+ if size > int64(len(f.fileData.data)) {
+ diff := size - int64(len(f.fileData.data))
+ f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{00}, int(diff))...)
+ } else {
+ f.fileData.data = f.fileData.data[0:size]
+ }
+ SetModTime(f.fileData, time.Now())
+ return nil
+}
+
+func (f *File) Seek(offset int64, whence int) (int64, error) {
+ if f.closed == true {
+ return 0, ErrFileClosed
+ }
+ switch whence {
+ case 0:
+ atomic.StoreInt64(&f.at, offset)
+ case 1:
+ atomic.AddInt64(&f.at, int64(offset))
+ case 2:
+ atomic.StoreInt64(&f.at, int64(len(f.fileData.data))+offset)
+ }
+ return f.at, nil
+}
+
+func (f *File) Write(b []byte) (n int, err error) {
+ if f.readOnly {
+ return 0, &os.PathError{Op: "write", Path: f.fileData.name, Err: errors.New("file handle is read only")}
+ }
+ n = len(b)
+ cur := atomic.LoadInt64(&f.at)
+ f.fileData.Lock()
+ defer f.fileData.Unlock()
+ diff := cur - int64(len(f.fileData.data))
+ var tail []byte
+ if n+int(cur) < len(f.fileData.data) {
+ tail = f.fileData.data[n+int(cur):]
+ }
+ if diff > 0 {
+ f.fileData.data = append(bytes.Repeat([]byte{00}, int(diff)), b...)
+ f.fileData.data = append(f.fileData.data, tail...)
+ } else {
+ f.fileData.data = append(f.fileData.data[:cur], b...)
+ f.fileData.data = append(f.fileData.data, tail...)
+ }
+ SetModTime(f.fileData, time.Now())
+
+ atomic.StoreInt64(&f.at, int64(len(f.fileData.data)))
+ return
+}
+
+func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
+ atomic.StoreInt64(&f.at, off)
+ return f.Write(b)
+}
+
+func (f *File) WriteString(s string) (ret int, err error) {
+ return f.Write([]byte(s))
+}
+
+func (f *File) Info() *FileInfo {
+ return &FileInfo{f.fileData}
+}
+
+type FileInfo struct {
+ *FileData
+}
+
+// Implements os.FileInfo
+func (s *FileInfo) Name() string {
+ _, name := filepath.Split(s.name)
+ return name
+}
+func (s *FileInfo) Mode() os.FileMode { return s.mode }
+func (s *FileInfo) ModTime() time.Time { return s.modtime }
+func (s *FileInfo) IsDir() bool { return s.dir }
+func (s *FileInfo) Sys() interface{} { return nil }
+func (s *FileInfo) Size() int64 {
+ if s.IsDir() {
+ return int64(42)
+ }
+ return int64(len(s.data))
+}
+
+var (
+ ErrFileClosed = errors.New("File is closed")
+ ErrOutOfRange = errors.New("Out of range")
+ ErrTooLarge = errors.New("Too large")
+ ErrFileNotFound = os.ErrNotExist
+ ErrFileExists = os.ErrExist
+ ErrDestinationExists = os.ErrExist
+)
diff --git a/vendor/github.com/spf13/afero/memmap.go b/vendor/github.com/spf13/afero/memmap.go
new file mode 100644
index 000000000..767ac1d5f
--- /dev/null
+++ b/vendor/github.com/spf13/afero/memmap.go
@@ -0,0 +1,361 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+//
+// 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.
+
+package afero
+
+import (
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/spf13/afero/mem"
+)
+
+type MemMapFs struct {
+ mu sync.RWMutex
+ data map[string]*mem.FileData
+ init sync.Once
+}
+
+func NewMemMapFs() Fs {
+ return &MemMapFs{}
+}
+
+func (m *MemMapFs) getData() map[string]*mem.FileData {
+ m.init.Do(func() {
+ m.data = make(map[string]*mem.FileData)
+ // Root should always exist, right?
+ // TODO: what about windows?
+ m.data[FilePathSeparator] = mem.CreateDir(FilePathSeparator)
+ })
+ return m.data
+}
+
+func (*MemMapFs) Name() string { return "MemMapFS" }
+
+func (m *MemMapFs) Create(name string) (File, error) {
+ name = normalizePath(name)
+ m.mu.Lock()
+ file := mem.CreateFile(name)
+ m.getData()[name] = file
+ m.registerWithParent(file)
+ m.mu.Unlock()
+ return mem.NewFileHandle(file), nil
+}
+
+func (m *MemMapFs) unRegisterWithParent(fileName string) error {
+ f, err := m.lockfreeOpen(fileName)
+ if err != nil {
+ return err
+ }
+ parent := m.findParent(f)
+ if parent == nil {
+ log.Panic("parent of ", f.Name(), " is nil")
+ }
+ mem.RemoveFromMemDir(parent, f)
+ return nil
+}
+
+func (m *MemMapFs) findParent(f *mem.FileData) *mem.FileData {
+ pdir, _ := filepath.Split(f.Name())
+ pdir = filepath.Clean(pdir)
+ pfile, err := m.lockfreeOpen(pdir)
+ if err != nil {
+ return nil
+ }
+ return pfile
+}
+
+func (m *MemMapFs) registerWithParent(f *mem.FileData) {
+ if f == nil {
+ return
+ }
+ parent := m.findParent(f)
+ if parent == nil {
+ pdir := filepath.Dir(filepath.Clean(f.Name()))
+ err := m.lockfreeMkdir(pdir, 0777)
+ if err != nil {
+ //log.Println("Mkdir error:", err)
+ return
+ }
+ parent, err = m.lockfreeOpen(pdir)
+ if err != nil {
+ //log.Println("Open after Mkdir error:", err)
+ return
+ }
+ }
+
+ mem.InitializeDir(parent)
+ mem.AddToMemDir(parent, f)
+}
+
+func (m *MemMapFs) lockfreeMkdir(name string, perm os.FileMode) error {
+ name = normalizePath(name)
+ x, ok := m.getData()[name]
+ if ok {
+ // Only return ErrFileExists if it's a file, not a directory.
+ i := mem.FileInfo{FileData: x}
+ if !i.IsDir() {
+ return ErrFileExists
+ }
+ } else {
+ item := mem.CreateDir(name)
+ m.getData()[name] = item
+ m.registerWithParent(item)
+ }
+ return nil
+}
+
+func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error {
+ name = normalizePath(name)
+
+ m.mu.RLock()
+ _, ok := m.getData()[name]
+ m.mu.RUnlock()
+ if ok {
+ return &os.PathError{Op: "mkdir", Path: name, Err: ErrFileExists}
+ }
+
+ m.mu.Lock()
+ item := mem.CreateDir(name)
+ m.getData()[name] = item
+ m.registerWithParent(item)
+ m.mu.Unlock()
+
+ m.Chmod(name, perm)
+
+ return nil
+}
+
+func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error {
+ err := m.Mkdir(path, perm)
+ if err != nil {
+ if err.(*os.PathError).Err == ErrFileExists {
+ return nil
+ } else {
+ return err
+ }
+ }
+ return nil
+}
+
+// Handle some relative paths
+func normalizePath(path string) string {
+ path = filepath.Clean(path)
+
+ switch path {
+ case ".":
+ return FilePathSeparator
+ case "..":
+ return FilePathSeparator
+ default:
+ return path
+ }
+}
+
+func (m *MemMapFs) Open(name string) (File, error) {
+ f, err := m.open(name)
+ if f != nil {
+ return mem.NewReadOnlyFileHandle(f), err
+ }
+ return nil, err
+}
+
+func (m *MemMapFs) openWrite(name string) (File, error) {
+ f, err := m.open(name)
+ if f != nil {
+ return mem.NewFileHandle(f), err
+ }
+ return nil, err
+}
+
+func (m *MemMapFs) open(name string) (*mem.FileData, error) {
+ name = normalizePath(name)
+
+ m.mu.RLock()
+ f, ok := m.getData()[name]
+ m.mu.RUnlock()
+ if !ok {
+ return nil, &os.PathError{Op: "open", Path: name, Err: ErrFileNotFound}
+ }
+ return f, nil
+}
+
+func (m *MemMapFs) lockfreeOpen(name string) (*mem.FileData, error) {
+ name = normalizePath(name)
+ f, ok := m.getData()[name]
+ if ok {
+ return f, nil
+ } else {
+ return nil, ErrFileNotFound
+ }
+}
+
+func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
+ chmod := false
+ file, err := m.openWrite(name)
+ if os.IsNotExist(err) && (flag&os.O_CREATE > 0) {
+ file, err = m.Create(name)
+ chmod = true
+ }
+ if err != nil {
+ return nil, err
+ }
+ if flag == os.O_RDONLY {
+ file = mem.NewReadOnlyFileHandle(file.(*mem.File).Data())
+ }
+ if flag&os.O_APPEND > 0 {
+ _, err = file.Seek(0, os.SEEK_END)
+ if err != nil {
+ file.Close()
+ return nil, err
+ }
+ }
+ if flag&os.O_TRUNC > 0 && flag&(os.O_RDWR|os.O_WRONLY) > 0 {
+ err = file.Truncate(0)
+ if err != nil {
+ file.Close()
+ return nil, err
+ }
+ }
+ if chmod {
+ m.Chmod(name, perm)
+ }
+ return file, nil
+}
+
+func (m *MemMapFs) Remove(name string) error {
+ name = normalizePath(name)
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ if _, ok := m.getData()[name]; ok {
+ err := m.unRegisterWithParent(name)
+ if err != nil {
+ return &os.PathError{Op: "remove", Path: name, Err: err}
+ }
+ delete(m.getData(), name)
+ } else {
+ return &os.PathError{Op: "remove", Path: name, Err: os.ErrNotExist}
+ }
+ return nil
+}
+
+func (m *MemMapFs) RemoveAll(path string) error {
+ path = normalizePath(path)
+ m.mu.Lock()
+ m.unRegisterWithParent(path)
+ m.mu.Unlock()
+
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ for p, _ := range m.getData() {
+ if strings.HasPrefix(p, path) {
+ m.mu.RUnlock()
+ m.mu.Lock()
+ delete(m.getData(), p)
+ m.mu.Unlock()
+ m.mu.RLock()
+ }
+ }
+ return nil
+}
+
+func (m *MemMapFs) Rename(oldname, newname string) error {
+ oldname = normalizePath(oldname)
+ newname = normalizePath(newname)
+
+ if oldname == newname {
+ return nil
+ }
+
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ if _, ok := m.getData()[oldname]; ok {
+ m.mu.RUnlock()
+ m.mu.Lock()
+ m.unRegisterWithParent(oldname)
+ fileData := m.getData()[oldname]
+ delete(m.getData(), oldname)
+ mem.ChangeFileName(fileData, newname)
+ m.getData()[newname] = fileData
+ m.registerWithParent(fileData)
+ m.mu.Unlock()
+ m.mu.RLock()
+ } else {
+ return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound}
+ }
+ return nil
+}
+
+func (m *MemMapFs) Stat(name string) (os.FileInfo, error) {
+ f, err := m.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ fi := mem.GetFileInfo(f.(*mem.File).Data())
+ return fi, nil
+}
+
+func (m *MemMapFs) Chmod(name string, mode os.FileMode) error {
+ name = normalizePath(name)
+
+ m.mu.RLock()
+ f, ok := m.getData()[name]
+ m.mu.RUnlock()
+ if !ok {
+ return &os.PathError{Op: "chmod", Path: name, Err: ErrFileNotFound}
+ }
+
+ m.mu.Lock()
+ mem.SetMode(f, mode)
+ m.mu.Unlock()
+
+ return nil
+}
+
+func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
+ name = normalizePath(name)
+
+ m.mu.RLock()
+ f, ok := m.getData()[name]
+ m.mu.RUnlock()
+ if !ok {
+ return &os.PathError{Op: "chtimes", Path: name, Err: ErrFileNotFound}
+ }
+
+ m.mu.Lock()
+ mem.SetModTime(f, mtime)
+ m.mu.Unlock()
+
+ return nil
+}
+
+func (m *MemMapFs) List() {
+ for _, x := range m.data {
+ y := mem.FileInfo{FileData: x}
+ fmt.Println(x.Name(), y.Size())
+ }
+}
+
+// func debugMemMapList(fs Fs) {
+// if x, ok := fs.(*MemMapFs); ok {
+// x.List()
+// }
+// }
diff --git a/vendor/github.com/spf13/afero/memmap_test.go b/vendor/github.com/spf13/afero/memmap_test.go
new file mode 100644
index 000000000..ca5abbca6
--- /dev/null
+++ b/vendor/github.com/spf13/afero/memmap_test.go
@@ -0,0 +1,345 @@
+package afero
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestNormalizePath(t *testing.T) {
+ type test struct {
+ input string
+ expected string
+ }
+
+ data := []test{
+ {".", FilePathSeparator},
+ {"./", FilePathSeparator},
+ {"..", FilePathSeparator},
+ {"../", FilePathSeparator},
+ {"./..", FilePathSeparator},
+ {"./../", FilePathSeparator},
+ }
+
+ for i, d := range data {
+ cpath := normalizePath(d.input)
+ if d.expected != cpath {
+ t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, cpath)
+ }
+ }
+}
+
+func TestPathErrors(t *testing.T) {
+ path := filepath.Join(".", "some", "path")
+ path2 := filepath.Join(".", "different", "path")
+ fs := NewMemMapFs()
+ perm := os.FileMode(0755)
+
+ // relevant functions:
+ // func (m *MemMapFs) Chmod(name string, mode os.FileMode) error
+ // func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error
+ // func (m *MemMapFs) Create(name string) (File, error)
+ // func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error
+ // func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error
+ // func (m *MemMapFs) Open(name string) (File, error)
+ // func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error)
+ // func (m *MemMapFs) Remove(name string) error
+ // func (m *MemMapFs) Rename(oldname, newname string) error
+ // func (m *MemMapFs) Stat(name string) (os.FileInfo, error)
+
+ err := fs.Chmod(path, perm)
+ checkPathError(t, err, "Chmod")
+
+ err = fs.Chtimes(path, time.Now(), time.Now())
+ checkPathError(t, err, "Chtimes")
+
+ // fs.Create doesn't return an error
+
+ err = fs.Mkdir(path2, perm)
+ if err != nil {
+ t.Error(err)
+ }
+ err = fs.Mkdir(path2, perm)
+ checkPathError(t, err, "Mkdir")
+
+ err = fs.MkdirAll(path2, perm)
+ if err != nil {
+ t.Error("MkdirAll:", err)
+ }
+
+ _, err = fs.Open(path)
+ checkPathError(t, err, "Open")
+
+ _, err = fs.OpenFile(path, os.O_RDWR, perm)
+ checkPathError(t, err, "OpenFile")
+
+ err = fs.Remove(path)
+ checkPathError(t, err, "Remove")
+
+ err = fs.RemoveAll(path)
+ if err != nil {
+ t.Error("RemoveAll:", err)
+ }
+
+ err = fs.Rename(path, path2)
+ checkPathError(t, err, "Rename")
+
+ _, err = fs.Stat(path)
+ checkPathError(t, err, "Stat")
+}
+
+func checkPathError(t *testing.T, err error, op string) {
+ pathErr, ok := err.(*os.PathError)
+ if !ok {
+ t.Error(op+":", err, "is not a os.PathError")
+ return
+ }
+ _, ok = pathErr.Err.(*os.PathError)
+ if ok {
+ t.Error(op+":", err, "contains another os.PathError")
+ }
+}
+
+// Ensure Permissions are set on OpenFile/Mkdir/MkdirAll
+func TestPermSet(t *testing.T) {
+ const fileName = "/myFileTest"
+ const dirPath = "/myDirTest"
+ const dirPathAll = "/my/path/to/dir"
+
+ const fileMode = os.FileMode(0765)
+
+ fs := NewMemMapFs()
+
+ // Test Openfile
+ f, err := fs.OpenFile(fileName, os.O_CREATE, fileMode)
+ if err != nil {
+ t.Errorf("OpenFile Create failed: %s", err)
+ return
+ }
+ f.Close()
+
+ s, err := fs.Stat(fileName)
+ if err != nil {
+ t.Errorf("Stat failed: %s", err)
+ return
+ }
+ if s.Mode().String() != fileMode.String() {
+ t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), fileMode.String())
+ return
+ }
+
+ // Test Mkdir
+ err = fs.Mkdir(dirPath, fileMode)
+ if err != nil {
+ t.Errorf("MkDir Create failed: %s", err)
+ return
+ }
+ s, err = fs.Stat(dirPath)
+ if err != nil {
+ t.Errorf("Stat failed: %s", err)
+ return
+ }
+ if s.Mode().String() != fileMode.String() {
+ t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), fileMode.String())
+ return
+ }
+
+ // Test MkdirAll
+ err = fs.MkdirAll(dirPathAll, fileMode)
+ if err != nil {
+ t.Errorf("MkDir Create failed: %s", err)
+ return
+ }
+ s, err = fs.Stat(dirPathAll)
+ if err != nil {
+ t.Errorf("Stat failed: %s", err)
+ return
+ }
+ if s.Mode().String() != fileMode.String() {
+ t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), fileMode.String())
+ return
+ }
+}
+
+// Fails if multiple file objects use the same file.at counter in MemMapFs
+func TestMultipleOpenFiles(t *testing.T) {
+ defer removeAllTestFiles(t)
+ const fileName = "afero-demo2.txt"
+
+ var data = make([][]byte, len(Fss))
+
+ for i, fs := range Fss {
+ dir := testDir(fs)
+ path := filepath.Join(dir, fileName)
+ fh1, err := fs.Create(path)
+ if err != nil {
+ t.Error("fs.Create failed: " + err.Error())
+ }
+ _, err = fh1.Write([]byte("test"))
+ if err != nil {
+ t.Error("fh.Write failed: " + err.Error())
+ }
+ _, err = fh1.Seek(0, os.SEEK_SET)
+ if err != nil {
+ t.Error(err)
+ }
+
+ fh2, err := fs.OpenFile(path, os.O_RDWR, 0777)
+ if err != nil {
+ t.Error("fs.OpenFile failed: " + err.Error())
+ }
+ _, err = fh2.Seek(0, os.SEEK_END)
+ if err != nil {
+ t.Error(err)
+ }
+ _, err = fh2.Write([]byte("data"))
+ if err != nil {
+ t.Error(err)
+ }
+ err = fh2.Close()
+ if err != nil {
+ t.Error(err)
+ }
+
+ _, err = fh1.Write([]byte("data"))
+ if err != nil {
+ t.Error(err)
+ }
+ err = fh1.Close()
+ if err != nil {
+ t.Error(err)
+ }
+ // the file now should contain "datadata"
+ data[i], err = ReadFile(fs, path)
+ if err != nil {
+ t.Error(err)
+ }
+ }
+
+ for i, fs := range Fss {
+ if i == 0 {
+ continue
+ }
+ if string(data[0]) != string(data[i]) {
+ t.Errorf("%s and %s don't behave the same\n"+
+ "%s: \"%s\"\n%s: \"%s\"\n",
+ Fss[0].Name(), fs.Name(), Fss[0].Name(), data[0], fs.Name(), data[i])
+ }
+ }
+}
+
+// Test if file.Write() fails when opened as read only
+func TestReadOnly(t *testing.T) {
+ defer removeAllTestFiles(t)
+ const fileName = "afero-demo.txt"
+
+ for _, fs := range Fss {
+ dir := testDir(fs)
+ path := filepath.Join(dir, fileName)
+
+ f, err := fs.Create(path)
+ if err != nil {
+ t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
+ }
+ _, err = f.Write([]byte("test"))
+ if err != nil {
+ t.Error(fs.Name()+":", "Write failed: "+err.Error())
+ }
+ f.Close()
+
+ f, err = fs.Open(path)
+ if err != nil {
+ t.Error("fs.Open failed: " + err.Error())
+ }
+ _, err = f.Write([]byte("data"))
+ if err == nil {
+ t.Error(fs.Name()+":", "No write error")
+ }
+ f.Close()
+
+ f, err = fs.OpenFile(path, os.O_RDONLY, 0644)
+ if err != nil {
+ t.Error("fs.Open failed: " + err.Error())
+ }
+ _, err = f.Write([]byte("data"))
+ if err == nil {
+ t.Error(fs.Name()+":", "No write error")
+ }
+ f.Close()
+ }
+}
+
+func TestWriteCloseTime(t *testing.T) {
+ defer removeAllTestFiles(t)
+ const fileName = "afero-demo.txt"
+
+ for _, fs := range Fss {
+ dir := testDir(fs)
+ path := filepath.Join(dir, fileName)
+
+ f, err := fs.Create(path)
+ if err != nil {
+ t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
+ }
+ f.Close()
+
+ f, err = fs.Create(path)
+ if err != nil {
+ t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
+ }
+ fi, err := f.Stat()
+ if err != nil {
+ t.Error(fs.Name()+":", "Stat failed: "+err.Error())
+ }
+ timeBefore := fi.ModTime()
+
+ // sorry for the delay, but we have to make sure time advances,
+ // also on non Un*x systems...
+ switch runtime.GOOS {
+ case "windows":
+ time.Sleep(2 * time.Second)
+ case "darwin":
+ time.Sleep(1 * time.Second)
+ default: // depending on the FS, this may work with < 1 second, on my old ext3 it does not
+ time.Sleep(1 * time.Second)
+ }
+
+ _, err = f.Write([]byte("test"))
+ if err != nil {
+ t.Error(fs.Name()+":", "Write failed: "+err.Error())
+ }
+ f.Close()
+ fi, err = fs.Stat(path)
+ if err != nil {
+ t.Error(fs.Name()+":", "fs.Stat failed: "+err.Error())
+ }
+ if fi.ModTime().Equal(timeBefore) {
+ t.Error(fs.Name()+":", "ModTime was not set on Close()")
+ }
+ }
+}
+
+// This test should be run with the race detector on:
+// go test -race -v -timeout 10s -run TestRacingDeleteAndClose
+func TestRacingDeleteAndClose(t *testing.T) {
+ fs := NewMemMapFs()
+ pathname := "testfile"
+ f, err := fs.Create(pathname)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ in := make(chan bool)
+
+ go func() {
+ <-in
+ f.Close()
+ }()
+ go func() {
+ <-in
+ fs.Remove(pathname)
+ }()
+ close(in)
+}
diff --git a/vendor/github.com/spf13/afero/memradix.go b/vendor/github.com/spf13/afero/memradix.go
new file mode 100644
index 000000000..87527f35a
--- /dev/null
+++ b/vendor/github.com/spf13/afero/memradix.go
@@ -0,0 +1,14 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+//
+// 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.
+
+package afero
diff --git a/vendor/github.com/spf13/afero/os.go b/vendor/github.com/spf13/afero/os.go
new file mode 100644
index 000000000..6b8bce1c5
--- /dev/null
+++ b/vendor/github.com/spf13/afero/os.go
@@ -0,0 +1,94 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+// Copyright 2013 tsuru authors. All rights reserved.
+//
+// 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.
+
+package afero
+
+import (
+ "os"
+ "time"
+)
+
+// OsFs is a Fs implementation that uses functions provided by the os package.
+//
+// For details in any method, check the documentation of the os package
+// (http://golang.org/pkg/os/).
+type OsFs struct{}
+
+func NewOsFs() Fs {
+ return &OsFs{}
+}
+
+func (OsFs) Name() string { return "OsFs" }
+
+func (OsFs) Create(name string) (File, error) {
+ f, e := os.Create(name)
+ if f == nil {
+ // while this looks strange, we need to return a bare nil (of type nil) not
+ // a nil value of type *os.File or nil won't be nil
+ return nil, e
+ }
+ return f, e
+}
+
+func (OsFs) Mkdir(name string, perm os.FileMode) error {
+ return os.Mkdir(name, perm)
+}
+
+func (OsFs) MkdirAll(path string, perm os.FileMode) error {
+ return os.MkdirAll(path, perm)
+}
+
+func (OsFs) Open(name string) (File, error) {
+ f, e := os.Open(name)
+ if f == nil {
+ // while this looks strange, we need to return a bare nil (of type nil) not
+ // a nil value of type *os.File or nil won't be nil
+ return nil, e
+ }
+ return f, e
+}
+
+func (OsFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
+ f, e := os.OpenFile(name, flag, perm)
+ if f == nil {
+ // while this looks strange, we need to return a bare nil (of type nil) not
+ // a nil value of type *os.File or nil won't be nil
+ return nil, e
+ }
+ return f, e
+}
+
+func (OsFs) Remove(name string) error {
+ return os.Remove(name)
+}
+
+func (OsFs) RemoveAll(path string) error {
+ return os.RemoveAll(path)
+}
+
+func (OsFs) Rename(oldname, newname string) error {
+ return os.Rename(oldname, newname)
+}
+
+func (OsFs) Stat(name string) (os.FileInfo, error) {
+ return os.Stat(name)
+}
+
+func (OsFs) Chmod(name string, mode os.FileMode) error {
+ return os.Chmod(name, mode)
+}
+
+func (OsFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
+ return os.Chtimes(name, atime, mtime)
+}
diff --git a/vendor/github.com/spf13/afero/path.go b/vendor/github.com/spf13/afero/path.go
new file mode 100644
index 000000000..1d90e46dd
--- /dev/null
+++ b/vendor/github.com/spf13/afero/path.go
@@ -0,0 +1,108 @@
+// Copyright ©2015 The Go Authors
+// Copyright ©2015 Steve Francia <spf@spf13.com>
+//
+// 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.
+
+package afero
+
+import (
+ "os"
+ "path/filepath"
+ "sort"
+)
+
+// readDirNames reads the directory named by dirname and returns
+// a sorted list of directory entries.
+// adapted from https://golang.org/src/path/filepath/path.go
+func readDirNames(fs Fs, dirname string) ([]string, error) {
+ f, err := fs.Open(dirname)
+ if err != nil {
+ return nil, err
+ }
+ names, err := f.Readdirnames(-1)
+ f.Close()
+ if err != nil {
+ return nil, err
+ }
+ sort.Strings(names)
+ return names, nil
+}
+
+// walk recursively descends path, calling walkFn
+// adapted from https://golang.org/src/path/filepath/path.go
+func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error {
+ err := walkFn(path, info, nil)
+ if err != nil {
+ if info.IsDir() && err == filepath.SkipDir {
+ return nil
+ }
+ return err
+ }
+
+ if !info.IsDir() {
+ return nil
+ }
+
+ names, err := readDirNames(fs, path)
+ if err != nil {
+ return walkFn(path, info, err)
+ }
+
+ for _, name := range names {
+ filename := filepath.Join(path, name)
+ fileInfo, err := lstatIfOs(fs, filename)
+ if err != nil {
+ if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
+ return err
+ }
+ } else {
+ err = walk(fs, filename, fileInfo, walkFn)
+ if err != nil {
+ if !fileInfo.IsDir() || err != filepath.SkipDir {
+ return err
+ }
+ }
+ }
+ }
+ return nil
+}
+
+// if the filesystem is OsFs use Lstat, else use fs.Stat
+func lstatIfOs(fs Fs, path string) (info os.FileInfo, err error) {
+ _, ok := fs.(*OsFs)
+ if ok {
+ info, err = os.Lstat(path)
+ } else {
+ info, err = fs.Stat(path)
+ }
+ return
+}
+
+// Walk walks the file tree rooted at root, calling walkFn for each file or
+// directory in the tree, including root. All errors that arise visiting files
+// and directories are filtered by walkFn. The files are walked in lexical
+// order, which makes the output deterministic but means that for very
+// large directories Walk can be inefficient.
+// Walk does not follow symbolic links.
+
+func (a Afero) Walk(root string, walkFn filepath.WalkFunc) error {
+ return Walk(a.Fs, root, walkFn)
+}
+
+func Walk(fs Fs, root string, walkFn filepath.WalkFunc) error {
+ info, err := lstatIfOs(fs, root)
+ if err != nil {
+ return walkFn(root, nil, err)
+ }
+ return walk(fs, root, info, walkFn)
+}
diff --git a/vendor/github.com/spf13/afero/path_test.go b/vendor/github.com/spf13/afero/path_test.go
new file mode 100644
index 000000000..104a6bcbe
--- /dev/null
+++ b/vendor/github.com/spf13/afero/path_test.go
@@ -0,0 +1,69 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+// Copyright 2009 The Go Authors. All rights reserved.
+//
+// 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.
+
+package afero
+
+import (
+ "fmt"
+ "os"
+ "testing"
+)
+
+func TestWalk(t *testing.T) {
+ defer removeAllTestFiles(t)
+ var testDir string
+ for i, fs := range Fss {
+ if i == 0 {
+ testDir = setupTestDirRoot(t, fs)
+ } else {
+ setupTestDirReusePath(t, fs, testDir)
+ }
+ }
+
+ outputs := make([]string, len(Fss))
+ for i, fs := range Fss {
+ walkFn := func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ t.Error("walkFn err:", err)
+ }
+ var size int64
+ if !info.IsDir() {
+ size = info.Size()
+ }
+ outputs[i] += fmt.Sprintln(path, info.Name(), size, info.IsDir(), err)
+ return nil
+ }
+ err := Walk(fs, testDir, walkFn)
+ if err != nil {
+ t.Error(err)
+ }
+ }
+ fail := false
+ for i, o := range outputs {
+ if i == 0 {
+ continue
+ }
+ if o != outputs[i-1] {
+ fail = true
+ break
+ }
+ }
+ if fail {
+ t.Log("Walk outputs not equal!")
+ for i, o := range outputs {
+ t.Log(Fss[i].Name() + "\n" + o)
+ }
+ t.Fail()
+ }
+}
diff --git a/vendor/github.com/spf13/afero/readonlyfs.go b/vendor/github.com/spf13/afero/readonlyfs.go
new file mode 100644
index 000000000..f1fa55bcf
--- /dev/null
+++ b/vendor/github.com/spf13/afero/readonlyfs.go
@@ -0,0 +1,70 @@
+package afero
+
+import (
+ "os"
+ "syscall"
+ "time"
+)
+
+type ReadOnlyFs struct {
+ source Fs
+}
+
+func NewReadOnlyFs(source Fs) Fs {
+ return &ReadOnlyFs{source: source}
+}
+
+func (r *ReadOnlyFs) ReadDir(name string) ([]os.FileInfo, error) {
+ return ReadDir(r.source, name)
+}
+
+func (r *ReadOnlyFs) Chtimes(n string, a, m time.Time) error {
+ return syscall.EPERM
+}
+
+func (r *ReadOnlyFs) Chmod(n string, m os.FileMode) error {
+ return syscall.EPERM
+}
+
+func (r *ReadOnlyFs) Name() string {
+ return "ReadOnlyFilter"
+}
+
+func (r *ReadOnlyFs) Stat(name string) (os.FileInfo, error) {
+ return r.source.Stat(name)
+}
+
+func (r *ReadOnlyFs) Rename(o, n string) error {
+ return syscall.EPERM
+}
+
+func (r *ReadOnlyFs) RemoveAll(p string) error {
+ return syscall.EPERM
+}
+
+func (r *ReadOnlyFs) Remove(n string) error {
+ return syscall.EPERM
+}
+
+func (r *ReadOnlyFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
+ if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
+ return nil, syscall.EPERM
+ }
+ return r.source.OpenFile(name, flag, perm)
+}
+
+func (r *ReadOnlyFs) Open(n string) (File, error) {
+ return r.source.Open(n)
+}
+
+func (r *ReadOnlyFs) Mkdir(n string, p os.FileMode) error {
+ return syscall.EPERM
+}
+
+func (r *ReadOnlyFs) MkdirAll(n string, p os.FileMode) error {
+ return syscall.EPERM
+}
+
+func (r *ReadOnlyFs) Create(n string) (File, error) {
+ return nil, syscall.EPERM
+}
diff --git a/vendor/github.com/spf13/afero/regexpfs.go b/vendor/github.com/spf13/afero/regexpfs.go
new file mode 100644
index 000000000..9d92dbc05
--- /dev/null
+++ b/vendor/github.com/spf13/afero/regexpfs.go
@@ -0,0 +1,214 @@
+package afero
+
+import (
+ "os"
+ "regexp"
+ "syscall"
+ "time"
+)
+
+// The RegexpFs filters files (not directories) by regular expression. Only
+// files matching the given regexp will be allowed, all others get a ENOENT error (
+// "No such file or directory").
+//
+type RegexpFs struct {
+ re *regexp.Regexp
+ source Fs
+}
+
+func NewRegexpFs(source Fs, re *regexp.Regexp) Fs {
+ return &RegexpFs{source: source, re: re}
+}
+
+type RegexpFile struct {
+ f File
+ re *regexp.Regexp
+}
+
+func (r *RegexpFs) matchesName(name string) error {
+ if r.re == nil {
+ return nil
+ }
+ if r.re.MatchString(name) {
+ return nil
+ }
+ return syscall.ENOENT
+}
+
+func (r *RegexpFs) dirOrMatches(name string) error {
+ dir, err := IsDir(r.source, name)
+ if err != nil {
+ return err
+ }
+ if dir {
+ return nil
+ }
+ return r.matchesName(name)
+}
+
+func (r *RegexpFs) Chtimes(name string, a, m time.Time) error {
+ if err := r.dirOrMatches(name); err != nil {
+ return err
+ }
+ return r.source.Chtimes(name, a, m)
+}
+
+func (r *RegexpFs) Chmod(name string, mode os.FileMode) error {
+ if err := r.dirOrMatches(name); err != nil {
+ return err
+ }
+ return r.source.Chmod(name, mode)
+}
+
+func (r *RegexpFs) Name() string {
+ return "RegexpFs"
+}
+
+func (r *RegexpFs) Stat(name string) (os.FileInfo, error) {
+ if err := r.dirOrMatches(name); err != nil {
+ return nil, err
+ }
+ return r.source.Stat(name)
+}
+
+func (r *RegexpFs) Rename(oldname, newname string) error {
+ dir, err := IsDir(r.source, oldname)
+ if err != nil {
+ return err
+ }
+ if dir {
+ return nil
+ }
+ if err := r.matchesName(oldname); err != nil {
+ return err
+ }
+ if err := r.matchesName(newname); err != nil {
+ return err
+ }
+ return r.source.Rename(oldname, newname)
+}
+
+func (r *RegexpFs) RemoveAll(p string) error {
+ dir, err := IsDir(r.source, p)
+ if err != nil {
+ return err
+ }
+ if !dir {
+ if err := r.matchesName(p); err != nil {
+ return err
+ }
+ }
+ return r.source.RemoveAll(p)
+}
+
+func (r *RegexpFs) Remove(name string) error {
+ if err := r.dirOrMatches(name); err != nil {
+ return err
+ }
+ return r.source.Remove(name)
+}
+
+func (r *RegexpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
+ if err := r.dirOrMatches(name); err != nil {
+ return nil, err
+ }
+ return r.source.OpenFile(name, flag, perm)
+}
+
+func (r *RegexpFs) Open(name string) (File, error) {
+ dir, err := IsDir(r.source, name)
+ if err != nil {
+ return nil, err
+ }
+ if !dir {
+ if err := r.matchesName(name); err != nil {
+ return nil, err
+ }
+ }
+ f, err := r.source.Open(name)
+ return &RegexpFile{f: f, re: r.re}, nil
+}
+
+func (r *RegexpFs) Mkdir(n string, p os.FileMode) error {
+ return r.source.Mkdir(n, p)
+}
+
+func (r *RegexpFs) MkdirAll(n string, p os.FileMode) error {
+ return r.source.MkdirAll(n, p)
+}
+
+func (r *RegexpFs) Create(name string) (File, error) {
+ if err := r.matchesName(name); err != nil {
+ return nil, err
+ }
+ return r.source.Create(name)
+}
+
+func (f *RegexpFile) Close() error {
+ return f.f.Close()
+}
+
+func (f *RegexpFile) Read(s []byte) (int, error) {
+ return f.f.Read(s)
+}
+
+func (f *RegexpFile) ReadAt(s []byte, o int64) (int, error) {
+ return f.f.ReadAt(s, o)
+}
+
+func (f *RegexpFile) Seek(o int64, w int) (int64, error) {
+ return f.f.Seek(o, w)
+}
+
+func (f *RegexpFile) Write(s []byte) (int, error) {
+ return f.f.Write(s)
+}
+
+func (f *RegexpFile) WriteAt(s []byte, o int64) (int, error) {
+ return f.f.WriteAt(s, o)
+}
+
+func (f *RegexpFile) Name() string {
+ return f.f.Name()
+}
+
+func (f *RegexpFile) Readdir(c int) (fi []os.FileInfo, err error) {
+ var rfi []os.FileInfo
+ rfi, err = f.f.Readdir(c)
+ if err != nil {
+ return nil, err
+ }
+ for _, i := range rfi {
+ if i.IsDir() || f.re.MatchString(i.Name()) {
+ fi = append(fi, i)
+ }
+ }
+ return fi, nil
+}
+
+func (f *RegexpFile) Readdirnames(c int) (n []string, err error) {
+ fi, err := f.Readdir(c)
+ if err != nil {
+ return nil, err
+ }
+ for _, s := range fi {
+ n = append(n, s.Name())
+ }
+ return n, nil
+}
+
+func (f *RegexpFile) Stat() (os.FileInfo, error) {
+ return f.f.Stat()
+}
+
+func (f *RegexpFile) Sync() error {
+ return f.f.Sync()
+}
+
+func (f *RegexpFile) Truncate(s int64) error {
+ return f.f.Truncate(s)
+}
+
+func (f *RegexpFile) WriteString(s string) (int, error) {
+ return f.f.WriteString(s)
+}
diff --git a/vendor/github.com/spf13/afero/ro_regexp_test.go b/vendor/github.com/spf13/afero/ro_regexp_test.go
new file mode 100644
index 000000000..ef8a35d0d
--- /dev/null
+++ b/vendor/github.com/spf13/afero/ro_regexp_test.go
@@ -0,0 +1,96 @@
+package afero
+
+import (
+ "regexp"
+ "testing"
+)
+
+func TestFilterReadOnly(t *testing.T) {
+ fs := &ReadOnlyFs{source: &MemMapFs{}}
+ _, err := fs.Create("/file.txt")
+ if err == nil {
+ t.Errorf("Did not fail to create file")
+ }
+ // t.Logf("ERR=%s", err)
+}
+
+func TestFilterReadonlyRemoveAndRead(t *testing.T) {
+ mfs := &MemMapFs{}
+ fh, err := mfs.Create("/file.txt")
+ fh.Write([]byte("content here"))
+ fh.Close()
+
+ fs := NewReadOnlyFs(mfs)
+ err = fs.Remove("/file.txt")
+ if err == nil {
+ t.Errorf("Did not fail to remove file")
+ }
+
+ fh, err = fs.Open("/file.txt")
+ if err != nil {
+ t.Errorf("Failed to open file: %s", err)
+ }
+
+ buf := make([]byte, len("content here"))
+ _, err = fh.Read(buf)
+ fh.Close()
+ if string(buf) != "content here" {
+ t.Errorf("Failed to read file: %s", err)
+ }
+
+ err = mfs.Remove("/file.txt")
+ if err != nil {
+ t.Errorf("Failed to remove file")
+ }
+
+ fh, err = fs.Open("/file.txt")
+ if err == nil {
+ fh.Close()
+ t.Errorf("File still present")
+ }
+}
+
+func TestFilterRegexp(t *testing.T) {
+ fs := NewRegexpFs(&MemMapFs{}, regexp.MustCompile(`\.txt$`))
+ _, err := fs.Create("/file.html")
+ if err == nil {
+
+ t.Errorf("Did not fail to create file")
+ }
+ // t.Logf("ERR=%s", err)
+}
+
+func TestFilterRORegexpChain(t *testing.T) {
+ rofs := &ReadOnlyFs{source: &MemMapFs{}}
+ fs := &RegexpFs{re: regexp.MustCompile(`\.txt$`), source: rofs}
+ _, err := fs.Create("/file.txt")
+ if err == nil {
+ t.Errorf("Did not fail to create file")
+ }
+ // t.Logf("ERR=%s", err)
+}
+
+func TestFilterRegexReadDir(t *testing.T) {
+ mfs := &MemMapFs{}
+ fs1 := &RegexpFs{re: regexp.MustCompile(`\.txt$`), source: mfs}
+ fs := &RegexpFs{re: regexp.MustCompile(`^a`), source: fs1}
+
+ mfs.MkdirAll("/dir/sub", 0777)
+ for _, name := range []string{"afile.txt", "afile.html", "bfile.txt"} {
+ for _, dir := range []string{"/dir/", "/dir/sub/"} {
+ fh, _ := mfs.Create(dir + name)
+ fh.Close()
+ }
+ }
+
+ files, _ := ReadDir(fs, "/dir")
+ if len(files) != 2 { // afile.txt, sub
+ t.Errorf("Got wrong number of files: %#v", files)
+ }
+
+ f, _ := fs.Open("/dir/sub")
+ names, _ := f.Readdirnames(-1)
+ if len(names) != 1 {
+ t.Errorf("Got wrong number of names: %v", names)
+ }
+}
diff --git a/vendor/github.com/spf13/afero/sftpfs/file.go b/vendor/github.com/spf13/afero/sftpfs/file.go
new file mode 100644
index 000000000..e4ccb55c0
--- /dev/null
+++ b/vendor/github.com/spf13/afero/sftpfs/file.go
@@ -0,0 +1,95 @@
+// Copyright © 2015 Jerry Jacobs <jerry.jacobs@xor-gate.org>.
+//
+// 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.
+
+package sftpfs
+
+import (
+ "github.com/pkg/sftp"
+ "os"
+)
+
+type File struct {
+ fd *sftp.File
+}
+
+func FileOpen(s *sftp.Client, name string) (*File, error) {
+ fd, err := s.Open(name)
+ if err != nil {
+ return &File{}, err
+ }
+ return &File{fd: fd}, nil
+}
+
+func FileCreate(s *sftp.Client, name string) (*File, error) {
+ fd, err := s.Create(name)
+ if err != nil {
+ return &File{}, err
+ }
+ return &File{fd: fd}, nil
+}
+
+func (f *File) Close() error {
+ return f.fd.Close()
+}
+
+func (f *File) Name() string {
+ return f.fd.Name()
+}
+
+func (f *File) Stat() (os.FileInfo, error) {
+ return f.fd.Stat()
+}
+
+func (f *File) Sync() error {
+ return nil
+}
+
+func (f *File) Truncate(size int64) error {
+ return f.fd.Truncate(size)
+}
+
+func (f *File) Read(b []byte) (n int, err error) {
+ return f.fd.Read(b)
+}
+
+// TODO
+func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
+ return 0, nil
+}
+
+// TODO
+func (f *File) Readdir(count int) (res []os.FileInfo, err error) {
+ return nil, nil
+}
+
+// TODO
+func (f *File) Readdirnames(n int) (names []string, err error) {
+ return nil, nil
+}
+
+func (f *File) Seek(offset int64, whence int) (int64, error) {
+ return f.fd.Seek(offset, whence)
+}
+
+func (f *File) Write(b []byte) (n int, err error) {
+ return f.fd.Write(b)
+}
+
+// TODO
+func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
+ return 0, nil
+}
+
+func (f *File) WriteString(s string) (ret int, err error) {
+ return f.fd.Write([]byte(s))
+}
diff --git a/vendor/github.com/spf13/afero/sftpfs/sftp.go b/vendor/github.com/spf13/afero/sftpfs/sftp.go
new file mode 100644
index 000000000..28721da76
--- /dev/null
+++ b/vendor/github.com/spf13/afero/sftpfs/sftp.go
@@ -0,0 +1,129 @@
+// Copyright © 2015 Jerry Jacobs <jerry.jacobs@xor-gate.org>.
+//
+// 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.
+
+package sftpfs
+
+import (
+ "os"
+ "time"
+
+ "github.com/pkg/sftp"
+ "github.com/spf13/afero"
+)
+
+// Fs is a afero.Fs implementation that uses functions provided by the sftp package.
+//
+// For details in any method, check the documentation of the sftp package
+// (github.com/pkg/sftp).
+type Fs struct {
+ client *sftp.Client
+}
+
+func New(client *sftp.Client) afero.Fs {
+ return &Fs{client: client}
+}
+
+func (s Fs) Name() string { return "sftpfs" }
+
+func (s Fs) Create(name string) (afero.File, error) {
+ return FileCreate(s.client, name)
+}
+
+func (s Fs) Mkdir(name string, perm os.FileMode) error {
+ err := s.client.Mkdir(name)
+ if err != nil {
+ return err
+ }
+ return s.client.Chmod(name, perm)
+}
+
+func (s Fs) MkdirAll(path string, perm os.FileMode) error {
+ // Fast path: if we can tell whether path is a directory or file, stop with success or error.
+ dir, err := s.Stat(path)
+ if err == nil {
+ if dir.IsDir() {
+ return nil
+ }
+ return err
+ }
+
+ // Slow path: make sure parent exists and then call Mkdir for path.
+ i := len(path)
+ for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator.
+ i--
+ }
+
+ j := i
+ for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element.
+ j--
+ }
+
+ if j > 1 {
+ // Create parent
+ err = s.MkdirAll(path[0:j-1], perm)
+ if err != nil {
+ return err
+ }
+ }
+
+ // Parent now exists; invoke Mkdir and use its result.
+ err = s.Mkdir(path, perm)
+ if err != nil {
+ // Handle arguments like "foo/." by
+ // double-checking that directory doesn't exist.
+ dir, err1 := s.Lstat(path)
+ if err1 == nil && dir.IsDir() {
+ return nil
+ }
+ return err
+ }
+ return nil
+}
+
+func (s Fs) Open(name string) (afero.File, error) {
+ return FileOpen(s.client, name)
+}
+
+func (s Fs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) {
+ return nil, nil
+}
+
+func (s Fs) Remove(name string) error {
+ return s.client.Remove(name)
+}
+
+func (s Fs) RemoveAll(path string) error {
+ // TODO have a look at os.RemoveAll
+ // https://github.com/golang/go/blob/master/src/os/path.go#L66
+ return nil
+}
+
+func (s Fs) Rename(oldname, newname string) error {
+ return s.client.Rename(oldname, newname)
+}
+
+func (s Fs) Stat(name string) (os.FileInfo, error) {
+ return s.client.Stat(name)
+}
+
+func (s Fs) Lstat(p string) (os.FileInfo, error) {
+ return s.client.Lstat(p)
+}
+
+func (s Fs) Chmod(name string, mode os.FileMode) error {
+ return s.client.Chmod(name, mode)
+}
+
+func (s Fs) Chtimes(name string, atime time.Time, mtime time.Time) error {
+ return s.client.Chtimes(name, atime, mtime)
+}
diff --git a/vendor/github.com/spf13/afero/sftpfs/sftp_test_go b/vendor/github.com/spf13/afero/sftpfs/sftp_test_go
new file mode 100644
index 000000000..bb00535d8
--- /dev/null
+++ b/vendor/github.com/spf13/afero/sftpfs/sftp_test_go
@@ -0,0 +1,286 @@
+// Copyright © 2015 Jerry Jacobs <jerry.jacobs@xor-gate.org>.
+//
+// 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.
+
+package afero
+
+import (
+ "testing"
+ "os"
+ "log"
+ "fmt"
+ "net"
+ "flag"
+ "time"
+ "io/ioutil"
+ "crypto/rsa"
+ _rand "crypto/rand"
+ "encoding/pem"
+ "crypto/x509"
+
+ "golang.org/x/crypto/ssh"
+ "github.com/pkg/sftp"
+)
+
+type SftpFsContext struct {
+ sshc *ssh.Client
+ sshcfg *ssh.ClientConfig
+ sftpc *sftp.Client
+}
+
+// TODO we only connect with hardcoded user+pass for now
+// it should be possible to use $HOME/.ssh/id_rsa to login into the stub sftp server
+func SftpConnect(user, password, host string) (*SftpFsContext, error) {
+/*
+ pemBytes, err := ioutil.ReadFile(os.Getenv("HOME") + "/.ssh/id_rsa")
+ if err != nil {
+ return nil,err
+ }
+
+ signer, err := ssh.ParsePrivateKey(pemBytes)
+ if err != nil {
+ return nil,err
+ }
+
+ sshcfg := &ssh.ClientConfig{
+ User: user,
+ Auth: []ssh.AuthMethod{
+ ssh.Password(password),
+ ssh.PublicKeys(signer),
+ },
+ }
+*/
+
+ sshcfg := &ssh.ClientConfig{
+ User: user,
+ Auth: []ssh.AuthMethod{
+ ssh.Password(password),
+ },
+ }
+
+ sshc, err := ssh.Dial("tcp", host, sshcfg)
+ if err != nil {
+ return nil,err
+ }
+
+ sftpc, err := sftp.NewClient(sshc)
+ if err != nil {
+ return nil,err
+ }
+
+ ctx := &SftpFsContext{
+ sshc: sshc,
+ sshcfg: sshcfg,
+ sftpc: sftpc,
+ }
+
+ return ctx,nil
+}
+
+func (ctx *SftpFsContext) Disconnect() error {
+ ctx.sftpc.Close()
+ ctx.sshc.Close()
+ return nil
+}
+
+// TODO for such a weird reason rootpath is "." when writing "file1" with afero sftp backend
+func RunSftpServer(rootpath string) {
+ var (
+ readOnly bool
+ debugLevelStr string
+ debugLevel int
+ debugStderr bool
+ rootDir string
+ )
+
+ flag.BoolVar(&readOnly, "R", false, "read-only server")
+ flag.BoolVar(&debugStderr, "e", true, "debug to stderr")
+ flag.StringVar(&debugLevelStr, "l", "none", "debug level")
+ flag.StringVar(&rootDir, "root", rootpath, "root directory")
+ flag.Parse()
+
+ debugStream := ioutil.Discard
+ if debugStderr {
+ debugStream = os.Stderr
+ debugLevel = 1
+ }
+
+ // An SSH server is represented by a ServerConfig, which holds
+ // certificate details and handles authentication of ServerConns.
+ config := &ssh.ServerConfig{
+ PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
+ // Should use constant-time compare (or better, salt+hash) in
+ // a production setting.
+ fmt.Fprintf(debugStream, "Login: %s\n", c.User())
+ if c.User() == "test" && string(pass) == "test" {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("password rejected for %q", c.User())
+ },
+ }
+
+ privateBytes, err := ioutil.ReadFile("./test/id_rsa")
+ if err != nil {
+ log.Fatal("Failed to load private key", err)
+ }
+
+ private, err := ssh.ParsePrivateKey(privateBytes)
+ if err != nil {
+ log.Fatal("Failed to parse private key", err)
+ }
+
+ config.AddHostKey(private)
+
+ // Once a ServerConfig has been configured, connections can be
+ // accepted.
+ listener, err := net.Listen("tcp", "0.0.0.0:2022")
+ if err != nil {
+ log.Fatal("failed to listen for connection", err)
+ }
+ fmt.Printf("Listening on %v\n", listener.Addr())
+
+ nConn, err := listener.Accept()
+ if err != nil {
+ log.Fatal("failed to accept incoming connection", err)
+ }
+
+ // Before use, a handshake must be performed on the incoming
+ // net.Conn.
+ _, chans, reqs, err := ssh.NewServerConn(nConn, config)
+ if err != nil {
+ log.Fatal("failed to handshake", err)
+ }
+ fmt.Fprintf(debugStream, "SSH server established\n")
+
+ // The incoming Request channel must be serviced.
+ go ssh.DiscardRequests(reqs)
+
+ // Service the incoming Channel channel.
+ for newChannel := range chans {
+ // Channels have a type, depending on the application level
+ // protocol intended. In the case of an SFTP session, this is "subsystem"
+ // with a payload string of "<length=4>sftp"
+ fmt.Fprintf(debugStream, "Incoming channel: %s\n", newChannel.ChannelType())
+ if newChannel.ChannelType() != "session" {
+ newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
+ fmt.Fprintf(debugStream, "Unknown channel type: %s\n", newChannel.ChannelType())
+ continue
+ }
+ channel, requests, err := newChannel.Accept()
+ if err != nil {
+ log.Fatal("could not accept channel.", err)
+ }
+ fmt.Fprintf(debugStream, "Channel accepted\n")
+
+ // Sessions have out-of-band requests such as "shell",
+ // "pty-req" and "env". Here we handle only the
+ // "subsystem" request.
+ go func(in <-chan *ssh.Request) {
+ for req := range in {
+ fmt.Fprintf(debugStream, "Request: %v\n", req.Type)
+ ok := false
+ switch req.Type {
+ case "subsystem":
+ fmt.Fprintf(debugStream, "Subsystem: %s\n", req.Payload[4:])
+ if string(req.Payload[4:]) == "sftp" {
+ ok = true
+ }
+ }
+ fmt.Fprintf(debugStream, " - accepted: %v\n", ok)
+ req.Reply(ok, nil)
+ }
+ }(requests)
+
+ server, err := sftp.NewServer(channel, channel, debugStream, debugLevel, readOnly, rootpath)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if err := server.Serve(); err != nil {
+ log.Fatal("sftp server completed with error:", err)
+ }
+ }
+}
+
+// MakeSSHKeyPair make a pair of public and private keys for SSH access.
+// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
+// Private Key generated is PEM encoded
+func MakeSSHKeyPair(bits int, pubKeyPath, privateKeyPath string) error {
+ privateKey, err := rsa.GenerateKey(_rand.Reader, bits)
+ if err != nil {
+ return err
+ }
+
+ // generate and write private key as PEM
+ privateKeyFile, err := os.Create(privateKeyPath)
+ defer privateKeyFile.Close()
+ if err != nil {
+ return err
+ }
+
+ privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
+ if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
+ return err
+ }
+
+ // generate and write public key
+ pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
+ if err != nil {
+ return err
+ }
+
+ return ioutil.WriteFile(pubKeyPath, ssh.MarshalAuthorizedKey(pub), 0655)
+}
+
+func TestSftpCreate(t *testing.T) {
+ os.Mkdir("./test", 0777)
+ MakeSSHKeyPair(1024, "./test/id_rsa.pub", "./test/id_rsa")
+
+ go RunSftpServer("./test/")
+ time.Sleep(5 * time.Second)
+
+ ctx, err := SftpConnect("test", "test", "localhost:2022")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ctx.Disconnect()
+
+ var AppFs Fs = SftpFs{
+ SftpClient: ctx.sftpc,
+ }
+
+ AppFs.MkdirAll("test/dir1/dir2/dir3", os.FileMode(0777))
+ AppFs.Mkdir("test/foo", os.FileMode(0000))
+ AppFs.Chmod("test/foo", os.FileMode(0700))
+ AppFs.Mkdir("test/bar", os.FileMode(0777))
+
+ file, err := AppFs.Create("file1")
+ if err != nil {
+ t.Error(err)
+ }
+ defer file.Close()
+
+ file.Write([]byte("hello\t"))
+ file.WriteString("world!\n")
+
+ f1, err := AppFs.Open("file1")
+ if err != nil {
+ log.Fatalf("open: %v", err)
+ }
+ defer f1.Close()
+
+ b := make([]byte, 100)
+
+ _, err = f1.Read(b)
+ fmt.Println(string(b))
+
+ // TODO check here if "hello\tworld\n" is in buffer b
+}
diff --git a/vendor/github.com/spf13/afero/unionFile.go b/vendor/github.com/spf13/afero/unionFile.go
new file mode 100644
index 000000000..99f9e5db2
--- /dev/null
+++ b/vendor/github.com/spf13/afero/unionFile.go
@@ -0,0 +1,274 @@
+package afero
+
+import (
+ "io"
+ "os"
+ "path/filepath"
+ "syscall"
+)
+
+// The UnionFile implements the afero.File interface and will be returned
+// when reading a directory present at least in the overlay or opening a file
+// for writing.
+//
+// The calls to
+// Readdir() and Readdirnames() merge the file os.FileInfo / names from the
+// base and the overlay - for files present in both layers, only those
+// from the overlay will be used.
+//
+// When opening files for writing (Create() / OpenFile() with the right flags)
+// the operations will be done in both layers, starting with the overlay. A
+// successful read in the overlay will move the cursor position in the base layer
+// by the number of bytes read.
+type UnionFile struct {
+ base File
+ layer File
+ off int
+ files []os.FileInfo
+}
+
+func (f *UnionFile) Close() error {
+ // first close base, so we have a newer timestamp in the overlay. If we'd close
+ // the overlay first, we'd get a cacheStale the next time we access this file
+ // -> cache would be useless ;-)
+ if f.base != nil {
+ f.base.Close()
+ }
+ if f.layer != nil {
+ return f.layer.Close()
+ }
+ return BADFD
+}
+
+func (f *UnionFile) Read(s []byte) (int, error) {
+ if f.layer != nil {
+ n, err := f.layer.Read(s)
+ if (err == nil || err == io.EOF) && f.base != nil {
+ // advance the file position also in the base file, the next
+ // call may be a write at this position (or a seek with SEEK_CUR)
+ if _, seekErr := f.base.Seek(int64(n), os.SEEK_CUR); seekErr != nil {
+ // only overwrite err in case the seek fails: we need to
+ // report an eventual io.EOF to the caller
+ err = seekErr
+ }
+ }
+ return n, err
+ }
+ if f.base != nil {
+ return f.base.Read(s)
+ }
+ return 0, BADFD
+}
+
+func (f *UnionFile) ReadAt(s []byte, o int64) (int, error) {
+ if f.layer != nil {
+ n, err := f.layer.ReadAt(s, o)
+ if (err == nil || err == io.EOF) && f.base != nil {
+ _, err = f.base.Seek(o+int64(n), os.SEEK_SET)
+ }
+ return n, err
+ }
+ if f.base != nil {
+ return f.base.ReadAt(s, o)
+ }
+ return 0, BADFD
+}
+
+func (f *UnionFile) Seek(o int64, w int) (pos int64, err error) {
+ if f.layer != nil {
+ pos, err = f.layer.Seek(o, w)
+ if (err == nil || err == io.EOF) && f.base != nil {
+ _, err = f.base.Seek(o, w)
+ }
+ return pos, err
+ }
+ if f.base != nil {
+ return f.base.Seek(o, w)
+ }
+ return 0, BADFD
+}
+
+func (f *UnionFile) Write(s []byte) (n int, err error) {
+ if f.layer != nil {
+ n, err = f.layer.Write(s)
+ if err == nil && f.base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark?
+ _, err = f.base.Write(s)
+ }
+ return n, err
+ }
+ if f.base != nil {
+ return f.base.Write(s)
+ }
+ return 0, BADFD
+}
+
+func (f *UnionFile) WriteAt(s []byte, o int64) (n int, err error) {
+ if f.layer != nil {
+ n, err = f.layer.WriteAt(s, o)
+ if err == nil && f.base != nil {
+ _, err = f.base.WriteAt(s, o)
+ }
+ return n, err
+ }
+ if f.base != nil {
+ return f.base.WriteAt(s, o)
+ }
+ return 0, BADFD
+}
+
+func (f *UnionFile) Name() string {
+ if f.layer != nil {
+ return f.layer.Name()
+ }
+ return f.base.Name()
+}
+
+// Readdir will weave the two directories together and
+// return a single view of the overlayed directories
+func (f *UnionFile) Readdir(c int) (ofi []os.FileInfo, err error) {
+ if f.off == 0 {
+ var files = make(map[string]os.FileInfo)
+ var rfi []os.FileInfo
+ if f.layer != nil {
+ rfi, err = f.layer.Readdir(-1)
+ if err != nil {
+ return nil, err
+ }
+ for _, fi := range rfi {
+ files[fi.Name()] = fi
+ }
+ }
+
+ if f.base != nil {
+ rfi, err = f.base.Readdir(-1)
+ if err != nil {
+ return nil, err
+ }
+ for _, fi := range rfi {
+ if _, exists := files[fi.Name()]; !exists {
+ files[fi.Name()] = fi
+ }
+ }
+ }
+ for _, fi := range files {
+ f.files = append(f.files, fi)
+ }
+ }
+ if c == -1 {
+ return f.files[f.off:], nil
+ }
+ defer func() { f.off += c }()
+ return f.files[f.off:c], nil
+}
+
+func (f *UnionFile) Readdirnames(c int) ([]string, error) {
+ rfi, err := f.Readdir(c)
+ if err != nil {
+ return nil, err
+ }
+ var names []string
+ for _, fi := range rfi {
+ names = append(names, fi.Name())
+ }
+ return names, nil
+}
+
+func (f *UnionFile) Stat() (os.FileInfo, error) {
+ if f.layer != nil {
+ return f.layer.Stat()
+ }
+ if f.base != nil {
+ return f.base.Stat()
+ }
+ return nil, BADFD
+}
+
+func (f *UnionFile) Sync() (err error) {
+ if f.layer != nil {
+ err = f.layer.Sync()
+ if err == nil && f.base != nil {
+ err = f.base.Sync()
+ }
+ return err
+ }
+ if f.base != nil {
+ return f.base.Sync()
+ }
+ return BADFD
+}
+
+func (f *UnionFile) Truncate(s int64) (err error) {
+ if f.layer != nil {
+ err = f.layer.Truncate(s)
+ if err == nil && f.base != nil {
+ err = f.base.Truncate(s)
+ }
+ return err
+ }
+ if f.base != nil {
+ return f.base.Truncate(s)
+ }
+ return BADFD
+}
+
+func (f *UnionFile) WriteString(s string) (n int, err error) {
+ if f.layer != nil {
+ n, err = f.layer.WriteString(s)
+ if err == nil && f.base != nil {
+ _, err = f.base.WriteString(s)
+ }
+ return n, err
+ }
+ if f.base != nil {
+ return f.base.WriteString(s)
+ }
+ return 0, BADFD
+}
+
+func copyToLayer(base Fs, layer Fs, name string) error {
+ bfh, err := base.Open(name)
+ if err != nil {
+ return err
+ }
+ defer bfh.Close()
+
+ // First make sure the directory exists
+ exists, err := Exists(layer, filepath.Dir(name))
+ if err != nil {
+ return err
+ }
+ if !exists {
+ err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME?
+ if err != nil {
+ return err
+ }
+ }
+
+ // Create the file on the overlay
+ lfh, err := layer.Create(name)
+ if err != nil {
+ return err
+ }
+ n, err := io.Copy(lfh, bfh)
+ if err != nil {
+ // If anything fails, clean up the file
+ layer.Remove(name)
+ lfh.Close()
+ return err
+ }
+
+ bfi, err := bfh.Stat()
+ if err != nil || bfi.Size() != n {
+ layer.Remove(name)
+ lfh.Close()
+ return syscall.EIO
+ }
+
+ err = lfh.Close()
+ if err != nil {
+ layer.Remove(name)
+ lfh.Close()
+ return err
+ }
+ return layer.Chtimes(name, bfi.ModTime(), bfi.ModTime())
+}
diff --git a/vendor/github.com/spf13/afero/util.go b/vendor/github.com/spf13/afero/util.go
new file mode 100644
index 000000000..2f44e6a10
--- /dev/null
+++ b/vendor/github.com/spf13/afero/util.go
@@ -0,0 +1,331 @@
+// Copyright ©2015 Steve Francia <spf@spf13.com>
+// Portions Copyright ©2015 The Hugo Authors
+// Portions Copyright 2016-present Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
+//
+// 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.
+
+package afero
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+ "unicode"
+
+ "golang.org/x/text/transform"
+ "golang.org/x/text/unicode/norm"
+)
+
+// Filepath separator defined by os.Separator.
+const FilePathSeparator = string(filepath.Separator)
+
+// Takes a reader and a path and writes the content
+func (a Afero) WriteReader(path string, r io.Reader) (err error) {
+ return WriteReader(a.Fs, path, r)
+}
+
+func WriteReader(fs Fs, path string, r io.Reader) (err error) {
+ dir, _ := filepath.Split(path)
+ ospath := filepath.FromSlash(dir)
+
+ if ospath != "" {
+ err = fs.MkdirAll(ospath, 0777) // rwx, rw, r
+ if err != nil {
+ if err != os.ErrExist {
+ log.Panicln(err)
+ }
+ }
+ }
+
+ file, err := fs.Create(path)
+ if err != nil {
+ return
+ }
+ defer file.Close()
+
+ _, err = io.Copy(file, r)
+ return
+}
+
+// Same as WriteReader but checks to see if file/directory already exists.
+func (a Afero) SafeWriteReader(path string, r io.Reader) (err error) {
+ return SafeWriteReader(a.Fs, path, r)
+}
+
+func SafeWriteReader(fs Fs, path string, r io.Reader) (err error) {
+ dir, _ := filepath.Split(path)
+ ospath := filepath.FromSlash(dir)
+
+ if ospath != "" {
+ err = fs.MkdirAll(ospath, 0777) // rwx, rw, r
+ if err != nil {
+ return
+ }
+ }
+
+ exists, err := Exists(fs, path)
+ if err != nil {
+ return
+ }
+ if exists {
+ return fmt.Errorf("%v already exists", path)
+ }
+
+ file, err := fs.Create(path)
+ if err != nil {
+ return
+ }
+ defer file.Close()
+
+ _, err = io.Copy(file, r)
+ return
+}
+
+func (a Afero) GetTempDir(subPath string) string {
+ return GetTempDir(a.Fs, subPath)
+}
+
+// GetTempDir returns the default temp directory with trailing slash
+// if subPath is not empty then it will be created recursively with mode 777 rwx rwx rwx
+func GetTempDir(fs Fs, subPath string) string {
+ addSlash := func(p string) string {
+ if FilePathSeparator != p[len(p)-1:] {
+ p = p + FilePathSeparator
+ }
+ return p
+ }
+ dir := addSlash(os.TempDir())
+
+ if subPath != "" {
+ // preserve windows backslash :-(
+ if FilePathSeparator == "\\" {
+ subPath = strings.Replace(subPath, "\\", "____", -1)
+ }
+ dir = dir + UnicodeSanitize((subPath))
+ if FilePathSeparator == "\\" {
+ dir = strings.Replace(dir, "____", "\\", -1)
+ }
+
+ if exists, _ := Exists(fs, dir); exists {
+ return addSlash(dir)
+ }
+
+ err := fs.MkdirAll(dir, 0777)
+ if err != nil {
+ panic(err)
+ }
+ dir = addSlash(dir)
+ }
+ return dir
+}
+
+// Rewrite string to remove non-standard path characters
+func UnicodeSanitize(s string) string {
+ source := []rune(s)
+ target := make([]rune, 0, len(source))
+
+ for _, r := range source {
+ if unicode.IsLetter(r) ||
+ unicode.IsDigit(r) ||
+ unicode.IsMark(r) ||
+ r == '.' ||
+ r == '/' ||
+ r == '\\' ||
+ r == '_' ||
+ r == '-' ||
+ r == '%' ||
+ r == ' ' ||
+ r == '#' {
+ target = append(target, r)
+ }
+ }
+
+ return string(target)
+}
+
+// Transform characters with accents into plan forms
+func NeuterAccents(s string) string {
+ t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
+ result, _, _ := transform.String(t, string(s))
+
+ return result
+}
+
+func isMn(r rune) bool {
+ return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
+}
+
+func (a Afero) FileContainsBytes(filename string, subslice []byte) (bool, error) {
+ return FileContainsBytes(a.Fs, filename, subslice)
+}
+
+// Check if a file contains a specified byte slice.
+func FileContainsBytes(fs Fs, filename string, subslice []byte) (bool, error) {
+ f, err := fs.Open(filename)
+ if err != nil {
+ return false, err
+ }
+ defer f.Close()
+
+ return readerContainsAny(f, subslice), nil
+}
+
+func (a Afero) FileContainsAnyBytes(filename string, subslices [][]byte) (bool, error) {
+ return FileContainsAnyBytes(a.Fs, filename, subslices)
+}
+
+// Check if a file contains any of the specified byte slices.
+func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, error) {
+ f, err := fs.Open(filename)
+ if err != nil {
+ return false, err
+ }
+ defer f.Close()
+
+ return readerContainsAny(f, subslices...), nil
+}
+
+// readerContains reports whether any of the subslices is within r.
+func readerContainsAny(r io.Reader, subslices ...[]byte) bool {
+
+ if r == nil || len(subslices) == 0 {
+ return false
+ }
+
+ largestSlice := 0
+
+ for _, sl := range subslices {
+ if len(sl) > largestSlice {
+ largestSlice = len(sl)
+ }
+ }
+
+ if largestSlice == 0 {
+ return false
+ }
+
+ bufflen := largestSlice * 4
+ halflen := bufflen / 2
+ buff := make([]byte, bufflen)
+ var err error
+ var n, i int
+
+ for {
+ i++
+ if i == 1 {
+ n, err = io.ReadAtLeast(r, buff[:halflen], halflen)
+ } else {
+ if i != 2 {
+ // shift left to catch overlapping matches
+ copy(buff[:], buff[halflen:])
+ }
+ n, err = io.ReadAtLeast(r, buff[halflen:], halflen)
+ }
+
+ if n > 0 {
+ for _, sl := range subslices {
+ if bytes.Contains(buff, sl) {
+ return true
+ }
+ }
+ }
+
+ if err != nil {
+ break
+ }
+ }
+ return false
+}
+
+func (a Afero) DirExists(path string) (bool, error) {
+ return DirExists(a.Fs, path)
+}
+
+// DirExists checks if a path exists and is a directory.
+func DirExists(fs Fs, path string) (bool, error) {
+ fi, err := fs.Stat(path)
+ if err == nil && fi.IsDir() {
+ return true, nil
+ }
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, err
+}
+
+func (a Afero) IsDir(path string) (bool, error) {
+ return IsDir(a.Fs, path)
+}
+
+// IsDir checks if a given path is a directory.
+func IsDir(fs Fs, path string) (bool, error) {
+ fi, err := fs.Stat(path)
+ if err != nil {
+ return false, err
+ }
+ return fi.IsDir(), nil
+}
+
+func (a Afero) IsEmpty(path string) (bool, error) {
+ return IsEmpty(a.Fs, path)
+}
+
+// IsEmpty checks if a given file or directory is empty.
+func IsEmpty(fs Fs, path string) (bool, error) {
+ if b, _ := Exists(fs, path); !b {
+ return false, fmt.Errorf("%q path does not exist", path)
+ }
+ fi, err := fs.Stat(path)
+ if err != nil {
+ return false, err
+ }
+ if fi.IsDir() {
+ f, err := fs.Open(path)
+ if err != nil {
+ return false, err
+ }
+ defer f.Close()
+ list, err := f.Readdir(-1)
+ return len(list) == 0, nil
+ }
+ return fi.Size() == 0, nil
+}
+
+func (a Afero) Exists(path string) (bool, error) {
+ return Exists(a.Fs, path)
+}
+
+// Check if a file or directory exists.
+func Exists(fs Fs, path string) (bool, error) {
+ _, err := fs.Stat(path)
+ if err == nil {
+ return true, nil
+ }
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, err
+}
+
+func FullBaseFsPath(basePathFs *BasePathFs, relativePath string) string {
+ combinedPath := filepath.Join(basePathFs.path, relativePath)
+ if parent, ok := basePathFs.source.(*BasePathFs); ok {
+ return FullBaseFsPath(parent, combinedPath)
+ }
+
+ return combinedPath
+}
diff --git a/vendor/github.com/spf13/afero/util_test.go b/vendor/github.com/spf13/afero/util_test.go
new file mode 100644
index 000000000..b5852f184
--- /dev/null
+++ b/vendor/github.com/spf13/afero/util_test.go
@@ -0,0 +1,450 @@
+// Copyright ©2015 Steve Francia <spf@spf13.com>
+// Portions Copyright ©2015 The Hugo Authors
+//
+//
+// 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.
+//
+
+package afero
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+var testFS = new(MemMapFs)
+
+func TestDirExists(t *testing.T) {
+ type test struct {
+ input string
+ expected bool
+ }
+
+ // First create a couple directories so there is something in the filesystem
+ //testFS := new(MemMapFs)
+ testFS.MkdirAll("/foo/bar", 0777)
+
+ data := []test{
+ {".", true},
+ {"./", true},
+ {"..", true},
+ {"../", true},
+ {"./..", true},
+ {"./../", true},
+ {"/foo/", true},
+ {"/foo", true},
+ {"/foo/bar", true},
+ {"/foo/bar/", true},
+ {"/", true},
+ {"/some-really-random-directory-name", false},
+ {"/some/really/random/directory/name", false},
+ {"./some-really-random-local-directory-name", false},
+ {"./some/really/random/local/directory/name", false},
+ }
+
+ for i, d := range data {
+ exists, _ := DirExists(testFS, filepath.FromSlash(d.input))
+ if d.expected != exists {
+ t.Errorf("Test %d %q failed. Expected %t got %t", i, d.input, d.expected, exists)
+ }
+ }
+}
+
+func TestIsDir(t *testing.T) {
+ testFS = new(MemMapFs)
+
+ type test struct {
+ input string
+ expected bool
+ }
+ data := []test{
+ {"./", true},
+ {"/", true},
+ {"./this-directory-does-not-existi", false},
+ {"/this-absolute-directory/does-not-exist", false},
+ }
+
+ for i, d := range data {
+
+ exists, _ := IsDir(testFS, d.input)
+ if d.expected != exists {
+ t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists)
+ }
+ }
+}
+
+func TestIsEmpty(t *testing.T) {
+ testFS = new(MemMapFs)
+
+ zeroSizedFile, _ := createZeroSizedFileInTempDir()
+ defer deleteFileInTempDir(zeroSizedFile)
+ nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir()
+ defer deleteFileInTempDir(nonZeroSizedFile)
+ emptyDirectory, _ := createEmptyTempDir()
+ defer deleteTempDir(emptyDirectory)
+ nonEmptyZeroLengthFilesDirectory, _ := createTempDirWithZeroLengthFiles()
+ defer deleteTempDir(nonEmptyZeroLengthFilesDirectory)
+ nonEmptyNonZeroLengthFilesDirectory, _ := createTempDirWithNonZeroLengthFiles()
+ defer deleteTempDir(nonEmptyNonZeroLengthFilesDirectory)
+ nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
+ nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/"
+
+ fileDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentFile)
+ dirDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentDir)
+
+ type test struct {
+ input string
+ expectedResult bool
+ expectedErr error
+ }
+
+ data := []test{
+ {zeroSizedFile.Name(), true, nil},
+ {nonZeroSizedFile.Name(), false, nil},
+ {emptyDirectory, true, nil},
+ {nonEmptyZeroLengthFilesDirectory, false, nil},
+ {nonEmptyNonZeroLengthFilesDirectory, false, nil},
+ {nonExistentFile, false, fileDoesNotExist},
+ {nonExistentDir, false, dirDoesNotExist},
+ }
+ for i, d := range data {
+ exists, err := IsEmpty(testFS, d.input)
+ if d.expectedResult != exists {
+ t.Errorf("Test %d %q failed exists. Expected result %t got %t", i, d.input, d.expectedResult, exists)
+ }
+ if d.expectedErr != nil {
+ if d.expectedErr.Error() != err.Error() {
+ t.Errorf("Test %d failed with err. Expected %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err)
+ }
+ } else {
+ if d.expectedErr != err {
+ t.Errorf("Test %d failed. Expected error %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err)
+ }
+ }
+ }
+}
+
+func TestReaderContains(t *testing.T) {
+ for i, this := range []struct {
+ v1 string
+ v2 [][]byte
+ expect bool
+ }{
+ {"abc", [][]byte{[]byte("a")}, true},
+ {"abc", [][]byte{[]byte("b")}, true},
+ {"abcdefg", [][]byte{[]byte("efg")}, true},
+ {"abc", [][]byte{[]byte("d")}, false},
+ {"abc", [][]byte{[]byte("d"), []byte("e")}, false},
+ {"abc", [][]byte{[]byte("d"), []byte("a")}, true},
+ {"abc", [][]byte{[]byte("b"), []byte("e")}, true},
+ {"", nil, false},
+ {"", [][]byte{[]byte("a")}, false},
+ {"a", [][]byte{[]byte("")}, false},
+ {"", [][]byte{[]byte("")}, false}} {
+ result := readerContainsAny(strings.NewReader(this.v1), this.v2...)
+ if result != this.expect {
+ t.Errorf("[%d] readerContains: got %t but expected %t", i, result, this.expect)
+ }
+ }
+
+ if readerContainsAny(nil, []byte("a")) {
+ t.Error("readerContains with nil reader")
+ }
+
+ if readerContainsAny(nil, nil) {
+ t.Error("readerContains with nil arguments")
+ }
+}
+
+func createZeroSizedFileInTempDir() (File, error) {
+ filePrefix := "_path_test_"
+ f, e := TempFile(testFS, "", filePrefix) // dir is os.TempDir()
+ if e != nil {
+ // if there was an error no file was created.
+ // => no requirement to delete the file
+ return nil, e
+ }
+ return f, nil
+}
+
+func createNonZeroSizedFileInTempDir() (File, error) {
+ f, err := createZeroSizedFileInTempDir()
+ if err != nil {
+ // no file ??
+ }
+ byteString := []byte("byteString")
+ err = WriteFile(testFS, f.Name(), byteString, 0644)
+ if err != nil {
+ // delete the file
+ deleteFileInTempDir(f)
+ return nil, err
+ }
+ return f, nil
+}
+
+func deleteFileInTempDir(f File) {
+ err := testFS.Remove(f.Name())
+ if err != nil {
+ // now what?
+ }
+}
+
+func createEmptyTempDir() (string, error) {
+ dirPrefix := "_dir_prefix_"
+ d, e := TempDir(testFS, "", dirPrefix) // will be in os.TempDir()
+ if e != nil {
+ // no directory to delete - it was never created
+ return "", e
+ }
+ return d, nil
+}
+
+func createTempDirWithZeroLengthFiles() (string, error) {
+ d, dirErr := createEmptyTempDir()
+ if dirErr != nil {
+ //now what?
+ }
+ filePrefix := "_path_test_"
+ _, fileErr := TempFile(testFS, d, filePrefix) // dir is os.TempDir()
+ if fileErr != nil {
+ // if there was an error no file was created.
+ // but we need to remove the directory to clean-up
+ deleteTempDir(d)
+ return "", fileErr
+ }
+ // the dir now has one, zero length file in it
+ return d, nil
+
+}
+
+func createTempDirWithNonZeroLengthFiles() (string, error) {
+ d, dirErr := createEmptyTempDir()
+ if dirErr != nil {
+ //now what?
+ }
+ filePrefix := "_path_test_"
+ f, fileErr := TempFile(testFS, d, filePrefix) // dir is os.TempDir()
+ if fileErr != nil {
+ // if there was an error no file was created.
+ // but we need to remove the directory to clean-up
+ deleteTempDir(d)
+ return "", fileErr
+ }
+ byteString := []byte("byteString")
+ fileErr = WriteFile(testFS, f.Name(), byteString, 0644)
+ if fileErr != nil {
+ // delete the file
+ deleteFileInTempDir(f)
+ // also delete the directory
+ deleteTempDir(d)
+ return "", fileErr
+ }
+
+ // the dir now has one, zero length file in it
+ return d, nil
+
+}
+
+func TestExists(t *testing.T) {
+ zeroSizedFile, _ := createZeroSizedFileInTempDir()
+ defer deleteFileInTempDir(zeroSizedFile)
+ nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir()
+ defer deleteFileInTempDir(nonZeroSizedFile)
+ emptyDirectory, _ := createEmptyTempDir()
+ defer deleteTempDir(emptyDirectory)
+ nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
+ nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/"
+
+ type test struct {
+ input string
+ expectedResult bool
+ expectedErr error
+ }
+
+ data := []test{
+ {zeroSizedFile.Name(), true, nil},
+ {nonZeroSizedFile.Name(), true, nil},
+ {emptyDirectory, true, nil},
+ {nonExistentFile, false, nil},
+ {nonExistentDir, false, nil},
+ }
+ for i, d := range data {
+ exists, err := Exists(testFS, d.input)
+ if d.expectedResult != exists {
+ t.Errorf("Test %d failed. Expected result %t got %t", i, d.expectedResult, exists)
+ }
+ if d.expectedErr != err {
+ t.Errorf("Test %d failed. Expected %q got %q", i, d.expectedErr, err)
+ }
+ }
+
+}
+
+func TestSafeWriteToDisk(t *testing.T) {
+ emptyFile, _ := createZeroSizedFileInTempDir()
+ defer deleteFileInTempDir(emptyFile)
+ tmpDir, _ := createEmptyTempDir()
+ defer deleteTempDir(tmpDir)
+
+ randomString := "This is a random string!"
+ reader := strings.NewReader(randomString)
+
+ fileExists := fmt.Errorf("%v already exists", emptyFile.Name())
+
+ type test struct {
+ filename string
+ expectedErr error
+ }
+
+ now := time.Now().Unix()
+ nowStr := strconv.FormatInt(now, 10)
+ data := []test{
+ {emptyFile.Name(), fileExists},
+ {tmpDir + "/" + nowStr, nil},
+ }
+
+ for i, d := range data {
+ e := SafeWriteReader(testFS, d.filename, reader)
+ if d.expectedErr != nil {
+ if d.expectedErr.Error() != e.Error() {
+ t.Errorf("Test %d failed. Expected error %q but got %q", i, d.expectedErr.Error(), e.Error())
+ }
+ } else {
+ if d.expectedErr != e {
+ t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedErr, e)
+ }
+ contents, _ := ReadFile(testFS, d.filename)
+ if randomString != string(contents) {
+ t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
+ }
+ }
+ reader.Seek(0, 0)
+ }
+}
+
+func TestWriteToDisk(t *testing.T) {
+ emptyFile, _ := createZeroSizedFileInTempDir()
+ defer deleteFileInTempDir(emptyFile)
+ tmpDir, _ := createEmptyTempDir()
+ defer deleteTempDir(tmpDir)
+
+ randomString := "This is a random string!"
+ reader := strings.NewReader(randomString)
+
+ type test struct {
+ filename string
+ expectedErr error
+ }
+
+ now := time.Now().Unix()
+ nowStr := strconv.FormatInt(now, 10)
+ data := []test{
+ {emptyFile.Name(), nil},
+ {tmpDir + "/" + nowStr, nil},
+ }
+
+ for i, d := range data {
+ e := WriteReader(testFS, d.filename, reader)
+ if d.expectedErr != e {
+ t.Errorf("Test %d failed. WriteToDisk Error Expected %q but got %q", i, d.expectedErr, e)
+ }
+ contents, e := ReadFile(testFS, d.filename)
+ if e != nil {
+ t.Errorf("Test %d failed. Could not read file %s. Reason: %s\n", i, d.filename, e)
+ }
+ if randomString != string(contents) {
+ t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
+ }
+ reader.Seek(0, 0)
+ }
+}
+
+func TestGetTempDir(t *testing.T) {
+ dir := os.TempDir()
+ if FilePathSeparator != dir[len(dir)-1:] {
+ dir = dir + FilePathSeparator
+ }
+ testDir := "hugoTestFolder" + FilePathSeparator
+ tests := []struct {
+ input string
+ expected string
+ }{
+ {"", dir},
+ {testDir + " Foo bar ", dir + testDir + " Foo bar " + FilePathSeparator},
+ {testDir + "Foo.Bar/foo_Bar-Foo", dir + testDir + "Foo.Bar/foo_Bar-Foo" + FilePathSeparator},
+ {testDir + "fOO,bar:foo%bAR", dir + testDir + "fOObarfoo%bAR" + FilePathSeparator},
+ {testDir + "FOo/BaR.html", dir + testDir + "FOo/BaR.html" + FilePathSeparator},
+ {testDir + "трям/трям", dir + testDir + "трям/трям" + FilePathSeparator},
+ {testDir + "은행", dir + testDir + "은행" + FilePathSeparator},
+ {testDir + "Банковский кассир", dir + testDir + "Банковский кассир" + FilePathSeparator},
+ }
+
+ for _, test := range tests {
+ output := GetTempDir(new(MemMapFs), test.input)
+ if output != test.expected {
+ t.Errorf("Expected %#v, got %#v\n", test.expected, output)
+ }
+ }
+}
+
+// This function is very dangerous. Don't use it.
+func deleteTempDir(d string) {
+ err := os.RemoveAll(d)
+ if err != nil {
+ // now what?
+ }
+}
+
+func TestFullBaseFsPath(t *testing.T) {
+ type dirSpec struct {
+ Dir1, Dir2, Dir3 string
+ }
+ dirSpecs := []dirSpec{
+ dirSpec{Dir1: "/", Dir2: "/", Dir3: "/"},
+ dirSpec{Dir1: "/", Dir2: "/path2", Dir3: "/"},
+ dirSpec{Dir1: "/path1/dir", Dir2: "/path2/dir/", Dir3: "/path3/dir"},
+ dirSpec{Dir1: "C:/path1", Dir2: "path2/dir", Dir3: "/path3/dir/"},
+ }
+
+ for _, ds := range dirSpecs {
+ memFs := NewMemMapFs()
+ level1Fs := NewBasePathFs(memFs, ds.Dir1)
+ level2Fs := NewBasePathFs(level1Fs, ds.Dir2)
+ level3Fs := NewBasePathFs(level2Fs, ds.Dir3)
+
+ type spec struct {
+ BaseFs Fs
+ FileName string
+ ExpectedPath string
+ }
+ specs := []spec{
+ spec{BaseFs: level3Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, ds.Dir3, "f.txt")},
+ spec{BaseFs: level3Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, ds.Dir3, "")},
+ spec{BaseFs: level2Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, "f.txt")},
+ spec{BaseFs: level2Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, "")},
+ spec{BaseFs: level1Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, "f.txt")},
+ spec{BaseFs: level1Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, "")},
+ }
+
+ for _, s := range specs {
+ if actualPath := FullBaseFsPath(s.BaseFs.(*BasePathFs), s.FileName); actualPath != s.ExpectedPath {
+ t.Errorf("Expected \n%s got \n%s", s.ExpectedPath, actualPath)
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/spf13/cast/.gitignore b/vendor/github.com/spf13/cast/.gitignore
new file mode 100644
index 000000000..53053a8ac
--- /dev/null
+++ b/vendor/github.com/spf13/cast/.gitignore
@@ -0,0 +1,25 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+
+*.bench
diff --git a/vendor/github.com/spf13/cast/.travis.yml b/vendor/github.com/spf13/cast/.travis.yml
new file mode 100644
index 000000000..4da976684
--- /dev/null
+++ b/vendor/github.com/spf13/cast/.travis.yml
@@ -0,0 +1,14 @@
+language: go
+sudo: required
+go:
+ - 1.7.5
+ - 1.8
+ - tip
+os:
+ - linux
+matrix:
+ allow_failures:
+ - go: tip
+ fast_finish: true
+script:
+ - make check
diff --git a/vendor/github.com/spf13/cast/LICENSE b/vendor/github.com/spf13/cast/LICENSE
new file mode 100644
index 000000000..4527efb9c
--- /dev/null
+++ b/vendor/github.com/spf13/cast/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Steve Francia
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE. \ No newline at end of file
diff --git a/vendor/github.com/spf13/cast/Makefile b/vendor/github.com/spf13/cast/Makefile
new file mode 100644
index 000000000..7ccf8930b
--- /dev/null
+++ b/vendor/github.com/spf13/cast/Makefile
@@ -0,0 +1,38 @@
+# A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
+
+.PHONY: check fmt lint test test-race vet test-cover-html help
+.DEFAULT_GOAL := help
+
+check: test-race fmt vet lint ## Run tests and linters
+
+test: ## Run tests
+ go test ./...
+
+test-race: ## Run tests with race detector
+ go test -race ./...
+
+fmt: ## Run gofmt linter
+ @for d in `go list` ; do \
+ if [ "`gofmt -l -s $$GOPATH/src/$$d | tee /dev/stderr`" ]; then \
+ echo "^ improperly formatted go files" && echo && exit 1; \
+ fi \
+ done
+
+lint: ## Run golint linter
+ @for d in `go list` ; do \
+ if [ "`golint $$d | tee /dev/stderr`" ]; then \
+ echo "^ golint errors!" && echo && exit 1; \
+ fi \
+ done
+
+vet: ## Run go vet linter
+ @if [ "`go vet | tee /dev/stderr`" ]; then \
+ echo "^ go vet errors!" && echo && exit 1; \
+ fi
+
+test-cover-html: ## Generate test coverage report
+ go test -coverprofile=coverage.out -covermode=count
+ go tool cover -func=coverage.out
+
+help:
+ @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
diff --git a/vendor/github.com/spf13/cast/README.md b/vendor/github.com/spf13/cast/README.md
new file mode 100644
index 000000000..e6939397d
--- /dev/null
+++ b/vendor/github.com/spf13/cast/README.md
@@ -0,0 +1,75 @@
+cast
+====
+[![GoDoc](https://godoc.org/github.com/spf13/cast?status.svg)](https://godoc.org/github.com/spf13/cast)
+[![Build Status](https://api.travis-ci.org/spf13/cast.svg?branch=master)](https://travis-ci.org/spf13/cast)
+[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cast)](https://goreportcard.com/report/github.com/spf13/cast)
+
+Easy and safe casting from one type to another in Go
+
+Don’t Panic! ... Cast
+
+## What is Cast?
+
+Cast is a library to convert between different go types in a consistent and easy way.
+
+Cast provides simple functions to easily convert a number to a string, an
+interface into a bool, etc. Cast does this intelligently when an obvious
+conversion is possible. It doesn’t make any attempts to guess what you meant,
+for example you can only convert a string to an int when it is a string
+representation of an int such as “8”. Cast was developed for use in
+[Hugo](http://hugo.spf13.com), a website engine which uses YAML, TOML or JSON
+for meta data.
+
+## Why use Cast?
+
+When working with dynamic data in Go you often need to cast or convert the data
+from one type into another. Cast goes beyond just using type assertion (though
+it uses that when possible) to provide a very straightforward and convenient
+library.
+
+If you are working with interfaces to handle things like dynamic content
+you’ll need an easy way to convert an interface into a given type. This
+is the library for you.
+
+If you are taking in data from YAML, TOML or JSON or other formats which lack
+full types, then Cast is the library for you.
+
+## Usage
+
+Cast provides a handful of To_____ methods. These methods will always return
+the desired type. **If input is provided that will not convert to that type, the
+0 or nil value for that type will be returned**.
+
+Cast also provides identical methods To_____E. These return the same result as
+the To_____ methods, plus an additional error which tells you if it successfully
+converted. Using these methods you can tell the difference between when the
+input matched the zero value or when the conversion failed and the zero value
+was returned.
+
+The following examples are merely a sample of what is available. Please review
+the code for a complete set.
+
+### Example ‘ToString’:
+
+ cast.ToString("mayonegg") // "mayonegg"
+ cast.ToString(8) // "8"
+ cast.ToString(8.31) // "8.31"
+ cast.ToString([]byte("one time")) // "one time"
+ cast.ToString(nil) // ""
+
+ var foo interface{} = "one more time"
+ cast.ToString(foo) // "one more time"
+
+
+### Example ‘ToInt’:
+
+ cast.ToInt(8) // 8
+ cast.ToInt(8.31) // 8
+ cast.ToInt("8") // 8
+ cast.ToInt(true) // 1
+ cast.ToInt(false) // 0
+
+ var eight interface{} = 8
+ cast.ToInt(eight) // 8
+ cast.ToInt(nil) // 0
+
diff --git a/vendor/github.com/spf13/cast/cast.go b/vendor/github.com/spf13/cast/cast.go
new file mode 100644
index 000000000..dc504b432
--- /dev/null
+++ b/vendor/github.com/spf13/cast/cast.go
@@ -0,0 +1,153 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+// Package cast provides easy and safe casting in Go.
+package cast
+
+import "time"
+
+// ToBool casts an interface to a bool type.
+func ToBool(i interface{}) bool {
+ v, _ := ToBoolE(i)
+ return v
+}
+
+// ToTime casts an interface to a time.Time type.
+func ToTime(i interface{}) time.Time {
+ v, _ := ToTimeE(i)
+ return v
+}
+
+// ToDuration casts an interface to a time.Duration type.
+func ToDuration(i interface{}) time.Duration {
+ v, _ := ToDurationE(i)
+ return v
+}
+
+// ToFloat64 casts an interface to a float64 type.
+func ToFloat64(i interface{}) float64 {
+ v, _ := ToFloat64E(i)
+ return v
+}
+
+// ToFloat32 casts an interface to a float32 type.
+func ToFloat32(i interface{}) float32 {
+ v, _ := ToFloat32E(i)
+ return v
+}
+
+// ToInt64 casts an interface to an int64 type.
+func ToInt64(i interface{}) int64 {
+ v, _ := ToInt64E(i)
+ return v
+}
+
+// ToInt32 casts an interface to an int32 type.
+func ToInt32(i interface{}) int32 {
+ v, _ := ToInt32E(i)
+ return v
+}
+
+// ToInt16 casts an interface to an int16 type.
+func ToInt16(i interface{}) int16 {
+ v, _ := ToInt16E(i)
+ return v
+}
+
+// ToInt8 casts an interface to an int8 type.
+func ToInt8(i interface{}) int8 {
+ v, _ := ToInt8E(i)
+ return v
+}
+
+// ToInt casts an interface to an int type.
+func ToInt(i interface{}) int {
+ v, _ := ToIntE(i)
+ return v
+}
+
+// ToUint casts an interface to a uint type.
+func ToUint(i interface{}) uint {
+ v, _ := ToUintE(i)
+ return v
+}
+
+// ToUint64 casts an interface to a uint64 type.
+func ToUint64(i interface{}) uint64 {
+ v, _ := ToUint64E(i)
+ return v
+}
+
+// ToUint32 casts an interface to a uint32 type.
+func ToUint32(i interface{}) uint32 {
+ v, _ := ToUint32E(i)
+ return v
+}
+
+// ToUint16 casts an interface to a uint16 type.
+func ToUint16(i interface{}) uint16 {
+ v, _ := ToUint16E(i)
+ return v
+}
+
+// ToUint8 casts an interface to a uint8 type.
+func ToUint8(i interface{}) uint8 {
+ v, _ := ToUint8E(i)
+ return v
+}
+
+// ToString casts an interface to a string type.
+func ToString(i interface{}) string {
+ v, _ := ToStringE(i)
+ return v
+}
+
+// ToStringMapString casts an interface to a map[string]string type.
+func ToStringMapString(i interface{}) map[string]string {
+ v, _ := ToStringMapStringE(i)
+ return v
+}
+
+// ToStringMapStringSlice casts an interface to a map[string][]string type.
+func ToStringMapStringSlice(i interface{}) map[string][]string {
+ v, _ := ToStringMapStringSliceE(i)
+ return v
+}
+
+// ToStringMapBool casts an interface to a map[string]bool type.
+func ToStringMapBool(i interface{}) map[string]bool {
+ v, _ := ToStringMapBoolE(i)
+ return v
+}
+
+// ToStringMap casts an interface to a map[string]interface{} type.
+func ToStringMap(i interface{}) map[string]interface{} {
+ v, _ := ToStringMapE(i)
+ return v
+}
+
+// ToSlice casts an interface to a []interface{} type.
+func ToSlice(i interface{}) []interface{} {
+ v, _ := ToSliceE(i)
+ return v
+}
+
+// ToBoolSlice casts an interface to a []bool type.
+func ToBoolSlice(i interface{}) []bool {
+ v, _ := ToBoolSliceE(i)
+ return v
+}
+
+// ToStringSlice casts an interface to a []string type.
+func ToStringSlice(i interface{}) []string {
+ v, _ := ToStringSliceE(i)
+ return v
+}
+
+// ToIntSlice casts an interface to a []int type.
+func ToIntSlice(i interface{}) []int {
+ v, _ := ToIntSliceE(i)
+ return v
+}
diff --git a/vendor/github.com/spf13/cast/cast_test.go b/vendor/github.com/spf13/cast/cast_test.go
new file mode 100644
index 000000000..2bb8c5f54
--- /dev/null
+++ b/vendor/github.com/spf13/cast/cast_test.go
@@ -0,0 +1,1151 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+package cast
+
+import (
+ "fmt"
+ "html/template"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestToUintE(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect uint
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8, false},
+ {float64(8.31), 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ {"8", 8, false},
+ {nil, 0, false},
+ // errors
+ {int(-8), 0, true},
+ {int8(-8), 0, true},
+ {int16(-8), 0, true},
+ {int32(-8), 0, true},
+ {int64(-8), 0, true},
+ {float32(-8.31), 0, true},
+ {float64(-8.31), 0, true},
+ {"-8", 0, true},
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToUintE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test:
+ v = ToUint(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToUint64E(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect uint64
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8, false},
+ {float64(8.31), 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ {"8", 8, false},
+ {nil, 0, false},
+ // errors
+ {int(-8), 0, true},
+ {int8(-8), 0, true},
+ {int16(-8), 0, true},
+ {int32(-8), 0, true},
+ {int64(-8), 0, true},
+ {float32(-8.31), 0, true},
+ {float64(-8.31), 0, true},
+ {"-8", 0, true},
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToUint64E(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test:
+ v = ToUint64(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToUint32E(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect uint32
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8, false},
+ {float64(8.31), 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ {"8", 8, false},
+ {nil, 0, false},
+ {int(-8), 0, true},
+ {int8(-8), 0, true},
+ {int16(-8), 0, true},
+ {int32(-8), 0, true},
+ {int64(-8), 0, true},
+ {float32(-8.31), 0, true},
+ {float64(-8.31), 0, true},
+ {"-8", 0, true},
+ // errors
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToUint32E(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test:
+ v = ToUint32(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToUint16E(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect uint16
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8, false},
+ {float64(8.31), 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ {"8", 8, false},
+ {nil, 0, false},
+ // errors
+ {int(-8), 0, true},
+ {int8(-8), 0, true},
+ {int16(-8), 0, true},
+ {int32(-8), 0, true},
+ {int64(-8), 0, true},
+ {float32(-8.31), 0, true},
+ {float64(-8.31), 0, true},
+ {"-8", 0, true},
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToUint16E(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToUint16(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToUint8E(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect uint8
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8, false},
+ {float64(8.31), 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ {"8", 8, false},
+ {nil, 0, false},
+ // errors
+ {int(-8), 0, true},
+ {int8(-8), 0, true},
+ {int16(-8), 0, true},
+ {int32(-8), 0, true},
+ {int64(-8), 0, true},
+ {float32(-8.31), 0, true},
+ {float64(-8.31), 0, true},
+ {"-8", 0, true},
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToUint8E(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToUint8(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToIntE(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect int
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8, false},
+ {float64(8.31), 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ {"8", 8, false},
+ {nil, 0, false},
+ // errors
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToIntE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToInt(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToInt64E(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect int64
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8, false},
+ {float64(8.31), 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ {"8", 8, false},
+ {nil, 0, false},
+ // errors
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToInt64E(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToInt64(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToInt32E(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect int32
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8, false},
+ {float64(8.31), 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ {"8", 8, false},
+ {nil, 0, false},
+ // errors
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToInt32E(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToInt32(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToInt16E(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect int16
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8, false},
+ {float64(8.31), 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ {"8", 8, false},
+ {nil, 0, false},
+ // errors
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToInt16E(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToInt16(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToInt8E(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect int8
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8, false},
+ {float64(8.31), 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ {"8", 8, false},
+ {nil, 0, false},
+ // errors
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToInt8E(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToInt8(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToFloat64E(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect float64
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8), 8, false},
+ {float64(8.31), 8.31, false},
+ {"8", 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ // errors
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToFloat64E(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToFloat64(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToFloat32E(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect float32
+ iserr bool
+ }{
+ {int(8), 8, false},
+ {int8(8), 8, false},
+ {int16(8), 8, false},
+ {int32(8), 8, false},
+ {int64(8), 8, false},
+ {uint(8), 8, false},
+ {uint8(8), 8, false},
+ {uint16(8), 8, false},
+ {uint32(8), 8, false},
+ {uint64(8), 8, false},
+ {float32(8.31), 8.31, false},
+ {float64(8.31), 8.31, false},
+ {"8", 8, false},
+ {true, 1, false},
+ {false, 0, false},
+ // errors
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToFloat32E(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToFloat32(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToStringE(t *testing.T) {
+ type Key struct {
+ k string
+ }
+ key := &Key{"foo"}
+
+ tests := []struct {
+ input interface{}
+ expect string
+ iserr bool
+ }{
+ {int(8), "8", false},
+ {int8(8), "8", false},
+ {int16(8), "8", false},
+ {int32(8), "8", false},
+ {int64(8), "8", false},
+ {uint(8), "8", false},
+ {uint8(8), "8", false},
+ {uint16(8), "8", false},
+ {uint32(8), "8", false},
+ {uint64(8), "8", false},
+ {float32(8.31), "8.31", false},
+ {float64(8.31), "8.31", false},
+ {true, "true", false},
+ {false, "false", false},
+ {nil, "", false},
+ {[]byte("one time"), "one time", false},
+ {"one more time", "one more time", false},
+ {template.HTML("one time"), "one time", false},
+ {template.URL("http://somehost.foo"), "http://somehost.foo", false},
+ {template.JS("(1+2)"), "(1+2)", false},
+ {template.CSS("a"), "a", false},
+ {template.HTMLAttr("a"), "a", false},
+ // errors
+ {testing.T{}, "", true},
+ {key, "", true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToStringE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToString(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+type foo struct {
+ val string
+}
+
+func (x foo) String() string {
+ return x.val
+}
+
+func TestStringerToString(t *testing.T) {
+ var x foo
+ x.val = "bar"
+ assert.Equal(t, "bar", ToString(x))
+}
+
+type fu struct {
+ val string
+}
+
+func (x fu) Error() string {
+ return x.val
+}
+
+func TestErrorToString(t *testing.T) {
+ var x fu
+ x.val = "bar"
+ assert.Equal(t, "bar", ToString(x))
+}
+
+func TestStringMapStringSliceE(t *testing.T) {
+ // ToStringMapString inputs/outputs
+ var stringMapString = map[string]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
+ var stringMapInterface = map[string]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
+ var interfaceMapString = map[interface{}]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
+ var interfaceMapInterface = map[interface{}]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
+
+ // ToStringMapStringSlice inputs/outputs
+ var stringMapStringSlice = map[string][]string{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
+ var stringMapInterfaceSlice = map[string][]interface{}{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
+ var stringMapInterfaceInterfaceSlice = map[string]interface{}{"key 1": []interface{}{"value 1", "value 2", "value 3"}, "key 2": []interface{}{"value 1", "value 2", "value 3"}, "key 3": []interface{}{"value 1", "value 2", "value 3"}}
+ var stringMapStringSingleSliceFieldsResult = map[string][]string{"key 1": {"value", "1"}, "key 2": {"value", "2"}, "key 3": {"value", "3"}}
+ var interfaceMapStringSlice = map[interface{}][]string{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
+ var interfaceMapInterfaceSlice = map[interface{}][]interface{}{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
+
+ var stringMapStringSliceMultiple = map[string][]string{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
+ var stringMapStringSliceSingle = map[string][]string{"key 1": {"value 1"}, "key 2": {"value 2"}, "key 3": {"value 3"}}
+
+ var stringMapInterface1 = map[string]interface{}{"key 1": []string{"value 1"}, "key 2": []string{"value 2"}}
+ var stringMapInterfaceResult1 = map[string][]string{"key 1": {"value 1"}, "key 2": {"value 2"}}
+
+ type Key struct {
+ k string
+ }
+
+ tests := []struct {
+ input interface{}
+ expect map[string][]string
+ iserr bool
+ }{
+ {stringMapStringSlice, stringMapStringSlice, false},
+ {stringMapInterfaceSlice, stringMapStringSlice, false},
+ {stringMapInterfaceInterfaceSlice, stringMapStringSlice, false},
+ {stringMapStringSliceMultiple, stringMapStringSlice, false},
+ {stringMapStringSliceMultiple, stringMapStringSlice, false},
+ {stringMapString, stringMapStringSliceSingle, false},
+ {stringMapInterface, stringMapStringSliceSingle, false},
+ {stringMapInterface1, stringMapInterfaceResult1, false},
+ {interfaceMapStringSlice, stringMapStringSlice, false},
+ {interfaceMapInterfaceSlice, stringMapStringSlice, false},
+ {interfaceMapString, stringMapStringSingleSliceFieldsResult, false},
+ {interfaceMapInterface, stringMapStringSingleSliceFieldsResult, false},
+ // errors
+ {nil, nil, true},
+ {testing.T{}, nil, true},
+ {map[interface{}]interface{}{"foo": testing.T{}}, nil, true},
+ {map[interface{}]interface{}{Key{"foo"}: "bar"}, nil, true}, // ToStringE(Key{"foo"}) should fail
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToStringMapStringSliceE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToStringMapStringSlice(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToStringMapE(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect map[string]interface{}
+ iserr bool
+ }{
+ {map[interface{}]interface{}{"tag": "tags", "group": "groups"}, map[string]interface{}{"tag": "tags", "group": "groups"}, false},
+ {map[string]interface{}{"tag": "tags", "group": "groups"}, map[string]interface{}{"tag": "tags", "group": "groups"}, false},
+ // errors
+ {nil, nil, true},
+ {testing.T{}, nil, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToStringMapE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToStringMap(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToStringMapBoolE(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect map[string]bool
+ iserr bool
+ }{
+ {map[interface{}]interface{}{"v1": true, "v2": false}, map[string]bool{"v1": true, "v2": false}, false},
+ {map[string]interface{}{"v1": true, "v2": false}, map[string]bool{"v1": true, "v2": false}, false},
+ {map[string]bool{"v1": true, "v2": false}, map[string]bool{"v1": true, "v2": false}, false},
+ // errors
+ {nil, nil, true},
+ {testing.T{}, nil, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToStringMapBoolE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToStringMapBool(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToStringMapStringE(t *testing.T) {
+ var stringMapString = map[string]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
+ var stringMapInterface = map[string]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
+ var interfaceMapString = map[interface{}]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
+ var interfaceMapInterface = map[interface{}]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
+
+ tests := []struct {
+ input interface{}
+ expect map[string]string
+ iserr bool
+ }{
+ {stringMapString, stringMapString, false},
+ {stringMapInterface, stringMapString, false},
+ {interfaceMapString, stringMapString, false},
+ {interfaceMapInterface, stringMapString, false},
+ // errors
+ {nil, nil, true},
+ {testing.T{}, nil, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToStringMapStringE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToStringMapString(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToBoolSliceE(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect []bool
+ iserr bool
+ }{
+ {[]bool{true, false, true}, []bool{true, false, true}, false},
+ {[]interface{}{true, false, true}, []bool{true, false, true}, false},
+ {[]int{1, 0, 1}, []bool{true, false, true}, false},
+ {[]string{"true", "false", "true"}, []bool{true, false, true}, false},
+ // errors
+ {nil, nil, true},
+ {testing.T{}, nil, true},
+ {[]string{"foo", "bar"}, nil, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToBoolSliceE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToBoolSlice(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToIntSliceE(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect []int
+ iserr bool
+ }{
+ {[]int{1, 3}, []int{1, 3}, false},
+ {[]interface{}{1.2, 3.2}, []int{1, 3}, false},
+ {[]string{"2", "3"}, []int{2, 3}, false},
+ {[2]string{"2", "3"}, []int{2, 3}, false},
+ // errors
+ {nil, nil, true},
+ {testing.T{}, nil, true},
+ {[]string{"foo", "bar"}, nil, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToIntSliceE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToIntSlice(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToSliceE(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect []interface{}
+ iserr bool
+ }{
+ {[]interface{}{1, 3}, []interface{}{1, 3}, false},
+ {[]map[string]interface{}{{"k1": 1}, {"k2": 2}}, []interface{}{map[string]interface{}{"k1": 1}, map[string]interface{}{"k2": 2}}, false},
+ // errors
+ {nil, nil, true},
+ {testing.T{}, nil, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToSliceE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToSlice(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToStringSliceE(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect []string
+ iserr bool
+ }{
+ {[]string{"a", "b"}, []string{"a", "b"}, false},
+ {[]interface{}{1, 3}, []string{"1", "3"}, false},
+ {interface{}(1), []string{"1"}, false},
+ // errors
+ {nil, nil, true},
+ {testing.T{}, nil, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToStringSliceE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToStringSlice(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func TestToBoolE(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect bool
+ iserr bool
+ }{
+ {0, false, false},
+ {nil, false, false},
+ {"false", false, false},
+ {"FALSE", false, false},
+ {"False", false, false},
+ {"f", false, false},
+ {"F", false, false},
+ {false, false, false},
+
+ {"true", true, false},
+ {"TRUE", true, false},
+ {"True", true, false},
+ {"t", true, false},
+ {"T", true, false},
+ {1, true, false},
+ {true, true, false},
+ {-1, true, false},
+
+ // errors
+ {"test", false, true},
+ {testing.T{}, false, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToBoolE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToBool(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
+
+func BenchmarkTooBool(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ if !ToBool(true) {
+ b.Fatal("ToBool returned false")
+ }
+ }
+}
+
+func TestIndirectPointers(t *testing.T) {
+ x := 13
+ y := &x
+ z := &y
+
+ assert.Equal(t, ToInt(y), 13)
+ assert.Equal(t, ToInt(z), 13)
+}
+
+func TestToTimeEE(t *testing.T) {
+ tests := []struct {
+ input interface{}
+ expect time.Time
+ iserr bool
+ }{
+ {"2009-11-10 23:00:00 +0000 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // Time.String()
+ {"Tue Nov 10 23:00:00 2009", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // ANSIC
+ {"Tue Nov 10 23:00:00 UTC 2009", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // UnixDate
+ {"Tue Nov 10 23:00:00 +0000 2009", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RubyDate
+ {"10 Nov 09 23:00 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC822
+ {"10 Nov 09 23:00 +0000", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC822Z
+ {"Tuesday, 10-Nov-09 23:00:00 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC850
+ {"Tue, 10 Nov 2009 23:00:00 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC1123
+ {"Tue, 10 Nov 2009 23:00:00 +0000", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC1123Z
+ {"2009-11-10T23:00:00Z", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC3339
+ {"2009-11-10T23:00:00Z", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC3339Nano
+ {"11:00PM", time.Date(0, 1, 1, 23, 0, 0, 0, time.UTC), false}, // Kitchen
+ {"Nov 10 23:00:00", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // Stamp
+ {"Nov 10 23:00:00.000", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // StampMilli
+ {"Nov 10 23:00:00.000000", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // StampMicro
+ {"Nov 10 23:00:00.000000000", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // StampNano
+ {"2016-03-06 15:28:01-00:00", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false}, // RFC3339 without T
+ {"2016-03-06 15:28:01", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false},
+ {"2016-03-06 15:28:01 -0000", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false},
+ {"2016-03-06 15:28:01 -00:00", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false},
+ {"2006-01-02", time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC), false},
+ {"02 Jan 2006", time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC), false},
+ {1472574600, time.Date(2016, 8, 30, 16, 30, 0, 0, time.UTC), false},
+ {int(1482597504), time.Date(2016, 12, 24, 16, 38, 24, 0, time.UTC), false},
+ {int64(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
+ {int32(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
+ {uint(1482597504), time.Date(2016, 12, 24, 16, 38, 24, 0, time.UTC), false},
+ {uint64(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
+ {uint32(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
+ {time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
+ // errors
+ {"2006", time.Time{}, true},
+ {testing.T{}, time.Time{}, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToTimeE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v.UTC(), errmsg)
+
+ // Non-E test
+ v = ToTime(test.input)
+ assert.Equal(t, test.expect, v.UTC(), errmsg)
+ }
+}
+
+func TestToDurationE(t *testing.T) {
+ var td time.Duration = 5
+
+ tests := []struct {
+ input interface{}
+ expect time.Duration
+ iserr bool
+ }{
+ {time.Duration(5), td, false},
+ {int(5), td, false},
+ {int64(5), td, false},
+ {int32(5), td, false},
+ {int16(5), td, false},
+ {int8(5), td, false},
+ {uint(5), td, false},
+ {uint64(5), td, false},
+ {uint32(5), td, false},
+ {uint16(5), td, false},
+ {uint8(5), td, false},
+ {float64(5), td, false},
+ {float32(5), td, false},
+ {string("5"), td, false},
+ {string("5ns"), td, false},
+ {string("5us"), time.Microsecond * td, false},
+ {string("5µs"), time.Microsecond * td, false},
+ {string("5ms"), time.Millisecond * td, false},
+ {string("5s"), time.Second * td, false},
+ {string("5m"), time.Minute * td, false},
+ {string("5h"), time.Hour * td, false},
+ // errors
+ {"test", 0, true},
+ {testing.T{}, 0, true},
+ }
+
+ for i, test := range tests {
+ errmsg := fmt.Sprintf("i = %d", i) // assert helper message
+
+ v, err := ToDurationE(test.input)
+ if test.iserr {
+ assert.Error(t, err, errmsg)
+ continue
+ }
+
+ assert.NoError(t, err, errmsg)
+ assert.Equal(t, test.expect, v, errmsg)
+
+ // Non-E test
+ v = ToDuration(test.input)
+ assert.Equal(t, test.expect, v, errmsg)
+ }
+}
diff --git a/vendor/github.com/spf13/cast/caste.go b/vendor/github.com/spf13/cast/caste.go
new file mode 100644
index 000000000..4e75f64ba
--- /dev/null
+++ b/vendor/github.com/spf13/cast/caste.go
@@ -0,0 +1,1117 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+package cast
+
+import (
+ "errors"
+ "fmt"
+ "html/template"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var errNegativeNotAllowed = errors.New("unable to cast negative value")
+
+// ToTimeE casts an interface to a time.Time type.
+func ToTimeE(i interface{}) (tim time.Time, err error) {
+ i = indirect(i)
+
+ switch v := i.(type) {
+ case time.Time:
+ return v, nil
+ case string:
+ return StringToDate(v)
+ case int:
+ return time.Unix(int64(v), 0), nil
+ case int64:
+ return time.Unix(v, 0), nil
+ case int32:
+ return time.Unix(int64(v), 0), nil
+ case uint:
+ return time.Unix(int64(v), 0), nil
+ case uint64:
+ return time.Unix(int64(v), 0), nil
+ case uint32:
+ return time.Unix(int64(v), 0), nil
+ default:
+ return time.Time{}, fmt.Errorf("unable to cast %#v of type %T to Time", i, i)
+ }
+}
+
+// ToDurationE casts an interface to a time.Duration type.
+func ToDurationE(i interface{}) (d time.Duration, err error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case time.Duration:
+ return s, nil
+ case int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8:
+ d = time.Duration(ToInt64(s))
+ return
+ case float32, float64:
+ d = time.Duration(ToFloat64(s))
+ return
+ case string:
+ if strings.ContainsAny(s, "nsuµmh") {
+ d, err = time.ParseDuration(s)
+ } else {
+ d, err = time.ParseDuration(s + "ns")
+ }
+ return
+ default:
+ err = fmt.Errorf("unable to cast %#v of type %T to Duration", i, i)
+ return
+ }
+}
+
+// ToBoolE casts an interface to a bool type.
+func ToBoolE(i interface{}) (bool, error) {
+ i = indirect(i)
+
+ switch b := i.(type) {
+ case bool:
+ return b, nil
+ case nil:
+ return false, nil
+ case int:
+ if i.(int) != 0 {
+ return true, nil
+ }
+ return false, nil
+ case string:
+ return strconv.ParseBool(i.(string))
+ default:
+ return false, fmt.Errorf("unable to cast %#v of type %T to bool", i, i)
+ }
+}
+
+// ToFloat64E casts an interface to a float64 type.
+func ToFloat64E(i interface{}) (float64, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case float64:
+ return s, nil
+ case float32:
+ return float64(s), nil
+ case int:
+ return float64(s), nil
+ case int64:
+ return float64(s), nil
+ case int32:
+ return float64(s), nil
+ case int16:
+ return float64(s), nil
+ case int8:
+ return float64(s), nil
+ case uint:
+ return float64(s), nil
+ case uint64:
+ return float64(s), nil
+ case uint32:
+ return float64(s), nil
+ case uint16:
+ return float64(s), nil
+ case uint8:
+ return float64(s), nil
+ case string:
+ v, err := strconv.ParseFloat(s, 64)
+ if err == nil {
+ return v, nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
+ }
+}
+
+// ToFloat32E casts an interface to a float32 type.
+func ToFloat32E(i interface{}) (float32, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case float64:
+ return float32(s), nil
+ case float32:
+ return s, nil
+ case int:
+ return float32(s), nil
+ case int64:
+ return float32(s), nil
+ case int32:
+ return float32(s), nil
+ case int16:
+ return float32(s), nil
+ case int8:
+ return float32(s), nil
+ case uint:
+ return float32(s), nil
+ case uint64:
+ return float32(s), nil
+ case uint32:
+ return float32(s), nil
+ case uint16:
+ return float32(s), nil
+ case uint8:
+ return float32(s), nil
+ case string:
+ v, err := strconv.ParseFloat(s, 32)
+ if err == nil {
+ return float32(v), nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
+ }
+}
+
+// ToInt64E casts an interface to an int64 type.
+func ToInt64E(i interface{}) (int64, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case int:
+ return int64(s), nil
+ case int64:
+ return s, nil
+ case int32:
+ return int64(s), nil
+ case int16:
+ return int64(s), nil
+ case int8:
+ return int64(s), nil
+ case uint:
+ return int64(s), nil
+ case uint64:
+ return int64(s), nil
+ case uint32:
+ return int64(s), nil
+ case uint16:
+ return int64(s), nil
+ case uint8:
+ return int64(s), nil
+ case float64:
+ return int64(s), nil
+ case float32:
+ return int64(s), nil
+ case string:
+ v, err := strconv.ParseInt(s, 0, 0)
+ if err == nil {
+ return v, nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ case nil:
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
+ }
+}
+
+// ToInt32E casts an interface to an int32 type.
+func ToInt32E(i interface{}) (int32, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case int:
+ return int32(s), nil
+ case int64:
+ return int32(s), nil
+ case int32:
+ return s, nil
+ case int16:
+ return int32(s), nil
+ case int8:
+ return int32(s), nil
+ case uint:
+ return int32(s), nil
+ case uint64:
+ return int32(s), nil
+ case uint32:
+ return int32(s), nil
+ case uint16:
+ return int32(s), nil
+ case uint8:
+ return int32(s), nil
+ case float64:
+ return int32(s), nil
+ case float32:
+ return int32(s), nil
+ case string:
+ v, err := strconv.ParseInt(s, 0, 0)
+ if err == nil {
+ return int32(v), nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ case nil:
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
+ }
+}
+
+// ToInt16E casts an interface to an int16 type.
+func ToInt16E(i interface{}) (int16, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case int:
+ return int16(s), nil
+ case int64:
+ return int16(s), nil
+ case int32:
+ return int16(s), nil
+ case int16:
+ return s, nil
+ case int8:
+ return int16(s), nil
+ case uint:
+ return int16(s), nil
+ case uint64:
+ return int16(s), nil
+ case uint32:
+ return int16(s), nil
+ case uint16:
+ return int16(s), nil
+ case uint8:
+ return int16(s), nil
+ case float64:
+ return int16(s), nil
+ case float32:
+ return int16(s), nil
+ case string:
+ v, err := strconv.ParseInt(s, 0, 0)
+ if err == nil {
+ return int16(v), nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ case nil:
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
+ }
+}
+
+// ToInt8E casts an interface to an int8 type.
+func ToInt8E(i interface{}) (int8, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case int:
+ return int8(s), nil
+ case int64:
+ return int8(s), nil
+ case int32:
+ return int8(s), nil
+ case int16:
+ return int8(s), nil
+ case int8:
+ return s, nil
+ case uint:
+ return int8(s), nil
+ case uint64:
+ return int8(s), nil
+ case uint32:
+ return int8(s), nil
+ case uint16:
+ return int8(s), nil
+ case uint8:
+ return int8(s), nil
+ case float64:
+ return int8(s), nil
+ case float32:
+ return int8(s), nil
+ case string:
+ v, err := strconv.ParseInt(s, 0, 0)
+ if err == nil {
+ return int8(v), nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ case nil:
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
+ }
+}
+
+// ToIntE casts an interface to an int type.
+func ToIntE(i interface{}) (int, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case int:
+ return s, nil
+ case int64:
+ return int(s), nil
+ case int32:
+ return int(s), nil
+ case int16:
+ return int(s), nil
+ case int8:
+ return int(s), nil
+ case uint:
+ return int(s), nil
+ case uint64:
+ return int(s), nil
+ case uint32:
+ return int(s), nil
+ case uint16:
+ return int(s), nil
+ case uint8:
+ return int(s), nil
+ case float64:
+ return int(s), nil
+ case float32:
+ return int(s), nil
+ case string:
+ v, err := strconv.ParseInt(s, 0, 0)
+ if err == nil {
+ return int(v), nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ case nil:
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
+ }
+}
+
+// ToUintE casts an interface to a uint type.
+func ToUintE(i interface{}) (uint, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case string:
+ v, err := strconv.ParseUint(s, 0, 0)
+ if err == nil {
+ return uint(v), nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v to uint: %s", i, err)
+ case int:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint(s), nil
+ case int64:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint(s), nil
+ case int32:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint(s), nil
+ case int16:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint(s), nil
+ case int8:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint(s), nil
+ case uint:
+ return s, nil
+ case uint64:
+ return uint(s), nil
+ case uint32:
+ return uint(s), nil
+ case uint16:
+ return uint(s), nil
+ case uint8:
+ return uint(s), nil
+ case float64:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint(s), nil
+ case float32:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint(s), nil
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ case nil:
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to uint", i, i)
+ }
+}
+
+// ToUint64E casts an interface to a uint64 type.
+func ToUint64E(i interface{}) (uint64, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case string:
+ v, err := strconv.ParseUint(s, 0, 64)
+ if err == nil {
+ return v, nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v to uint64: %s", i, err)
+ case int:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint64(s), nil
+ case int64:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint64(s), nil
+ case int32:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint64(s), nil
+ case int16:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint64(s), nil
+ case int8:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint64(s), nil
+ case uint:
+ return uint64(s), nil
+ case uint64:
+ return s, nil
+ case uint32:
+ return uint64(s), nil
+ case uint16:
+ return uint64(s), nil
+ case uint8:
+ return uint64(s), nil
+ case float32:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint64(s), nil
+ case float64:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint64(s), nil
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ case nil:
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to uint64", i, i)
+ }
+}
+
+// ToUint32E casts an interface to a uint32 type.
+func ToUint32E(i interface{}) (uint32, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case string:
+ v, err := strconv.ParseUint(s, 0, 32)
+ if err == nil {
+ return uint32(v), nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v to uint32: %s", i, err)
+ case int:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint32(s), nil
+ case int64:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint32(s), nil
+ case int32:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint32(s), nil
+ case int16:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint32(s), nil
+ case int8:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint32(s), nil
+ case uint:
+ return uint32(s), nil
+ case uint64:
+ return uint32(s), nil
+ case uint32:
+ return s, nil
+ case uint16:
+ return uint32(s), nil
+ case uint8:
+ return uint32(s), nil
+ case float64:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint32(s), nil
+ case float32:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint32(s), nil
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ case nil:
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to uint32", i, i)
+ }
+}
+
+// ToUint16E casts an interface to a uint16 type.
+func ToUint16E(i interface{}) (uint16, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case string:
+ v, err := strconv.ParseUint(s, 0, 16)
+ if err == nil {
+ return uint16(v), nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v to uint16: %s", i, err)
+ case int:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint16(s), nil
+ case int64:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint16(s), nil
+ case int32:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint16(s), nil
+ case int16:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint16(s), nil
+ case int8:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint16(s), nil
+ case uint:
+ return uint16(s), nil
+ case uint64:
+ return uint16(s), nil
+ case uint32:
+ return uint16(s), nil
+ case uint16:
+ return s, nil
+ case uint8:
+ return uint16(s), nil
+ case float64:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint16(s), nil
+ case float32:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint16(s), nil
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ case nil:
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to uint16", i, i)
+ }
+}
+
+// ToUint8E casts an interface to a uint type.
+func ToUint8E(i interface{}) (uint8, error) {
+ i = indirect(i)
+
+ switch s := i.(type) {
+ case string:
+ v, err := strconv.ParseUint(s, 0, 8)
+ if err == nil {
+ return uint8(v), nil
+ }
+ return 0, fmt.Errorf("unable to cast %#v to uint8: %s", i, err)
+ case int:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint8(s), nil
+ case int64:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint8(s), nil
+ case int32:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint8(s), nil
+ case int16:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint8(s), nil
+ case int8:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint8(s), nil
+ case uint:
+ return uint8(s), nil
+ case uint64:
+ return uint8(s), nil
+ case uint32:
+ return uint8(s), nil
+ case uint16:
+ return uint8(s), nil
+ case uint8:
+ return s, nil
+ case float64:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint8(s), nil
+ case float32:
+ if s < 0 {
+ return 0, errNegativeNotAllowed
+ }
+ return uint8(s), nil
+ case bool:
+ if s {
+ return 1, nil
+ }
+ return 0, nil
+ case nil:
+ return 0, nil
+ default:
+ return 0, fmt.Errorf("unable to cast %#v of type %T to uint8", i, i)
+ }
+}
+
+// From html/template/content.go
+// Copyright 2011 The Go Authors. All rights reserved.
+// indirect returns the value, after dereferencing as many times
+// as necessary to reach the base type (or nil).
+func indirect(a interface{}) interface{} {
+ if a == nil {
+ return nil
+ }
+ if t := reflect.TypeOf(a); t.Kind() != reflect.Ptr {
+ // Avoid creating a reflect.Value if it's not a pointer.
+ return a
+ }
+ v := reflect.ValueOf(a)
+ for v.Kind() == reflect.Ptr && !v.IsNil() {
+ v = v.Elem()
+ }
+ return v.Interface()
+}
+
+// From html/template/content.go
+// Copyright 2011 The Go Authors. All rights reserved.
+// indirectToStringerOrError returns the value, after dereferencing as many times
+// as necessary to reach the base type (or nil) or an implementation of fmt.Stringer
+// or error,
+func indirectToStringerOrError(a interface{}) interface{} {
+ if a == nil {
+ return nil
+ }
+
+ var errorType = reflect.TypeOf((*error)(nil)).Elem()
+ var fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
+
+ v := reflect.ValueOf(a)
+ for !v.Type().Implements(fmtStringerType) && !v.Type().Implements(errorType) && v.Kind() == reflect.Ptr && !v.IsNil() {
+ v = v.Elem()
+ }
+ return v.Interface()
+}
+
+// ToStringE casts an interface to a string type.
+func ToStringE(i interface{}) (string, error) {
+ i = indirectToStringerOrError(i)
+
+ switch s := i.(type) {
+ case string:
+ return s, nil
+ case bool:
+ return strconv.FormatBool(s), nil
+ case float64:
+ return strconv.FormatFloat(s, 'f', -1, 64), nil
+ case float32:
+ return strconv.FormatFloat(float64(s), 'f', -1, 32), nil
+ case int:
+ return strconv.Itoa(s), nil
+ case int64:
+ return strconv.FormatInt(s, 10), nil
+ case int32:
+ return strconv.Itoa(int(s)), nil
+ case int16:
+ return strconv.FormatInt(int64(s), 10), nil
+ case int8:
+ return strconv.FormatInt(int64(s), 10), nil
+ case uint:
+ return strconv.FormatInt(int64(s), 10), nil
+ case uint64:
+ return strconv.FormatInt(int64(s), 10), nil
+ case uint32:
+ return strconv.FormatInt(int64(s), 10), nil
+ case uint16:
+ return strconv.FormatInt(int64(s), 10), nil
+ case uint8:
+ return strconv.FormatInt(int64(s), 10), nil
+ case []byte:
+ return string(s), nil
+ case template.HTML:
+ return string(s), nil
+ case template.URL:
+ return string(s), nil
+ case template.JS:
+ return string(s), nil
+ case template.CSS:
+ return string(s), nil
+ case template.HTMLAttr:
+ return string(s), nil
+ case nil:
+ return "", nil
+ case fmt.Stringer:
+ return s.String(), nil
+ case error:
+ return s.Error(), nil
+ default:
+ return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
+ }
+}
+
+// ToStringMapStringE casts an interface to a map[string]string type.
+func ToStringMapStringE(i interface{}) (map[string]string, error) {
+ var m = map[string]string{}
+
+ switch v := i.(type) {
+ case map[string]string:
+ return v, nil
+ case map[string]interface{}:
+ for k, val := range v {
+ m[ToString(k)] = ToString(val)
+ }
+ return m, nil
+ case map[interface{}]string:
+ for k, val := range v {
+ m[ToString(k)] = ToString(val)
+ }
+ return m, nil
+ case map[interface{}]interface{}:
+ for k, val := range v {
+ m[ToString(k)] = ToString(val)
+ }
+ return m, nil
+ default:
+ return m, fmt.Errorf("unable to cast %#v of type %T to map[string]string", i, i)
+ }
+}
+
+// ToStringMapStringSliceE casts an interface to a map[string][]string type.
+func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) {
+ var m = map[string][]string{}
+
+ switch v := i.(type) {
+ case map[string][]string:
+ return v, nil
+ case map[string][]interface{}:
+ for k, val := range v {
+ m[ToString(k)] = ToStringSlice(val)
+ }
+ return m, nil
+ case map[string]string:
+ for k, val := range v {
+ m[ToString(k)] = []string{val}
+ }
+ case map[string]interface{}:
+ for k, val := range v {
+ switch vt := val.(type) {
+ case []interface{}:
+ m[ToString(k)] = ToStringSlice(vt)
+ case []string:
+ m[ToString(k)] = vt
+ default:
+ m[ToString(k)] = []string{ToString(val)}
+ }
+ }
+ return m, nil
+ case map[interface{}][]string:
+ for k, val := range v {
+ m[ToString(k)] = ToStringSlice(val)
+ }
+ return m, nil
+ case map[interface{}]string:
+ for k, val := range v {
+ m[ToString(k)] = ToStringSlice(val)
+ }
+ return m, nil
+ case map[interface{}][]interface{}:
+ for k, val := range v {
+ m[ToString(k)] = ToStringSlice(val)
+ }
+ return m, nil
+ case map[interface{}]interface{}:
+ for k, val := range v {
+ key, err := ToStringE(k)
+ if err != nil {
+ return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
+ }
+ value, err := ToStringSliceE(val)
+ if err != nil {
+ return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
+ }
+ m[key] = value
+ }
+ default:
+ return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
+ }
+ return m, nil
+}
+
+// ToStringMapBoolE casts an interface to a map[string]bool type.
+func ToStringMapBoolE(i interface{}) (map[string]bool, error) {
+ var m = map[string]bool{}
+
+ switch v := i.(type) {
+ case map[interface{}]interface{}:
+ for k, val := range v {
+ m[ToString(k)] = ToBool(val)
+ }
+ return m, nil
+ case map[string]interface{}:
+ for k, val := range v {
+ m[ToString(k)] = ToBool(val)
+ }
+ return m, nil
+ case map[string]bool:
+ return v, nil
+ default:
+ return m, fmt.Errorf("unable to cast %#v of type %T to map[string]bool", i, i)
+ }
+}
+
+// ToStringMapE casts an interface to a map[string]interface{} type.
+func ToStringMapE(i interface{}) (map[string]interface{}, error) {
+ var m = map[string]interface{}{}
+
+ switch v := i.(type) {
+ case map[interface{}]interface{}:
+ for k, val := range v {
+ m[ToString(k)] = val
+ }
+ return m, nil
+ case map[string]interface{}:
+ return v, nil
+ default:
+ return m, fmt.Errorf("unable to cast %#v of type %T to map[string]interface{}", i, i)
+ }
+}
+
+// ToSliceE casts an interface to a []interface{} type.
+func ToSliceE(i interface{}) ([]interface{}, error) {
+ var s []interface{}
+
+ switch v := i.(type) {
+ case []interface{}:
+ return append(s, v...), nil
+ case []map[string]interface{}:
+ for _, u := range v {
+ s = append(s, u)
+ }
+ return s, nil
+ default:
+ return s, fmt.Errorf("unable to cast %#v of type %T to []interface{}", i, i)
+ }
+}
+
+// ToBoolSliceE casts an interface to a []bool type.
+func ToBoolSliceE(i interface{}) ([]bool, error) {
+ if i == nil {
+ return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
+ }
+
+ switch v := i.(type) {
+ case []bool:
+ return v, nil
+ }
+
+ kind := reflect.TypeOf(i).Kind()
+ switch kind {
+ case reflect.Slice, reflect.Array:
+ s := reflect.ValueOf(i)
+ a := make([]bool, s.Len())
+ for j := 0; j < s.Len(); j++ {
+ val, err := ToBoolE(s.Index(j).Interface())
+ if err != nil {
+ return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
+ }
+ a[j] = val
+ }
+ return a, nil
+ default:
+ return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
+ }
+}
+
+// ToStringSliceE casts an interface to a []string type.
+func ToStringSliceE(i interface{}) ([]string, error) {
+ var a []string
+
+ switch v := i.(type) {
+ case []interface{}:
+ for _, u := range v {
+ a = append(a, ToString(u))
+ }
+ return a, nil
+ case []string:
+ return v, nil
+ case string:
+ return strings.Fields(v), nil
+ case interface{}:
+ str, err := ToStringE(v)
+ if err != nil {
+ return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
+ }
+ return []string{str}, nil
+ default:
+ return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
+ }
+}
+
+// ToIntSliceE casts an interface to a []int type.
+func ToIntSliceE(i interface{}) ([]int, error) {
+ if i == nil {
+ return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
+ }
+
+ switch v := i.(type) {
+ case []int:
+ return v, nil
+ }
+
+ kind := reflect.TypeOf(i).Kind()
+ switch kind {
+ case reflect.Slice, reflect.Array:
+ s := reflect.ValueOf(i)
+ a := make([]int, s.Len())
+ for j := 0; j < s.Len(); j++ {
+ val, err := ToIntE(s.Index(j).Interface())
+ if err != nil {
+ return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
+ }
+ a[j] = val
+ }
+ return a, nil
+ default:
+ return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
+ }
+}
+
+// StringToDate attempts to parse a string into a time.Time type using a
+// predefined list of formats. If no suitable format is found, an error is
+// returned.
+func StringToDate(s string) (time.Time, error) {
+ return parseDateWith(s, []string{
+ time.RFC3339,
+ "2006-01-02T15:04:05", // iso8601 without timezone
+ time.RFC1123Z,
+ time.RFC1123,
+ time.RFC822Z,
+ time.RFC822,
+ time.RFC850,
+ time.ANSIC,
+ time.UnixDate,
+ time.RubyDate,
+ "2006-01-02 15:04:05.999999999 -0700 MST", // Time.String()
+ "2006-01-02",
+ "02 Jan 2006",
+ "2006-01-02 15:04:05 -07:00",
+ "2006-01-02 15:04:05 -0700",
+ "2006-01-02 15:04:05Z07:00", // RFC3339 without T
+ "2006-01-02 15:04:05",
+ time.Kitchen,
+ time.Stamp,
+ time.StampMilli,
+ time.StampMicro,
+ time.StampNano,
+ })
+}
+
+func parseDateWith(s string, dates []string) (d time.Time, e error) {
+ for _, dateType := range dates {
+ if d, e = time.Parse(dateType, s); e == nil {
+ return
+ }
+ }
+ return d, fmt.Errorf("unable to parse date: %s", s)
+}
diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go
index ae3930dfc..664bf5aa5 100644
--- a/vendor/github.com/spf13/cobra/command.go
+++ b/vendor/github.com/spf13/cobra/command.go
@@ -788,6 +788,7 @@ func (c *Command) initHelpCmd() {
},
}
}
+ c.RemoveCommand(c.helpCommand)
c.AddCommand(c.helpCommand)
}
diff --git a/vendor/github.com/spf13/jwalterweatherman/.gitignore b/vendor/github.com/spf13/jwalterweatherman/.gitignore
new file mode 100644
index 000000000..00268614f
--- /dev/null
+++ b/vendor/github.com/spf13/jwalterweatherman/.gitignore
@@ -0,0 +1,22 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
diff --git a/vendor/github.com/spf13/jwalterweatherman/LICENSE b/vendor/github.com/spf13/jwalterweatherman/LICENSE
new file mode 100644
index 000000000..4527efb9c
--- /dev/null
+++ b/vendor/github.com/spf13/jwalterweatherman/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Steve Francia
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE. \ No newline at end of file
diff --git a/vendor/github.com/spf13/jwalterweatherman/README.md b/vendor/github.com/spf13/jwalterweatherman/README.md
new file mode 100644
index 000000000..350a9683d
--- /dev/null
+++ b/vendor/github.com/spf13/jwalterweatherman/README.md
@@ -0,0 +1,148 @@
+jWalterWeatherman
+=================
+
+Seamless printing to the terminal (stdout) and logging to a io.Writer
+(file) that’s as easy to use as fmt.Println.
+
+![and_that__s_why_you_always_leave_a_note_by_jonnyetc-d57q7um](https://cloud.githubusercontent.com/assets/173412/11002937/ccd01654-847d-11e5-828e-12ebaf582eaf.jpg)
+Graphic by [JonnyEtc](http://jonnyetc.deviantart.com/art/And-That-s-Why-You-Always-Leave-a-Note-315311422)
+
+JWW is primarily a wrapper around the excellent standard log library. It
+provides a few advantages over using the standard log library alone.
+
+1. Ready to go out of the box.
+2. One library for both printing to the terminal and logging (to files).
+3. Really easy to log to either a temp file or a file you specify.
+
+
+I really wanted a very straightforward library that could seamlessly do
+the following things.
+
+1. Replace all the println, printf, etc statements thought my code with
+ something more useful
+2. Allow the user to easily control what levels are printed to stdout
+3. Allow the user to easily control what levels are logged
+4. Provide an easy mechanism (like fmt.Println) to print info to the user
+ which can be easily logged as well
+5. Due to 2 & 3 provide easy verbose mode for output and logs
+6. Not have any unnecessary initialization cruft. Just use it.
+
+# Usage
+
+## Step 1. Use it
+Put calls throughout your source based on type of feedback.
+No initialization or setup needs to happen. Just start calling things.
+
+Available Loggers are:
+
+ * TRACE
+ * DEBUG
+ * INFO
+ * WARN
+ * ERROR
+ * CRITICAL
+ * FATAL
+
+These each are loggers based on the log standard library and follow the
+standard usage. Eg.
+
+```go
+ import (
+ jww "github.com/spf13/jwalterweatherman"
+ )
+
+ ...
+
+ if err != nil {
+
+ // This is a pretty serious error and the user should know about
+ // it. It will be printed to the terminal as well as logged under the
+ // default thresholds.
+
+ jww.ERROR.Println(err)
+ }
+
+ if err2 != nil {
+ // This error isn’t going to materially change the behavior of the
+ // application, but it’s something that may not be what the user
+ // expects. Under the default thresholds, Warn will be logged, but
+ // not printed to the terminal.
+
+ jww.WARN.Println(err2)
+ }
+
+ // Information that’s relevant to what’s happening, but not very
+ // important for the user. Under the default thresholds this will be
+ // discarded.
+
+ jww.INFO.Printf("information %q", response)
+
+```
+
+NOTE: You can also use the library in a non-global setting by creating an instance of a Notebook:
+
+```go
+notepad = jww.NewNotepad(jww.LevelInfo, jww.LevelTrace, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
+notepad.WARN.Println("Some warning"")
+```
+
+_Why 7 levels?_
+
+Maybe you think that 7 levels are too much for any application... and you
+are probably correct. Just because there are seven levels doesn’t mean
+that you should be using all 7 levels. Pick the right set for your needs.
+Remember they only have to mean something to your project.
+
+## Step 2. Optionally configure JWW
+
+Under the default thresholds :
+
+ * Debug, Trace & Info goto /dev/null
+ * Warn and above is logged (when a log file/io.Writer is provided)
+ * Error and above is printed to the terminal (stdout)
+
+### Changing the thresholds
+
+The threshold can be changed at any time, but will only affect calls that
+execute after the change was made.
+
+This is very useful if your application has a verbose mode. Of course you
+can decide what verbose means to you or even have multiple levels of
+verbosity.
+
+
+```go
+ import (
+ jww "github.com/spf13/jwalterweatherman"
+ )
+
+ if Verbose {
+ jww.SetLogThreshold(jww.LevelTrace)
+ jww.SetStdoutThreshold(jww.LevelInfo)
+ }
+```
+
+Note that JWW's own internal output uses log levels as well, so set the log
+level before making any other calls if you want to see what it's up to.
+
+
+### Setting a log file
+
+JWW can log to any `io.Writer`:
+
+
+```go
+
+ jww.SetLogOutput(customWriter)
+
+```
+
+
+# More information
+
+This is an early release. I’ve been using it for a while and this is the
+third interface I’ve tried. I like this one pretty well, but no guarantees
+that it won’t change a bit.
+
+I wrote this for use in [hugo](http://hugo.spf13.com). If you are looking
+for a static website engine that’s super fast please checkout Hugo.
diff --git a/vendor/github.com/spf13/jwalterweatherman/default_notepad.go b/vendor/github.com/spf13/jwalterweatherman/default_notepad.go
new file mode 100644
index 000000000..bcb763403
--- /dev/null
+++ b/vendor/github.com/spf13/jwalterweatherman/default_notepad.go
@@ -0,0 +1,113 @@
+// Copyright © 2016 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+package jwalterweatherman
+
+import (
+ "io"
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+var (
+ TRACE *log.Logger
+ DEBUG *log.Logger
+ INFO *log.Logger
+ WARN *log.Logger
+ ERROR *log.Logger
+ CRITICAL *log.Logger
+ FATAL *log.Logger
+
+ LOG *log.Logger
+ FEEDBACK *Feedback
+
+ defaultNotepad *Notepad
+)
+
+func reloadDefaultNotepad() {
+ TRACE = defaultNotepad.TRACE
+ DEBUG = defaultNotepad.DEBUG
+ INFO = defaultNotepad.INFO
+ WARN = defaultNotepad.WARN
+ ERROR = defaultNotepad.ERROR
+ CRITICAL = defaultNotepad.CRITICAL
+ FATAL = defaultNotepad.FATAL
+
+ LOG = defaultNotepad.LOG
+ FEEDBACK = defaultNotepad.FEEDBACK
+}
+
+func init() {
+ defaultNotepad = NewNotepad(LevelError, LevelWarn, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
+ reloadDefaultNotepad()
+}
+
+// SetLogThreshold set the log threshold for the default notepad. Trace by default.
+func SetLogThreshold(threshold Threshold) {
+ defaultNotepad.SetLogThreshold(threshold)
+ reloadDefaultNotepad()
+}
+
+// SetLogOutput set the log output for the default notepad. Discarded by default.
+func SetLogOutput(handle io.Writer) {
+ defaultNotepad.SetLogOutput(handle)
+ reloadDefaultNotepad()
+}
+
+// SetStdoutThreshold set the standard output threshold for the default notepad.
+// Info by default.
+func SetStdoutThreshold(threshold Threshold) {
+ defaultNotepad.SetStdoutThreshold(threshold)
+ reloadDefaultNotepad()
+}
+
+// SetPrefix set the prefix for the default logger. Empty by default.
+func SetPrefix(prefix string) {
+ defaultNotepad.SetPrefix(prefix)
+ reloadDefaultNotepad()
+}
+
+// SetFlags set the flags for the default logger. "log.Ldate | log.Ltime" by default.
+func SetFlags(flags int) {
+ defaultNotepad.SetFlags(flags)
+ reloadDefaultNotepad()
+}
+
+// Level returns the current global log threshold.
+func LogThreshold() Threshold {
+ return defaultNotepad.logThreshold
+}
+
+// Level returns the current global output threshold.
+func StdoutThreshold() Threshold {
+ return defaultNotepad.stdoutThreshold
+}
+
+// GetStdoutThreshold returns the defined Treshold for the log logger.
+func GetLogThreshold() Threshold {
+ return defaultNotepad.GetLogThreshold()
+}
+
+// GetStdoutThreshold returns the Treshold for the stdout logger.
+func GetStdoutThreshold() Threshold {
+ return defaultNotepad.GetStdoutThreshold()
+}
+
+// LogCountForLevel returns the number of log invocations for a given threshold.
+func LogCountForLevel(l Threshold) uint64 {
+ return defaultNotepad.LogCountForLevel(l)
+}
+
+// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations
+// greater than or equal to a given threshold.
+func LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 {
+ return defaultNotepad.LogCountForLevelsGreaterThanorEqualTo(threshold)
+}
+
+// ResetLogCounters resets the invocation counters for all levels.
+func ResetLogCounters() {
+ defaultNotepad.ResetLogCounters()
+}
diff --git a/vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go b/vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go
new file mode 100644
index 000000000..2670c8d96
--- /dev/null
+++ b/vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go
@@ -0,0 +1,102 @@
+// Copyright © 2016 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+package jwalterweatherman
+
+import (
+ "bytes"
+ "io/ioutil"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestThresholds(t *testing.T) {
+ SetStdoutThreshold(LevelError)
+ require.Equal(t, StdoutThreshold(), LevelError)
+ SetLogThreshold(LevelCritical)
+ require.Equal(t, LogThreshold(), LevelCritical)
+ require.NotEqual(t, StdoutThreshold(), LevelCritical)
+ SetStdoutThreshold(LevelWarn)
+ require.Equal(t, StdoutThreshold(), LevelWarn)
+}
+
+func TestDefaultLogging(t *testing.T) {
+ var outputBuf, logBuf bytes.Buffer
+
+ defaultNotepad.logHandle = &logBuf
+ defaultNotepad.outHandle = &outputBuf
+
+ SetLogThreshold(LevelWarn)
+ SetStdoutThreshold(LevelError)
+
+ FATAL.Println("fatal err")
+ CRITICAL.Println("critical err")
+ ERROR.Println("an error")
+ WARN.Println("a warning")
+ INFO.Println("information")
+ DEBUG.Println("debugging info")
+ TRACE.Println("trace")
+
+ require.Contains(t, logBuf.String(), "fatal err")
+ require.Contains(t, logBuf.String(), "critical err")
+ require.Contains(t, logBuf.String(), "an error")
+ require.Contains(t, logBuf.String(), "a warning")
+ require.NotContains(t, logBuf.String(), "information")
+ require.NotContains(t, logBuf.String(), "debugging info")
+ require.NotContains(t, logBuf.String(), "trace")
+
+ require.Contains(t, outputBuf.String(), "fatal err")
+ require.Contains(t, outputBuf.String(), "critical err")
+ require.Contains(t, outputBuf.String(), "an error")
+ require.NotContains(t, outputBuf.String(), "a warning")
+ require.NotContains(t, outputBuf.String(), "information")
+ require.NotContains(t, outputBuf.String(), "debugging info")
+ require.NotContains(t, outputBuf.String(), "trace")
+}
+
+func TestLogCounter(t *testing.T) {
+ defaultNotepad.logHandle = ioutil.Discard
+ defaultNotepad.outHandle = ioutil.Discard
+
+ SetLogThreshold(LevelTrace)
+ SetStdoutThreshold(LevelTrace)
+
+ FATAL.Println("fatal err")
+ CRITICAL.Println("critical err")
+ WARN.Println("a warning")
+ WARN.Println("another warning")
+ INFO.Println("information")
+ DEBUG.Println("debugging info")
+ TRACE.Println("trace")
+
+ wg := &sync.WaitGroup{}
+
+ for i := 0; i < 10; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for j := 0; j < 10; j++ {
+ ERROR.Println("error", j)
+ // check for data races
+ require.True(t, LogCountForLevel(LevelError) > uint64(j))
+ require.True(t, LogCountForLevelsGreaterThanorEqualTo(LevelError) > uint64(j))
+ }
+ }()
+
+ }
+
+ wg.Wait()
+
+ require.Equal(t, uint64(1), LogCountForLevel(LevelFatal))
+ require.Equal(t, uint64(1), LogCountForLevel(LevelCritical))
+ require.Equal(t, uint64(2), LogCountForLevel(LevelWarn))
+ require.Equal(t, uint64(1), LogCountForLevel(LevelInfo))
+ require.Equal(t, uint64(1), LogCountForLevel(LevelDebug))
+ require.Equal(t, uint64(1), LogCountForLevel(LevelTrace))
+ require.Equal(t, uint64(100), LogCountForLevel(LevelError))
+ require.Equal(t, uint64(102), LogCountForLevelsGreaterThanorEqualTo(LevelError))
+}
diff --git a/vendor/github.com/spf13/jwalterweatherman/log_counter.go b/vendor/github.com/spf13/jwalterweatherman/log_counter.go
new file mode 100644
index 000000000..570db1d4c
--- /dev/null
+++ b/vendor/github.com/spf13/jwalterweatherman/log_counter.go
@@ -0,0 +1,56 @@
+// Copyright © 2016 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+package jwalterweatherman
+
+import (
+ "sync/atomic"
+)
+
+type logCounter struct {
+ counter uint64
+}
+
+func (c *logCounter) incr() {
+ atomic.AddUint64(&c.counter, 1)
+}
+
+func (c *logCounter) resetCounter() {
+ atomic.StoreUint64(&c.counter, 0)
+}
+
+func (c *logCounter) getCount() uint64 {
+ return atomic.LoadUint64(&c.counter)
+}
+
+func (c *logCounter) Write(p []byte) (n int, err error) {
+ c.incr()
+
+ return len(p), nil
+}
+
+// LogCountForLevel returns the number of log invocations for a given threshold.
+func (n *Notepad) LogCountForLevel(l Threshold) uint64 {
+ return n.logCounters[l].getCount()
+}
+
+// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations
+// greater than or equal to a given threshold.
+func (n *Notepad) LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 {
+ var cnt uint64
+
+ for i := int(threshold); i < len(n.logCounters); i++ {
+ cnt += n.LogCountForLevel(Threshold(i))
+ }
+
+ return cnt
+}
+
+// ResetLogCounters resets the invocation counters for all levels.
+func (n *Notepad) ResetLogCounters() {
+ for _, np := range n.logCounters {
+ np.resetCounter()
+ }
+}
diff --git a/vendor/github.com/spf13/jwalterweatherman/notepad.go b/vendor/github.com/spf13/jwalterweatherman/notepad.go
new file mode 100644
index 000000000..5a623f487
--- /dev/null
+++ b/vendor/github.com/spf13/jwalterweatherman/notepad.go
@@ -0,0 +1,195 @@
+// Copyright © 2016 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+package jwalterweatherman
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "os"
+)
+
+type Threshold int
+
+func (t Threshold) String() string {
+ return prefixes[t]
+}
+
+const (
+ LevelTrace Threshold = iota
+ LevelDebug
+ LevelInfo
+ LevelWarn
+ LevelError
+ LevelCritical
+ LevelFatal
+)
+
+var prefixes map[Threshold]string = map[Threshold]string{
+ LevelTrace: "TRACE",
+ LevelDebug: "DEBUG",
+ LevelInfo: "INFO",
+ LevelWarn: "WARN",
+ LevelError: "ERROR",
+ LevelCritical: "CRITICAL",
+ LevelFatal: "FATAL",
+}
+
+func prefix(t Threshold) string {
+ return t.String() + " "
+}
+
+// Notepad is where you leave a note !
+type Notepad struct {
+ TRACE *log.Logger
+ DEBUG *log.Logger
+ INFO *log.Logger
+ WARN *log.Logger
+ ERROR *log.Logger
+ CRITICAL *log.Logger
+ FATAL *log.Logger
+
+ LOG *log.Logger
+ FEEDBACK *Feedback
+
+ loggers []**log.Logger
+ logHandle io.Writer
+ outHandle io.Writer
+ logThreshold Threshold
+ stdoutThreshold Threshold
+ prefix string
+ flags int
+
+ // One per Threshold
+ logCounters [7]*logCounter
+}
+
+// NewNotepad create a new notepad.
+func NewNotepad(outThreshold Threshold, logThreshold Threshold, outHandle, logHandle io.Writer, prefix string, flags int) *Notepad {
+ n := &Notepad{}
+
+ n.loggers = append(n.loggers, &n.TRACE, &n.DEBUG, &n.INFO, &n.WARN, &n.ERROR, &n.CRITICAL, &n.FATAL)
+ n.logHandle = logHandle
+ n.outHandle = outHandle
+ n.logThreshold = logThreshold
+ n.stdoutThreshold = outThreshold
+
+ if len(prefix) != 0 {
+ n.prefix = "[" + prefix + "] "
+ } else {
+ n.prefix = ""
+ }
+
+ n.flags = flags
+
+ n.LOG = log.New(n.logHandle,
+ "LOG: ",
+ n.flags)
+
+ n.FEEDBACK = &Feedback{n}
+
+ n.init()
+
+ return n
+}
+
+// Feedback is special. It writes plainly to the output while
+// logging with the standard extra information (date, file, etc)
+// Only Println and Printf are currently provided for this
+type Feedback struct {
+ *Notepad
+}
+
+// init create the loggers for each level depending on the notepad thresholds
+func (n *Notepad) init() {
+ bothHandle := io.MultiWriter(n.outHandle, n.logHandle)
+
+ for t, logger := range n.loggers {
+ threshold := Threshold(t)
+ counter := &logCounter{}
+ n.logCounters[t] = counter
+
+ switch {
+ case threshold >= n.logThreshold && threshold >= n.stdoutThreshold:
+ *logger = log.New(io.MultiWriter(counter, bothHandle), n.prefix+prefix(threshold), n.flags)
+
+ case threshold >= n.logThreshold:
+ *logger = log.New(io.MultiWriter(counter, n.logHandle), n.prefix+prefix(threshold), n.flags)
+
+ case threshold >= n.stdoutThreshold:
+ *logger = log.New(io.MultiWriter(counter, os.Stdout), n.prefix+prefix(threshold), n.flags)
+
+ default:
+ *logger = log.New(counter, n.prefix+prefix(threshold), n.flags)
+ }
+ }
+}
+
+// SetLogThreshold change the threshold above which messages are written to the
+// log file
+func (n *Notepad) SetLogThreshold(threshold Threshold) {
+ n.logThreshold = threshold
+ n.init()
+}
+
+// SetLogOutput change the file where log messages are written
+func (n *Notepad) SetLogOutput(handle io.Writer) {
+ n.logHandle = handle
+ n.init()
+}
+
+// GetStdoutThreshold returns the defined Treshold for the log logger.
+func (n *Notepad) GetLogThreshold() Threshold {
+ return n.logThreshold
+}
+
+// SetStdoutThreshold change the threshold above which messages are written to the
+// standard output
+func (n *Notepad) SetStdoutThreshold(threshold Threshold) {
+ n.stdoutThreshold = threshold
+ n.init()
+}
+
+// GetStdoutThreshold returns the Treshold for the stdout logger.
+func (n *Notepad) GetStdoutThreshold() Threshold {
+ return n.stdoutThreshold
+}
+
+// SetPrefix change the prefix used by the notepad. Prefixes are displayed between
+// brackets at the begining of the line. An empty prefix won't be displayed at all.
+func (n *Notepad) SetPrefix(prefix string) {
+ if len(prefix) != 0 {
+ n.prefix = "[" + prefix + "] "
+ } else {
+ n.prefix = ""
+ }
+ n.init()
+}
+
+// SetFlags choose which flags the logger will display (after prefix and message
+// level). See the package log for more informations on this.
+func (n *Notepad) SetFlags(flags int) {
+ n.flags = flags
+ n.init()
+}
+
+// Feedback is special. It writes plainly to the output while
+// logging with the standard extra information (date, file, etc)
+// Only Println and Printf are currently provided for this
+func (fb *Feedback) Println(v ...interface{}) {
+ s := fmt.Sprintln(v...)
+ fmt.Print(s)
+ fb.LOG.Output(2, s)
+}
+
+// Feedback is special. It writes plainly to the output while
+// logging with the standard extra information (date, file, etc)
+// Only Println and Printf are currently provided for this
+func (fb *Feedback) Printf(format string, v ...interface{}) {
+ s := fmt.Sprintf(format, v...)
+ fmt.Print(s)
+ fb.LOG.Output(2, s)
+}
diff --git a/vendor/github.com/spf13/jwalterweatherman/notepad_test.go b/vendor/github.com/spf13/jwalterweatherman/notepad_test.go
new file mode 100644
index 000000000..d0e3ab04b
--- /dev/null
+++ b/vendor/github.com/spf13/jwalterweatherman/notepad_test.go
@@ -0,0 +1,41 @@
+// Copyright © 2016 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+package jwalterweatherman
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestNotepad(t *testing.T) {
+
+ var logHandle, outHandle bytes.Buffer
+
+ n := NewNotepad(LevelCritical, LevelError, &outHandle, &logHandle, "TestNotePad", 0)
+
+ require.Equal(t, LevelCritical, n.GetStdoutThreshold())
+ require.Equal(t, LevelError, n.GetLogThreshold())
+
+ n.DEBUG.Println("Some debug")
+ n.ERROR.Println("Some error")
+ n.CRITICAL.Println("Some critical error")
+
+ require.Contains(t, logHandle.String(), "[TestNotePad] ERROR Some error")
+ require.NotContains(t, logHandle.String(), "Some debug")
+ require.NotContains(t, outHandle.String(), "Some error")
+ require.Contains(t, outHandle.String(), "Some critical error")
+
+ require.Equal(t, n.LogCountForLevel(LevelError), uint64(1))
+ require.Equal(t, n.LogCountForLevel(LevelDebug), uint64(1))
+ require.Equal(t, n.LogCountForLevel(LevelTrace), uint64(0))
+}
+
+func TestThresholdString(t *testing.T) {
+ require.Equal(t, LevelError.String(), "ERROR")
+ require.Equal(t, LevelTrace.String(), "TRACE")
+}
diff --git a/vendor/github.com/spf13/viper/.gitignore b/vendor/github.com/spf13/viper/.gitignore
new file mode 100644
index 000000000..352a34a56
--- /dev/null
+++ b/vendor/github.com/spf13/viper/.gitignore
@@ -0,0 +1,24 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.bench \ No newline at end of file
diff --git a/vendor/github.com/spf13/viper/.travis.yml b/vendor/github.com/spf13/viper/.travis.yml
new file mode 100644
index 000000000..d4c2559c2
--- /dev/null
+++ b/vendor/github.com/spf13/viper/.travis.yml
@@ -0,0 +1,26 @@
+go_import_path: github.com/spf13/viper
+
+language: go
+go:
+ - 1.7.5
+ - 1.8
+ - tip
+
+os:
+ - linux
+ - osx
+
+matrix:
+ allow_failures:
+ - go: tip
+ fast_finish: true
+
+script:
+ - go install ./...
+ - go test -v ./...
+
+after_success:
+ - go get -u -d github.com/spf13/hugo
+ - cd $GOPATH/src/github.com/spf13/hugo && make && ./hugo -s docs && cd -
+
+sudo: false
diff --git a/vendor/github.com/spf13/viper/LICENSE b/vendor/github.com/spf13/viper/LICENSE
new file mode 100644
index 000000000..4527efb9c
--- /dev/null
+++ b/vendor/github.com/spf13/viper/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Steve Francia
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE. \ No newline at end of file
diff --git a/vendor/github.com/spf13/viper/README.md b/vendor/github.com/spf13/viper/README.md
new file mode 100644
index 000000000..25181dff1
--- /dev/null
+++ b/vendor/github.com/spf13/viper/README.md
@@ -0,0 +1,621 @@
+![viper logo](https://cloud.githubusercontent.com/assets/173412/10886745/998df88a-8151-11e5-9448-4736db51020d.png)
+
+Go configuration with fangs!
+
+Many Go projects are built using Viper including:
+
+* [Hugo](http://gohugo.io)
+* [EMC RexRay](http://rexray.readthedocs.org/en/stable/)
+* [Imgur's Incus](https://github.com/Imgur/incus)
+* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
+* [Docker Notary](https://github.com/docker/Notary)
+* [BloomApi](https://www.bloomapi.com/)
+* [doctl](https://github.com/digitalocean/doctl)
+
+[![Build Status](https://travis-ci.org/spf13/viper.svg)](https://travis-ci.org/spf13/viper) [![Join the chat at https://gitter.im/spf13/viper](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/spf13/viper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![GoDoc](https://godoc.org/github.com/spf13/viper?status.svg)](https://godoc.org/github.com/spf13/viper)
+
+
+## What is Viper?
+
+Viper is a complete configuration solution for go applications including 12 factor apps. It is designed
+to work within an application, and can handle all types of configuration needs
+and formats. It supports:
+
+* setting defaults
+* reading from JSON, TOML, YAML, HCL, and Java properties config files
+* live watching and re-reading of config files (optional)
+* reading from environment variables
+* reading from remote config systems (etcd or Consul), and watching changes
+* reading from command line flags
+* reading from buffer
+* setting explicit values
+
+Viper can be thought of as a registry for all of your applications
+configuration needs.
+
+## Why Viper?
+
+When building a modern application, you don’t want to worry about
+configuration file formats; you want to focus on building awesome software.
+Viper is here to help with that.
+
+Viper does the following for you:
+
+1. Find, load, and unmarshal a configuration file in JSON, TOML, YAML, HCL, or Java properties formats.
+2. Provide a mechanism to set default values for your different
+ configuration options.
+3. Provide a mechanism to set override values for options specified through
+ command line flags.
+4. Provide an alias system to easily rename parameters without breaking existing
+ code.
+5. Make it easy to tell the difference between when a user has provided a
+ command line or config file which is the same as the default.
+
+Viper uses the following precedence order. Each item takes precedence over the
+item below it:
+
+ * explicit call to Set
+ * flag
+ * env
+ * config
+ * key/value store
+ * default
+
+Viper configuration keys are case insensitive.
+
+## Putting Values into Viper
+
+### Establishing Defaults
+
+A good configuration system will support default values. A default value is not
+required for a key, but it's useful in the event that a key hasn’t been set via
+config file, environment variable, remote configuration or flag.
+
+Examples:
+
+```go
+viper.SetDefault("ContentDir", "content")
+viper.SetDefault("LayoutDir", "layouts")
+viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})
+```
+
+### Reading Config Files
+
+Viper requires minimal configuration so it knows where to look for config files.
+Viper supports JSON, TOML, YAML, HCL, and Java Properties files. Viper can search multiple paths, but
+currently a single Viper instance only supports a single configuration file.
+Viper does not default to any configuration search paths leaving defaults decision
+to an application.
+
+Here is an example of how to use Viper to search for and read a configuration file.
+None of the specific paths are required, but at least one path should be provided
+where a configuration file is expected.
+
+```go
+viper.SetConfigName("config") // name of config file (without extension)
+viper.AddConfigPath("/etc/appname/") // path to look for the config file in
+viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths
+viper.AddConfigPath(".") // optionally look for config in the working directory
+err := viper.ReadInConfig() // Find and read the config file
+if err != nil { // Handle errors reading the config file
+ panic(fmt.Errorf("Fatal error config file: %s \n", err))
+}
+```
+
+### Watching and re-reading config files
+
+Viper supports the ability to have your application live read a config file while running.
+
+Gone are the days of needing to restart a server to have a config take effect,
+viper powered applications can read an update to a config file while running and
+not miss a beat.
+
+Simply tell the viper instance to watchConfig.
+Optionally you can provide a function for Viper to run each time a change occurs.
+
+**Make sure you add all of the configPaths prior to calling `WatchConfig()`**
+
+```go
+ viper.WatchConfig()
+ viper.OnConfigChange(func(e fsnotify.Event) {
+ fmt.Println("Config file changed:", e.Name)
+ })
+```
+
+### Reading Config from io.Reader
+
+Viper predefines many configuration sources such as files, environment
+variables, flags, and remote K/V store, but you are not bound to them. You can
+also implement your own required configuration source and feed it to viper.
+
+```go
+viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")
+
+// any approach to require this configuration into your program.
+var yamlExample = []byte(`
+Hacker: true
+name: steve
+hobbies:
+- skateboarding
+- snowboarding
+- go
+clothing:
+ jacket: leather
+ trousers: denim
+age: 35
+eyes : brown
+beard: true
+`)
+
+viper.ReadConfig(bytes.NewBuffer(yamlExample))
+
+viper.Get("name") // this would be "steve"
+```
+
+### Setting Overrides
+
+These could be from a command line flag, or from your own application logic.
+
+```go
+viper.Set("Verbose", true)
+viper.Set("LogFile", LogFile)
+```
+
+### Registering and Using Aliases
+
+Aliases permit a single value to be referenced by multiple keys
+
+```go
+viper.RegisterAlias("loud", "Verbose")
+
+viper.Set("verbose", true) // same result as next line
+viper.Set("loud", true) // same result as prior line
+
+viper.GetBool("loud") // true
+viper.GetBool("verbose") // true
+```
+
+### Working with Environment Variables
+
+Viper has full support for environment variables. This enables 12 factor
+applications out of the box. There are four methods that exist to aid working
+with ENV:
+
+ * `AutomaticEnv()`
+ * `BindEnv(string...) : error`
+ * `SetEnvPrefix(string)`
+ * `SetEnvReplacer(string...) *strings.Replacer`
+
+_When working with ENV variables, it’s important to recognize that Viper
+treats ENV variables as case sensitive._
+
+Viper provides a mechanism to try to ensure that ENV variables are unique. By
+using `SetEnvPrefix`, you can tell Viper to use add a prefix while reading from
+the environment variables. Both `BindEnv` and `AutomaticEnv` will use this
+prefix.
+
+`BindEnv` takes one or two parameters. The first parameter is the key name, the
+second is the name of the environment variable. The name of the environment
+variable is case sensitive. If the ENV variable name is not provided, then
+Viper will automatically assume that the key name matches the ENV variable name,
+but the ENV variable is IN ALL CAPS. When you explicitly provide the ENV
+variable name, it **does not** automatically add the prefix.
+
+One important thing to recognize when working with ENV variables is that the
+value will be read each time it is accessed. Viper does not fix the value when
+the `BindEnv` is called.
+
+`AutomaticEnv` is a powerful helper especially when combined with
+`SetEnvPrefix`. When called, Viper will check for an environment variable any
+time a `viper.Get` request is made. It will apply the following rules. It will
+check for a environment variable with a name matching the key uppercased and
+prefixed with the `EnvPrefix` if set.
+
+`SetEnvReplacer` allows you to use a `strings.Replacer` object to rewrite Env
+keys to an extent. This is useful if you want to use `-` or something in your
+`Get()` calls, but want your environmental variables to use `_` delimiters. An
+example of using it can be found in `viper_test.go`.
+
+#### Env example
+
+```go
+SetEnvPrefix("spf") // will be uppercased automatically
+BindEnv("id")
+
+os.Setenv("SPF_ID", "13") // typically done outside of the app
+
+id := Get("id") // 13
+```
+
+### Working with Flags
+
+Viper has the ability to bind to flags. Specifically, Viper supports `Pflags`
+as used in the [Cobra](https://github.com/spf13/cobra) library.
+
+Like `BindEnv`, the value is not set when the binding method is called, but when
+it is accessed. This means you can bind as early as you want, even in an
+`init()` function.
+
+The `BindPFlag()` method provides this functionality.
+
+Example:
+
+```go
+serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
+viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
+```
+
+The use of [pflag](https://github.com/spf13/pflag/) in Viper does not preclude
+the use of other packages that use the [flag](https://golang.org/pkg/flag/)
+package from the standard library. The pflag package can handle the flags
+defined for the flag package by importing these flags. This is accomplished
+by a calling a convenience function provided by the pflag package called
+AddGoFlagSet().
+
+Example:
+
+```go
+package main
+
+import (
+ "flag"
+ "github.com/spf13/pflag"
+)
+
+func main() {
+ pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
+ pflag.Parse()
+ ...
+}
+```
+
+#### Flag interfaces
+
+Viper provides two Go interfaces to bind other flag systems if you don't use `Pflags`.
+
+`FlagValue` represents a single flag. This is a very simple example on how to implement this interface:
+
+```go
+type myFlag struct {}
+func (f myFlag) HasChanged() bool { return false }
+func (f myFlag) Name() string { return "my-flag-name" }
+func (f myFlag) ValueString() string { return "my-flag-value" }
+func (f myFlag) ValueType() string { return "string" }
+```
+
+Once your flag implements this interface, you can simply tell Viper to bind it:
+
+```go
+viper.BindFlagValue("my-flag-name", myFlag{})
+```
+
+`FlagValueSet` represents a group of flags. This is a very simple example on how to implement this interface:
+
+```go
+type myFlagSet struct {
+ flags []myFlag
+}
+
+func (f myFlagSet) VisitAll(fn func(FlagValue)) {
+ for _, flag := range flags {
+ fn(flag)
+ }
+}
+```
+
+Once your flag set implements this interface, you can simply tell Viper to bind it:
+
+```go
+fSet := myFlagSet{
+ flags: []myFlag{myFlag{}, myFlag{}},
+}
+viper.BindFlagValues("my-flags", fSet)
+```
+
+### Remote Key/Value Store Support
+
+To enable remote support in Viper, do a blank import of the `viper/remote`
+package:
+
+`import _ "github.com/spf13/viper/remote"`
+
+Viper will read a config string (as JSON, TOML, YAML or HCL) retrieved from a path
+in a Key/Value store such as etcd or Consul. These values take precedence over
+default values, but are overridden by configuration values retrieved from disk,
+flags, or environment variables.
+
+Viper uses [crypt](https://github.com/xordataexchange/crypt) to retrieve
+configuration from the K/V store, which means that you can store your
+configuration values encrypted and have them automatically decrypted if you have
+the correct gpg keyring. Encryption is optional.
+
+You can use remote configuration in conjunction with local configuration, or
+independently of it.
+
+`crypt` has a command-line helper that you can use to put configurations in your
+K/V store. `crypt` defaults to etcd on http://127.0.0.1:4001.
+
+```bash
+$ go get github.com/xordataexchange/crypt/bin/crypt
+$ crypt set -plaintext /config/hugo.json /Users/hugo/settings/config.json
+```
+
+Confirm that your value was set:
+
+```bash
+$ crypt get -plaintext /config/hugo.json
+```
+
+See the `crypt` documentation for examples of how to set encrypted values, or
+how to use Consul.
+
+### Remote Key/Value Store Example - Unencrypted
+
+```go
+viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001","/config/hugo.json")
+viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop"
+err := viper.ReadRemoteConfig()
+```
+
+### Remote Key/Value Store Example - Encrypted
+
+```go
+viper.AddSecureRemoteProvider("etcd","http://127.0.0.1:4001","/config/hugo.json","/etc/secrets/mykeyring.gpg")
+viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop"
+err := viper.ReadRemoteConfig()
+```
+
+### Watching Changes in etcd - Unencrypted
+
+```go
+// alternatively, you can create a new viper instance.
+var runtime_viper = viper.New()
+
+runtime_viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001", "/config/hugo.yml")
+runtime_viper.SetConfigType("yaml") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop"
+
+// read from remote config the first time.
+err := runtime_viper.ReadRemoteConfig()
+
+// unmarshal config
+runtime_viper.Unmarshal(&runtime_conf)
+
+// open a goroutine to watch remote changes forever
+go func(){
+ for {
+ time.Sleep(time.Second * 5) // delay after each request
+
+ // currently, only tested with etcd support
+ err := runtime_viper.WatchRemoteConfig()
+ if err != nil {
+ log.Errorf("unable to read remote config: %v", err)
+ continue
+ }
+
+ // unmarshal new config into our runtime config struct. you can also use channel
+ // to implement a signal to notify the system of the changes
+ runtime_viper.Unmarshal(&runtime_conf)
+ }
+}()
+```
+
+## Getting Values From Viper
+
+In Viper, there are a few ways to get a value depending on the value's type.
+The following functions and methods exist:
+
+ * `Get(key string) : interface{}`
+ * `GetBool(key string) : bool`
+ * `GetFloat64(key string) : float64`
+ * `GetInt(key string) : int`
+ * `GetString(key string) : string`
+ * `GetStringMap(key string) : map[string]interface{}`
+ * `GetStringMapString(key string) : map[string]string`
+ * `GetStringSlice(key string) : []string`
+ * `GetTime(key string) : time.Time`
+ * `GetDuration(key string) : time.Duration`
+ * `IsSet(key string) : bool`
+
+One important thing to recognize is that each Get function will return a zero
+value if it’s not found. To check if a given key exists, the `IsSet()` method
+has been provided.
+
+Example:
+```go
+viper.GetString("logfile") // case-insensitive Setting & Getting
+if viper.GetBool("verbose") {
+ fmt.Println("verbose enabled")
+}
+```
+### Accessing nested keys
+
+The accessor methods also accept formatted paths to deeply nested keys. For
+example, if the following JSON file is loaded:
+
+```json
+{
+ "host": {
+ "address": "localhost",
+ "port": 5799
+ },
+ "datastore": {
+ "metric": {
+ "host": "127.0.0.1",
+ "port": 3099
+ },
+ "warehouse": {
+ "host": "198.0.0.1",
+ "port": 2112
+ }
+ }
+}
+
+```
+
+Viper can access a nested field by passing a `.` delimited path of keys:
+
+```go
+GetString("datastore.metric.host") // (returns "127.0.0.1")
+```
+
+This obeys the precedence rules established above; the search for the path
+will cascade through the remaining configuration registries until found.
+
+For example, given this configuration file, both `datastore.metric.host` and
+`datastore.metric.port` are already defined (and may be overridden). If in addition
+`datastore.metric.protocol` was defined in the defaults, Viper would also find it.
+
+However, if `datastore.metric` was overridden (by a flag, an environment variable,
+the `Set()` method, …) with an immediate value, then all sub-keys of
+`datastore.metric` become undefined, they are “shadowed” by the higher-priority
+configuration level.
+
+Lastly, if there exists a key that matches the delimited key path, its value
+will be returned instead. E.g.
+
+```json
+{
+ "datastore.metric.host": "0.0.0.0",
+ "host": {
+ "address": "localhost",
+ "port": 5799
+ },
+ "datastore": {
+ "metric": {
+ "host": "127.0.0.1",
+ "port": 3099
+ },
+ "warehouse": {
+ "host": "198.0.0.1",
+ "port": 2112
+ }
+ }
+}
+
+GetString("datastore.metric.host") // returns "0.0.0.0"
+```
+
+### Extract sub-tree
+
+Extract sub-tree from Viper.
+
+For example, `viper` represents:
+
+```json
+app:
+ cache1:
+ max-items: 100
+ item-size: 64
+ cache2:
+ max-items: 200
+ item-size: 80
+```
+
+After executing:
+
+```go
+subv := viper.Sub("app.cache1")
+```
+
+`subv` represents:
+
+```json
+max-items: 100
+item-size: 64
+```
+
+Suppose we have:
+
+```go
+func NewCache(cfg *Viper) *Cache {...}
+```
+
+which creates a cache based on config information formatted as `subv`.
+Now it's easy to create these 2 caches separately as:
+
+```go
+cfg1 := viper.Sub("app.cache1")
+cache1 := NewCache(cfg1)
+
+cfg2 := viper.Sub("app.cache2")
+cache2 := NewCache(cfg2)
+```
+
+### Unmarshaling
+
+You also have the option of Unmarshaling all or a specific value to a struct, map,
+etc.
+
+There are two methods to do this:
+
+ * `Unmarshal(rawVal interface{}) : error`
+ * `UnmarshalKey(key string, rawVal interface{}) : error`
+
+Example:
+
+```go
+type config struct {
+ Port int
+ Name string
+ PathMap string `mapstructure:"path_map"`
+}
+
+var C config
+
+err := Unmarshal(&C)
+if err != nil {
+ t.Fatalf("unable to decode into struct, %v", err)
+}
+```
+
+## Viper or Vipers?
+
+Viper comes ready to use out of the box. There is no configuration or
+initialization needed to begin using Viper. Since most applications will want
+to use a single central repository for their configuration, the viper package
+provides this. It is similar to a singleton.
+
+In all of the examples above, they demonstrate using viper in it's singleton
+style approach.
+
+### Working with multiple vipers
+
+You can also create many different vipers for use in your application. Each will
+have it’s own unique set of configurations and values. Each can read from a
+different config file, key value store, etc. All of the functions that viper
+package supports are mirrored as methods on a viper.
+
+Example:
+
+```go
+x := viper.New()
+y := viper.New()
+
+x.SetDefault("ContentDir", "content")
+y.SetDefault("ContentDir", "foobar")
+
+//...
+```
+
+When working with multiple vipers, it is up to the user to keep track of the
+different vipers.
+
+## Q & A
+
+Q: Why not INI files?
+
+A: Ini files are pretty awful. There’s no standard format, and they are hard to
+validate. Viper is designed to work with JSON, TOML or YAML files. If someone
+really wants to add this feature, I’d be happy to merge it. It’s easy to specify
+which formats your application will permit.
+
+Q: Why is it called “Viper”?
+
+A: Viper is designed to be a [companion](http://en.wikipedia.org/wiki/Viper_(G.I._Joe))
+to [Cobra](https://github.com/spf13/cobra). While both can operate completely
+independently, together they make a powerful pair to handle much of your
+application foundation needs.
+
+Q: Why is it called “Cobra”?
+
+A: Is there a better name for a [commander](http://en.wikipedia.org/wiki/Cobra_Commander)?
diff --git a/vendor/github.com/spf13/viper/flags.go b/vendor/github.com/spf13/viper/flags.go
new file mode 100644
index 000000000..dd32f4e1c
--- /dev/null
+++ b/vendor/github.com/spf13/viper/flags.go
@@ -0,0 +1,57 @@
+package viper
+
+import "github.com/spf13/pflag"
+
+// FlagValueSet is an interface that users can implement
+// to bind a set of flags to viper.
+type FlagValueSet interface {
+ VisitAll(fn func(FlagValue))
+}
+
+// FlagValue is an interface that users can implement
+// to bind different flags to viper.
+type FlagValue interface {
+ HasChanged() bool
+ Name() string
+ ValueString() string
+ ValueType() string
+}
+
+// pflagValueSet is a wrapper around *pflag.ValueSet
+// that implements FlagValueSet.
+type pflagValueSet struct {
+ flags *pflag.FlagSet
+}
+
+// VisitAll iterates over all *pflag.Flag inside the *pflag.FlagSet.
+func (p pflagValueSet) VisitAll(fn func(flag FlagValue)) {
+ p.flags.VisitAll(func(flag *pflag.Flag) {
+ fn(pflagValue{flag})
+ })
+}
+
+// pflagValue is a wrapper aroung *pflag.flag
+// that implements FlagValue
+type pflagValue struct {
+ flag *pflag.Flag
+}
+
+// HasChanges returns whether the flag has changes or not.
+func (p pflagValue) HasChanged() bool {
+ return p.flag.Changed
+}
+
+// Name returns the name of the flag.
+func (p pflagValue) Name() string {
+ return p.flag.Name
+}
+
+// ValueString returns the value of the flag as a string.
+func (p pflagValue) ValueString() string {
+ return p.flag.Value.String()
+}
+
+// ValueType returns the type of the flag as a string.
+func (p pflagValue) ValueType() string {
+ return p.flag.Value.Type()
+}
diff --git a/vendor/github.com/spf13/viper/flags_test.go b/vendor/github.com/spf13/viper/flags_test.go
new file mode 100644
index 000000000..5bffca36c
--- /dev/null
+++ b/vendor/github.com/spf13/viper/flags_test.go
@@ -0,0 +1,66 @@
+package viper
+
+import (
+ "testing"
+
+ "github.com/spf13/pflag"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestBindFlagValueSet(t *testing.T) {
+ flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
+
+ var testValues = map[string]*string{
+ "host": nil,
+ "port": nil,
+ "endpoint": nil,
+ }
+
+ var mutatedTestValues = map[string]string{
+ "host": "localhost",
+ "port": "6060",
+ "endpoint": "/public",
+ }
+
+ for name := range testValues {
+ testValues[name] = flagSet.String(name, "", "test")
+ }
+
+ flagValueSet := pflagValueSet{flagSet}
+
+ err := BindFlagValues(flagValueSet)
+ if err != nil {
+ t.Fatalf("error binding flag set, %v", err)
+ }
+
+ flagSet.VisitAll(func(flag *pflag.Flag) {
+ flag.Value.Set(mutatedTestValues[flag.Name])
+ flag.Changed = true
+ })
+
+ for name, expected := range mutatedTestValues {
+ assert.Equal(t, Get(name), expected)
+ }
+}
+
+func TestBindFlagValue(t *testing.T) {
+ var testString = "testing"
+ var testValue = newStringValue(testString, &testString)
+
+ flag := &pflag.Flag{
+ Name: "testflag",
+ Value: testValue,
+ Changed: false,
+ }
+
+ flagValue := pflagValue{flag}
+ BindFlagValue("testvalue", flagValue)
+
+ assert.Equal(t, testString, Get("testvalue"))
+
+ flag.Value.Set("testing_mutate")
+ flag.Changed = true //hack for pflag usage
+
+ assert.Equal(t, "testing_mutate", Get("testvalue"))
+
+}
diff --git a/vendor/github.com/spf13/viper/nohup.out b/vendor/github.com/spf13/viper/nohup.out
new file mode 100644
index 000000000..8973bf27b
--- /dev/null
+++ b/vendor/github.com/spf13/viper/nohup.out
@@ -0,0 +1 @@
+QProcess::start: Process is already running
diff --git a/vendor/github.com/spf13/viper/overrides_test.go b/vendor/github.com/spf13/viper/overrides_test.go
new file mode 100644
index 000000000..dd2aa9b0d
--- /dev/null
+++ b/vendor/github.com/spf13/viper/overrides_test.go
@@ -0,0 +1,173 @@
+package viper
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cast"
+ "github.com/stretchr/testify/assert"
+)
+
+type layer int
+
+const (
+ defaultLayer layer = iota + 1
+ overrideLayer
+)
+
+func TestNestedOverrides(t *testing.T) {
+ assert := assert.New(t)
+ var v *Viper
+
+ // Case 0: value overridden by a value
+ overrideDefault(assert, "tom", 10, "tom", 20) // "tom" is first given 10 as default value, then overridden by 20
+ override(assert, "tom", 10, "tom", 20) // "tom" is first given value 10, then overridden by 20
+ overrideDefault(assert, "tom.age", 10, "tom.age", 20)
+ override(assert, "tom.age", 10, "tom.age", 20)
+ overrideDefault(assert, "sawyer.tom.age", 10, "sawyer.tom.age", 20)
+ override(assert, "sawyer.tom.age", 10, "sawyer.tom.age", 20)
+
+ // Case 1: key:value overridden by a value
+ v = overrideDefault(assert, "tom.age", 10, "tom", "boy") // "tom.age" is first given 10 as default value, then "tom" is overridden by "boy"
+ assert.Nil(v.Get("tom.age")) // "tom.age" should not exist anymore
+ v = override(assert, "tom.age", 10, "tom", "boy")
+ assert.Nil(v.Get("tom.age"))
+
+ // Case 2: value overridden by a key:value
+ overrideDefault(assert, "tom", "boy", "tom.age", 10) // "tom" is first given "boy" as default value, then "tom" is overridden by map{"age":10}
+ override(assert, "tom.age", 10, "tom", "boy")
+
+ // Case 3: key:value overridden by a key:value
+ v = overrideDefault(assert, "tom.size", 4, "tom.age", 10)
+ assert.Equal(4, v.Get("tom.size")) // value should still be reachable
+ v = override(assert, "tom.size", 4, "tom.age", 10)
+ assert.Equal(4, v.Get("tom.size"))
+ deepCheckValue(assert, v, overrideLayer, []string{"tom", "size"}, 4)
+
+ // Case 4: key:value overridden by a map
+ v = overrideDefault(assert, "tom.size", 4, "tom", map[string]interface{}{"age": 10}) // "tom.size" is first given "4" as default value, then "tom" is overridden by map{"age":10}
+ assert.Equal(4, v.Get("tom.size")) // "tom.size" should still be reachable
+ assert.Equal(10, v.Get("tom.age")) // new value should be there
+ deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10) // new value should be there
+ v = override(assert, "tom.size", 4, "tom", map[string]interface{}{"age": 10})
+ assert.Nil(v.Get("tom.size"))
+ assert.Equal(10, v.Get("tom.age"))
+ deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10)
+
+ // Case 5: array overridden by a value
+ overrideDefault(assert, "tom", []int{10, 20}, "tom", 30)
+ override(assert, "tom", []int{10, 20}, "tom", 30)
+ overrideDefault(assert, "tom.age", []int{10, 20}, "tom.age", 30)
+ override(assert, "tom.age", []int{10, 20}, "tom.age", 30)
+
+ // Case 6: array overridden by an array
+ overrideDefault(assert, "tom", []int{10, 20}, "tom", []int{30, 40})
+ override(assert, "tom", []int{10, 20}, "tom", []int{30, 40})
+ overrideDefault(assert, "tom.age", []int{10, 20}, "tom.age", []int{30, 40})
+ v = override(assert, "tom.age", []int{10, 20}, "tom.age", []int{30, 40})
+ // explicit array merge:
+ s, ok := v.Get("tom.age").([]int)
+ if assert.True(ok, "tom[\"age\"] is not a slice") {
+ v.Set("tom.age", append(s, []int{50, 60}...))
+ assert.Equal([]int{30, 40, 50, 60}, v.Get("tom.age"))
+ deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, []int{30, 40, 50, 60})
+ }
+}
+
+func overrideDefault(assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
+ return overrideFromLayer(defaultLayer, assert, firstPath, firstValue, secondPath, secondValue)
+}
+func override(assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
+ return overrideFromLayer(overrideLayer, assert, firstPath, firstValue, secondPath, secondValue)
+}
+
+// overrideFromLayer performs the sequential override and low-level checks.
+//
+// First assignment is made on layer l for path firstPath with value firstValue,
+// the second one on the override layer (i.e., with the Set() function)
+// for path secondPath with value secondValue.
+//
+// firstPath and secondPath can include an arbitrary number of dots to indicate
+// a nested element.
+//
+// After each assignment, the value is checked, retrieved both by its full path
+// and by its key sequence (successive maps).
+func overrideFromLayer(l layer, assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
+ v := New()
+ firstKeys := strings.Split(firstPath, v.keyDelim)
+ if assert == nil ||
+ len(firstKeys) == 0 || len(firstKeys[0]) == 0 {
+ return v
+ }
+
+ // Set and check first value
+ switch l {
+ case defaultLayer:
+ v.SetDefault(firstPath, firstValue)
+ case overrideLayer:
+ v.Set(firstPath, firstValue)
+ default:
+ return v
+ }
+ assert.Equal(firstValue, v.Get(firstPath))
+ deepCheckValue(assert, v, l, firstKeys, firstValue)
+
+ // Override and check new value
+ secondKeys := strings.Split(secondPath, v.keyDelim)
+ if len(secondKeys) == 0 || len(secondKeys[0]) == 0 {
+ return v
+ }
+ v.Set(secondPath, secondValue)
+ assert.Equal(secondValue, v.Get(secondPath))
+ deepCheckValue(assert, v, overrideLayer, secondKeys, secondValue)
+
+ return v
+}
+
+// deepCheckValue checks that all given keys correspond to a valid path in the
+// configuration map of the given layer, and that the final value equals the one given
+func deepCheckValue(assert *assert.Assertions, v *Viper, l layer, keys []string, value interface{}) {
+ if assert == nil || v == nil ||
+ len(keys) == 0 || len(keys[0]) == 0 {
+ return
+ }
+
+ // init
+ var val interface{}
+ var ms string
+ switch l {
+ case defaultLayer:
+ val = v.defaults
+ ms = "v.defaults"
+ case overrideLayer:
+ val = v.override
+ ms = "v.override"
+ }
+
+ // loop through map
+ var m map[string]interface{}
+ err := false
+ for _, k := range keys {
+ if val == nil {
+ assert.Fail(fmt.Sprintf("%s is not a map[string]interface{}", ms))
+ return
+ }
+
+ // deep scan of the map to get the final value
+ switch val.(type) {
+ case map[interface{}]interface{}:
+ m = cast.ToStringMap(val)
+ case map[string]interface{}:
+ m = val.(map[string]interface{})
+ default:
+ assert.Fail(fmt.Sprintf("%s is not a map[string]interface{}", ms))
+ return
+ }
+ ms = ms + "[\"" + k + "\"]"
+ val = m[k]
+ }
+ if !err {
+ assert.Equal(value, val)
+ }
+}
diff --git a/vendor/github.com/spf13/viper/remote/remote.go b/vendor/github.com/spf13/viper/remote/remote.go
new file mode 100644
index 000000000..f100a9c7f
--- /dev/null
+++ b/vendor/github.com/spf13/viper/remote/remote.go
@@ -0,0 +1,107 @@
+// Copyright © 2015 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+// Package remote integrates the remote features of Viper.
+package remote
+
+import (
+ "bytes"
+ "github.com/spf13/viper"
+ crypt "github.com/xordataexchange/crypt/config"
+ "io"
+ "os"
+)
+
+type remoteConfigProvider struct{}
+
+func (rc remoteConfigProvider) Get(rp viper.RemoteProvider) (io.Reader, error) {
+ cm, err := getConfigManager(rp)
+ if err != nil {
+ return nil, err
+ }
+ b, err := cm.Get(rp.Path())
+ if err != nil {
+ return nil, err
+ }
+ return bytes.NewReader(b), nil
+}
+
+func (rc remoteConfigProvider) Watch(rp viper.RemoteProvider) (io.Reader, error) {
+ cm, err := getConfigManager(rp)
+ if err != nil {
+ return nil, err
+ }
+ resp,err := cm.Get(rp.Path())
+ if err != nil {
+ return nil, err
+ }
+
+ return bytes.NewReader(resp), nil
+}
+func (rc remoteConfigProvider) WatchChannel(rp viper.RemoteProvider) (<-chan *viper.RemoteResponse, chan bool) {
+ cm, err := getConfigManager(rp)
+ if err != nil {
+ return nil, nil
+ }
+ quit := make(chan bool)
+ quitwc := make(chan bool)
+ viperResponsCh := make(chan *viper.RemoteResponse)
+ cryptoResponseCh := cm.Watch(rp.Path(), quit)
+ // need this function to convert the Channel response form crypt.Response to viper.Response
+ go func(cr <-chan *crypt.Response,vr chan<- *viper.RemoteResponse, quitwc <-chan bool, quit chan<- bool) {
+ for {
+ select {
+ case <- quitwc:
+ quit <- true
+ return
+ case resp := <-cr:
+ vr <- &viper.RemoteResponse{
+ Error: resp.Error,
+ Value: resp.Value,
+ }
+
+ }
+
+ }
+ }(cryptoResponseCh,viperResponsCh,quitwc,quit)
+
+ return viperResponsCh,quitwc
+
+}
+
+
+func getConfigManager(rp viper.RemoteProvider) (crypt.ConfigManager, error) {
+
+ var cm crypt.ConfigManager
+ var err error
+
+ if rp.SecretKeyring() != "" {
+ kr, err := os.Open(rp.SecretKeyring())
+ defer kr.Close()
+ if err != nil {
+ return nil, err
+ }
+ if rp.Provider() == "etcd" {
+ cm, err = crypt.NewEtcdConfigManager([]string{rp.Endpoint()}, kr)
+ } else {
+ cm, err = crypt.NewConsulConfigManager([]string{rp.Endpoint()}, kr)
+ }
+ } else {
+ if rp.Provider() == "etcd" {
+ cm, err = crypt.NewStandardEtcdConfigManager([]string{rp.Endpoint()})
+ } else {
+ cm, err = crypt.NewStandardConsulConfigManager([]string{rp.Endpoint()})
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ return cm, nil
+
+}
+
+func init() {
+ viper.RemoteConfig = &remoteConfigProvider{}
+}
diff --git a/vendor/github.com/spf13/viper/util.go b/vendor/github.com/spf13/viper/util.go
new file mode 100644
index 000000000..3ebada91a
--- /dev/null
+++ b/vendor/github.com/spf13/viper/util.go
@@ -0,0 +1,282 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+// Viper is a application configuration system.
+// It believes that applications can be configured a variety of ways
+// via flags, ENVIRONMENT variables, configuration files retrieved
+// from the file system, or a remote key/value store.
+
+package viper
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "unicode"
+
+ "github.com/hashicorp/hcl"
+ "github.com/magiconair/properties"
+ toml "github.com/pelletier/go-toml"
+ "github.com/spf13/cast"
+ jww "github.com/spf13/jwalterweatherman"
+ "gopkg.in/yaml.v2"
+)
+
+// ConfigParseError denotes failing to parse configuration file.
+type ConfigParseError struct {
+ err error
+}
+
+// Error returns the formatted configuration error.
+func (pe ConfigParseError) Error() string {
+ return fmt.Sprintf("While parsing config: %s", pe.err.Error())
+}
+
+// toCaseInsensitiveValue checks if the value is a map;
+// if so, create a copy and lower-case the keys recursively.
+func toCaseInsensitiveValue(value interface{}) interface{} {
+ switch v := value.(type) {
+ case map[interface{}]interface{}:
+ value = copyAndInsensitiviseMap(cast.ToStringMap(v))
+ case map[string]interface{}:
+ value = copyAndInsensitiviseMap(v)
+ }
+
+ return value
+}
+
+// copyAndInsensitiviseMap behaves like insensitiviseMap, but creates a copy of
+// any map it makes case insensitive.
+func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} {
+ nm := make(map[string]interface{})
+
+ for key, val := range m {
+ lkey := strings.ToLower(key)
+ switch v := val.(type) {
+ case map[interface{}]interface{}:
+ nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v))
+ case map[string]interface{}:
+ nm[lkey] = copyAndInsensitiviseMap(v)
+ default:
+ nm[lkey] = v
+ }
+ }
+
+ return nm
+}
+
+func insensitiviseMap(m map[string]interface{}) {
+ for key, val := range m {
+ switch val.(type) {
+ case map[interface{}]interface{}:
+ // nested map: cast and recursively insensitivise
+ val = cast.ToStringMap(val)
+ insensitiviseMap(val.(map[string]interface{}))
+ case map[string]interface{}:
+ // nested map: recursively insensitivise
+ insensitiviseMap(val.(map[string]interface{}))
+ }
+
+ lower := strings.ToLower(key)
+ if key != lower {
+ // remove old key (not lower-cased)
+ delete(m, key)
+ }
+ // update map
+ m[lower] = val
+ }
+}
+
+func absPathify(inPath string) string {
+ jww.INFO.Println("Trying to resolve absolute path to", inPath)
+
+ if strings.HasPrefix(inPath, "$HOME") {
+ inPath = userHomeDir() + inPath[5:]
+ }
+
+ if strings.HasPrefix(inPath, "$") {
+ end := strings.Index(inPath, string(os.PathSeparator))
+ inPath = os.Getenv(inPath[1:end]) + inPath[end:]
+ }
+
+ if filepath.IsAbs(inPath) {
+ return filepath.Clean(inPath)
+ }
+
+ p, err := filepath.Abs(inPath)
+ if err == nil {
+ return filepath.Clean(p)
+ }
+
+ jww.ERROR.Println("Couldn't discover absolute path")
+ jww.ERROR.Println(err)
+ return ""
+}
+
+// Check if File / Directory Exists
+func exists(path string) (bool, error) {
+ _, err := v.fs.Stat(path)
+ if err == nil {
+ return true, nil
+ }
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, err
+}
+
+func stringInSlice(a string, list []string) bool {
+ for _, b := range list {
+ if b == a {
+ return true
+ }
+ }
+ return false
+}
+
+func userHomeDir() string {
+ if runtime.GOOS == "windows" {
+ home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
+ if home == "" {
+ home = os.Getenv("USERPROFILE")
+ }
+ return home
+ }
+ return os.Getenv("HOME")
+}
+
+func unmarshallConfigReader(in io.Reader, c map[string]interface{}, configType string) error {
+ buf := new(bytes.Buffer)
+ buf.ReadFrom(in)
+
+ switch strings.ToLower(configType) {
+ case "yaml", "yml":
+ if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil {
+ return ConfigParseError{err}
+ }
+
+ case "json":
+ if err := json.Unmarshal(buf.Bytes(), &c); err != nil {
+ return ConfigParseError{err}
+ }
+
+ case "hcl":
+ obj, err := hcl.Parse(string(buf.Bytes()))
+ if err != nil {
+ return ConfigParseError{err}
+ }
+ if err = hcl.DecodeObject(&c, obj); err != nil {
+ return ConfigParseError{err}
+ }
+
+ case "toml":
+ tree, err := toml.LoadReader(buf)
+ if err != nil {
+ return ConfigParseError{err}
+ }
+ tmap := tree.ToMap()
+ for k, v := range tmap {
+ c[k] = v
+ }
+
+ case "properties", "props", "prop":
+ var p *properties.Properties
+ var err error
+ if p, err = properties.Load(buf.Bytes(), properties.UTF8); err != nil {
+ return ConfigParseError{err}
+ }
+ for _, key := range p.Keys() {
+ value, _ := p.Get(key)
+ // recursively build nested maps
+ path := strings.Split(key, ".")
+ lastKey := strings.ToLower(path[len(path)-1])
+ deepestMap := deepSearch(c, path[0:len(path)-1])
+ // set innermost value
+ deepestMap[lastKey] = value
+ }
+ }
+
+ insensitiviseMap(c)
+ return nil
+}
+
+func safeMul(a, b uint) uint {
+ c := a * b
+ if a > 1 && b > 1 && c/b != a {
+ return 0
+ }
+ return c
+}
+
+// parseSizeInBytes converts strings like 1GB or 12 mb into an unsigned integer number of bytes
+func parseSizeInBytes(sizeStr string) uint {
+ sizeStr = strings.TrimSpace(sizeStr)
+ lastChar := len(sizeStr) - 1
+ multiplier := uint(1)
+
+ if lastChar > 0 {
+ if sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B' {
+ if lastChar > 1 {
+ switch unicode.ToLower(rune(sizeStr[lastChar-1])) {
+ case 'k':
+ multiplier = 1 << 10
+ sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
+ case 'm':
+ multiplier = 1 << 20
+ sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
+ case 'g':
+ multiplier = 1 << 30
+ sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
+ default:
+ multiplier = 1
+ sizeStr = strings.TrimSpace(sizeStr[:lastChar])
+ }
+ }
+ }
+ }
+
+ size := cast.ToInt(sizeStr)
+ if size < 0 {
+ size = 0
+ }
+
+ return safeMul(uint(size), multiplier)
+}
+
+// deepSearch scans deep maps, following the key indexes listed in the
+// sequence "path".
+// The last value is expected to be another map, and is returned.
+//
+// In case intermediate keys do not exist, or map to a non-map value,
+// a new map is created and inserted, and the search continues from there:
+// the initial map "m" may be modified!
+func deepSearch(m map[string]interface{}, path []string) map[string]interface{} {
+ for _, k := range path {
+ m2, ok := m[k]
+ if !ok {
+ // intermediate key does not exist
+ // => create it and continue from there
+ m3 := make(map[string]interface{})
+ m[k] = m3
+ m = m3
+ continue
+ }
+ m3, ok := m2.(map[string]interface{})
+ if !ok {
+ // intermediate key is a value
+ // => replace with a new map
+ m3 = make(map[string]interface{})
+ m[k] = m3
+ }
+ // continue search from here
+ m = m3
+ }
+ return m
+}
diff --git a/vendor/github.com/spf13/viper/util_test.go b/vendor/github.com/spf13/viper/util_test.go
new file mode 100644
index 000000000..5949e09e4
--- /dev/null
+++ b/vendor/github.com/spf13/viper/util_test.go
@@ -0,0 +1,55 @@
+// Copyright © 2016 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+// Viper is a application configuration system.
+// It believes that applications can be configured a variety of ways
+// via flags, ENVIRONMENT variables, configuration files retrieved
+// from the file system, or a remote key/value store.
+
+package viper
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestCopyAndInsensitiviseMap(t *testing.T) {
+
+ var (
+ given = map[string]interface{}{
+ "Foo": 32,
+ "Bar": map[interface{}]interface {
+ }{
+ "ABc": "A",
+ "cDE": "B"},
+ }
+ expected = map[string]interface{}{
+ "foo": 32,
+ "bar": map[string]interface {
+ }{
+ "abc": "A",
+ "cde": "B"},
+ }
+ )
+
+ got := copyAndInsensitiviseMap(given)
+
+ if !reflect.DeepEqual(got, expected) {
+ t.Fatalf("Got %q\nexpected\n%q", got, expected)
+ }
+
+ if _, ok := given["foo"]; ok {
+ t.Fatal("Input map changed")
+ }
+
+ if _, ok := given["bar"]; ok {
+ t.Fatal("Input map changed")
+ }
+
+ m := given["Bar"].(map[interface{}]interface{})
+ if _, ok := m["ABc"]; !ok {
+ t.Fatal("Input map changed")
+ }
+}
diff --git a/vendor/github.com/spf13/viper/viper.go b/vendor/github.com/spf13/viper/viper.go
new file mode 100644
index 000000000..22a2ed8ad
--- /dev/null
+++ b/vendor/github.com/spf13/viper/viper.go
@@ -0,0 +1,1550 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+// Viper is a application configuration system.
+// It believes that applications can be configured a variety of ways
+// via flags, ENVIRONMENT variables, configuration files retrieved
+// from the file system, or a remote key/value store.
+
+// Each item takes precedence over the item below it:
+
+// overrides
+// flag
+// env
+// config
+// key/value store
+// default
+
+package viper
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "time"
+
+ "github.com/fsnotify/fsnotify"
+ "github.com/mitchellh/mapstructure"
+ "github.com/spf13/afero"
+ "github.com/spf13/cast"
+ jww "github.com/spf13/jwalterweatherman"
+ "github.com/spf13/pflag"
+)
+
+var v *Viper
+
+type RemoteResponse struct {
+ Value []byte
+ Error error
+}
+
+func init() {
+ v = New()
+}
+
+type remoteConfigFactory interface {
+ Get(rp RemoteProvider) (io.Reader, error)
+ Watch(rp RemoteProvider) (io.Reader, error)
+ WatchChannel(rp RemoteProvider)(<-chan *RemoteResponse, chan bool)
+}
+
+// RemoteConfig is optional, see the remote package
+var RemoteConfig remoteConfigFactory
+
+// UnsupportedConfigError denotes encountering an unsupported
+// configuration filetype.
+type UnsupportedConfigError string
+
+// Error returns the formatted configuration error.
+func (str UnsupportedConfigError) Error() string {
+ return fmt.Sprintf("Unsupported Config Type %q", string(str))
+}
+
+// UnsupportedRemoteProviderError denotes encountering an unsupported remote
+// provider. Currently only etcd and Consul are
+// supported.
+type UnsupportedRemoteProviderError string
+
+// Error returns the formatted remote provider error.
+func (str UnsupportedRemoteProviderError) Error() string {
+ return fmt.Sprintf("Unsupported Remote Provider Type %q", string(str))
+}
+
+// RemoteConfigError denotes encountering an error while trying to
+// pull the configuration from the remote provider.
+type RemoteConfigError string
+
+// Error returns the formatted remote provider error
+func (rce RemoteConfigError) Error() string {
+ return fmt.Sprintf("Remote Configurations Error: %s", string(rce))
+}
+
+// ConfigFileNotFoundError denotes failing to find configuration file.
+type ConfigFileNotFoundError struct {
+ name, locations string
+}
+
+// Error returns the formatted configuration error.
+func (fnfe ConfigFileNotFoundError) Error() string {
+ return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations)
+}
+
+// Viper is a prioritized configuration registry. It
+// maintains a set of configuration sources, fetches
+// values to populate those, and provides them according
+// to the source's priority.
+// The priority of the sources is the following:
+// 1. overrides
+// 2. flags
+// 3. env. variables
+// 4. config file
+// 5. key/value store
+// 6. defaults
+//
+// For example, if values from the following sources were loaded:
+//
+// Defaults : {
+// "secret": "",
+// "user": "default",
+// "endpoint": "https://localhost"
+// }
+// Config : {
+// "user": "root"
+// "secret": "defaultsecret"
+// }
+// Env : {
+// "secret": "somesecretkey"
+// }
+//
+// The resulting config will have the following values:
+//
+// {
+// "secret": "somesecretkey",
+// "user": "root",
+// "endpoint": "https://localhost"
+// }
+type Viper struct {
+ // Delimiter that separates a list of keys
+ // used to access a nested value in one go
+ keyDelim string
+
+ // A set of paths to look for the config file in
+ configPaths []string
+
+ // The filesystem to read config from.
+ fs afero.Fs
+
+ // A set of remote providers to search for the configuration
+ remoteProviders []*defaultRemoteProvider
+
+ // Name of file to look for inside the path
+ configName string
+ configFile string
+ configType string
+ envPrefix string
+
+ automaticEnvApplied bool
+ envKeyReplacer *strings.Replacer
+
+ config map[string]interface{}
+ override map[string]interface{}
+ defaults map[string]interface{}
+ kvstore map[string]interface{}
+ pflags map[string]FlagValue
+ env map[string]string
+ aliases map[string]string
+ typeByDefValue bool
+
+ onConfigChange func(fsnotify.Event)
+}
+
+// New returns an initialized Viper instance.
+func New() *Viper {
+ v := new(Viper)
+ v.keyDelim = "."
+ v.configName = "config"
+ v.fs = afero.NewOsFs()
+ v.config = make(map[string]interface{})
+ v.override = make(map[string]interface{})
+ v.defaults = make(map[string]interface{})
+ v.kvstore = make(map[string]interface{})
+ v.pflags = make(map[string]FlagValue)
+ v.env = make(map[string]string)
+ v.aliases = make(map[string]string)
+ v.typeByDefValue = false
+
+ return v
+}
+
+// Intended for testing, will reset all to default settings.
+// In the public interface for the viper package so applications
+// can use it in their testing as well.
+func Reset() {
+ v = New()
+ SupportedExts = []string{"json", "toml", "yaml", "yml", "hcl"}
+ SupportedRemoteProviders = []string{"etcd", "consul"}
+}
+
+type defaultRemoteProvider struct {
+ provider string
+ endpoint string
+ path string
+ secretKeyring string
+}
+
+func (rp defaultRemoteProvider) Provider() string {
+ return rp.provider
+}
+
+func (rp defaultRemoteProvider) Endpoint() string {
+ return rp.endpoint
+}
+
+func (rp defaultRemoteProvider) Path() string {
+ return rp.path
+}
+
+func (rp defaultRemoteProvider) SecretKeyring() string {
+ return rp.secretKeyring
+}
+
+// RemoteProvider stores the configuration necessary
+// to connect to a remote key/value store.
+// Optional secretKeyring to unencrypt encrypted values
+// can be provided.
+type RemoteProvider interface {
+ Provider() string
+ Endpoint() string
+ Path() string
+ SecretKeyring() string
+}
+
+// SupportedExts are universally supported extensions.
+var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl"}
+
+// SupportedRemoteProviders are universally supported remote providers.
+var SupportedRemoteProviders = []string{"etcd", "consul"}
+
+func OnConfigChange(run func(in fsnotify.Event)) { v.OnConfigChange(run) }
+func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
+ v.onConfigChange = run
+}
+
+func WatchConfig() { v.WatchConfig() }
+func (v *Viper) WatchConfig() {
+ go func() {
+ watcher, err := fsnotify.NewWatcher()
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer watcher.Close()
+
+ // we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
+ filename, err := v.getConfigFile()
+ if err != nil {
+ log.Println("error:", err)
+ return
+ }
+
+ configFile := filepath.Clean(filename)
+ configDir, _ := filepath.Split(configFile)
+
+ done := make(chan bool)
+ go func() {
+ for {
+ select {
+ case event := <-watcher.Events:
+ // we only care about the config file
+ if filepath.Clean(event.Name) == configFile {
+ if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create {
+ err := v.ReadInConfig()
+ if err != nil {
+ log.Println("error:", err)
+ }
+ v.onConfigChange(event)
+ }
+ }
+ case err := <-watcher.Errors:
+ log.Println("error:", err)
+ }
+ }
+ }()
+
+ watcher.Add(configDir)
+ <-done
+ }()
+}
+
+// SetConfigFile explicitly defines the path, name and extension of the config file
+// Viper will use this and not check any of the config paths
+func SetConfigFile(in string) { v.SetConfigFile(in) }
+func (v *Viper) SetConfigFile(in string) {
+ if in != "" {
+ v.configFile = in
+ }
+}
+
+// SetEnvPrefix defines a prefix that ENVIRONMENT variables will use.
+// E.g. if your prefix is "spf", the env registry
+// will look for env. variables that start with "SPF_"
+func SetEnvPrefix(in string) { v.SetEnvPrefix(in) }
+func (v *Viper) SetEnvPrefix(in string) {
+ if in != "" {
+ v.envPrefix = in
+ }
+}
+
+func (v *Viper) mergeWithEnvPrefix(in string) string {
+ if v.envPrefix != "" {
+ return strings.ToUpper(v.envPrefix + "_" + in)
+ }
+
+ return strings.ToUpper(in)
+}
+
+// TODO: should getEnv logic be moved into find(). Can generalize the use of
+// rewriting keys many things, Ex: Get('someKey') -> some_key
+// (cammel case to snake case for JSON keys perhaps)
+
+// getEnv is a wrapper around os.Getenv which replaces characters in the original
+// key. This allows env vars which have different keys then the config object
+// keys
+func (v *Viper) getEnv(key string) string {
+ if v.envKeyReplacer != nil {
+ key = v.envKeyReplacer.Replace(key)
+ }
+ return os.Getenv(key)
+}
+
+// ConfigFileUsed returns the file used to populate the config registry
+func ConfigFileUsed() string { return v.ConfigFileUsed() }
+func (v *Viper) ConfigFileUsed() string { return v.configFile }
+
+// AddConfigPath adds a path for Viper to search for the config file in.
+// Can be called multiple times to define multiple search paths.
+func AddConfigPath(in string) { v.AddConfigPath(in) }
+func (v *Viper) AddConfigPath(in string) {
+ if in != "" {
+ absin := absPathify(in)
+ jww.INFO.Println("adding", absin, "to paths to search")
+ if !stringInSlice(absin, v.configPaths) {
+ v.configPaths = append(v.configPaths, absin)
+ }
+ }
+}
+
+// AddRemoteProvider adds a remote configuration source.
+// Remote Providers are searched in the order they are added.
+// provider is a string value, "etcd" or "consul" are currently supported.
+// endpoint is the url. etcd requires http://ip:port consul requires ip:port
+// path is the path in the k/v store to retrieve configuration
+// To retrieve a config file called myapp.json from /configs/myapp.json
+// you should set path to /configs and set config name (SetConfigName()) to
+// "myapp"
+func AddRemoteProvider(provider, endpoint, path string) error {
+ return v.AddRemoteProvider(provider, endpoint, path)
+}
+func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error {
+ if !stringInSlice(provider, SupportedRemoteProviders) {
+ return UnsupportedRemoteProviderError(provider)
+ }
+ if provider != "" && endpoint != "" {
+ jww.INFO.Printf("adding %s:%s to remote provider list", provider, endpoint)
+ rp := &defaultRemoteProvider{
+ endpoint: endpoint,
+ provider: provider,
+ path: path,
+ }
+ if !v.providerPathExists(rp) {
+ v.remoteProviders = append(v.remoteProviders, rp)
+ }
+ }
+ return nil
+}
+
+// AddSecureRemoteProvider adds a remote configuration source.
+// Secure Remote Providers are searched in the order they are added.
+// provider is a string value, "etcd" or "consul" are currently supported.
+// endpoint is the url. etcd requires http://ip:port consul requires ip:port
+// secretkeyring is the filepath to your openpgp secret keyring. e.g. /etc/secrets/myring.gpg
+// path is the path in the k/v store to retrieve configuration
+// To retrieve a config file called myapp.json from /configs/myapp.json
+// you should set path to /configs and set config name (SetConfigName()) to
+// "myapp"
+// Secure Remote Providers are implemented with github.com/xordataexchange/crypt
+func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
+ return v.AddSecureRemoteProvider(provider, endpoint, path, secretkeyring)
+}
+
+func (v *Viper) AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
+ if !stringInSlice(provider, SupportedRemoteProviders) {
+ return UnsupportedRemoteProviderError(provider)
+ }
+ if provider != "" && endpoint != "" {
+ jww.INFO.Printf("adding %s:%s to remote provider list", provider, endpoint)
+ rp := &defaultRemoteProvider{
+ endpoint: endpoint,
+ provider: provider,
+ path: path,
+ secretKeyring: secretkeyring,
+ }
+ if !v.providerPathExists(rp) {
+ v.remoteProviders = append(v.remoteProviders, rp)
+ }
+ }
+ return nil
+}
+
+func (v *Viper) providerPathExists(p *defaultRemoteProvider) bool {
+ for _, y := range v.remoteProviders {
+ if reflect.DeepEqual(y, p) {
+ return true
+ }
+ }
+ return false
+}
+
+// searchMap recursively searches for a value for path in source map.
+// Returns nil if not found.
+// Note: This assumes that the path entries and map keys are lower cased.
+func (v *Viper) searchMap(source map[string]interface{}, path []string) interface{} {
+ if len(path) == 0 {
+ return source
+ }
+
+ next, ok := source[path[0]]
+ if ok {
+ // Fast path
+ if len(path) == 1 {
+ return next
+ }
+
+ // Nested case
+ switch next.(type) {
+ case map[interface{}]interface{}:
+ return v.searchMap(cast.ToStringMap(next), path[1:])
+ case map[string]interface{}:
+ // Type assertion is safe here since it is only reached
+ // if the type of `next` is the same as the type being asserted
+ return v.searchMap(next.(map[string]interface{}), path[1:])
+ default:
+ // got a value but nested key expected, return "nil" for not found
+ return nil
+ }
+ }
+ return nil
+}
+
+// searchMapWithPathPrefixes recursively searches for a value for path in source map.
+//
+// While searchMap() considers each path element as a single map key, this
+// function searches for, and prioritizes, merged path elements.
+// e.g., if in the source, "foo" is defined with a sub-key "bar", and "foo.bar"
+// is also defined, this latter value is returned for path ["foo", "bar"].
+//
+// This should be useful only at config level (other maps may not contain dots
+// in their keys).
+//
+// Note: This assumes that the path entries and map keys are lower cased.
+func (v *Viper) searchMapWithPathPrefixes(source map[string]interface{}, path []string) interface{} {
+ if len(path) == 0 {
+ return source
+ }
+
+ // search for path prefixes, starting from the longest one
+ for i := len(path); i > 0; i-- {
+ prefixKey := strings.ToLower(strings.Join(path[0:i], v.keyDelim))
+
+ next, ok := source[prefixKey]
+ if ok {
+ // Fast path
+ if i == len(path) {
+ return next
+ }
+
+ // Nested case
+ var val interface{}
+ switch next.(type) {
+ case map[interface{}]interface{}:
+ val = v.searchMapWithPathPrefixes(cast.ToStringMap(next), path[i:])
+ case map[string]interface{}:
+ // Type assertion is safe here since it is only reached
+ // if the type of `next` is the same as the type being asserted
+ val = v.searchMapWithPathPrefixes(next.(map[string]interface{}), path[i:])
+ default:
+ // got a value but nested key expected, do nothing and look for next prefix
+ }
+ if val != nil {
+ return val
+ }
+ }
+ }
+
+ // not found
+ return nil
+}
+
+// isPathShadowedInDeepMap makes sure the given path is not shadowed somewhere
+// on its path in the map.
+// e.g., if "foo.bar" has a value in the given map, it “shadows”
+// "foo.bar.baz" in a lower-priority map
+func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]interface{}) string {
+ var parentVal interface{}
+ for i := 1; i < len(path); i++ {
+ parentVal = v.searchMap(m, path[0:i])
+ if parentVal == nil {
+ // not found, no need to add more path elements
+ return ""
+ }
+ switch parentVal.(type) {
+ case map[interface{}]interface{}:
+ continue
+ case map[string]interface{}:
+ continue
+ default:
+ // parentVal is a regular value which shadows "path"
+ return strings.Join(path[0:i], v.keyDelim)
+ }
+ }
+ return ""
+}
+
+// isPathShadowedInFlatMap makes sure the given path is not shadowed somewhere
+// in a sub-path of the map.
+// e.g., if "foo.bar" has a value in the given map, it “shadows”
+// "foo.bar.baz" in a lower-priority map
+func (v *Viper) isPathShadowedInFlatMap(path []string, mi interface{}) string {
+ // unify input map
+ var m map[string]interface{}
+ switch mi.(type) {
+ case map[string]string, map[string]FlagValue:
+ m = cast.ToStringMap(mi)
+ default:
+ return ""
+ }
+
+ // scan paths
+ var parentKey string
+ for i := 1; i < len(path); i++ {
+ parentKey = strings.Join(path[0:i], v.keyDelim)
+ if _, ok := m[parentKey]; ok {
+ return parentKey
+ }
+ }
+ return ""
+}
+
+// isPathShadowedInAutoEnv makes sure the given path is not shadowed somewhere
+// in the environment, when automatic env is on.
+// e.g., if "foo.bar" has a value in the environment, it “shadows”
+// "foo.bar.baz" in a lower-priority map
+func (v *Viper) isPathShadowedInAutoEnv(path []string) string {
+ var parentKey string
+ var val string
+ for i := 1; i < len(path); i++ {
+ parentKey = strings.Join(path[0:i], v.keyDelim)
+ if val = v.getEnv(v.mergeWithEnvPrefix(parentKey)); val != "" {
+ return parentKey
+ }
+ }
+ return ""
+}
+
+// SetTypeByDefaultValue enables or disables the inference of a key value's
+// type when the Get function is used based upon a key's default value as
+// opposed to the value returned based on the normal fetch logic.
+//
+// For example, if a key has a default value of []string{} and the same key
+// is set via an environment variable to "a b c", a call to the Get function
+// would return a string slice for the key if the key's type is inferred by
+// the default value and the Get function would return:
+//
+// []string {"a", "b", "c"}
+//
+// Otherwise the Get function would return:
+//
+// "a b c"
+func SetTypeByDefaultValue(enable bool) { v.SetTypeByDefaultValue(enable) }
+func (v *Viper) SetTypeByDefaultValue(enable bool) {
+ v.typeByDefValue = enable
+}
+
+// GetViper gets the global Viper instance.
+func GetViper() *Viper {
+ return v
+}
+
+// Get can retrieve any value given the key to use.
+// Get is case-insensitive for a key.
+// Get has the behavior of returning the value associated with the first
+// place from where it is set. Viper will check in the following order:
+// override, flag, env, config file, key/value store, default
+//
+// Get returns an interface. For a specific value use one of the Get____ methods.
+func Get(key string) interface{} { return v.Get(key) }
+func (v *Viper) Get(key string) interface{} {
+ lcaseKey := strings.ToLower(key)
+ val := v.find(lcaseKey)
+ if val == nil {
+ return nil
+ }
+
+ valType := val
+ if v.typeByDefValue {
+ // TODO(bep) this branch isn't covered by a single test.
+ path := strings.Split(lcaseKey, v.keyDelim)
+ defVal := v.searchMap(v.defaults, path)
+ if defVal != nil {
+ valType = defVal
+ }
+ }
+
+ switch valType.(type) {
+ case bool:
+ return cast.ToBool(val)
+ case string:
+ return cast.ToString(val)
+ case int64, int32, int16, int8, int:
+ return cast.ToInt(val)
+ case float64, float32:
+ return cast.ToFloat64(val)
+ case time.Time:
+ return cast.ToTime(val)
+ case time.Duration:
+ return cast.ToDuration(val)
+ case []string:
+ return cast.ToStringSlice(val)
+ }
+ return val
+}
+
+// Sub returns new Viper instance representing a sub tree of this instance.
+// Sub is case-insensitive for a key.
+func Sub(key string) *Viper { return v.Sub(key) }
+func (v *Viper) Sub(key string) *Viper {
+ subv := New()
+ data := v.Get(key)
+ if data == nil {
+ return nil
+ }
+
+ if reflect.TypeOf(data).Kind() == reflect.Map {
+ subv.config = cast.ToStringMap(data)
+ return subv
+ }
+ return nil
+}
+
+// GetString returns the value associated with the key as a string.
+func GetString(key string) string { return v.GetString(key) }
+func (v *Viper) GetString(key string) string {
+ return cast.ToString(v.Get(key))
+}
+
+// GetBool returns the value associated with the key as a boolean.
+func GetBool(key string) bool { return v.GetBool(key) }
+func (v *Viper) GetBool(key string) bool {
+ return cast.ToBool(v.Get(key))
+}
+
+// GetInt returns the value associated with the key as an integer.
+func GetInt(key string) int { return v.GetInt(key) }
+func (v *Viper) GetInt(key string) int {
+ return cast.ToInt(v.Get(key))
+}
+
+// GetInt64 returns the value associated with the key as an integer.
+func GetInt64(key string) int64 { return v.GetInt64(key) }
+func (v *Viper) GetInt64(key string) int64 {
+ return cast.ToInt64(v.Get(key))
+}
+
+// GetFloat64 returns the value associated with the key as a float64.
+func GetFloat64(key string) float64 { return v.GetFloat64(key) }
+func (v *Viper) GetFloat64(key string) float64 {
+ return cast.ToFloat64(v.Get(key))
+}
+
+// GetTime returns the value associated with the key as time.
+func GetTime(key string) time.Time { return v.GetTime(key) }
+func (v *Viper) GetTime(key string) time.Time {
+ return cast.ToTime(v.Get(key))
+}
+
+// GetDuration returns the value associated with the key as a duration.
+func GetDuration(key string) time.Duration { return v.GetDuration(key) }
+func (v *Viper) GetDuration(key string) time.Duration {
+ return cast.ToDuration(v.Get(key))
+}
+
+// GetStringSlice returns the value associated with the key as a slice of strings.
+func GetStringSlice(key string) []string { return v.GetStringSlice(key) }
+func (v *Viper) GetStringSlice(key string) []string {
+ return cast.ToStringSlice(v.Get(key))
+}
+
+// GetStringMap returns the value associated with the key as a map of interfaces.
+func GetStringMap(key string) map[string]interface{} { return v.GetStringMap(key) }
+func (v *Viper) GetStringMap(key string) map[string]interface{} {
+ return cast.ToStringMap(v.Get(key))
+}
+
+// GetStringMapString returns the value associated with the key as a map of strings.
+func GetStringMapString(key string) map[string]string { return v.GetStringMapString(key) }
+func (v *Viper) GetStringMapString(key string) map[string]string {
+ return cast.ToStringMapString(v.Get(key))
+}
+
+// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
+func GetStringMapStringSlice(key string) map[string][]string { return v.GetStringMapStringSlice(key) }
+func (v *Viper) GetStringMapStringSlice(key string) map[string][]string {
+ return cast.ToStringMapStringSlice(v.Get(key))
+}
+
+// GetSizeInBytes returns the size of the value associated with the given key
+// in bytes.
+func GetSizeInBytes(key string) uint { return v.GetSizeInBytes(key) }
+func (v *Viper) GetSizeInBytes(key string) uint {
+ sizeStr := cast.ToString(v.Get(key))
+ return parseSizeInBytes(sizeStr)
+}
+
+// UnmarshalKey takes a single key and unmarshals it into a Struct.
+func UnmarshalKey(key string, rawVal interface{}) error { return v.UnmarshalKey(key, rawVal) }
+func (v *Viper) UnmarshalKey(key string, rawVal interface{}) error {
+ return mapstructure.Decode(v.Get(key), rawVal)
+}
+
+// Unmarshal unmarshals the config into a Struct. Make sure that the tags
+// on the fields of the structure are properly set.
+func Unmarshal(rawVal interface{}) error { return v.Unmarshal(rawVal) }
+func (v *Viper) Unmarshal(rawVal interface{}) error {
+ err := decode(v.AllSettings(), defaultDecoderConfig(rawVal))
+
+ if err != nil {
+ return err
+ }
+
+ v.insensitiviseMaps()
+
+ return nil
+}
+
+// defaultDecoderConfig returns default mapsstructure.DecoderConfig with suppot
+// of time.Duration values
+func defaultDecoderConfig(output interface{}) *mapstructure.DecoderConfig {
+ return &mapstructure.DecoderConfig{
+ Metadata: nil,
+ Result: output,
+ WeaklyTypedInput: true,
+ DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
+ }
+}
+
+// A wrapper around mapstructure.Decode that mimics the WeakDecode functionality
+func decode(input interface{}, config *mapstructure.DecoderConfig) error {
+ decoder, err := mapstructure.NewDecoder(config)
+ if err != nil {
+ return err
+ }
+ return decoder.Decode(input)
+}
+
+// UnmarshalExact unmarshals the config into a Struct, erroring if a field is nonexistent
+// in the destination struct.
+func (v *Viper) UnmarshalExact(rawVal interface{}) error {
+ config := defaultDecoderConfig(rawVal)
+ config.ErrorUnused = true
+
+ err := decode(v.AllSettings(), config)
+
+ if err != nil {
+ return err
+ }
+
+ v.insensitiviseMaps()
+
+ return nil
+}
+
+// BindPFlags binds a full flag set to the configuration, using each flag's long
+// name as the config key.
+func BindPFlags(flags *pflag.FlagSet) error { return v.BindPFlags(flags) }
+func (v *Viper) BindPFlags(flags *pflag.FlagSet) error {
+ return v.BindFlagValues(pflagValueSet{flags})
+}
+
+// BindPFlag binds a specific key to a pflag (as used by cobra).
+// Example (where serverCmd is a Cobra instance):
+//
+// serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
+// Viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
+//
+func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) }
+func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error {
+ return v.BindFlagValue(key, pflagValue{flag})
+}
+
+// BindFlagValues binds a full FlagValue set to the configuration, using each flag's long
+// name as the config key.
+func BindFlagValues(flags FlagValueSet) error { return v.BindFlagValues(flags) }
+func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) {
+ flags.VisitAll(func(flag FlagValue) {
+ if err = v.BindFlagValue(flag.Name(), flag); err != nil {
+ return
+ }
+ })
+ return nil
+}
+
+// BindFlagValue binds a specific key to a FlagValue.
+// Example(where serverCmd is a Cobra instance):
+//
+// serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
+// Viper.BindFlagValue("port", serverCmd.Flags().Lookup("port"))
+//
+func BindFlagValue(key string, flag FlagValue) error { return v.BindFlagValue(key, flag) }
+func (v *Viper) BindFlagValue(key string, flag FlagValue) error {
+ if flag == nil {
+ return fmt.Errorf("flag for %q is nil", key)
+ }
+ v.pflags[strings.ToLower(key)] = flag
+ return nil
+}
+
+// BindEnv binds a Viper key to a ENV variable.
+// ENV variables are case sensitive.
+// If only a key is provided, it will use the env key matching the key, uppercased.
+// EnvPrefix will be used when set when env name is not provided.
+func BindEnv(input ...string) error { return v.BindEnv(input...) }
+func (v *Viper) BindEnv(input ...string) error {
+ var key, envkey string
+ if len(input) == 0 {
+ return fmt.Errorf("BindEnv missing key to bind to")
+ }
+
+ key = strings.ToLower(input[0])
+
+ if len(input) == 1 {
+ envkey = v.mergeWithEnvPrefix(key)
+ } else {
+ envkey = input[1]
+ }
+
+ v.env[key] = envkey
+
+ return nil
+}
+
+// Given a key, find the value.
+// Viper will check in the following order:
+// flag, env, config file, key/value store, default.
+// Viper will check to see if an alias exists first.
+// Note: this assumes a lower-cased key given.
+func (v *Viper) find(lcaseKey string) interface{} {
+
+ var (
+ val interface{}
+ exists bool
+ path = strings.Split(lcaseKey, v.keyDelim)
+ nested = len(path) > 1
+ )
+
+ // compute the path through the nested maps to the nested value
+ if nested && v.isPathShadowedInDeepMap(path, castMapStringToMapInterface(v.aliases)) != "" {
+ return nil
+ }
+
+ // if the requested key is an alias, then return the proper key
+ lcaseKey = v.realKey(lcaseKey)
+ path = strings.Split(lcaseKey, v.keyDelim)
+ nested = len(path) > 1
+
+ // Set() override first
+ val = v.searchMap(v.override, path)
+ if val != nil {
+ return val
+ }
+ if nested && v.isPathShadowedInDeepMap(path, v.override) != "" {
+ return nil
+ }
+
+ // PFlag override next
+ flag, exists := v.pflags[lcaseKey]
+ if exists && flag.HasChanged() {
+ switch flag.ValueType() {
+ case "int", "int8", "int16", "int32", "int64":
+ return cast.ToInt(flag.ValueString())
+ case "bool":
+ return cast.ToBool(flag.ValueString())
+ case "stringSlice":
+ s := strings.TrimPrefix(flag.ValueString(), "[")
+ return strings.TrimSuffix(s, "]")
+ default:
+ return flag.ValueString()
+ }
+ }
+ if nested && v.isPathShadowedInFlatMap(path, v.pflags) != "" {
+ return nil
+ }
+
+ // Env override next
+ if v.automaticEnvApplied {
+ // even if it hasn't been registered, if automaticEnv is used,
+ // check any Get request
+ if val = v.getEnv(v.mergeWithEnvPrefix(lcaseKey)); val != "" {
+ return val
+ }
+ if nested && v.isPathShadowedInAutoEnv(path) != "" {
+ return nil
+ }
+ }
+ envkey, exists := v.env[lcaseKey]
+ if exists {
+ if val = v.getEnv(envkey); val != "" {
+ return val
+ }
+ }
+ if nested && v.isPathShadowedInFlatMap(path, v.env) != "" {
+ return nil
+ }
+
+ // Config file next
+ val = v.searchMapWithPathPrefixes(v.config, path)
+ if val != nil {
+ return val
+ }
+ if nested && v.isPathShadowedInDeepMap(path, v.config) != "" {
+ return nil
+ }
+
+ // K/V store next
+ val = v.searchMap(v.kvstore, path)
+ if val != nil {
+ return val
+ }
+ if nested && v.isPathShadowedInDeepMap(path, v.kvstore) != "" {
+ return nil
+ }
+
+ // Default next
+ val = v.searchMap(v.defaults, path)
+ if val != nil {
+ return val
+ }
+ if nested && v.isPathShadowedInDeepMap(path, v.defaults) != "" {
+ return nil
+ }
+
+ // last chance: if no other value is returned and a flag does exist for the value,
+ // get the flag's value even if the flag's value has not changed
+ if flag, exists := v.pflags[lcaseKey]; exists {
+ switch flag.ValueType() {
+ case "int", "int8", "int16", "int32", "int64":
+ return cast.ToInt(flag.ValueString())
+ case "bool":
+ return cast.ToBool(flag.ValueString())
+ case "stringSlice":
+ s := strings.TrimPrefix(flag.ValueString(), "[")
+ return strings.TrimSuffix(s, "]")
+ default:
+ return flag.ValueString()
+ }
+ }
+ // last item, no need to check shadowing
+
+ return nil
+}
+
+// IsSet checks to see if the key has been set in any of the data locations.
+// IsSet is case-insensitive for a key.
+func IsSet(key string) bool { return v.IsSet(key) }
+func (v *Viper) IsSet(key string) bool {
+ lcaseKey := strings.ToLower(key)
+ val := v.find(lcaseKey)
+ return val != nil
+}
+
+// AutomaticEnv has Viper check ENV variables for all.
+// keys set in config, default & flags
+func AutomaticEnv() { v.AutomaticEnv() }
+func (v *Viper) AutomaticEnv() {
+ v.automaticEnvApplied = true
+}
+
+// SetEnvKeyReplacer sets the strings.Replacer on the viper object
+// Useful for mapping an environmental variable to a key that does
+// not match it.
+func SetEnvKeyReplacer(r *strings.Replacer) { v.SetEnvKeyReplacer(r) }
+func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) {
+ v.envKeyReplacer = r
+}
+
+// Aliases provide another accessor for the same key.
+// This enables one to change a name without breaking the application
+func RegisterAlias(alias string, key string) { v.RegisterAlias(alias, key) }
+func (v *Viper) RegisterAlias(alias string, key string) {
+ v.registerAlias(alias, strings.ToLower(key))
+}
+
+func (v *Viper) registerAlias(alias string, key string) {
+ alias = strings.ToLower(alias)
+ if alias != key && alias != v.realKey(key) {
+ _, exists := v.aliases[alias]
+
+ if !exists {
+ // if we alias something that exists in one of the maps to another
+ // name, we'll never be able to get that value using the original
+ // name, so move the config value to the new realkey.
+ if val, ok := v.config[alias]; ok {
+ delete(v.config, alias)
+ v.config[key] = val
+ }
+ if val, ok := v.kvstore[alias]; ok {
+ delete(v.kvstore, alias)
+ v.kvstore[key] = val
+ }
+ if val, ok := v.defaults[alias]; ok {
+ delete(v.defaults, alias)
+ v.defaults[key] = val
+ }
+ if val, ok := v.override[alias]; ok {
+ delete(v.override, alias)
+ v.override[key] = val
+ }
+ v.aliases[alias] = key
+ }
+ } else {
+ jww.WARN.Println("Creating circular reference alias", alias, key, v.realKey(key))
+ }
+}
+
+func (v *Viper) realKey(key string) string {
+ newkey, exists := v.aliases[key]
+ if exists {
+ jww.DEBUG.Println("Alias", key, "to", newkey)
+ return v.realKey(newkey)
+ }
+ return key
+}
+
+// InConfig checks to see if the given key (or an alias) is in the config file.
+func InConfig(key string) bool { return v.InConfig(key) }
+func (v *Viper) InConfig(key string) bool {
+ // if the requested key is an alias, then return the proper key
+ key = v.realKey(key)
+
+ _, exists := v.config[key]
+ return exists
+}
+
+// SetDefault sets the default value for this key.
+// SetDefault is case-insensitive for a key.
+// Default only used when no value is provided by the user via flag, config or ENV.
+func SetDefault(key string, value interface{}) { v.SetDefault(key, value) }
+func (v *Viper) SetDefault(key string, value interface{}) {
+ // If alias passed in, then set the proper default
+ key = v.realKey(strings.ToLower(key))
+ value = toCaseInsensitiveValue(value)
+
+ path := strings.Split(key, v.keyDelim)
+ lastKey := strings.ToLower(path[len(path)-1])
+ deepestMap := deepSearch(v.defaults, path[0:len(path)-1])
+
+ // set innermost value
+ deepestMap[lastKey] = value
+}
+
+// Set sets the value for the key in the override regiser.
+// Set is case-insensitive for a key.
+// Will be used instead of values obtained via
+// flags, config file, ENV, default, or key/value store.
+func Set(key string, value interface{}) { v.Set(key, value) }
+func (v *Viper) Set(key string, value interface{}) {
+ // If alias passed in, then set the proper override
+ key = v.realKey(strings.ToLower(key))
+ value = toCaseInsensitiveValue(value)
+
+ path := strings.Split(key, v.keyDelim)
+ lastKey := strings.ToLower(path[len(path)-1])
+ deepestMap := deepSearch(v.override, path[0:len(path)-1])
+
+ // set innermost value
+ deepestMap[lastKey] = value
+}
+
+// ReadInConfig will discover and load the configuration file from disk
+// and key/value stores, searching in one of the defined paths.
+func ReadInConfig() error { return v.ReadInConfig() }
+func (v *Viper) ReadInConfig() error {
+ jww.INFO.Println("Attempting to read in config file")
+ filename, err := v.getConfigFile()
+ if err != nil {
+ return err
+ }
+
+ if !stringInSlice(v.getConfigType(), SupportedExts) {
+ return UnsupportedConfigError(v.getConfigType())
+ }
+
+ file, err := afero.ReadFile(v.fs, filename)
+ if err != nil {
+ return err
+ }
+
+ config := make(map[string]interface{})
+
+ err = v.unmarshalReader(bytes.NewReader(file), config)
+ if err != nil {
+ return err
+ }
+
+ v.config = config
+ return nil
+}
+
+// MergeInConfig merges a new configuration with an existing config.
+func MergeInConfig() error { return v.MergeInConfig() }
+func (v *Viper) MergeInConfig() error {
+ jww.INFO.Println("Attempting to merge in config file")
+ filename, err := v.getConfigFile()
+ if err != nil {
+ return err
+ }
+
+ if !stringInSlice(v.getConfigType(), SupportedExts) {
+ return UnsupportedConfigError(v.getConfigType())
+ }
+
+ file, err := afero.ReadFile(v.fs, filename)
+ if err != nil {
+ return err
+ }
+
+ return v.MergeConfig(bytes.NewReader(file))
+}
+
+// ReadConfig will read a configuration file, setting existing keys to nil if the
+// key does not exist in the file.
+func ReadConfig(in io.Reader) error { return v.ReadConfig(in) }
+func (v *Viper) ReadConfig(in io.Reader) error {
+ v.config = make(map[string]interface{})
+ return v.unmarshalReader(in, v.config)
+}
+
+// MergeConfig merges a new configuration with an existing config.
+func MergeConfig(in io.Reader) error { return v.MergeConfig(in) }
+func (v *Viper) MergeConfig(in io.Reader) error {
+ if v.config == nil {
+ v.config = make(map[string]interface{})
+ }
+ cfg := make(map[string]interface{})
+ if err := v.unmarshalReader(in, cfg); err != nil {
+ return err
+ }
+ mergeMaps(cfg, v.config, nil)
+ return nil
+}
+
+func keyExists(k string, m map[string]interface{}) string {
+ lk := strings.ToLower(k)
+ for mk := range m {
+ lmk := strings.ToLower(mk)
+ if lmk == lk {
+ return mk
+ }
+ }
+ return ""
+}
+
+func castToMapStringInterface(
+ src map[interface{}]interface{}) map[string]interface{} {
+ tgt := map[string]interface{}{}
+ for k, v := range src {
+ tgt[fmt.Sprintf("%v", k)] = v
+ }
+ return tgt
+}
+
+func castMapStringToMapInterface(src map[string]string) map[string]interface{} {
+ tgt := map[string]interface{}{}
+ for k, v := range src {
+ tgt[k] = v
+ }
+ return tgt
+}
+
+func castMapFlagToMapInterface(src map[string]FlagValue) map[string]interface{} {
+ tgt := map[string]interface{}{}
+ for k, v := range src {
+ tgt[k] = v
+ }
+ return tgt
+}
+
+// mergeMaps merges two maps. The `itgt` parameter is for handling go-yaml's
+// insistence on parsing nested structures as `map[interface{}]interface{}`
+// instead of using a `string` as the key for nest structures beyond one level
+// deep. Both map types are supported as there is a go-yaml fork that uses
+// `map[string]interface{}` instead.
+func mergeMaps(
+ src, tgt map[string]interface{}, itgt map[interface{}]interface{}) {
+ for sk, sv := range src {
+ tk := keyExists(sk, tgt)
+ if tk == "" {
+ jww.TRACE.Printf("tk=\"\", tgt[%s]=%v", sk, sv)
+ tgt[sk] = sv
+ if itgt != nil {
+ itgt[sk] = sv
+ }
+ continue
+ }
+
+ tv, ok := tgt[tk]
+ if !ok {
+ jww.TRACE.Printf("tgt[%s] != ok, tgt[%s]=%v", tk, sk, sv)
+ tgt[sk] = sv
+ if itgt != nil {
+ itgt[sk] = sv
+ }
+ continue
+ }
+
+ svType := reflect.TypeOf(sv)
+ tvType := reflect.TypeOf(tv)
+ if svType != tvType {
+ jww.ERROR.Printf(
+ "svType != tvType; key=%s, st=%v, tt=%v, sv=%v, tv=%v",
+ sk, svType, tvType, sv, tv)
+ continue
+ }
+
+ jww.TRACE.Printf("processing key=%s, st=%v, tt=%v, sv=%v, tv=%v",
+ sk, svType, tvType, sv, tv)
+
+ switch ttv := tv.(type) {
+ case map[interface{}]interface{}:
+ jww.TRACE.Printf("merging maps (must convert)")
+ tsv := sv.(map[interface{}]interface{})
+ ssv := castToMapStringInterface(tsv)
+ stv := castToMapStringInterface(ttv)
+ mergeMaps(ssv, stv, ttv)
+ case map[string]interface{}:
+ jww.TRACE.Printf("merging maps")
+ mergeMaps(sv.(map[string]interface{}), ttv, nil)
+ default:
+ jww.TRACE.Printf("setting value")
+ tgt[tk] = sv
+ if itgt != nil {
+ itgt[tk] = sv
+ }
+ }
+ }
+}
+
+// ReadRemoteConfig attempts to get configuration from a remote source
+// and read it in the remote configuration registry.
+func ReadRemoteConfig() error { return v.ReadRemoteConfig() }
+func (v *Viper) ReadRemoteConfig() error {
+ return v.getKeyValueConfig()
+}
+
+func WatchRemoteConfig() error { return v.WatchRemoteConfig() }
+func (v *Viper) WatchRemoteConfig() error {
+ return v.watchKeyValueConfig()
+}
+
+func (v *Viper) WatchRemoteConfigOnChannel() error {
+ return v.watchKeyValueConfigOnChannel()
+}
+
+// Unmarshall a Reader into a map.
+// Should probably be an unexported function.
+func unmarshalReader(in io.Reader, c map[string]interface{}) error {
+ return v.unmarshalReader(in, c)
+}
+
+func (v *Viper) unmarshalReader(in io.Reader, c map[string]interface{}) error {
+ return unmarshallConfigReader(in, c, v.getConfigType())
+}
+
+func (v *Viper) insensitiviseMaps() {
+ insensitiviseMap(v.config)
+ insensitiviseMap(v.defaults)
+ insensitiviseMap(v.override)
+ insensitiviseMap(v.kvstore)
+}
+
+// Retrieve the first found remote configuration.
+func (v *Viper) getKeyValueConfig() error {
+ if RemoteConfig == nil {
+ return RemoteConfigError("Enable the remote features by doing a blank import of the viper/remote package: '_ github.com/spf13/viper/remote'")
+ }
+
+ for _, rp := range v.remoteProviders {
+ val, err := v.getRemoteConfig(rp)
+ if err != nil {
+ continue
+ }
+ v.kvstore = val
+ return nil
+ }
+ return RemoteConfigError("No Files Found")
+}
+
+func (v *Viper) getRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
+ reader, err := RemoteConfig.Get(provider)
+ if err != nil {
+ return nil, err
+ }
+ err = v.unmarshalReader(reader, v.kvstore)
+ return v.kvstore, err
+}
+
+// Retrieve the first found remote configuration.
+func (v *Viper) watchKeyValueConfigOnChannel() error {
+ for _, rp := range v.remoteProviders {
+ respc, _ := RemoteConfig.WatchChannel(rp)
+ //Todo: Add quit channel
+ go func(rc <-chan *RemoteResponse) {
+ for {
+ b := <-rc
+ reader := bytes.NewReader(b.Value)
+ v.unmarshalReader(reader, v.kvstore)
+ }
+ }(respc)
+ return nil
+ }
+ return RemoteConfigError("No Files Found")
+}
+
+// Retrieve the first found remote configuration.
+func (v *Viper) watchKeyValueConfig() error {
+ for _, rp := range v.remoteProviders {
+ val, err := v.watchRemoteConfig(rp)
+ if err != nil {
+ continue
+ }
+ v.kvstore = val
+ return nil
+ }
+ return RemoteConfigError("No Files Found")
+}
+
+func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
+ reader, err := RemoteConfig.Watch(provider)
+ if err != nil {
+ return nil, err
+ }
+ err = v.unmarshalReader(reader, v.kvstore)
+ return v.kvstore, err
+}
+
+// AllKeys returns all keys holding a value, regardless of where they are set.
+// Nested keys are returned with a v.keyDelim (= ".") separator
+func AllKeys() []string { return v.AllKeys() }
+func (v *Viper) AllKeys() []string {
+ m := map[string]bool{}
+ // add all paths, by order of descending priority to ensure correct shadowing
+ m = v.flattenAndMergeMap(m, castMapStringToMapInterface(v.aliases), "")
+ m = v.flattenAndMergeMap(m, v.override, "")
+ m = v.mergeFlatMap(m, castMapFlagToMapInterface(v.pflags))
+ m = v.mergeFlatMap(m, castMapStringToMapInterface(v.env))
+ m = v.flattenAndMergeMap(m, v.config, "")
+ m = v.flattenAndMergeMap(m, v.kvstore, "")
+ m = v.flattenAndMergeMap(m, v.defaults, "")
+
+ // convert set of paths to list
+ a := []string{}
+ for x := range m {
+ a = append(a, x)
+ }
+ return a
+}
+
+// flattenAndMergeMap recursively flattens the given map into a map[string]bool
+// of key paths (used as a set, easier to manipulate than a []string):
+// - each path is merged into a single key string, delimited with v.keyDelim (= ".")
+// - if a path is shadowed by an earlier value in the initial shadow map,
+// it is skipped.
+// The resulting set of paths is merged to the given shadow set at the same time.
+func (v *Viper) flattenAndMergeMap(shadow map[string]bool, m map[string]interface{}, prefix string) map[string]bool {
+ if shadow != nil && prefix != "" && shadow[prefix] {
+ // prefix is shadowed => nothing more to flatten
+ return shadow
+ }
+ if shadow == nil {
+ shadow = make(map[string]bool)
+ }
+
+ var m2 map[string]interface{}
+ if prefix != "" {
+ prefix += v.keyDelim
+ }
+ for k, val := range m {
+ fullKey := prefix + k
+ switch val.(type) {
+ case map[string]interface{}:
+ m2 = val.(map[string]interface{})
+ case map[interface{}]interface{}:
+ m2 = cast.ToStringMap(val)
+ default:
+ // immediate value
+ shadow[strings.ToLower(fullKey)] = true
+ continue
+ }
+ // recursively merge to shadow map
+ shadow = v.flattenAndMergeMap(shadow, m2, fullKey)
+ }
+ return shadow
+}
+
+// mergeFlatMap merges the given maps, excluding values of the second map
+// shadowed by values from the first map.
+func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]interface{}) map[string]bool {
+ // scan keys
+outer:
+ for k, _ := range m {
+ path := strings.Split(k, v.keyDelim)
+ // scan intermediate paths
+ var parentKey string
+ for i := 1; i < len(path); i++ {
+ parentKey = strings.Join(path[0:i], v.keyDelim)
+ if shadow[parentKey] {
+ // path is shadowed, continue
+ continue outer
+ }
+ }
+ // add key
+ shadow[strings.ToLower(k)] = true
+ }
+ return shadow
+}
+
+// AllSettings merges all settings and returns them as a map[string]interface{}.
+func AllSettings() map[string]interface{} { return v.AllSettings() }
+func (v *Viper) AllSettings() map[string]interface{} {
+ m := map[string]interface{}{}
+ // start from the list of keys, and construct the map one value at a time
+ for _, k := range v.AllKeys() {
+ value := v.Get(k)
+ if value == nil {
+ // should not happen, since AllKeys() returns only keys holding a value,
+ // check just in case anything changes
+ continue
+ }
+ path := strings.Split(k, v.keyDelim)
+ lastKey := strings.ToLower(path[len(path)-1])
+ deepestMap := deepSearch(m, path[0:len(path)-1])
+ // set innermost value
+ deepestMap[lastKey] = value
+ }
+ return m
+}
+
+// SetFs sets the filesystem to use to read configuration.
+func SetFs(fs afero.Fs) { v.SetFs(fs) }
+func (v *Viper) SetFs(fs afero.Fs) {
+ v.fs = fs
+}
+
+// SetConfigName sets name for the config file.
+// Does not include extension.
+func SetConfigName(in string) { v.SetConfigName(in) }
+func (v *Viper) SetConfigName(in string) {
+ if in != "" {
+ v.configName = in
+ v.configFile = ""
+ }
+}
+
+// SetConfigType sets the type of the configuration returned by the
+// remote source, e.g. "json".
+func SetConfigType(in string) { v.SetConfigType(in) }
+func (v *Viper) SetConfigType(in string) {
+ if in != "" {
+ v.configType = in
+ }
+}
+
+func (v *Viper) getConfigType() string {
+ if v.configType != "" {
+ return v.configType
+ }
+
+ cf, err := v.getConfigFile()
+ if err != nil {
+ return ""
+ }
+
+ ext := filepath.Ext(cf)
+
+ if len(ext) > 1 {
+ return ext[1:]
+ }
+
+ return ""
+}
+
+func (v *Viper) getConfigFile() (string, error) {
+ // if explicitly set, then use it
+ if v.configFile != "" {
+ return v.configFile, nil
+ }
+
+ cf, err := v.findConfigFile()
+ if err != nil {
+ return "", err
+ }
+
+ v.configFile = cf
+ return v.getConfigFile()
+}
+
+func (v *Viper) searchInPath(in string) (filename string) {
+ jww.DEBUG.Println("Searching for config in ", in)
+ for _, ext := range SupportedExts {
+ jww.DEBUG.Println("Checking for", filepath.Join(in, v.configName+"."+ext))
+ if b, _ := exists(filepath.Join(in, v.configName+"."+ext)); b {
+ jww.DEBUG.Println("Found: ", filepath.Join(in, v.configName+"."+ext))
+ return filepath.Join(in, v.configName+"."+ext)
+ }
+ }
+
+ return ""
+}
+
+// Search all configPaths for any config file.
+// Returns the first path that exists (and is a config file).
+func (v *Viper) findConfigFile() (string, error) {
+
+ jww.INFO.Println("Searching for config in ", v.configPaths)
+
+ for _, cp := range v.configPaths {
+ file := v.searchInPath(cp)
+ if file != "" {
+ return file, nil
+ }
+ }
+ return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}
+}
+
+// Debug prints all configuration registries for debugging
+// purposes.
+func Debug() { v.Debug() }
+func (v *Viper) Debug() {
+ fmt.Printf("Aliases:\n%#v\n", v.aliases)
+ fmt.Printf("Override:\n%#v\n", v.override)
+ fmt.Printf("PFlags:\n%#v\n", v.pflags)
+ fmt.Printf("Env:\n%#v\n", v.env)
+ fmt.Printf("Key/Value Store:\n%#v\n", v.kvstore)
+ fmt.Printf("Config:\n%#v\n", v.config)
+ fmt.Printf("Defaults:\n%#v\n", v.defaults)
+}
diff --git a/vendor/github.com/spf13/viper/viper_test.go b/vendor/github.com/spf13/viper/viper_test.go
new file mode 100644
index 000000000..cd7b65cbd
--- /dev/null
+++ b/vendor/github.com/spf13/viper/viper_test.go
@@ -0,0 +1,1154 @@
+// Copyright © 2014 Steve Francia <spf@spf13.com>.
+//
+// Use of this source code is governed by an MIT-style
+// license that can be found in the LICENSE file.
+
+package viper
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "path"
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/spf13/cast"
+
+ "github.com/spf13/pflag"
+ "github.com/stretchr/testify/assert"
+)
+
+var yamlExample = []byte(`Hacker: true
+name: steve
+hobbies:
+- skateboarding
+- snowboarding
+- go
+clothing:
+ jacket: leather
+ trousers: denim
+ pants:
+ size: large
+age: 35
+eyes : brown
+beard: true
+`)
+
+var yamlExampleWithExtras = []byte(`Existing: true
+Bogus: true
+`)
+
+type testUnmarshalExtra struct {
+ Existing bool
+}
+
+var tomlExample = []byte(`
+title = "TOML Example"
+
+[owner]
+organization = "MongoDB"
+Bio = "MongoDB Chief Developer Advocate & Hacker at Large"
+dob = 1979-05-27T07:32:00Z # First class dates? Why not?`)
+
+var jsonExample = []byte(`{
+"id": "0001",
+"type": "donut",
+"name": "Cake",
+"ppu": 0.55,
+"batters": {
+ "batter": [
+ { "type": "Regular" },
+ { "type": "Chocolate" },
+ { "type": "Blueberry" },
+ { "type": "Devil's Food" }
+ ]
+ }
+}`)
+
+var hclExample = []byte(`
+id = "0001"
+type = "donut"
+name = "Cake"
+ppu = 0.55
+foos {
+ foo {
+ key = 1
+ }
+ foo {
+ key = 2
+ }
+ foo {
+ key = 3
+ }
+ foo {
+ key = 4
+ }
+}`)
+
+var propertiesExample = []byte(`
+p_id: 0001
+p_type: donut
+p_name: Cake
+p_ppu: 0.55
+p_batters.batter.type: Regular
+`)
+
+var remoteExample = []byte(`{
+"id":"0002",
+"type":"cronut",
+"newkey":"remote"
+}`)
+
+func initConfigs() {
+ Reset()
+ var r io.Reader
+ SetConfigType("yaml")
+ r = bytes.NewReader(yamlExample)
+ unmarshalReader(r, v.config)
+
+ SetConfigType("json")
+ r = bytes.NewReader(jsonExample)
+ unmarshalReader(r, v.config)
+
+ SetConfigType("hcl")
+ r = bytes.NewReader(hclExample)
+ unmarshalReader(r, v.config)
+
+ SetConfigType("properties")
+ r = bytes.NewReader(propertiesExample)
+ unmarshalReader(r, v.config)
+
+ SetConfigType("toml")
+ r = bytes.NewReader(tomlExample)
+ unmarshalReader(r, v.config)
+
+ SetConfigType("json")
+ remote := bytes.NewReader(remoteExample)
+ unmarshalReader(remote, v.kvstore)
+}
+
+func initConfig(typ, config string) {
+ Reset()
+ SetConfigType(typ)
+ r := strings.NewReader(config)
+
+ if err := unmarshalReader(r, v.config); err != nil {
+ panic(err)
+ }
+}
+
+func initYAML() {
+ initConfig("yaml", string(yamlExample))
+}
+
+func initJSON() {
+ Reset()
+ SetConfigType("json")
+ r := bytes.NewReader(jsonExample)
+
+ unmarshalReader(r, v.config)
+}
+
+func initProperties() {
+ Reset()
+ SetConfigType("properties")
+ r := bytes.NewReader(propertiesExample)
+
+ unmarshalReader(r, v.config)
+}
+
+func initTOML() {
+ Reset()
+ SetConfigType("toml")
+ r := bytes.NewReader(tomlExample)
+
+ unmarshalReader(r, v.config)
+}
+
+func initHcl() {
+ Reset()
+ SetConfigType("hcl")
+ r := bytes.NewReader(hclExample)
+
+ unmarshalReader(r, v.config)
+}
+
+// make directories for testing
+func initDirs(t *testing.T) (string, string, func()) {
+
+ var (
+ testDirs = []string{`a a`, `b`, `c\c`, `D_`}
+ config = `improbable`
+ )
+
+ root, err := ioutil.TempDir("", "")
+
+ cleanup := true
+ defer func() {
+ if cleanup {
+ os.Chdir("..")
+ os.RemoveAll(root)
+ }
+ }()
+
+ assert.Nil(t, err)
+
+ err = os.Chdir(root)
+ assert.Nil(t, err)
+
+ for _, dir := range testDirs {
+ err = os.Mkdir(dir, 0750)
+ assert.Nil(t, err)
+
+ err = ioutil.WriteFile(
+ path.Join(dir, config+".toml"),
+ []byte("key = \"value is "+dir+"\"\n"),
+ 0640)
+ assert.Nil(t, err)
+ }
+
+ cleanup = false
+ return root, config, func() {
+ os.Chdir("..")
+ os.RemoveAll(root)
+ }
+}
+
+//stubs for PFlag Values
+type stringValue string
+
+func newStringValue(val string, p *string) *stringValue {
+ *p = val
+ return (*stringValue)(p)
+}
+
+func (s *stringValue) Set(val string) error {
+ *s = stringValue(val)
+ return nil
+}
+
+func (s *stringValue) Type() string {
+ return "string"
+}
+
+func (s *stringValue) String() string {
+ return fmt.Sprintf("%s", *s)
+}
+
+func TestBasics(t *testing.T) {
+ SetConfigFile("/tmp/config.yaml")
+ filename, err := v.getConfigFile()
+ assert.Equal(t, "/tmp/config.yaml", filename)
+ assert.NoError(t, err)
+}
+
+func TestDefault(t *testing.T) {
+ SetDefault("age", 45)
+ assert.Equal(t, 45, Get("age"))
+
+ SetDefault("clothing.jacket", "slacks")
+ assert.Equal(t, "slacks", Get("clothing.jacket"))
+
+ SetConfigType("yaml")
+ err := ReadConfig(bytes.NewBuffer(yamlExample))
+
+ assert.NoError(t, err)
+ assert.Equal(t, "leather", Get("clothing.jacket"))
+}
+
+func TestUnmarshalling(t *testing.T) {
+ SetConfigType("yaml")
+ r := bytes.NewReader(yamlExample)
+
+ unmarshalReader(r, v.config)
+ assert.True(t, InConfig("name"))
+ assert.False(t, InConfig("state"))
+ assert.Equal(t, "steve", Get("name"))
+ assert.Equal(t, []interface{}{"skateboarding", "snowboarding", "go"}, Get("hobbies"))
+ assert.Equal(t, map[string]interface{}{"jacket": "leather", "trousers": "denim", "pants": map[string]interface{}{"size": "large"}}, Get("clothing"))
+ assert.Equal(t, 35, Get("age"))
+}
+
+func TestUnmarshalExact(t *testing.T) {
+ vip := New()
+ target := &testUnmarshalExtra{}
+ vip.SetConfigType("yaml")
+ r := bytes.NewReader(yamlExampleWithExtras)
+ vip.ReadConfig(r)
+ err := vip.UnmarshalExact(target)
+ if err == nil {
+ t.Fatal("UnmarshalExact should error when populating a struct from a conf that contains unused fields")
+ }
+}
+
+func TestOverrides(t *testing.T) {
+ Set("age", 40)
+ assert.Equal(t, 40, Get("age"))
+}
+
+func TestDefaultPost(t *testing.T) {
+ assert.NotEqual(t, "NYC", Get("state"))
+ SetDefault("state", "NYC")
+ assert.Equal(t, "NYC", Get("state"))
+}
+
+func TestAliases(t *testing.T) {
+ RegisterAlias("years", "age")
+ assert.Equal(t, 40, Get("years"))
+ Set("years", 45)
+ assert.Equal(t, 45, Get("age"))
+}
+
+func TestAliasInConfigFile(t *testing.T) {
+ // the config file specifies "beard". If we make this an alias for
+ // "hasbeard", we still want the old config file to work with beard.
+ RegisterAlias("beard", "hasbeard")
+ assert.Equal(t, true, Get("hasbeard"))
+ Set("hasbeard", false)
+ assert.Equal(t, false, Get("beard"))
+}
+
+func TestYML(t *testing.T) {
+ initYAML()
+ assert.Equal(t, "steve", Get("name"))
+}
+
+func TestJSON(t *testing.T) {
+ initJSON()
+ assert.Equal(t, "0001", Get("id"))
+}
+
+func TestProperties(t *testing.T) {
+ initProperties()
+ assert.Equal(t, "0001", Get("p_id"))
+}
+
+func TestTOML(t *testing.T) {
+ initTOML()
+ assert.Equal(t, "TOML Example", Get("title"))
+}
+
+func TestHCL(t *testing.T) {
+ initHcl()
+ assert.Equal(t, "0001", Get("id"))
+ assert.Equal(t, 0.55, Get("ppu"))
+ assert.Equal(t, "donut", Get("type"))
+ assert.Equal(t, "Cake", Get("name"))
+ Set("id", "0002")
+ assert.Equal(t, "0002", Get("id"))
+ assert.NotEqual(t, "cronut", Get("type"))
+}
+
+func TestRemotePrecedence(t *testing.T) {
+ initJSON()
+
+ remote := bytes.NewReader(remoteExample)
+ assert.Equal(t, "0001", Get("id"))
+ unmarshalReader(remote, v.kvstore)
+ assert.Equal(t, "0001", Get("id"))
+ assert.NotEqual(t, "cronut", Get("type"))
+ assert.Equal(t, "remote", Get("newkey"))
+ Set("newkey", "newvalue")
+ assert.NotEqual(t, "remote", Get("newkey"))
+ assert.Equal(t, "newvalue", Get("newkey"))
+ Set("newkey", "remote")
+}
+
+func TestEnv(t *testing.T) {
+ initJSON()
+
+ BindEnv("id")
+ BindEnv("f", "FOOD")
+
+ os.Setenv("ID", "13")
+ os.Setenv("FOOD", "apple")
+ os.Setenv("NAME", "crunk")
+
+ assert.Equal(t, "13", Get("id"))
+ assert.Equal(t, "apple", Get("f"))
+ assert.Equal(t, "Cake", Get("name"))
+
+ AutomaticEnv()
+
+ assert.Equal(t, "crunk", Get("name"))
+
+}
+
+func TestEnvPrefix(t *testing.T) {
+ initJSON()
+
+ SetEnvPrefix("foo") // will be uppercased automatically
+ BindEnv("id")
+ BindEnv("f", "FOOD") // not using prefix
+
+ os.Setenv("FOO_ID", "13")
+ os.Setenv("FOOD", "apple")
+ os.Setenv("FOO_NAME", "crunk")
+
+ assert.Equal(t, "13", Get("id"))
+ assert.Equal(t, "apple", Get("f"))
+ assert.Equal(t, "Cake", Get("name"))
+
+ AutomaticEnv()
+
+ assert.Equal(t, "crunk", Get("name"))
+}
+
+func TestAutoEnv(t *testing.T) {
+ Reset()
+
+ AutomaticEnv()
+ os.Setenv("FOO_BAR", "13")
+ assert.Equal(t, "13", Get("foo_bar"))
+}
+
+func TestAutoEnvWithPrefix(t *testing.T) {
+ Reset()
+
+ AutomaticEnv()
+ SetEnvPrefix("Baz")
+ os.Setenv("BAZ_BAR", "13")
+ assert.Equal(t, "13", Get("bar"))
+}
+
+func TestSetEnvReplacer(t *testing.T) {
+ Reset()
+
+ AutomaticEnv()
+ os.Setenv("REFRESH_INTERVAL", "30s")
+
+ replacer := strings.NewReplacer("-", "_")
+ SetEnvKeyReplacer(replacer)
+
+ assert.Equal(t, "30s", Get("refresh-interval"))
+}
+
+func TestAllKeys(t *testing.T) {
+ initConfigs()
+
+ ks := sort.StringSlice{"title", "newkey", "owner.organization", "owner.dob", "owner.bio", "name", "beard", "ppu", "batters.batter", "hobbies", "clothing.jacket", "clothing.trousers", "clothing.pants.size", "age", "hacker", "id", "type", "eyes", "p_id", "p_ppu", "p_batters.batter.type", "p_type", "p_name", "foos"}
+ dob, _ := time.Parse(time.RFC3339, "1979-05-27T07:32:00Z")
+ all := map[string]interface{}{"owner": map[string]interface{}{"organization": "MongoDB", "bio": "MongoDB Chief Developer Advocate & Hacker at Large", "dob": dob}, "title": "TOML Example", "ppu": 0.55, "eyes": "brown", "clothing": map[string]interface{}{"trousers": "denim", "jacket": "leather", "pants": map[string]interface{}{"size": "large"}}, "id": "0001", "batters": map[string]interface{}{"batter": []interface{}{map[string]interface{}{"type": "Regular"}, map[string]interface{}{"type": "Chocolate"}, map[string]interface{}{"type": "Blueberry"}, map[string]interface{}{"type": "Devil's Food"}}}, "hacker": true, "beard": true, "hobbies": []interface{}{"skateboarding", "snowboarding", "go"}, "age": 35, "type": "donut", "newkey": "remote", "name": "Cake", "p_id": "0001", "p_ppu": "0.55", "p_name": "Cake", "p_batters": map[string]interface{}{"batter": map[string]interface{}{"type": "Regular"}}, "p_type": "donut", "foos": []map[string]interface{}{map[string]interface{}{"foo": []map[string]interface{}{map[string]interface{}{"key": 1}, map[string]interface{}{"key": 2}, map[string]interface{}{"key": 3}, map[string]interface{}{"key": 4}}}}}
+
+ var allkeys sort.StringSlice
+ allkeys = AllKeys()
+ allkeys.Sort()
+ ks.Sort()
+
+ assert.Equal(t, ks, allkeys)
+ assert.Equal(t, all, AllSettings())
+}
+
+func TestAllKeysWithEnv(t *testing.T) {
+ v := New()
+
+ // bind and define environment variables (including a nested one)
+ v.BindEnv("id")
+ v.BindEnv("foo.bar")
+ v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
+ os.Setenv("ID", "13")
+ os.Setenv("FOO_BAR", "baz")
+
+ expectedKeys := sort.StringSlice{"id", "foo.bar"}
+ expectedKeys.Sort()
+ keys := sort.StringSlice(v.AllKeys())
+ keys.Sort()
+ assert.Equal(t, expectedKeys, keys)
+}
+
+func TestAliasesOfAliases(t *testing.T) {
+ Set("Title", "Checking Case")
+ RegisterAlias("Foo", "Bar")
+ RegisterAlias("Bar", "Title")
+ assert.Equal(t, "Checking Case", Get("FOO"))
+}
+
+func TestRecursiveAliases(t *testing.T) {
+ RegisterAlias("Baz", "Roo")
+ RegisterAlias("Roo", "baz")
+}
+
+func TestUnmarshal(t *testing.T) {
+ SetDefault("port", 1313)
+ Set("name", "Steve")
+ Set("duration", "1s1ms")
+
+ type config struct {
+ Port int
+ Name string
+ Duration time.Duration
+ }
+
+ var C config
+
+ err := Unmarshal(&C)
+ if err != nil {
+ t.Fatalf("unable to decode into struct, %v", err)
+ }
+
+ assert.Equal(t, &config{Name: "Steve", Port: 1313, Duration: time.Second + time.Millisecond}, &C)
+
+ Set("port", 1234)
+ err = Unmarshal(&C)
+ if err != nil {
+ t.Fatalf("unable to decode into struct, %v", err)
+ }
+ assert.Equal(t, &config{Name: "Steve", Port: 1234, Duration: time.Second + time.Millisecond}, &C)
+}
+
+func TestBindPFlags(t *testing.T) {
+ v := New() // create independent Viper object
+ flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
+
+ var testValues = map[string]*string{
+ "host": nil,
+ "port": nil,
+ "endpoint": nil,
+ }
+
+ var mutatedTestValues = map[string]string{
+ "host": "localhost",
+ "port": "6060",
+ "endpoint": "/public",
+ }
+
+ for name := range testValues {
+ testValues[name] = flagSet.String(name, "", "test")
+ }
+
+ err := v.BindPFlags(flagSet)
+ if err != nil {
+ t.Fatalf("error binding flag set, %v", err)
+ }
+
+ flagSet.VisitAll(func(flag *pflag.Flag) {
+ flag.Value.Set(mutatedTestValues[flag.Name])
+ flag.Changed = true
+ })
+
+ for name, expected := range mutatedTestValues {
+ assert.Equal(t, expected, v.Get(name))
+ }
+
+}
+
+func TestBindPFlag(t *testing.T) {
+ var testString = "testing"
+ var testValue = newStringValue(testString, &testString)
+
+ flag := &pflag.Flag{
+ Name: "testflag",
+ Value: testValue,
+ Changed: false,
+ }
+
+ BindPFlag("testvalue", flag)
+
+ assert.Equal(t, testString, Get("testvalue"))
+
+ flag.Value.Set("testing_mutate")
+ flag.Changed = true //hack for pflag usage
+
+ assert.Equal(t, "testing_mutate", Get("testvalue"))
+
+}
+
+func TestBoundCaseSensitivity(t *testing.T) {
+ assert.Equal(t, "brown", Get("eyes"))
+
+ BindEnv("eYEs", "TURTLE_EYES")
+ os.Setenv("TURTLE_EYES", "blue")
+
+ assert.Equal(t, "blue", Get("eyes"))
+
+ var testString = "green"
+ var testValue = newStringValue(testString, &testString)
+
+ flag := &pflag.Flag{
+ Name: "eyeballs",
+ Value: testValue,
+ Changed: true,
+ }
+
+ BindPFlag("eYEs", flag)
+ assert.Equal(t, "green", Get("eyes"))
+
+}
+
+func TestSizeInBytes(t *testing.T) {
+ input := map[string]uint{
+ "": 0,
+ "b": 0,
+ "12 bytes": 0,
+ "200000000000gb": 0,
+ "12 b": 12,
+ "43 MB": 43 * (1 << 20),
+ "10mb": 10 * (1 << 20),
+ "1gb": 1 << 30,
+ }
+
+ for str, expected := range input {
+ assert.Equal(t, expected, parseSizeInBytes(str), str)
+ }
+}
+
+func TestFindsNestedKeys(t *testing.T) {
+ initConfigs()
+ dob, _ := time.Parse(time.RFC3339, "1979-05-27T07:32:00Z")
+
+ Set("super", map[string]interface{}{
+ "deep": map[string]interface{}{
+ "nested": "value",
+ },
+ })
+
+ expected := map[string]interface{}{
+ "super": map[string]interface{}{
+ "deep": map[string]interface{}{
+ "nested": "value",
+ },
+ },
+ "super.deep": map[string]interface{}{
+ "nested": "value",
+ },
+ "super.deep.nested": "value",
+ "owner.organization": "MongoDB",
+ "batters.batter": []interface{}{
+ map[string]interface{}{
+ "type": "Regular",
+ },
+ map[string]interface{}{
+ "type": "Chocolate",
+ },
+ map[string]interface{}{
+ "type": "Blueberry",
+ },
+ map[string]interface{}{
+ "type": "Devil's Food",
+ },
+ },
+ "hobbies": []interface{}{
+ "skateboarding", "snowboarding", "go",
+ },
+ "title": "TOML Example",
+ "newkey": "remote",
+ "batters": map[string]interface{}{
+ "batter": []interface{}{
+ map[string]interface{}{
+ "type": "Regular",
+ },
+ map[string]interface{}{
+ "type": "Chocolate",
+ }, map[string]interface{}{
+ "type": "Blueberry",
+ }, map[string]interface{}{
+ "type": "Devil's Food",
+ },
+ },
+ },
+ "eyes": "brown",
+ "age": 35,
+ "owner": map[string]interface{}{
+ "organization": "MongoDB",
+ "bio": "MongoDB Chief Developer Advocate & Hacker at Large",
+ "dob": dob,
+ },
+ "owner.bio": "MongoDB Chief Developer Advocate & Hacker at Large",
+ "type": "donut",
+ "id": "0001",
+ "name": "Cake",
+ "hacker": true,
+ "ppu": 0.55,
+ "clothing": map[string]interface{}{
+ "jacket": "leather",
+ "trousers": "denim",
+ "pants": map[string]interface{}{
+ "size": "large",
+ },
+ },
+ "clothing.jacket": "leather",
+ "clothing.pants.size": "large",
+ "clothing.trousers": "denim",
+ "owner.dob": dob,
+ "beard": true,
+ "foos": []map[string]interface{}{
+ map[string]interface{}{
+ "foo": []map[string]interface{}{
+ map[string]interface{}{
+ "key": 1,
+ },
+ map[string]interface{}{
+ "key": 2,
+ },
+ map[string]interface{}{
+ "key": 3,
+ },
+ map[string]interface{}{
+ "key": 4,
+ },
+ },
+ },
+ },
+ }
+
+ for key, expectedValue := range expected {
+
+ assert.Equal(t, expectedValue, v.Get(key))
+ }
+
+}
+
+func TestReadBufConfig(t *testing.T) {
+ v := New()
+ v.SetConfigType("yaml")
+ v.ReadConfig(bytes.NewBuffer(yamlExample))
+ t.Log(v.AllKeys())
+
+ assert.True(t, v.InConfig("name"))
+ assert.False(t, v.InConfig("state"))
+ assert.Equal(t, "steve", v.Get("name"))
+ assert.Equal(t, []interface{}{"skateboarding", "snowboarding", "go"}, v.Get("hobbies"))
+ assert.Equal(t, map[string]interface{}{"jacket": "leather", "trousers": "denim", "pants": map[string]interface{}{"size": "large"}}, v.Get("clothing"))
+ assert.Equal(t, 35, v.Get("age"))
+}
+
+func TestIsSet(t *testing.T) {
+ v := New()
+ v.SetConfigType("yaml")
+ v.ReadConfig(bytes.NewBuffer(yamlExample))
+ assert.True(t, v.IsSet("clothing.jacket"))
+ assert.False(t, v.IsSet("clothing.jackets"))
+ assert.False(t, v.IsSet("helloworld"))
+ v.Set("helloworld", "fubar")
+ assert.True(t, v.IsSet("helloworld"))
+}
+
+func TestDirsSearch(t *testing.T) {
+
+ root, config, cleanup := initDirs(t)
+ defer cleanup()
+
+ v := New()
+ v.SetConfigName(config)
+ v.SetDefault(`key`, `default`)
+
+ entries, err := ioutil.ReadDir(root)
+ for _, e := range entries {
+ if e.IsDir() {
+ v.AddConfigPath(e.Name())
+ }
+ }
+
+ err = v.ReadInConfig()
+ assert.Nil(t, err)
+
+ assert.Equal(t, `value is `+path.Base(v.configPaths[0]), v.GetString(`key`))
+}
+
+func TestWrongDirsSearchNotFound(t *testing.T) {
+
+ _, config, cleanup := initDirs(t)
+ defer cleanup()
+
+ v := New()
+ v.SetConfigName(config)
+ v.SetDefault(`key`, `default`)
+
+ v.AddConfigPath(`whattayoutalkingbout`)
+ v.AddConfigPath(`thispathaintthere`)
+
+ err := v.ReadInConfig()
+ assert.Equal(t, reflect.TypeOf(ConfigFileNotFoundError{"", ""}), reflect.TypeOf(err))
+
+ // Even though config did not load and the error might have
+ // been ignored by the client, the default still loads
+ assert.Equal(t, `default`, v.GetString(`key`))
+}
+
+func TestWrongDirsSearchNotFoundForMerge(t *testing.T) {
+
+ _, config, cleanup := initDirs(t)
+ defer cleanup()
+
+ v := New()
+ v.SetConfigName(config)
+ v.SetDefault(`key`, `default`)
+
+ v.AddConfigPath(`whattayoutalkingbout`)
+ v.AddConfigPath(`thispathaintthere`)
+
+ err := v.MergeInConfig()
+ assert.Equal(t, reflect.TypeOf(ConfigFileNotFoundError{"", ""}), reflect.TypeOf(err))
+
+ // Even though config did not load and the error might have
+ // been ignored by the client, the default still loads
+ assert.Equal(t, `default`, v.GetString(`key`))
+}
+
+func TestSub(t *testing.T) {
+ v := New()
+ v.SetConfigType("yaml")
+ v.ReadConfig(bytes.NewBuffer(yamlExample))
+
+ subv := v.Sub("clothing")
+ assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("pants.size"))
+
+ subv = v.Sub("clothing.pants")
+ assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("size"))
+
+ subv = v.Sub("clothing.pants.size")
+ assert.Equal(t, (*Viper)(nil), subv)
+
+ subv = v.Sub("missing.key")
+ assert.Equal(t, (*Viper)(nil), subv)
+}
+
+var yamlMergeExampleTgt = []byte(`
+hello:
+ pop: 37890
+ lagrenum: 765432101234567
+ world:
+ - us
+ - uk
+ - fr
+ - de
+`)
+
+var yamlMergeExampleSrc = []byte(`
+hello:
+ pop: 45000
+ lagrenum: 7654321001234567
+ universe:
+ - mw
+ - ad
+fu: bar
+`)
+
+func TestMergeConfig(t *testing.T) {
+ v := New()
+ v.SetConfigType("yml")
+ if err := v.ReadConfig(bytes.NewBuffer(yamlMergeExampleTgt)); err != nil {
+ t.Fatal(err)
+ }
+
+ if pop := v.GetInt("hello.pop"); pop != 37890 {
+ t.Fatalf("pop != 37890, = %d", pop)
+ }
+
+ if pop := v.GetInt("hello.lagrenum"); pop != 765432101234567 {
+ t.Fatalf("lagrenum != 765432101234567, = %d", pop)
+ }
+
+ if pop := v.GetInt64("hello.lagrenum"); pop != int64(765432101234567) {
+ t.Fatalf("int64 lagrenum != 765432101234567, = %d", pop)
+ }
+
+ if world := v.GetStringSlice("hello.world"); len(world) != 4 {
+ t.Fatalf("len(world) != 4, = %d", len(world))
+ }
+
+ if fu := v.GetString("fu"); fu != "" {
+ t.Fatalf("fu != \"\", = %s", fu)
+ }
+
+ if err := v.MergeConfig(bytes.NewBuffer(yamlMergeExampleSrc)); err != nil {
+ t.Fatal(err)
+ }
+
+ if pop := v.GetInt("hello.pop"); pop != 45000 {
+ t.Fatalf("pop != 45000, = %d", pop)
+ }
+
+ if pop := v.GetInt("hello.lagrenum"); pop != 7654321001234567 {
+ t.Fatalf("lagrenum != 7654321001234567, = %d", pop)
+ }
+
+ if pop := v.GetInt64("hello.lagrenum"); pop != int64(7654321001234567) {
+ t.Fatalf("int64 lagrenum != 7654321001234567, = %d", pop)
+ }
+
+ if world := v.GetStringSlice("hello.world"); len(world) != 4 {
+ t.Fatalf("len(world) != 4, = %d", len(world))
+ }
+
+ if universe := v.GetStringSlice("hello.universe"); len(universe) != 2 {
+ t.Fatalf("len(universe) != 2, = %d", len(universe))
+ }
+
+ if fu := v.GetString("fu"); fu != "bar" {
+ t.Fatalf("fu != \"bar\", = %s", fu)
+ }
+}
+
+func TestMergeConfigNoMerge(t *testing.T) {
+ v := New()
+ v.SetConfigType("yml")
+ if err := v.ReadConfig(bytes.NewBuffer(yamlMergeExampleTgt)); err != nil {
+ t.Fatal(err)
+ }
+
+ if pop := v.GetInt("hello.pop"); pop != 37890 {
+ t.Fatalf("pop != 37890, = %d", pop)
+ }
+
+ if world := v.GetStringSlice("hello.world"); len(world) != 4 {
+ t.Fatalf("len(world) != 4, = %d", len(world))
+ }
+
+ if fu := v.GetString("fu"); fu != "" {
+ t.Fatalf("fu != \"\", = %s", fu)
+ }
+
+ if err := v.ReadConfig(bytes.NewBuffer(yamlMergeExampleSrc)); err != nil {
+ t.Fatal(err)
+ }
+
+ if pop := v.GetInt("hello.pop"); pop != 45000 {
+ t.Fatalf("pop != 45000, = %d", pop)
+ }
+
+ if world := v.GetStringSlice("hello.world"); len(world) != 0 {
+ t.Fatalf("len(world) != 0, = %d", len(world))
+ }
+
+ if universe := v.GetStringSlice("hello.universe"); len(universe) != 2 {
+ t.Fatalf("len(universe) != 2, = %d", len(universe))
+ }
+
+ if fu := v.GetString("fu"); fu != "bar" {
+ t.Fatalf("fu != \"bar\", = %s", fu)
+ }
+}
+
+func TestUnmarshalingWithAliases(t *testing.T) {
+ v := New()
+ v.SetDefault("ID", 1)
+ v.Set("name", "Steve")
+ v.Set("lastname", "Owen")
+
+ v.RegisterAlias("UserID", "ID")
+ v.RegisterAlias("Firstname", "name")
+ v.RegisterAlias("Surname", "lastname")
+
+ type config struct {
+ ID int
+ FirstName string
+ Surname string
+ }
+
+ var C config
+ err := v.Unmarshal(&C)
+ if err != nil {
+ t.Fatalf("unable to decode into struct, %v", err)
+ }
+
+ assert.Equal(t, &config{ID: 1, FirstName: "Steve", Surname: "Owen"}, &C)
+}
+
+func TestSetConfigNameClearsFileCache(t *testing.T) {
+ SetConfigFile("/tmp/config.yaml")
+ SetConfigName("default")
+ f, err := v.getConfigFile()
+ if err == nil {
+ t.Fatalf("config file cache should have been cleared")
+ }
+ assert.Empty(t, f)
+}
+
+func TestShadowedNestedValue(t *testing.T) {
+
+ config := `name: steve
+clothing:
+ jacket: leather
+ trousers: denim
+ pants:
+ size: large
+`
+ initConfig("yaml", config)
+
+ assert.Equal(t, "steve", GetString("name"))
+
+ polyester := "polyester"
+ SetDefault("clothing.shirt", polyester)
+ SetDefault("clothing.jacket.price", 100)
+
+ assert.Equal(t, "leather", GetString("clothing.jacket"))
+ assert.Nil(t, Get("clothing.jacket.price"))
+ assert.Equal(t, polyester, GetString("clothing.shirt"))
+
+ clothingSettings := AllSettings()["clothing"].(map[string]interface{})
+ assert.Equal(t, "leather", clothingSettings["jacket"])
+ assert.Equal(t, polyester, clothingSettings["shirt"])
+}
+
+func TestDotParameter(t *testing.T) {
+ initJSON()
+ // shoud take precedence over batters defined in jsonExample
+ r := bytes.NewReader([]byte(`{ "batters.batter": [ { "type": "Small" } ] }`))
+ unmarshalReader(r, v.config)
+
+ actual := Get("batters.batter")
+ expected := []interface{}{map[string]interface{}{"type": "Small"}}
+ assert.Equal(t, expected, actual)
+}
+
+func TestCaseInsensitive(t *testing.T) {
+ for _, config := range []struct {
+ typ string
+ content string
+ }{
+ {"yaml", `
+aBcD: 1
+eF:
+ gH: 2
+ iJk: 3
+ Lm:
+ nO: 4
+ P:
+ Q: 5
+ R: 6
+`},
+ {"json", `{
+ "aBcD": 1,
+ "eF": {
+ "iJk": 3,
+ "Lm": {
+ "P": {
+ "Q": 5,
+ "R": 6
+ },
+ "nO": 4
+ },
+ "gH": 2
+ }
+}`},
+ {"toml", `aBcD = 1
+[eF]
+gH = 2
+iJk = 3
+[eF.Lm]
+nO = 4
+[eF.Lm.P]
+Q = 5
+R = 6
+`},
+ } {
+ doTestCaseInsensitive(t, config.typ, config.content)
+ }
+}
+
+func TestCaseInsensitiveSet(t *testing.T) {
+ Reset()
+ m1 := map[string]interface{}{
+ "Foo": 32,
+ "Bar": map[interface{}]interface {
+ }{
+ "ABc": "A",
+ "cDE": "B"},
+ }
+
+ m2 := map[string]interface{}{
+ "Foo": 52,
+ "Bar": map[interface{}]interface {
+ }{
+ "bCd": "A",
+ "eFG": "B"},
+ }
+
+ Set("Given1", m1)
+ Set("Number1", 42)
+
+ SetDefault("Given2", m2)
+ SetDefault("Number2", 52)
+
+ // Verify SetDefault
+ if v := Get("number2"); v != 52 {
+ t.Fatalf("Expected 52 got %q", v)
+ }
+
+ if v := Get("given2.foo"); v != 52 {
+ t.Fatalf("Expected 52 got %q", v)
+ }
+
+ if v := Get("given2.bar.bcd"); v != "A" {
+ t.Fatalf("Expected A got %q", v)
+ }
+
+ if _, ok := m2["Foo"]; !ok {
+ t.Fatal("Input map changed")
+ }
+
+ // Verify Set
+ if v := Get("number1"); v != 42 {
+ t.Fatalf("Expected 42 got %q", v)
+ }
+
+ if v := Get("given1.foo"); v != 32 {
+ t.Fatalf("Expected 32 got %q", v)
+ }
+
+ if v := Get("given1.bar.abc"); v != "A" {
+ t.Fatalf("Expected A got %q", v)
+ }
+
+ if _, ok := m1["Foo"]; !ok {
+ t.Fatal("Input map changed")
+ }
+}
+
+func doTestCaseInsensitive(t *testing.T, typ, config string) {
+ initConfig(typ, config)
+ Set("RfD", true)
+ assert.Equal(t, true, Get("rfd"))
+ assert.Equal(t, true, Get("rFD"))
+ assert.Equal(t, 1, cast.ToInt(Get("abcd")))
+ assert.Equal(t, 1, cast.ToInt(Get("Abcd")))
+ assert.Equal(t, 2, cast.ToInt(Get("ef.gh")))
+ assert.Equal(t, 3, cast.ToInt(Get("ef.ijk")))
+ assert.Equal(t, 4, cast.ToInt(Get("ef.lm.no")))
+ assert.Equal(t, 5, cast.ToInt(Get("ef.lm.p.q")))
+
+}
+
+func BenchmarkGetBool(b *testing.B) {
+ key := "BenchmarkGetBool"
+ v = New()
+ v.Set(key, true)
+
+ for i := 0; i < b.N; i++ {
+ if !v.GetBool(key) {
+ b.Fatal("GetBool returned false")
+ }
+ }
+}
+
+func BenchmarkGet(b *testing.B) {
+ key := "BenchmarkGet"
+ v = New()
+ v.Set(key, true)
+
+ for i := 0; i < b.N; i++ {
+ if !v.Get(key).(bool) {
+ b.Fatal("Get returned false")
+ }
+ }
+}
+
+// This is the "perfect result" for the above.
+func BenchmarkGetBoolFromMap(b *testing.B) {
+ m := make(map[string]bool)
+ key := "BenchmarkGetBool"
+ m[key] = true
+
+ for i := 0; i < b.N; i++ {
+ if !m[key] {
+ b.Fatal("Map value was false")
+ }
+ }
+}
diff --git a/vendor/github.com/xenolf/lego/acme/client.go b/vendor/github.com/xenolf/lego/acme/client.go
index ba56e796c..ee519f2e2 100644
--- a/vendor/github.com/xenolf/lego/acme/client.go
+++ b/vendor/github.com/xenolf/lego/acme/client.go
@@ -23,8 +23,15 @@ var (
Logger *log.Logger
)
-// maxBodySize is the maximum size of body that we will read.
-const maxBodySize = 1024 * 1024
+const (
+ // maxBodySize is the maximum size of body that we will read.
+ maxBodySize = 1024 * 1024
+
+ // overallRequestLimit is the overall number of request per second limited on the
+ // “new-reg”, “new-authz” and “new-cert” endpoints. From the documentation the
+ // limitation is 20 requests per second, but using 20 as value doesn't work but 18 do
+ overallRequestLimit = 18
+)
// logf writes a log entry. It uses Logger if not
// nil, otherwise it uses the default log.Logger.
@@ -522,7 +529,14 @@ func (c *Client) chooseSolvers(auth authorization, domain string) map[int]solver
func (c *Client) getChallenges(domains []string) ([]authorizationResource, map[string]error) {
resc, errc := make(chan authorizationResource), make(chan domainError)
+ var delay time.Duration
+ if len(domains) > overallRequestLimit {
+ delay = time.Second / overallRequestLimit
+ }
+
for _, domain := range domains {
+ time.Sleep(delay)
+
go func(domain string) {
authMsg := authorization{Resource: "new-authz", Identifier: identifier{Type: "dns", Value: domain}}
var authz authorization
diff --git a/vendor/github.com/xenolf/lego/acme/jws.go b/vendor/github.com/xenolf/lego/acme/jws.go
index 1b4d29d53..3b77cd491 100644
--- a/vendor/github.com/xenolf/lego/acme/jws.go
+++ b/vendor/github.com/xenolf/lego/acme/jws.go
@@ -41,7 +41,10 @@ func (j *jws) post(url string, content []byte) (*http.Response, error) {
}
resp, err := httpPost(url, "application/jose+json", bytes.NewBuffer([]byte(signedContent.FullSerialize())))
-
+ if err != nil {
+ return nil, fmt.Errorf("Failed to HTTP POST to %s -> %s", url, err.Error())
+ }
+
// Even in case of an error, the response should still contain a nonce.
nonce, nonceErr := getNonceFromResponse(resp)
if nonceErr == nil {
diff --git a/vendor/github.com/xenolf/lego/providers/dns/dnsimple/dnsimple.go b/vendor/github.com/xenolf/lego/providers/dns/dnsimple/dnsimple.go
index c903a35ce..155cacd25 100644
--- a/vendor/github.com/xenolf/lego/providers/dns/dnsimple/dnsimple.go
+++ b/vendor/github.com/xenolf/lego/providers/dns/dnsimple/dnsimple.go
@@ -5,9 +5,10 @@ package dnsimple
import (
"fmt"
"os"
+ "strconv"
"strings"
- "github.com/weppos/dnsimple-go/dnsimple"
+ "github.com/dnsimple/dnsimple-go/dnsimple"
"github.com/xenolf/lego/acme"
)
@@ -17,37 +18,50 @@ type DNSProvider struct {
}
// NewDNSProvider returns a DNSProvider instance configured for dnsimple.
-// Credentials must be passed in the environment variables: DNSIMPLE_EMAIL
-// and DNSIMPLE_API_KEY.
+// Credentials must be passed in the environment variables: DNSIMPLE_OAUTH_TOKEN.
+//
+// See: https://developer.dnsimple.com/v2/#authentication
func NewDNSProvider() (*DNSProvider, error) {
- email := os.Getenv("DNSIMPLE_EMAIL")
- key := os.Getenv("DNSIMPLE_API_KEY")
- return NewDNSProviderCredentials(email, key)
+ accessToken := os.Getenv("DNSIMPLE_OAUTH_TOKEN")
+ baseUrl := os.Getenv("DNSIMPLE_BASE_URL")
+
+ return NewDNSProviderCredentials(accessToken, baseUrl)
}
// NewDNSProviderCredentials uses the supplied credentials to return a
// DNSProvider instance configured for dnsimple.
-func NewDNSProviderCredentials(email, key string) (*DNSProvider, error) {
- if email == "" || key == "" {
- return nil, fmt.Errorf("DNSimple credentials missing")
+func NewDNSProviderCredentials(accessToken, baseUrl string) (*DNSProvider, error) {
+ if accessToken == "" {
+ return nil, fmt.Errorf("DNSimple OAuth token missing")
+ }
+
+ client := dnsimple.NewClient(dnsimple.NewOauthTokenCredentials(accessToken))
+ client.UserAgent = "lego"
+
+ if baseUrl != "" {
+ client.BaseURL = baseUrl
}
- return &DNSProvider{
- client: dnsimple.NewClient(key, email),
- }, nil
+ return &DNSProvider{client: client}, nil
}
// Present creates a TXT record to fulfil the dns-01 challenge.
func (c *DNSProvider) Present(domain, token, keyAuth string) error {
fqdn, value, ttl := acme.DNS01Record(domain, keyAuth)
- zoneID, zoneName, err := c.getHostedZone(domain)
+ zoneName, err := c.getHostedZone(domain)
+
+ if err != nil {
+ return err
+ }
+
+ accountID, err := c.getAccountID()
if err != nil {
return err
}
recordAttributes := c.newTxtRecord(zoneName, fqdn, value, ttl)
- _, _, err = c.client.Domains.CreateRecord(zoneID, *recordAttributes)
+ _, err = c.client.Zones.CreateRecord(accountID, zoneName, *recordAttributes)
if err != nil {
return fmt.Errorf("DNSimple API call failed: %v", err)
}
@@ -64,67 +78,79 @@ func (c *DNSProvider) CleanUp(domain, token, keyAuth string) error {
return err
}
+ accountID, err := c.getAccountID()
+ if err != nil {
+ return err
+ }
+
for _, rec := range records {
- _, err := c.client.Domains.DeleteRecord(rec.DomainId, rec.Id)
+ _, err := c.client.Zones.DeleteRecord(accountID, rec.ZoneID, rec.ID)
if err != nil {
return err
}
}
+
return nil
}
-func (c *DNSProvider) getHostedZone(domain string) (string, string, error) {
- zones, _, err := c.client.Domains.List()
+func (c *DNSProvider) getHostedZone(domain string) (string, error) {
+ authZone, err := acme.FindZoneByFqdn(acme.ToFqdn(domain), acme.RecursiveNameservers)
if err != nil {
- return "", "", fmt.Errorf("DNSimple API call failed: %v", err)
+ return "", err
}
- authZone, err := acme.FindZoneByFqdn(acme.ToFqdn(domain), acme.RecursiveNameservers)
+ accountID, err := c.getAccountID()
if err != nil {
- return "", "", err
+ return "", err
}
- var hostedZone dnsimple.Domain
- for _, zone := range zones {
- if zone.Name == acme.UnFqdn(authZone) {
+ zoneName := acme.UnFqdn(authZone)
+
+ zones, err := c.client.Zones.ListZones(accountID, &dnsimple.ZoneListOptions{NameLike: zoneName})
+ if err != nil {
+ return "", fmt.Errorf("DNSimple API call failed: %v", err)
+ }
+
+ var hostedZone dnsimple.Zone
+ for _, zone := range zones.Data {
+ if zone.Name == zoneName {
hostedZone = zone
}
}
- if hostedZone.Id == 0 {
- return "", "", fmt.Errorf("Zone %s not found in DNSimple for domain %s", authZone, domain)
+ if hostedZone.ID == 0 {
+ return "", fmt.Errorf("Zone %s not found in DNSimple for domain %s", authZone, domain)
}
- return fmt.Sprintf("%v", hostedZone.Id), hostedZone.Name, nil
+ return hostedZone.Name, nil
}
-func (c *DNSProvider) findTxtRecords(domain, fqdn string) ([]dnsimple.Record, error) {
- zoneID, zoneName, err := c.getHostedZone(domain)
+func (c *DNSProvider) findTxtRecords(domain, fqdn string) ([]dnsimple.ZoneRecord, error) {
+ zoneName, err := c.getHostedZone(domain)
if err != nil {
return nil, err
}
- var records []dnsimple.Record
- result, _, err := c.client.Domains.ListRecords(zoneID, "", "TXT")
+ accountID, err := c.getAccountID()
if err != nil {
- return records, fmt.Errorf("DNSimple API call has failed: %v", err)
+ return nil, err
}
recordName := c.extractRecordName(fqdn, zoneName)
- for _, record := range result {
- if record.Name == recordName {
- records = append(records, record)
- }
+
+ result, err := c.client.Zones.ListRecords(accountID, zoneName, &dnsimple.ZoneRecordListOptions{Name: recordName, Type: "TXT", ListOptions: dnsimple.ListOptions{}})
+ if err != nil {
+ return []dnsimple.ZoneRecord{}, fmt.Errorf("DNSimple API call has failed: %v", err)
}
- return records, nil
+ return result.Data, nil
}
-func (c *DNSProvider) newTxtRecord(zone, fqdn, value string, ttl int) *dnsimple.Record {
- name := c.extractRecordName(fqdn, zone)
+func (c *DNSProvider) newTxtRecord(zoneName, fqdn, value string, ttl int) *dnsimple.ZoneRecord {
+ name := c.extractRecordName(fqdn, zoneName)
- return &dnsimple.Record{
+ return &dnsimple.ZoneRecord{
Type: "TXT",
Name: name,
Content: value,
@@ -139,3 +165,16 @@ func (c *DNSProvider) extractRecordName(fqdn, domain string) string {
}
return name
}
+
+func (c *DNSProvider) getAccountID() (string, error) {
+ whoamiResponse, err := c.client.Identity.Whoami()
+ if err != nil {
+ return "", err
+ }
+
+ if whoamiResponse.Data.Account == nil {
+ return "", fmt.Errorf("DNSimple API returned empty account ID")
+ }
+
+ return strconv.Itoa(whoamiResponse.Data.Account.ID), nil
+}
diff --git a/vendor/github.com/xenolf/lego/providers/dns/dnsimple/dnsimple_test.go b/vendor/github.com/xenolf/lego/providers/dns/dnsimple/dnsimple_test.go
index 4926b3df9..ee65dd42b 100644
--- a/vendor/github.com/xenolf/lego/providers/dns/dnsimple/dnsimple_test.go
+++ b/vendor/github.com/xenolf/lego/providers/dns/dnsimple/dnsimple_test.go
@@ -9,61 +9,122 @@ import (
)
var (
- dnsimpleLiveTest bool
- dnsimpleEmail string
- dnsimpleAPIKey string
- dnsimpleDomain string
+ dnsimpleLiveTest bool
+ dnsimpleOauthToken string
+ dnsimpleDomain string
+ dnsimpleBaseUrl string
)
func init() {
- dnsimpleEmail = os.Getenv("DNSIMPLE_EMAIL")
- dnsimpleAPIKey = os.Getenv("DNSIMPLE_API_KEY")
+ dnsimpleOauthToken = os.Getenv("DNSIMPLE_OAUTH_TOKEN")
dnsimpleDomain = os.Getenv("DNSIMPLE_DOMAIN")
- if len(dnsimpleEmail) > 0 && len(dnsimpleAPIKey) > 0 && len(dnsimpleDomain) > 0 {
+ dnsimpleBaseUrl = "https://api.sandbox.dnsimple.com"
+
+ if len(dnsimpleOauthToken) > 0 && len(dnsimpleDomain) > 0 {
+ baseUrl := os.Getenv("DNSIMPLE_BASE_URL")
+
+ if baseUrl != "" {
+ dnsimpleBaseUrl = baseUrl
+ }
+
dnsimpleLiveTest = true
}
}
func restoreDNSimpleEnv() {
- os.Setenv("DNSIMPLE_EMAIL", dnsimpleEmail)
- os.Setenv("DNSIMPLE_API_KEY", dnsimpleAPIKey)
+ os.Setenv("DNSIMPLE_OAUTH_TOKEN", dnsimpleOauthToken)
+ os.Setenv("DNSIMPLE_BASE_URL", dnsimpleBaseUrl)
}
+//
+// NewDNSProvider
+//
+
func TestNewDNSProviderValid(t *testing.T) {
- os.Setenv("DNSIMPLE_EMAIL", "")
- os.Setenv("DNSIMPLE_API_KEY", "")
- _, err := NewDNSProviderCredentials("example@example.com", "123")
+ defer restoreDNSimpleEnv()
+
+ os.Setenv("DNSIMPLE_OAUTH_TOKEN", "123")
+ provider, err := NewDNSProvider()
+
+ assert.NotNil(t, provider)
+ assert.Equal(t, "lego", provider.client.UserAgent)
assert.NoError(t, err)
- restoreDNSimpleEnv()
}
-func TestNewDNSProviderValidEnv(t *testing.T) {
- os.Setenv("DNSIMPLE_EMAIL", "example@example.com")
- os.Setenv("DNSIMPLE_API_KEY", "123")
- _, err := NewDNSProvider()
+
+func TestNewDNSProviderValidWithBaseUrl(t *testing.T) {
+ defer restoreDNSimpleEnv()
+
+ os.Setenv("DNSIMPLE_OAUTH_TOKEN", "123")
+ os.Setenv("DNSIMPLE_BASE_URL", "https://api.dnsimple.test")
+ provider, err := NewDNSProvider()
+
+ assert.NotNil(t, provider)
assert.NoError(t, err)
- restoreDNSimpleEnv()
+
+ assert.Equal(t, provider.client.BaseURL, "https://api.dnsimple.test")
}
-func TestNewDNSProviderMissingCredErr(t *testing.T) {
- os.Setenv("DNSIMPLE_EMAIL", "")
- os.Setenv("DNSIMPLE_API_KEY", "")
- _, err := NewDNSProvider()
- assert.EqualError(t, err, "DNSimple credentials missing")
- restoreDNSimpleEnv()
+func TestNewDNSProviderInvalidWithMissingOauthToken(t *testing.T) {
+ if dnsimpleLiveTest {
+ t.Skip("skipping test in live mode")
+ }
+
+ defer restoreDNSimpleEnv()
+
+ provider, err := NewDNSProvider()
+
+ assert.Nil(t, provider)
+ assert.EqualError(t, err, "DNSimple OAuth token missing")
}
+//
+// NewDNSProviderCredentials
+//
+
+func TestNewDNSProviderCredentialsValid(t *testing.T) {
+ provider, err := NewDNSProviderCredentials("123", "")
+
+ assert.NotNil(t, provider)
+ assert.Equal(t, "lego", provider.client.UserAgent)
+ assert.NoError(t, err)
+}
+
+func TestNewDNSProviderCredentialsValidWithBaseUrl(t *testing.T) {
+ provider, err := NewDNSProviderCredentials("123", "https://api.dnsimple.test")
+
+ assert.NotNil(t, provider)
+ assert.NoError(t, err)
+
+ assert.Equal(t, provider.client.BaseURL, "https://api.dnsimple.test")
+}
+
+func TestNewDNSProviderCredentialsInvalidWithMissingOauthToken(t *testing.T) {
+ provider, err := NewDNSProviderCredentials("", "")
+
+ assert.Nil(t, provider)
+ assert.EqualError(t, err, "DNSimple OAuth token missing")
+}
+
+//
+// Present
+//
+
func TestLiveDNSimplePresent(t *testing.T) {
if !dnsimpleLiveTest {
t.Skip("skipping live test")
}
- provider, err := NewDNSProviderCredentials(dnsimpleEmail, dnsimpleAPIKey)
+ provider, err := NewDNSProviderCredentials(dnsimpleOauthToken, dnsimpleBaseUrl)
assert.NoError(t, err)
err = provider.Present(dnsimpleDomain, "", "123d==")
assert.NoError(t, err)
}
+//
+// Cleanup
+//
+
func TestLiveDNSimpleCleanUp(t *testing.T) {
if !dnsimpleLiveTest {
t.Skip("skipping live test")
@@ -71,7 +132,7 @@ func TestLiveDNSimpleCleanUp(t *testing.T) {
time.Sleep(time.Second * 1)
- provider, err := NewDNSProviderCredentials(dnsimpleEmail, dnsimpleAPIKey)
+ provider, err := NewDNSProviderCredentials(dnsimpleOauthToken, dnsimpleBaseUrl)
assert.NoError(t, err)
err = provider.CleanUp(dnsimpleDomain, "", "123d==")