From 364f8633f0793d3de823ecbbd49bffb73765255f Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Mon, 18 Jun 2018 00:38:05 +0000 Subject: [PATCH] start making files --- Tupfile.rules | 2 +- build.sh | 11 + cmd/land/process.go | 31 + cmd/land/process_test.go | 15 + cmd/land/stdout.go | 60 + cmd/land/stdout_test.go | 11 + go.mod | 2 + go.modverify | 2 + vendor/github.com/spf13/afero/.travis.yml | 21 + vendor/github.com/spf13/afero/LICENSE.txt | 174 + vendor/github.com/spf13/afero/README.md | 452 + vendor/github.com/spf13/afero/afero.go | 108 + vendor/github.com/spf13/afero/afero_test.go | 718 ++ vendor/github.com/spf13/afero/appveyor.yml | 15 + vendor/github.com/spf13/afero/basepath.go | 180 + .../github.com/spf13/afero/basepath_test.go | 190 + .../github.com/spf13/afero/cacheOnReadFs.go | 290 + .../github.com/spf13/afero/composite_test.go | 403 + vendor/github.com/spf13/afero/const_bsds.go | 22 + .../github.com/spf13/afero/const_win_unix.go | 25 + .../github.com/spf13/afero/copyOnWriteFs.go | 292 + .../spf13/afero/copyOnWriteFs_test.go | 40 + vendor/github.com/spf13/afero/httpFs.go | 110 + vendor/github.com/spf13/afero/ioutil.go | 230 + vendor/github.com/spf13/afero/ioutil_test.go | 112 + vendor/github.com/spf13/afero/lstater.go | 27 + vendor/github.com/spf13/afero/lstater_test.go | 102 + vendor/github.com/spf13/afero/match.go | 110 + vendor/github.com/spf13/afero/match_test.go | 183 + vendor/github.com/spf13/afero/mem/dir.go | 37 + vendor/github.com/spf13/afero/mem/dirmap.go | 43 + vendor/github.com/spf13/afero/mem/file.go | 317 + .../github.com/spf13/afero/mem/file_test.go | 154 + vendor/github.com/spf13/afero/memmap.go | 365 + vendor/github.com/spf13/afero/memmap_test.go | 451 + vendor/github.com/spf13/afero/os.go | 101 + vendor/github.com/spf13/afero/path.go | 106 + vendor/github.com/spf13/afero/path_test.go | 69 + vendor/github.com/spf13/afero/readonlyfs.go | 80 + vendor/github.com/spf13/afero/regexpfs.go | 214 + .../github.com/spf13/afero/ro_regexp_test.go | 96 + vendor/github.com/spf13/afero/unionFile.go | 305 + vendor/github.com/spf13/afero/util.go | 330 + vendor/github.com/spf13/afero/util_test.go | 450 + vendor/golang.org/x/text/internal/gen/code.go | 369 + vendor/golang.org/x/text/internal/gen/gen.go | 333 + .../x/text/internal/testtext/codesize.go | 53 + .../x/text/internal/testtext/flag.go | 22 + .../golang.org/x/text/internal/testtext/gc.go | 14 + .../x/text/internal/testtext/gccgo.go | 11 + .../x/text/internal/testtext/go1_6.go | 23 + .../x/text/internal/testtext/go1_7.go | 17 + .../x/text/internal/testtext/text.go | 105 + .../x/text/transform/examples_test.go | 37 + .../golang.org/x/text/transform/transform.go | 705 ++ .../x/text/transform/transform_test.go | 1317 +++ vendor/golang.org/x/text/unicode/cldr/base.go | 105 + vendor/golang.org/x/text/unicode/cldr/cldr.go | 130 + .../x/text/unicode/cldr/cldr_test.go | 27 + .../golang.org/x/text/unicode/cldr/collate.go | 359 + .../x/text/unicode/cldr/collate_test.go | 275 + .../x/text/unicode/cldr/data_test.go | 186 + .../golang.org/x/text/unicode/cldr/decode.go | 171 + .../x/text/unicode/cldr/examples_test.go | 21 + .../golang.org/x/text/unicode/cldr/makexml.go | 400 + .../golang.org/x/text/unicode/cldr/resolve.go | 602 ++ .../x/text/unicode/cldr/resolve_test.go | 368 + .../golang.org/x/text/unicode/cldr/slice.go | 144 + .../x/text/unicode/cldr/slice_test.go | 175 + vendor/golang.org/x/text/unicode/cldr/xml.go | 1494 ++++ .../x/text/unicode/norm/composition.go | 508 ++ .../x/text/unicode/norm/composition_test.go | 130 + .../x/text/unicode/norm/data10.0.0_test.go | 7424 ++++++++++++++++ .../x/text/unicode/norm/data9.0.0_test.go | 7409 ++++++++++++++++ .../x/text/unicode/norm/example_iter_test.go | 82 + .../x/text/unicode/norm/example_test.go | 27 + .../x/text/unicode/norm/forminfo.go | 259 + .../x/text/unicode/norm/forminfo_test.go | 54 + .../golang.org/x/text/unicode/norm/input.go | 109 + vendor/golang.org/x/text/unicode/norm/iter.go | 457 + .../x/text/unicode/norm/iter_test.go | 98 + .../x/text/unicode/norm/maketables.go | 976 +++ .../x/text/unicode/norm/normalize.go | 609 ++ .../x/text/unicode/norm/normalize_test.go | 1287 +++ .../x/text/unicode/norm/readwriter.go | 125 + .../x/text/unicode/norm/readwriter_test.go | 56 + .../x/text/unicode/norm/tables10.0.0.go | 7653 +++++++++++++++++ .../x/text/unicode/norm/tables9.0.0.go | 7633 ++++++++++++++++ .../x/text/unicode/norm/transform.go | 88 + .../x/text/unicode/norm/transform_test.go | 101 + vendor/golang.org/x/text/unicode/norm/trie.go | 54 + .../golang.org/x/text/unicode/norm/triegen.go | 117 + .../x/text/unicode/norm/ucd_test.go | 275 + vendor/vgo.list | 9 + 94 files changed, 50058 insertions(+), 1 deletion(-) create mode 100755 build.sh create mode 100644 cmd/land/stdout.go create mode 100644 cmd/land/stdout_test.go create mode 100644 vendor/github.com/spf13/afero/.travis.yml create mode 100644 vendor/github.com/spf13/afero/LICENSE.txt create mode 100644 vendor/github.com/spf13/afero/README.md create mode 100644 vendor/github.com/spf13/afero/afero.go create mode 100644 vendor/github.com/spf13/afero/afero_test.go create mode 100644 vendor/github.com/spf13/afero/appveyor.yml create mode 100644 vendor/github.com/spf13/afero/basepath.go create mode 100644 vendor/github.com/spf13/afero/basepath_test.go create mode 100644 vendor/github.com/spf13/afero/cacheOnReadFs.go create mode 100644 vendor/github.com/spf13/afero/composite_test.go create mode 100644 vendor/github.com/spf13/afero/const_bsds.go create mode 100644 vendor/github.com/spf13/afero/const_win_unix.go create mode 100644 vendor/github.com/spf13/afero/copyOnWriteFs.go create mode 100644 vendor/github.com/spf13/afero/copyOnWriteFs_test.go create mode 100644 vendor/github.com/spf13/afero/httpFs.go create mode 100644 vendor/github.com/spf13/afero/ioutil.go create mode 100644 vendor/github.com/spf13/afero/ioutil_test.go create mode 100644 vendor/github.com/spf13/afero/lstater.go create mode 100644 vendor/github.com/spf13/afero/lstater_test.go create mode 100644 vendor/github.com/spf13/afero/match.go create mode 100644 vendor/github.com/spf13/afero/match_test.go create mode 100644 vendor/github.com/spf13/afero/mem/dir.go create mode 100644 vendor/github.com/spf13/afero/mem/dirmap.go create mode 100644 vendor/github.com/spf13/afero/mem/file.go create mode 100644 vendor/github.com/spf13/afero/mem/file_test.go create mode 100644 vendor/github.com/spf13/afero/memmap.go create mode 100644 vendor/github.com/spf13/afero/memmap_test.go create mode 100644 vendor/github.com/spf13/afero/os.go create mode 100644 vendor/github.com/spf13/afero/path.go create mode 100644 vendor/github.com/spf13/afero/path_test.go create mode 100644 vendor/github.com/spf13/afero/readonlyfs.go create mode 100644 vendor/github.com/spf13/afero/regexpfs.go create mode 100644 vendor/github.com/spf13/afero/ro_regexp_test.go create mode 100644 vendor/github.com/spf13/afero/unionFile.go create mode 100644 vendor/github.com/spf13/afero/util.go create mode 100644 vendor/github.com/spf13/afero/util_test.go create mode 100644 vendor/golang.org/x/text/internal/gen/code.go create mode 100644 vendor/golang.org/x/text/internal/gen/gen.go create mode 100644 vendor/golang.org/x/text/internal/testtext/codesize.go create mode 100644 vendor/golang.org/x/text/internal/testtext/flag.go create mode 100644 vendor/golang.org/x/text/internal/testtext/gc.go create mode 100644 vendor/golang.org/x/text/internal/testtext/gccgo.go create mode 100644 vendor/golang.org/x/text/internal/testtext/go1_6.go create mode 100644 vendor/golang.org/x/text/internal/testtext/go1_7.go create mode 100644 vendor/golang.org/x/text/internal/testtext/text.go create mode 100644 vendor/golang.org/x/text/transform/examples_test.go create mode 100644 vendor/golang.org/x/text/transform/transform.go create mode 100644 vendor/golang.org/x/text/transform/transform_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/base.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/cldr.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/cldr_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/collate.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/collate_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/data_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/decode.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/examples_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/makexml.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/resolve.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/resolve_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/slice.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/slice_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/xml.go create mode 100644 vendor/golang.org/x/text/unicode/norm/composition.go create mode 100644 vendor/golang.org/x/text/unicode/norm/composition_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/data10.0.0_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/data9.0.0_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/example_iter_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/example_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo.go create mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/input.go create mode 100644 vendor/golang.org/x/text/unicode/norm/iter.go create mode 100644 vendor/golang.org/x/text/unicode/norm/iter_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/maketables.go create mode 100644 vendor/golang.org/x/text/unicode/norm/normalize.go create mode 100644 vendor/golang.org/x/text/unicode/norm/normalize_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter.go create mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/tables10.0.0.go create mode 100644 vendor/golang.org/x/text/unicode/norm/tables9.0.0.go create mode 100644 vendor/golang.org/x/text/unicode/norm/transform.go create mode 100644 vendor/golang.org/x/text/unicode/norm/transform_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/trie.go create mode 100644 vendor/golang.org/x/text/unicode/norm/triegen.go create mode 100644 vendor/golang.org/x/text/unicode/norm/ucd_test.go diff --git a/Tupfile.rules b/Tupfile.rules index 271061b..f38a2d0 100644 --- a/Tupfile.rules +++ b/Tupfile.rules @@ -1,3 +1,3 @@ .gitignore -: *_test.go |> go test -v -cover -race -o %o |> ./bin/%d.test +: *_test.go |> vgo test -v -cover -race -o %o |> ./bin/%d.test diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..c9905a9 --- /dev/null +++ b/build.sh @@ -0,0 +1,11 @@ +#! /bin/sh -e +cd "cmd/land" +vgo build -o ../../bin/land +cd "../../userland/src/lib" +node ../../compile.js counter.walt counter.wasm +node ../../compile.js memory.walt memory.wasm +wat2wasm -o add.wasm add.wast +wat2wasm -o env.wasm env.wast +wat2wasm -o hello.wasm hello.wast +cd "../../.." +go test -v ./cmd/land | tee bin/test.log diff --git a/cmd/land/process.go b/cmd/land/process.go index 69f6575..04406f6 100644 --- a/cmd/land/process.go +++ b/cmd/land/process.go @@ -11,6 +11,7 @@ import ( "github.com/go-interpreter/wagon/exec" "github.com/go-interpreter/wagon/validate" "github.com/go-interpreter/wagon/wasm" + "github.com/spf13/afero" ) // Process is a larger level wrapper around a webassembly VM that gives it @@ -19,6 +20,8 @@ type Process struct { id int32 vm *exec.VM mod *wasm.Module + fs afero.Fs + files []afero.File } // NewProcess constructs a new webassembly process based on the input webassembly module as a reader. @@ -115,6 +118,34 @@ func (p *Process) log(ptr int32, len int32) int32 { return 0 } +func (p *Process) writeMem(ptr int32, data []byte) (int, error) { + mem := p.vm.Memory() + if mem == nil { + return 0, errors.New("wtf") + } + + for i, d := range data { + mem[ptr+int32(i)] = d + } + + return len(data), nil +} + +func (p *Process) readMem(ptr int32) []byte { + var result []byte + + mem := p.vm.Memory()[ptr:] + for _, bt := range mem { + if bt == 0 { + return result + } + + result = append(result, bt) + } + + return result +} + func (p *Process) Main() (uint32, error) { foundMain := false mainID := uint32(0) diff --git a/cmd/land/process_test.go b/cmd/land/process_test.go index 98a3d0b..9466b3f 100644 --- a/cmd/land/process_test.go +++ b/cmd/land/process_test.go @@ -25,4 +25,19 @@ func TestHelloWorld(t *testing.T) { if ret != 0 { t.Fatalf("expected return code to be 0, got: %d", ret) } + + data := p.readMem(200) // should be "Hello" + if string(data) != "Hello" { + t.Fatalf("wanted \"Hello\", got: %q", string(data)) + } + + _, err = p.writeMem(200, []byte("goodbye")) + if err != nil { + t.Fatal(err) + } + + data = p.readMem(200) + if string(data) != "goodbye" { + t.Fatalf("wanted \"goodbye\", got: %q", string(data)) + } } diff --git a/cmd/land/stdout.go b/cmd/land/stdout.go new file mode 100644 index 0000000..c1e0aab --- /dev/null +++ b/cmd/land/stdout.go @@ -0,0 +1,60 @@ +package main + +import ( + "errors" + "io" + "os" +) + +var ( + ErrNotSupported = errors.New("land: not supported") +) + +type stdFD struct { + io.ReadWriteCloser + name string +} + +func (s stdFD) Close() error { + return nil +} + +func (s stdFD) Name() string { + return s.name +} + +func (s stdFD) ReadAt(p []byte, off int64) (int, error) { + return 0, ErrNotSupported +} + +func (s stdFD) WriteAt(p []byte, off int64) (int, error) { + return 0, ErrNotSupported +} + +func (s stdFD) Seek(offset int64, whence int) (int64, error) { + return 0, ErrNotSupported +} + +func (s stdFD) Readdir(count int) ([]os.FileInfo, error) { + return nil, ErrNotSupported +} + +func (s stdFD) Readdirnames(n int) ([]string, error) { + return nil, ErrNotSupported +} + +func (s stdFD) Stat() (os.FileInfo, error) { + return nil, ErrNotSupported +} + +func (s stdFD) Sync() error { + return ErrNotSupported +} + +func (s stdFD) Truncate(size int64) error { + return ErrNotSupported +} + +func (s stdFD) WriteString(st string) (int, error) { + return s.Write([]byte(st)) +} diff --git a/cmd/land/stdout_test.go b/cmd/land/stdout_test.go new file mode 100644 index 0000000..e9766e6 --- /dev/null +++ b/cmd/land/stdout_test.go @@ -0,0 +1,11 @@ +package main + +import ( + "testing" + + "github.com/spf13/afero" +) + +func TestStdFDIsAferoFile(t *testing.T) { + var _ afero.File = stdFD{} +} diff --git a/go.mod b/go.mod index cdf63a1..f172049 100644 --- a/go.mod +++ b/go.mod @@ -4,4 +4,6 @@ require ( github.com/Xe/ln v0.0.0-20180508032019-ae4f7456500d github.com/go-interpreter/wagon v0.0.0-20180520092357-d4bc452fd57e github.com/pkg/errors v0.8.0 + github.com/spf13/afero v1.1.1 + golang.org/x/text v0.3.0 ) diff --git a/go.modverify b/go.modverify index 2f41cba..a2d893c 100644 --- a/go.modverify +++ b/go.modverify @@ -1,3 +1,5 @@ github.com/Xe/ln v0.0.0-20180508032019-ae4f7456500d h1:dQgIfnQayXRfcxefFjA7rfL2hIouSrIEiOyB2hypQTw= github.com/go-interpreter/wagon v0.0.0-20180520092357-d4bc452fd57e h1:l4e38KpmR/OxRvJrZtqQ0yFwuGH8ta8ZZkOA+h5ovPg= github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= +github.com/spf13/afero v1.1.1 h1:Lt3ihYMlE+lreX1GS4Qw4ZsNpYQLxIXKBTEOXm3nt6I= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= diff --git a/vendor/github.com/spf13/afero/.travis.yml b/vendor/github.com/spf13/afero/.travis.yml new file mode 100644 index 0000000..0637db7 --- /dev/null +++ b/vendor/github.com/spf13/afero/.travis.yml @@ -0,0 +1,21 @@ +sudo: false +language: go + +go: + - 1.9 + - "1.10" + - tip + +os: + - linux + - osx + +matrix: + allow_failures: + - go: tip + fast_finish: true + +script: + - go build + - go test -race -v ./... + diff --git a/vendor/github.com/spf13/afero/LICENSE.txt b/vendor/github.com/spf13/afero/LICENSE.txt new file mode 100644 index 0000000..298f0e2 --- /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 0000000..0c9b04b --- /dev/null +++ b/vendor/github.com/spf13/afero/README.md @@ -0,0 +1,452 @@ +![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.NewMemMapFs() + +or + +var AppFs = 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: +```go +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.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() +fileserver := http.FileServer(httpFs.Dir())) +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 0000000..f5b5e12 --- /dev/null +++ b/vendor/github.com/spf13/afero/afero.go @@ -0,0 +1,108 @@ +// Copyright © 2014 Steve Francia . +// 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 0000000..e2c1362 --- /dev/null +++ b/vendor/github.com/spf13/afero/afero_test.go @@ -0,0 +1,718 @@ +// Copyright © 2014 Steve Francia . +// 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() + } + } +} + +// https://github.com/spf13/afero/issues/169 +func TestReaddirRegularFile(t *testing.T) { + defer removeAllTestFiles(t) + for _, fs := range Fss { + f := tmpFile(fs) + defer f.Close() + + _, err := f.Readdirnames(-1) + if err == nil { + t.Fatal("Expected error") + } + + _, err = f.Readdir(-1) + if err == nil { + t.Fatal("Expected error") + } + } +} + +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 0000000..a633ad5 --- /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 -race -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 0000000..616ff8f --- /dev/null +++ b/vendor/github.com/spf13/afero/basepath.go @@ -0,0 +1,180 @@ +package afero + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "time" +) + +var _ Lstater = (*BasePathFs)(nil) + +// 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 +} + +type BasePathFile struct { + File + path string +} + +func (f *BasePathFile) Name() string { + sourcename := f.File.Name() + return strings.TrimPrefix(sourcename, filepath.Clean(f.path)) +} + +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 name, 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.ErrNotExist + } + + 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} + } + sourcef, err := b.source.OpenFile(name, flag, mode) + if err != nil { + return nil, err + } + return &BasePathFile{sourcef, b.path}, nil +} + +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} + } + sourcef, err := b.source.Open(name) + if err != nil { + return nil, err + } + return &BasePathFile{File: sourcef, path: b.path}, nil +} + +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} + } + sourcef, err := b.source.Create(name) + if err != nil { + return nil, err + } + return &BasePathFile{File: sourcef, path: b.path}, nil +} + +func (b *BasePathFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { + name, err := b.RealPath(name) + if err != nil { + return nil, false, &os.PathError{Op: "lstat", Path: name, Err: err} + } + if lstater, ok := b.source.(Lstater); ok { + return lstater.LstatIfPossible(name) + } + fi, err := b.source.Stat(name) + return fi, false, err +} + +// 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 0000000..77aa7df --- /dev/null +++ b/vendor/github.com/spf13/afero/basepath_test.go @@ -0,0 +1,190 @@ +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 != os.ErrNotExist { + t.Errorf("Expected os.ErrNotExist") + } + + } 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) + } + } + } + } +} + +func TestBasePathOpenFile(t *testing.T) { + baseFs := &MemMapFs{} + baseFs.MkdirAll("/base/path/tmp", 0777) + bp := NewBasePathFs(baseFs, "/base/path") + f, err := bp.OpenFile("/tmp/file.txt", os.O_CREATE, 0600) + if err != nil { + t.Fatalf("failed to open file: %v", err) + } + if filepath.Dir(f.Name()) != filepath.Clean("/tmp") { + t.Fatalf("realpath leaked: %s", f.Name()) + } +} + +func TestBasePathCreate(t *testing.T) { + baseFs := &MemMapFs{} + baseFs.MkdirAll("/base/path/tmp", 0777) + bp := NewBasePathFs(baseFs, "/base/path") + f, err := bp.Create("/tmp/file.txt") + if err != nil { + t.Fatalf("failed to create file: %v", err) + } + if filepath.Dir(f.Name()) != filepath.Clean("/tmp") { + t.Fatalf("realpath leaked: %s", f.Name()) + } +} + +func TestBasePathTempFile(t *testing.T) { + baseFs := &MemMapFs{} + baseFs.MkdirAll("/base/path/tmp", 0777) + bp := NewBasePathFs(baseFs, "/base/path") + + tDir, err := TempDir(bp, "/tmp", "") + if err != nil { + t.Fatalf("Failed to TempDir: %v", err) + } + if filepath.Dir(tDir) != filepath.Clean("/tmp") { + t.Fatalf("Tempdir realpath leaked: %s", tDir) + } + tempFile, err := TempFile(bp, tDir, "") + if err != nil { + t.Fatalf("Failed to TempFile: %v", err) + } + defer tempFile.Close() + if expected, actual := tDir, filepath.Dir(tempFile.Name()); expected != actual { + t.Fatalf("TempFile realpath leaked: expected %s, got %s", expected, actual) + } +} diff --git a/vendor/github.com/spf13/afero/cacheOnReadFs.go b/vendor/github.com/spf13/afero/cacheOnReadFs.go new file mode 100644 index 0000000..29a26c6 --- /dev/null +++ b/vendor/github.com/spf13/afero/cacheOnReadFs.go @@ -0,0 +1,290 @@ +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 || os.IsNotExist(err) { + 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 0000000..2a20440 --- /dev/null +++ b/vendor/github.com/spf13/afero/composite_test.go @@ -0,0 +1,403 @@ +package afero + +import ( + "bytes" + "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) + } +} + +func TestCacheOnReadFsNotInLayer(t *testing.T) { + base := NewMemMapFs() + layer := NewMemMapFs() + fs := NewCacheOnReadFs(base, layer, 0) + + fh, err := base.Create("/file.txt") + if err != nil { + t.Fatal("unable to create file: ", err) + } + + txt := []byte("This is a test") + fh.Write(txt) + fh.Close() + + fh, err = fs.Open("/file.txt") + if err != nil { + t.Fatal("could not open file: ", err) + } + + b, err := ReadAll(fh) + fh.Close() + + if err != nil { + t.Fatal("could not read file: ", err) + } else if !bytes.Equal(txt, b) { + t.Fatalf("wanted file text %q, got %q", txt, b) + } + + fh, err = layer.Open("/file.txt") + if err != nil { + t.Fatal("could not open file from layer: ", err) + } + fh.Close() +} 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 0000000..5728243 --- /dev/null +++ b/vendor/github.com/spf13/afero/const_bsds.go @@ -0,0 +1,22 @@ +// Copyright © 2016 Steve Francia . +// +// 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 0000000..968fc27 --- /dev/null +++ b/vendor/github.com/spf13/afero/const_win_unix.go @@ -0,0 +1,25 @@ +// Copyright © 2016 Steve Francia . +// +// 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 0000000..9aef397 --- /dev/null +++ b/vendor/github.com/spf13/afero/copyOnWriteFs.go @@ -0,0 +1,292 @@ +package afero + +import ( + "fmt" + "os" + "path/filepath" + "syscall" + "time" +) + +var _ Lstater = (*CopyOnWriteFs)(nil) + +// 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 { + isNotExist := u.isNotExist(err) + if isNotExist { + return u.base.Stat(name) + } + return nil, err + } + return fi, nil +} + +func (u *CopyOnWriteFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { + llayer, ok1 := u.layer.(Lstater) + lbase, ok2 := u.base.(Lstater) + + if ok1 { + fi, b, err := llayer.LstatIfPossible(name) + if err == nil { + return fi, b, nil + } + + if !u.isNotExist(err) { + return nil, b, err + } + } + + if ok2 { + fi, b, err := lbase.LstatIfPossible(name) + if err == nil { + return fi, b, nil + } + if !u.isNotExist(err) { + return nil, b, err + } + } + + fi, err := u.Stat(name) + + return fi, false, err +} + +func (u *CopyOnWriteFs) isNotExist(err error) bool { + if e, ok := err.(*os.PathError); ok { + err = e.Err + } + if err == os.ErrNotExist || err == syscall.ENOENT || err == syscall.ENOTDIR { + return true + } + return false +} + +// 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 0000000..0f199dc --- /dev/null +++ b/vendor/github.com/spf13/afero/copyOnWriteFs_test.go @@ -0,0 +1,40 @@ +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 + } + +} + +func TestCopyOnWriteFileInMemMapBase(t *testing.T) { + base := &MemMapFs{} + layer := &MemMapFs{} + + if err := WriteFile(base, "base.txt", []byte("base"), 0755); err != nil { + t.Fatalf("Failed to write file: %s", err) + } + + ufs := NewCopyOnWriteFs(base, layer) + + _, err := ufs.Stat("base.txt") + if err != nil { + t.Fatal(err) + } +} diff --git a/vendor/github.com/spf13/afero/httpFs.go b/vendor/github.com/spf13/afero/httpFs.go new file mode 100644 index 0000000..c421936 --- /dev/null +++ b/vendor/github.com/spf13/afero/httpFs.go @@ -0,0 +1,110 @@ +// Copyright © 2014 Steve Francia . +// +// 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 0000000..5c3a3d8 --- /dev/null +++ b/vendor/github.com/spf13/afero/ioutil.go @@ -0,0 +1,230 @@ +// Copyright ©2015 The Go Authors +// Copyright ©2015 Steve Francia +// +// 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 0000000..e7c9f06 --- /dev/null +++ b/vendor/github.com/spf13/afero/ioutil_test.go @@ -0,0 +1,112 @@ +// ©2015 The Go Authors +// Copyright ©2015 Steve Francia +// +// 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/lstater.go b/vendor/github.com/spf13/afero/lstater.go new file mode 100644 index 0000000..89c1bfc --- /dev/null +++ b/vendor/github.com/spf13/afero/lstater.go @@ -0,0 +1,27 @@ +// Copyright © 2018 Steve Francia . +// +// 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" +) + +// Lstater is an optional interface in Afero. It is only implemented by the +// filesystems saying so. +// It will call Lstat if the filesystem iself is, or it delegates to, the os filesystem. +// Else it will call Stat. +// In addtion to the FileInfo, it will return a boolean telling whether Lstat was called or not. +type Lstater interface { + LstatIfPossible(name string) (os.FileInfo, bool, error) +} diff --git a/vendor/github.com/spf13/afero/lstater_test.go b/vendor/github.com/spf13/afero/lstater_test.go new file mode 100644 index 0000000..477924f --- /dev/null +++ b/vendor/github.com/spf13/afero/lstater_test.go @@ -0,0 +1,102 @@ +// Copyright ©2018 Steve Francia +// +// 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" + "testing" +) + +func TestLstatIfPossible(t *testing.T) { + wd, _ := os.Getwd() + defer func() { + os.Chdir(wd) + }() + + osFs := &OsFs{} + + workDir, err := TempDir(osFs, "", "afero-lstate") + if err != nil { + t.Fatal(err) + } + + defer func() { + osFs.RemoveAll(workDir) + }() + + memWorkDir := "/lstate" + + memFs := NewMemMapFs() + overlayFs1 := &CopyOnWriteFs{base: osFs, layer: memFs} + overlayFs2 := &CopyOnWriteFs{base: memFs, layer: osFs} + overlayFsMemOnly := &CopyOnWriteFs{base: memFs, layer: NewMemMapFs()} + basePathFs := &BasePathFs{source: osFs, path: workDir} + basePathFsMem := &BasePathFs{source: memFs, path: memWorkDir} + roFs := &ReadOnlyFs{source: osFs} + roFsMem := &ReadOnlyFs{source: memFs} + + pathFileMem := filepath.Join(memWorkDir, "aferom.txt") + + WriteFile(osFs, filepath.Join(workDir, "afero.txt"), []byte("Hi, Afero!"), 0777) + WriteFile(memFs, filepath.Join(pathFileMem), []byte("Hi, Afero!"), 0777) + + os.Chdir(workDir) + if err := os.Symlink("afero.txt", "symafero.txt"); err != nil { + t.Fatal(err) + } + + pathFile := filepath.Join(workDir, "afero.txt") + pathSymlink := filepath.Join(workDir, "symafero.txt") + + checkLstat := func(l Lstater, name string, shouldLstat bool) os.FileInfo { + statFile, isLstat, err := l.LstatIfPossible(name) + if err != nil { + t.Fatalf("Lstat check failed: %s", err) + } + if isLstat != shouldLstat { + t.Fatalf("Lstat status was %t for %s", isLstat, name) + } + return statFile + } + + testLstat := func(l Lstater, pathFile, pathSymlink string) { + shouldLstat := pathSymlink != "" + statRegular := checkLstat(l, pathFile, shouldLstat) + statSymlink := checkLstat(l, pathSymlink, shouldLstat) + if statRegular == nil || statSymlink == nil { + t.Fatal("got nil FileInfo") + } + + symSym := statSymlink.Mode()&os.ModeSymlink == os.ModeSymlink + if symSym == (pathSymlink == "") { + t.Fatal("expected the FileInfo to describe the symlink") + } + + _, _, err := l.LstatIfPossible("this-should-not-exist.txt") + if err == nil || !os.IsNotExist(err) { + t.Fatalf("expected file to not exist, got %s", err) + } + } + + testLstat(osFs, pathFile, pathSymlink) + testLstat(overlayFs1, pathFile, pathSymlink) + testLstat(overlayFs2, pathFile, pathSymlink) + testLstat(basePathFs, "afero.txt", "symafero.txt") + testLstat(overlayFsMemOnly, pathFileMem, "") + testLstat(basePathFsMem, "aferom.txt", "") + testLstat(roFs, pathFile, pathSymlink) + testLstat(roFsMem, pathFileMem, "") +} diff --git a/vendor/github.com/spf13/afero/match.go b/vendor/github.com/spf13/afero/match.go new file mode 100644 index 0000000..c18a87f --- /dev/null +++ b/vendor/github.com/spf13/afero/match.go @@ -0,0 +1,110 @@ +// Copyright © 2014 Steve Francia . +// 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 ( + "path/filepath" + "sort" + "strings" +) + +// Glob returns the names of all files matching pattern or nil +// if there is no matching file. The syntax of patterns is the same +// as in Match. The pattern may describe hierarchical names such as +// /usr/*/bin/ed (assuming the Separator is '/'). +// +// Glob ignores file system errors such as I/O errors reading directories. +// The only possible returned error is ErrBadPattern, when pattern +// is malformed. +// +// This was adapted from (http://golang.org/pkg/path/filepath) and uses several +// built-ins from that package. +func Glob(fs Fs, pattern string) (matches []string, err error) { + if !hasMeta(pattern) { + // Lstat not supported by a ll filesystems. + if _, err = lstatIfPossible(fs, pattern); err != nil { + return nil, nil + } + return []string{pattern}, nil + } + + dir, file := filepath.Split(pattern) + switch dir { + case "": + dir = "." + case string(filepath.Separator): + // nothing + default: + dir = dir[0 : len(dir)-1] // chop off trailing separator + } + + if !hasMeta(dir) { + return glob(fs, dir, file, nil) + } + + var m []string + m, err = Glob(fs, dir) + if err != nil { + return + } + for _, d := range m { + matches, err = glob(fs, d, file, matches) + if err != nil { + return + } + } + return +} + +// glob searches for files matching pattern in the directory dir +// and appends them to matches. If the directory cannot be +// opened, it returns the existing matches. New matches are +// added in lexicographical order. +func glob(fs Fs, dir, pattern string, matches []string) (m []string, e error) { + m = matches + fi, err := fs.Stat(dir) + if err != nil { + return + } + if !fi.IsDir() { + return + } + d, err := fs.Open(dir) + if err != nil { + return + } + defer d.Close() + + names, _ := d.Readdirnames(-1) + sort.Strings(names) + + for _, n := range names { + matched, err := filepath.Match(pattern, n) + if err != nil { + return m, err + } + if matched { + m = append(m, filepath.Join(dir, n)) + } + } + return +} + +// hasMeta reports whether path contains any of the magic characters +// recognized by Match. +func hasMeta(path string) bool { + // TODO(niemeyer): Should other magic characters be added here? + return strings.IndexAny(path, "*?[") >= 0 +} diff --git a/vendor/github.com/spf13/afero/match_test.go b/vendor/github.com/spf13/afero/match_test.go new file mode 100644 index 0000000..21e1fae --- /dev/null +++ b/vendor/github.com/spf13/afero/match_test.go @@ -0,0 +1,183 @@ +// Copyright © 2014 Steve Francia . +// 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 ( + "os" + "path/filepath" + "runtime" + "testing" +) + +// contains returns true if vector contains the string s. +func contains(vector []string, s string) bool { + for _, elem := range vector { + if elem == s { + return true + } + } + return false +} + +func setupGlobDirRoot(t *testing.T, fs Fs) string { + path := testDir(fs) + setupGlobFiles(t, fs, path) + return path +} + +func setupGlobDirReusePath(t *testing.T, fs Fs, path string) string { + testRegistry[fs] = append(testRegistry[fs], path) + return setupGlobFiles(t, fs, path) +} + +func setupGlobFiles(t *testing.T, fs Fs, path string) string { + testSubDir := filepath.Join(path, "globs", "bobs") + err := fs.MkdirAll(testSubDir, 0700) + if err != nil && !os.IsExist(err) { + t.Fatal(err) + } + + f, err := fs.Create(filepath.Join(testSubDir, "/matcher")) + if err != nil { + t.Fatal(err) + } + f.WriteString("Testfile 1 content") + f.Close() + + f, err = fs.Create(filepath.Join(testSubDir, "/../submatcher")) + if err != nil { + t.Fatal(err) + } + f.WriteString("Testfile 2 content") + f.Close() + + f, err = fs.Create(filepath.Join(testSubDir, "/../../match")) + if err != nil { + t.Fatal(err) + } + f.WriteString("Testfile 3 content") + f.Close() + + return testSubDir +} + +func TestGlob(t *testing.T) { + defer removeAllTestFiles(t) + var testDir string + for i, fs := range Fss { + if i == 0 { + testDir = setupGlobDirRoot(t, fs) + } else { + setupGlobDirReusePath(t, fs, testDir) + } + } + + var globTests = []struct { + pattern, result string + }{ + {testDir + "/globs/bobs/matcher", testDir + "/globs/bobs/matcher"}, + {testDir + "/globs/*/mat?her", testDir + "/globs/bobs/matcher"}, + {testDir + "/globs/bobs/../*", testDir + "/globs/submatcher"}, + {testDir + "/match", testDir + "/match"}, + } + + for _, fs := range Fss { + + for _, tt := range globTests { + pattern := tt.pattern + result := tt.result + if runtime.GOOS == "windows" { + pattern = filepath.Clean(pattern) + result = filepath.Clean(result) + } + matches, err := Glob(fs, pattern) + if err != nil { + t.Errorf("Glob error for %q: %s", pattern, err) + continue + } + if !contains(matches, result) { + t.Errorf("Glob(%#q) = %#v want %v", pattern, matches, result) + } + } + for _, pattern := range []string{"no_match", "../*/no_match"} { + matches, err := Glob(fs, pattern) + if err != nil { + t.Errorf("Glob error for %q: %s", pattern, err) + continue + } + if len(matches) != 0 { + t.Errorf("Glob(%#q) = %#v want []", pattern, matches) + } + } + + } +} + +func TestGlobSymlink(t *testing.T) { + defer removeAllTestFiles(t) + + fs := &OsFs{} + testDir := setupGlobDirRoot(t, fs) + + err := os.Symlink("target", filepath.Join(testDir, "symlink")) + if err != nil { + t.Skipf("skipping on %s", runtime.GOOS) + } + + var globSymlinkTests = []struct { + path, dest string + brokenLink bool + }{ + {"test1", "link1", false}, + {"test2", "link2", true}, + } + + for _, tt := range globSymlinkTests { + path := filepath.Join(testDir, tt.path) + dest := filepath.Join(testDir, tt.dest) + f, err := fs.Create(path) + if err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + err = os.Symlink(path, dest) + if err != nil { + t.Fatal(err) + } + if tt.brokenLink { + // Break the symlink. + fs.Remove(path) + } + matches, err := Glob(fs, dest) + if err != nil { + t.Errorf("GlobSymlink error for %q: %s", dest, err) + } + if !contains(matches, dest) { + t.Errorf("Glob(%#q) = %#v want %v", dest, matches, dest) + } + } +} + + +func TestGlobError(t *testing.T) { + for _, fs := range Fss { + _, err := Glob(fs, "[7]") + if err != nil { + t.Error("expected error for bad pattern; got none") + } + } +} 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 0000000..e104013 --- /dev/null +++ b/vendor/github.com/spf13/afero/mem/dir.go @@ -0,0 +1,37 @@ +// Copyright © 2014 Steve Francia . +// +// 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 0000000..03a57ee --- /dev/null +++ b/vendor/github.com/spf13/afero/mem/dirmap.go @@ -0,0 +1,43 @@ +// Copyright © 2015 Steve Francia . +// +// 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 0000000..7af2fb5 --- /dev/null +++ b/vendor/github.com/spf13/afero/mem/file.go @@ -0,0 +1,317 @@ +// Copyright © 2015 Steve Francia . +// 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.Lock() + f.name = newname + f.Unlock() +} + +func SetMode(f *FileData, mode os.FileMode) { + f.Lock() + f.mode = mode + f.Unlock() +} + +func SetModTime(f *FileData, mtime time.Time) { + f.Lock() + setModTime(f, mtime) + f.Unlock() +} + +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) { + if !f.fileData.dir { + return nil, &os.PathError{Op: "readdir", Path: f.fileData.name, Err: errors.New("not a dir")} + } + 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 int(f.at) > len(f.fileData.data) { + return 0, io.ErrUnexpectedEOF + } + 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 { + s.Lock() + _, name := filepath.Split(s.name) + s.Unlock() + return name +} +func (s *FileInfo) Mode() os.FileMode { + s.Lock() + defer s.Unlock() + return s.mode +} +func (s *FileInfo) ModTime() time.Time { + s.Lock() + defer s.Unlock() + return s.modtime +} +func (s *FileInfo) IsDir() bool { + s.Lock() + defer s.Unlock() + return s.dir +} +func (s *FileInfo) Sys() interface{} { return nil } +func (s *FileInfo) Size() int64 { + if s.IsDir() { + return int64(42) + } + s.Lock() + defer s.Unlock() + 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/mem/file_test.go b/vendor/github.com/spf13/afero/mem/file_test.go new file mode 100644 index 0000000..5769067 --- /dev/null +++ b/vendor/github.com/spf13/afero/mem/file_test.go @@ -0,0 +1,154 @@ +package mem + +import ( + "testing" + "time" +) + +func TestFileDataNameRace(t *testing.T) { + t.Parallel() + const someName = "someName" + const someOtherName = "someOtherName" + d := FileData{ + name: someName, + } + + if d.Name() != someName { + t.Errorf("Failed to read correct Name, was %v", d.Name()) + } + + ChangeFileName(&d, someOtherName) + if d.Name() != someOtherName { + t.Errorf("Failed to set Name, was %v", d.Name()) + } + + go func() { + ChangeFileName(&d, someName) + }() + + if d.Name() != someName && d.Name() != someOtherName { + t.Errorf("Failed to read either Name, was %v", d.Name()) + } +} + +func TestFileDataModTimeRace(t *testing.T) { + t.Parallel() + someTime := time.Now() + someOtherTime := someTime.Add(1 * time.Minute) + + d := FileData{ + modtime: someTime, + } + + s := FileInfo{ + FileData: &d, + } + + if s.ModTime() != someTime { + t.Errorf("Failed to read correct value, was %v", s.ModTime()) + } + + SetModTime(&d, someOtherTime) + if s.ModTime() != someOtherTime { + t.Errorf("Failed to set ModTime, was %v", s.ModTime()) + } + + go func() { + SetModTime(&d, someTime) + }() + + if s.ModTime() != someTime && s.ModTime() != someOtherTime { + t.Errorf("Failed to read either modtime, was %v", s.ModTime()) + } +} + +func TestFileDataModeRace(t *testing.T) { + t.Parallel() + const someMode = 0777 + const someOtherMode = 0660 + + d := FileData{ + mode: someMode, + } + + s := FileInfo{ + FileData: &d, + } + + if s.Mode() != someMode { + t.Errorf("Failed to read correct value, was %v", s.Mode()) + } + + SetMode(&d, someOtherMode) + if s.Mode() != someOtherMode { + t.Errorf("Failed to set Mode, was %v", s.Mode()) + } + + go func() { + SetMode(&d, someMode) + }() + + if s.Mode() != someMode && s.Mode() != someOtherMode { + t.Errorf("Failed to read either mode, was %v", s.Mode()) + } +} + +func TestFileDataIsDirRace(t *testing.T) { + t.Parallel() + + d := FileData{ + dir: true, + } + + s := FileInfo{ + FileData: &d, + } + + if s.IsDir() != true { + t.Errorf("Failed to read correct value, was %v", s.IsDir()) + } + + go func() { + s.Lock() + d.dir = false + s.Unlock() + }() + + //just logging the value to trigger a read: + t.Logf("Value is %v", s.IsDir()) +} + +func TestFileDataSizeRace(t *testing.T) { + t.Parallel() + + const someData = "Hello" + const someOtherDataSize = "Hello World" + + d := FileData{ + data: []byte(someData), + dir: false, + } + + s := FileInfo{ + FileData: &d, + } + + if s.Size() != int64(len(someData)) { + t.Errorf("Failed to read correct value, was %v", s.Size()) + } + + go func() { + s.Lock() + d.data = []byte(someOtherDataSize) + s.Unlock() + }() + + //just logging the value to trigger a read: + t.Logf("Value is %v", s.Size()) + + //Testing the Dir size case + d.dir = true + if s.Size() != int64(42) { + t.Errorf("Failed to read correct value for dir, was %v", s.Size()) + } +} diff --git a/vendor/github.com/spf13/afero/memmap.go b/vendor/github.com/spf13/afero/memmap.go new file mode 100644 index 0000000..09498e7 --- /dev/null +++ b/vendor/github.com/spf13/afero/memmap.go @@ -0,0 +1,365 @@ +// Copyright © 2014 Steve Francia . +// +// 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") + } + + parent.Lock() + mem.RemoveFromMemDir(parent, f) + parent.Unlock() + 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 + } + } + + parent.Lock() + mem.InitializeDir(parent) + mem.AddToMemDir(parent, f) + parent.Unlock() +} + +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|os.ModeDir) + + 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 + } + 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 0000000..47414ab --- /dev/null +++ b/vendor/github.com/spf13/afero/memmap_test.go @@ -0,0 +1,451 @@ +package afero + +import ( + "fmt" + "io" + "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) + // directories will also have the directory bit set + const dirMode = fileMode | os.ModeDir + + 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, dirMode) + 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 + } + // sets File + if s.Mode().String() != dirMode.String() { + t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), dirMode.String()) + return + } + + // Test MkdirAll + err = fs.MkdirAll(dirPathAll, dirMode) + 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() != dirMode.String() { + t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), dirMode.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) +} + +// This test should be run with the race detector on: +// go test -run TestMemFsDataRace -race +func TestMemFsDataRace(t *testing.T) { + const dir = "test_dir" + fs := NewMemMapFs() + + if err := fs.MkdirAll(dir, 0777); err != nil { + t.Fatal(err) + } + + const n = 1000 + done := make(chan struct{}) + + go func() { + defer close(done) + for i := 0; i < n; i++ { + fname := filepath.Join(dir, fmt.Sprintf("%d.txt", i)) + if err := WriteFile(fs, fname, []byte(""), 0777); err != nil { + panic(err) + } + if err := fs.Remove(fname); err != nil { + panic(err) + } + } + }() + +loop: + for { + select { + case <-done: + break loop + default: + _, err := ReadDir(fs, dir) + if err != nil { + t.Fatal(err) + } + } + } +} + +func TestMemFsDirMode(t *testing.T) { + fs := NewMemMapFs() + err := fs.Mkdir("/testDir1", 0644) + if err != nil { + t.Error(err) + } + err = fs.MkdirAll("/sub/testDir2", 0644) + if err != nil { + t.Error(err) + } + info, err := fs.Stat("/testDir1") + if err != nil { + t.Error(err) + } + if !info.IsDir() { + t.Error("should be a directory") + } + if !info.Mode().IsDir() { + t.Error("FileMode is not directory") + } + info, err = fs.Stat("/sub/testDir2") + if err != nil { + t.Error(err) + } + if !info.IsDir() { + t.Error("should be a directory") + } + if !info.Mode().IsDir() { + t.Error("FileMode is not directory") + } +} + +func TestMemFsUnexpectedEOF(t *testing.T) { + t.Parallel() + + fs := NewMemMapFs() + + if err := WriteFile(fs, "file.txt", []byte("abc"), 0777); err != nil { + t.Fatal(err) + } + + f, err := fs.Open("file.txt") + if err != nil { + t.Fatal(err) + } + defer f.Close() + + // Seek beyond the end. + _, err = f.Seek(512, 0) + if err != nil { + t.Fatal(err) + } + + buff := make([]byte, 256) + _, err = io.ReadAtLeast(f, buff, 256) + + if err != io.ErrUnexpectedEOF { + t.Fatal("Expected ErrUnexpectedEOF") + } +} diff --git a/vendor/github.com/spf13/afero/os.go b/vendor/github.com/spf13/afero/os.go new file mode 100644 index 0000000..13cc1b8 --- /dev/null +++ b/vendor/github.com/spf13/afero/os.go @@ -0,0 +1,101 @@ +// Copyright © 2014 Steve Francia . +// 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" +) + +var _ Lstater = (*OsFs)(nil) + +// 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) +} + +func (OsFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { + fi, err := os.Lstat(name) + return fi, true, err +} diff --git a/vendor/github.com/spf13/afero/path.go b/vendor/github.com/spf13/afero/path.go new file mode 100644 index 0000000..18f60a0 --- /dev/null +++ b/vendor/github.com/spf13/afero/path.go @@ -0,0 +1,106 @@ +// Copyright ©2015 The Go Authors +// Copyright ©2015 Steve Francia +// +// 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 := lstatIfPossible(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 supports it, use Lstat, else use fs.Stat +func lstatIfPossible(fs Fs, path string) (os.FileInfo, error) { + if lfs, ok := fs.(Lstater); ok { + fi, _, err := lfs.LstatIfPossible(path) + return fi, err + } + return fs.Stat(path) +} + +// 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 := lstatIfPossible(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 0000000..104a6bc --- /dev/null +++ b/vendor/github.com/spf13/afero/path_test.go @@ -0,0 +1,69 @@ +// Copyright © 2014 Steve Francia . +// 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 0000000..c6376ec --- /dev/null +++ b/vendor/github.com/spf13/afero/readonlyfs.go @@ -0,0 +1,80 @@ +package afero + +import ( + "os" + "syscall" + "time" +) + +var _ Lstater = (*ReadOnlyFs)(nil) + +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) LstatIfPossible(name string) (os.FileInfo, bool, error) { + if lsf, ok := r.source.(Lstater); ok { + return lsf.LstatIfPossible(name) + } + fi, err := r.Stat(name) + return fi, false, err +} + +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 0000000..9d92dbc --- /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 0000000..ef8a35d --- /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/unionFile.go b/vendor/github.com/spf13/afero/unionFile.go new file mode 100644 index 0000000..1e78f7d --- /dev/null +++ b/vendor/github.com/spf13/afero/unionFile.go @@ -0,0 +1,305 @@ +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 + Merger DirsMerger + 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() +} + +// DirsMerger is how UnionFile weaves two directories together. +// It takes the FileInfo slices from the layer and the base and returns a +// single view. +type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) + +var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) { + var files = make(map[string]os.FileInfo) + + for _, fi := range lofi { + files[fi.Name()] = fi + } + + for _, fi := range bofi { + if _, exists := files[fi.Name()]; !exists { + files[fi.Name()] = fi + } + } + + rfi := make([]os.FileInfo, len(files)) + + i := 0 + for _, fi := range files { + rfi[i] = fi + i++ + } + + return rfi, nil + +} + +// 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) { + var merge DirsMerger = f.Merger + if merge == nil { + merge = defaultUnionMergeDirsFn + } + + if f.off == 0 { + var lfi []os.FileInfo + if f.Layer != nil { + lfi, err = f.Layer.Readdir(-1) + if err != nil { + return nil, err + } + } + + var bfi []os.FileInfo + if f.Base != nil { + bfi, err = f.Base.Readdir(-1) + if err != nil { + return nil, err + } + + } + merged, err := merge(lfi, bfi) + if err != nil { + return nil, err + } + f.files = append(f.files, merged...) + } + 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 0000000..4f253f4 --- /dev/null +++ b/vendor/github.com/spf13/afero/util.go @@ -0,0 +1,330 @@ +// Copyright ©2015 Steve Francia +// Portions Copyright ©2015 The Hugo Authors +// Portions Copyright 2016-present Bjørn Erik Pedersen +// +// 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" + "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 { + return 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 plain 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 0000000..b5852f1 --- /dev/null +++ b/vendor/github.com/spf13/afero/util_test.go @@ -0,0 +1,450 @@ +// Copyright ©2015 Steve Francia +// 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/golang.org/x/text/internal/gen/code.go b/vendor/golang.org/x/text/internal/gen/code.go new file mode 100644 index 0000000..0389509 --- /dev/null +++ b/vendor/golang.org/x/text/internal/gen/code.go @@ -0,0 +1,369 @@ +// 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. + +package gen + +import ( + "bytes" + "encoding/gob" + "fmt" + "hash" + "hash/fnv" + "io" + "log" + "os" + "reflect" + "strings" + "unicode" + "unicode/utf8" +) + +// This file contains utilities for generating code. + +// TODO: other write methods like: +// - slices, maps, types, etc. + +// CodeWriter is a utility for writing structured code. It computes the content +// hash and size of written content. It ensures there are newlines between +// written code blocks. +type CodeWriter struct { + buf bytes.Buffer + Size int + Hash hash.Hash32 // content hash + gob *gob.Encoder + // For comments we skip the usual one-line separator if they are followed by + // a code block. + skipSep bool +} + +func (w *CodeWriter) Write(p []byte) (n int, err error) { + return w.buf.Write(p) +} + +// NewCodeWriter returns a new CodeWriter. +func NewCodeWriter() *CodeWriter { + h := fnv.New32() + return &CodeWriter{Hash: h, gob: gob.NewEncoder(h)} +} + +// WriteGoFile appends the buffer with the total size of all created structures +// and writes it as a Go file to the the given file with the given package name. +func (w *CodeWriter) WriteGoFile(filename, pkg string) { + f, err := os.Create(filename) + if err != nil { + log.Fatalf("Could not create file %s: %v", filename, err) + } + defer f.Close() + if _, err = w.WriteGo(f, pkg, ""); err != nil { + log.Fatalf("Error writing file %s: %v", filename, err) + } +} + +// WriteVersionedGoFile appends the buffer with the total size of all created +// structures and writes it as a Go file to the the given file with the given +// package name and build tags for the current Unicode version, +func (w *CodeWriter) WriteVersionedGoFile(filename, pkg string) { + tags := buildTags() + if tags != "" { + filename = insertVersion(filename, UnicodeVersion()) + } + f, err := os.Create(filename) + if err != nil { + log.Fatalf("Could not create file %s: %v", filename, err) + } + defer f.Close() + if _, err = w.WriteGo(f, pkg, tags); err != nil { + log.Fatalf("Error writing file %s: %v", filename, err) + } +} + +// WriteGo appends the buffer with the total size of all created structures and +// writes it as a Go file to the the given writer with the given package name. +func (w *CodeWriter) WriteGo(out io.Writer, pkg, tags string) (n int, err error) { + sz := w.Size + w.WriteComment("Total table size %d bytes (%dKiB); checksum: %X\n", sz, sz/1024, w.Hash.Sum32()) + defer w.buf.Reset() + return WriteGo(out, pkg, tags, w.buf.Bytes()) +} + +func (w *CodeWriter) printf(f string, x ...interface{}) { + fmt.Fprintf(w, f, x...) +} + +func (w *CodeWriter) insertSep() { + if w.skipSep { + w.skipSep = false + return + } + // Use at least two newlines to ensure a blank space between the previous + // block. WriteGoFile will remove extraneous newlines. + w.printf("\n\n") +} + +// WriteComment writes a comment block. All line starts are prefixed with "//". +// Initial empty lines are gobbled. The indentation for the first line is +// stripped from consecutive lines. +func (w *CodeWriter) WriteComment(comment string, args ...interface{}) { + s := fmt.Sprintf(comment, args...) + s = strings.Trim(s, "\n") + + // Use at least two newlines to ensure a blank space between the previous + // block. WriteGoFile will remove extraneous newlines. + w.printf("\n\n// ") + w.skipSep = true + + // strip first indent level. + sep := "\n" + for ; len(s) > 0 && (s[0] == '\t' || s[0] == ' '); s = s[1:] { + sep += s[:1] + } + + strings.NewReplacer(sep, "\n// ", "\n", "\n// ").WriteString(w, s) + + w.printf("\n") +} + +func (w *CodeWriter) writeSizeInfo(size int) { + w.printf("// Size: %d bytes\n", size) +} + +// WriteConst writes a constant of the given name and value. +func (w *CodeWriter) WriteConst(name string, x interface{}) { + w.insertSep() + v := reflect.ValueOf(x) + + switch v.Type().Kind() { + case reflect.String: + w.printf("const %s %s = ", name, typeName(x)) + w.WriteString(v.String()) + w.printf("\n") + default: + w.printf("const %s = %#v\n", name, x) + } +} + +// WriteVar writes a variable of the given name and value. +func (w *CodeWriter) WriteVar(name string, x interface{}) { + w.insertSep() + v := reflect.ValueOf(x) + oldSize := w.Size + sz := int(v.Type().Size()) + w.Size += sz + + switch v.Type().Kind() { + case reflect.String: + w.printf("var %s %s = ", name, typeName(x)) + w.WriteString(v.String()) + case reflect.Struct: + w.gob.Encode(x) + fallthrough + case reflect.Slice, reflect.Array: + w.printf("var %s = ", name) + w.writeValue(v) + w.writeSizeInfo(w.Size - oldSize) + default: + w.printf("var %s %s = ", name, typeName(x)) + w.gob.Encode(x) + w.writeValue(v) + w.writeSizeInfo(w.Size - oldSize) + } + w.printf("\n") +} + +func (w *CodeWriter) writeValue(v reflect.Value) { + x := v.Interface() + switch v.Kind() { + case reflect.String: + w.WriteString(v.String()) + case reflect.Array: + // Don't double count: callers of WriteArray count on the size being + // added, so we need to discount it here. + w.Size -= int(v.Type().Size()) + w.writeSlice(x, true) + case reflect.Slice: + w.writeSlice(x, false) + case reflect.Struct: + w.printf("%s{\n", typeName(v.Interface())) + t := v.Type() + for i := 0; i < v.NumField(); i++ { + w.printf("%s: ", t.Field(i).Name) + w.writeValue(v.Field(i)) + w.printf(",\n") + } + w.printf("}") + default: + w.printf("%#v", x) + } +} + +// WriteString writes a string literal. +func (w *CodeWriter) WriteString(s string) { + s = strings.Replace(s, `\`, `\\`, -1) + io.WriteString(w.Hash, s) // content hash + w.Size += len(s) + + const maxInline = 40 + if len(s) <= maxInline { + w.printf("%q", s) + return + } + + // We will render the string as a multi-line string. + const maxWidth = 80 - 4 - len(`"`) - len(`" +`) + + // When starting on its own line, go fmt indents line 2+ an extra level. + n, max := maxWidth, maxWidth-4 + + // As per https://golang.org/issue/18078, the compiler has trouble + // compiling the concatenation of many strings, s0 + s1 + s2 + ... + sN, + // for large N. We insert redundant, explicit parentheses to work around + // that, lowering the N at any given step: (s0 + s1 + ... + s63) + (s64 + + // ... + s127) + etc + (etc + ... + sN). + explicitParens, extraComment := len(s) > 128*1024, "" + if explicitParens { + w.printf(`(`) + extraComment = "; the redundant, explicit parens are for https://golang.org/issue/18078" + } + + // Print "" +\n, if a string does not start on its own line. + b := w.buf.Bytes() + if p := len(bytes.TrimRight(b, " \t")); p > 0 && b[p-1] != '\n' { + w.printf("\"\" + // Size: %d bytes%s\n", len(s), extraComment) + n, max = maxWidth, maxWidth + } + + w.printf(`"`) + + for sz, p, nLines := 0, 0, 0; p < len(s); { + var r rune + r, sz = utf8.DecodeRuneInString(s[p:]) + out := s[p : p+sz] + chars := 1 + if !unicode.IsPrint(r) || r == utf8.RuneError || r == '"' { + switch sz { + case 1: + out = fmt.Sprintf("\\x%02x", s[p]) + case 2, 3: + out = fmt.Sprintf("\\u%04x", r) + case 4: + out = fmt.Sprintf("\\U%08x", r) + } + chars = len(out) + } + if n -= chars; n < 0 { + nLines++ + if explicitParens && nLines&63 == 63 { + w.printf("\") + (\"") + } + w.printf("\" +\n\"") + n = max - len(out) + } + w.printf("%s", out) + p += sz + } + w.printf(`"`) + if explicitParens { + w.printf(`)`) + } +} + +// WriteSlice writes a slice value. +func (w *CodeWriter) WriteSlice(x interface{}) { + w.writeSlice(x, false) +} + +// WriteArray writes an array value. +func (w *CodeWriter) WriteArray(x interface{}) { + w.writeSlice(x, true) +} + +func (w *CodeWriter) writeSlice(x interface{}, isArray bool) { + v := reflect.ValueOf(x) + w.gob.Encode(v.Len()) + w.Size += v.Len() * int(v.Type().Elem().Size()) + name := typeName(x) + if isArray { + name = fmt.Sprintf("[%d]%s", v.Len(), name[strings.Index(name, "]")+1:]) + } + if isArray { + w.printf("%s{\n", name) + } else { + w.printf("%s{ // %d elements\n", name, v.Len()) + } + + switch kind := v.Type().Elem().Kind(); kind { + case reflect.String: + for _, s := range x.([]string) { + w.WriteString(s) + w.printf(",\n") + } + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + // nLine and nBlock are the number of elements per line and block. + nLine, nBlock, format := 8, 64, "%d," + switch kind { + case reflect.Uint8: + format = "%#02x," + case reflect.Uint16: + format = "%#04x," + case reflect.Uint32: + nLine, nBlock, format = 4, 32, "%#08x," + case reflect.Uint, reflect.Uint64: + nLine, nBlock, format = 4, 32, "%#016x," + case reflect.Int8: + nLine = 16 + } + n := nLine + for i := 0; i < v.Len(); i++ { + if i%nBlock == 0 && v.Len() > nBlock { + w.printf("// Entry %X - %X\n", i, i+nBlock-1) + } + x := v.Index(i).Interface() + w.gob.Encode(x) + w.printf(format, x) + if n--; n == 0 { + n = nLine + w.printf("\n") + } + } + w.printf("\n") + case reflect.Struct: + zero := reflect.Zero(v.Type().Elem()).Interface() + for i := 0; i < v.Len(); i++ { + x := v.Index(i).Interface() + w.gob.EncodeValue(v) + if !reflect.DeepEqual(zero, x) { + line := fmt.Sprintf("%#v,\n", x) + line = line[strings.IndexByte(line, '{'):] + w.printf("%d: ", i) + w.printf(line) + } + } + case reflect.Array: + for i := 0; i < v.Len(); i++ { + w.printf("%d: %#v,\n", i, v.Index(i).Interface()) + } + default: + panic("gen: slice elem type not supported") + } + w.printf("}") +} + +// WriteType writes a definition of the type of the given value and returns the +// type name. +func (w *CodeWriter) WriteType(x interface{}) string { + t := reflect.TypeOf(x) + w.printf("type %s struct {\n", t.Name()) + for i := 0; i < t.NumField(); i++ { + w.printf("\t%s %s\n", t.Field(i).Name, t.Field(i).Type) + } + w.printf("}\n") + return t.Name() +} + +// typeName returns the name of the go type of x. +func typeName(x interface{}) string { + t := reflect.ValueOf(x).Type() + return strings.Replace(fmt.Sprint(t), "main.", "", 1) +} diff --git a/vendor/golang.org/x/text/internal/gen/gen.go b/vendor/golang.org/x/text/internal/gen/gen.go new file mode 100644 index 0000000..4c3f760 --- /dev/null +++ b/vendor/golang.org/x/text/internal/gen/gen.go @@ -0,0 +1,333 @@ +// 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. + +// Package gen contains common code for the various code generation tools in the +// text repository. Its usage ensures consistency between tools. +// +// This package defines command line flags that are common to most generation +// tools. The flags allow for specifying specific Unicode and CLDR versions +// in the public Unicode data repository (http://www.unicode.org/Public). +// +// A local Unicode data mirror can be set through the flag -local or the +// environment variable UNICODE_DIR. The former takes precedence. The local +// directory should follow the same structure as the public repository. +// +// IANA data can also optionally be mirrored by putting it in the iana directory +// rooted at the top of the local mirror. Beware, though, that IANA data is not +// versioned. So it is up to the developer to use the right version. +package gen // import "golang.org/x/text/internal/gen" + +import ( + "bytes" + "flag" + "fmt" + "go/build" + "go/format" + "io" + "io/ioutil" + "log" + "net/http" + "os" + "path" + "path/filepath" + "strings" + "sync" + "unicode" + + "golang.org/x/text/unicode/cldr" +) + +var ( + url = flag.String("url", + "http://www.unicode.org/Public", + "URL of Unicode database directory") + iana = flag.String("iana", + "http://www.iana.org", + "URL of the IANA repository") + unicodeVersion = flag.String("unicode", + getEnv("UNICODE_VERSION", unicode.Version), + "unicode version to use") + cldrVersion = flag.String("cldr", + getEnv("CLDR_VERSION", cldr.Version), + "cldr version to use") +) + +func getEnv(name, def string) string { + if v := os.Getenv(name); v != "" { + return v + } + return def +} + +// Init performs common initialization for a gen command. It parses the flags +// and sets up the standard logging parameters. +func Init() { + log.SetPrefix("") + log.SetFlags(log.Lshortfile) + flag.Parse() +} + +const header = `// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +` + +// UnicodeVersion reports the requested Unicode version. +func UnicodeVersion() string { + return *unicodeVersion +} + +// CLDRVersion reports the requested CLDR version. +func CLDRVersion() string { + return *cldrVersion +} + +var tags = []struct{ version, buildTags string }{ + {"10.0.0", "go1.10"}, + {"", "!go1.10"}, +} + +// buildTags reports the build tags used for the current Unicode version. +func buildTags() string { + v := UnicodeVersion() + for _, x := range tags { + // We should do a numeric comparison, but including the collate package + // would create an import cycle. We approximate it by assuming that + // longer version strings are later. + if len(x.version) <= len(v) { + return x.buildTags + } + if len(x.version) == len(v) && x.version <= v { + return x.buildTags + } + } + return tags[0].buildTags +} + +// IsLocal reports whether data files are available locally. +func IsLocal() bool { + dir, err := localReadmeFile() + if err != nil { + return false + } + if _, err = os.Stat(dir); err != nil { + return false + } + return true +} + +// OpenUCDFile opens the requested UCD file. The file is specified relative to +// the public Unicode root directory. It will call log.Fatal if there are any +// errors. +func OpenUCDFile(file string) io.ReadCloser { + return openUnicode(path.Join(*unicodeVersion, "ucd", file)) +} + +// OpenCLDRCoreZip opens the CLDR core zip file. It will call log.Fatal if there +// are any errors. +func OpenCLDRCoreZip() io.ReadCloser { + return OpenUnicodeFile("cldr", *cldrVersion, "core.zip") +} + +// OpenUnicodeFile opens the requested file of the requested category from the +// root of the Unicode data archive. The file is specified relative to the +// public Unicode root directory. If version is "", it will use the default +// Unicode version. It will call log.Fatal if there are any errors. +func OpenUnicodeFile(category, version, file string) io.ReadCloser { + if version == "" { + version = UnicodeVersion() + } + return openUnicode(path.Join(category, version, file)) +} + +// OpenIANAFile opens the requested IANA file. The file is specified relative +// to the IANA root, which is typically either http://www.iana.org or the +// iana directory in the local mirror. It will call log.Fatal if there are any +// errors. +func OpenIANAFile(path string) io.ReadCloser { + return Open(*iana, "iana", path) +} + +var ( + dirMutex sync.Mutex + localDir string +) + +const permissions = 0755 + +func localReadmeFile() (string, error) { + p, err := build.Import("golang.org/x/text", "", build.FindOnly) + if err != nil { + return "", fmt.Errorf("Could not locate package: %v", err) + } + return filepath.Join(p.Dir, "DATA", "README"), nil +} + +func getLocalDir() string { + dirMutex.Lock() + defer dirMutex.Unlock() + + readme, err := localReadmeFile() + if err != nil { + log.Fatal(err) + } + dir := filepath.Dir(readme) + if _, err := os.Stat(readme); err != nil { + if err := os.MkdirAll(dir, permissions); err != nil { + log.Fatalf("Could not create directory: %v", err) + } + ioutil.WriteFile(readme, []byte(readmeTxt), permissions) + } + return dir +} + +const readmeTxt = `Generated by golang.org/x/text/internal/gen. DO NOT EDIT. + +This directory contains downloaded files used to generate the various tables +in the golang.org/x/text subrepo. + +Note that the language subtag repo (iana/assignments/language-subtag-registry) +and all other times in the iana subdirectory are not versioned and will need +to be periodically manually updated. The easiest way to do this is to remove +the entire iana directory. This is mostly of concern when updating the language +package. +` + +// Open opens subdir/path if a local directory is specified and the file exists, +// where subdir is a directory relative to the local root, or fetches it from +// urlRoot/path otherwise. It will call log.Fatal if there are any errors. +func Open(urlRoot, subdir, path string) io.ReadCloser { + file := filepath.Join(getLocalDir(), subdir, filepath.FromSlash(path)) + return open(file, urlRoot, path) +} + +func openUnicode(path string) io.ReadCloser { + file := filepath.Join(getLocalDir(), filepath.FromSlash(path)) + return open(file, *url, path) +} + +// TODO: automatically periodically update non-versioned files. + +func open(file, urlRoot, path string) io.ReadCloser { + if f, err := os.Open(file); err == nil { + return f + } + r := get(urlRoot, path) + defer r.Close() + b, err := ioutil.ReadAll(r) + if err != nil { + log.Fatalf("Could not download file: %v", err) + } + os.MkdirAll(filepath.Dir(file), permissions) + if err := ioutil.WriteFile(file, b, permissions); err != nil { + log.Fatalf("Could not create file: %v", err) + } + return ioutil.NopCloser(bytes.NewReader(b)) +} + +func get(root, path string) io.ReadCloser { + url := root + "/" + path + fmt.Printf("Fetching %s...", url) + defer fmt.Println(" done.") + resp, err := http.Get(url) + if err != nil { + log.Fatalf("HTTP GET: %v", err) + } + if resp.StatusCode != 200 { + log.Fatalf("Bad GET status for %q: %q", url, resp.Status) + } + return resp.Body +} + +// TODO: use Write*Version in all applicable packages. + +// WriteUnicodeVersion writes a constant for the Unicode version from which the +// tables are generated. +func WriteUnicodeVersion(w io.Writer) { + fmt.Fprintf(w, "// UnicodeVersion is the Unicode version from which the tables in this package are derived.\n") + fmt.Fprintf(w, "const UnicodeVersion = %q\n\n", UnicodeVersion()) +} + +// WriteCLDRVersion writes a constant for the CLDR version from which the +// tables are generated. +func WriteCLDRVersion(w io.Writer) { + fmt.Fprintf(w, "// CLDRVersion is the CLDR version from which the tables in this package are derived.\n") + fmt.Fprintf(w, "const CLDRVersion = %q\n\n", CLDRVersion()) +} + +// WriteGoFile prepends a standard file comment and package statement to the +// given bytes, applies gofmt, and writes them to a file with the given name. +// It will call log.Fatal if there are any errors. +func WriteGoFile(filename, pkg string, b []byte) { + w, err := os.Create(filename) + if err != nil { + log.Fatalf("Could not create file %s: %v", filename, err) + } + defer w.Close() + if _, err = WriteGo(w, pkg, "", b); err != nil { + log.Fatalf("Error writing file %s: %v", filename, err) + } +} + +func insertVersion(filename, version string) string { + suffix := ".go" + if strings.HasSuffix(filename, "_test.go") { + suffix = "_test.go" + } + return fmt.Sprint(filename[:len(filename)-len(suffix)], version, suffix) +} + +// WriteVersionedGoFile prepends a standard file comment, adds build tags to +// version the file for the current Unicode version, and package statement to +// the given bytes, applies gofmt, and writes them to a file with the given +// name. It will call log.Fatal if there are any errors. +func WriteVersionedGoFile(filename, pkg string, b []byte) { + tags := buildTags() + if tags != "" { + filename = insertVersion(filename, UnicodeVersion()) + } + w, err := os.Create(filename) + if err != nil { + log.Fatalf("Could not create file %s: %v", filename, err) + } + defer w.Close() + if _, err = WriteGo(w, pkg, tags, b); err != nil { + log.Fatalf("Error writing file %s: %v", filename, err) + } +} + +// WriteGo prepends a standard file comment and package statement to the given +// bytes, applies gofmt, and writes them to w. +func WriteGo(w io.Writer, pkg, tags string, b []byte) (n int, err error) { + src := []byte(header) + if tags != "" { + src = append(src, fmt.Sprintf("// +build %s\n\n", tags)...) + } + src = append(src, fmt.Sprintf("package %s\n\n", pkg)...) + src = append(src, b...) + formatted, err := format.Source(src) + if err != nil { + // Print the generated code even in case of an error so that the + // returned error can be meaningfully interpreted. + n, _ = w.Write(src) + return n, err + } + return w.Write(formatted) +} + +// Repackage rewrites a Go file from belonging to package main to belonging to +// the given package. +func Repackage(inFile, outFile, pkg string) { + src, err := ioutil.ReadFile(inFile) + if err != nil { + log.Fatalf("reading %s: %v", inFile, err) + } + const toDelete = "package main\n\n" + i := bytes.Index(src, []byte(toDelete)) + if i < 0 { + log.Fatalf("Could not find %q in %s.", toDelete, inFile) + } + w := &bytes.Buffer{} + w.Write(src[i+len(toDelete):]) + WriteGoFile(outFile, pkg, w.Bytes()) +} diff --git a/vendor/golang.org/x/text/internal/testtext/codesize.go b/vendor/golang.org/x/text/internal/testtext/codesize.go new file mode 100644 index 0000000..5fc5eae --- /dev/null +++ b/vendor/golang.org/x/text/internal/testtext/codesize.go @@ -0,0 +1,53 @@ +// 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. + +package testtext + +import ( + "bytes" + "fmt" + "io/ioutil" + "os" + "os/exec" + "path/filepath" + "runtime" +) + +// CodeSize builds the given code sample and returns the binary size or en error +// if an error occurred. The code sample typically will look like this: +// package main +// import "golang.org/x/text/somepackage" +// func main() { +// somepackage.Func() // reference Func to cause it to be linked in. +// } +// See dict_test.go in the display package for an example. +func CodeSize(s string) (int, error) { + // Write the file. + tmpdir, err := ioutil.TempDir(os.TempDir(), "testtext") + if err != nil { + return 0, fmt.Errorf("testtext: failed to create tmpdir: %v", err) + } + defer os.RemoveAll(tmpdir) + filename := filepath.Join(tmpdir, "main.go") + if err := ioutil.WriteFile(filename, []byte(s), 0644); err != nil { + return 0, fmt.Errorf("testtext: failed to write main.go: %v", err) + } + + // Build the binary. + w := &bytes.Buffer{} + cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "build", "-o", "main") + cmd.Dir = tmpdir + cmd.Stderr = w + cmd.Stdout = w + if err := cmd.Run(); err != nil { + return 0, fmt.Errorf("testtext: failed to execute command: %v\nmain.go:\n%vErrors:%s", err, s, w) + } + + // Determine the size. + fi, err := os.Stat(filepath.Join(tmpdir, "main")) + if err != nil { + return 0, fmt.Errorf("testtext: failed to get file info: %v", err) + } + return int(fi.Size()), nil +} diff --git a/vendor/golang.org/x/text/internal/testtext/flag.go b/vendor/golang.org/x/text/internal/testtext/flag.go new file mode 100644 index 0000000..45b32b2 --- /dev/null +++ b/vendor/golang.org/x/text/internal/testtext/flag.go @@ -0,0 +1,22 @@ +// 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. + +package testtext + +import ( + "flag" + "testing" + + "golang.org/x/text/internal/gen" +) + +var long = flag.Bool("long", false, + "run tests that require fetching data online") + +// SkipIfNotLong returns whether long tests should be performed. +func SkipIfNotLong(t *testing.T) { + if testing.Short() || !(gen.IsLocal() || *long) { + t.Skip("skipping test to prevent downloading; to run use -long or use -local or UNICODE_DIR to specify a local source") + } +} diff --git a/vendor/golang.org/x/text/internal/testtext/gc.go b/vendor/golang.org/x/text/internal/testtext/gc.go new file mode 100644 index 0000000..a54e1bc --- /dev/null +++ b/vendor/golang.org/x/text/internal/testtext/gc.go @@ -0,0 +1,14 @@ +// 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 !gccgo + +package testtext + +import "testing" + +// AllocsPerRun wraps testing.AllocsPerRun. +func AllocsPerRun(runs int, f func()) (avg float64) { + return testing.AllocsPerRun(runs, f) +} diff --git a/vendor/golang.org/x/text/internal/testtext/gccgo.go b/vendor/golang.org/x/text/internal/testtext/gccgo.go new file mode 100644 index 0000000..30e98ef --- /dev/null +++ b/vendor/golang.org/x/text/internal/testtext/gccgo.go @@ -0,0 +1,11 @@ +// 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 gccgo + +package testtext + +// AllocsPerRun always returns 0 for gccgo until gccgo implements escape +// analysis equal or better to that of gc. +func AllocsPerRun(runs int, f func()) (avg float64) { return 0 } diff --git a/vendor/golang.org/x/text/internal/testtext/go1_6.go b/vendor/golang.org/x/text/internal/testtext/go1_6.go new file mode 100644 index 0000000..7b23847 --- /dev/null +++ b/vendor/golang.org/x/text/internal/testtext/go1_6.go @@ -0,0 +1,23 @@ +// 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 !go1.7 + +package testtext + +import "testing" + +func Run(t *testing.T, name string, fn func(t *testing.T)) bool { + t.Logf("Running %s...", name) + fn(t) + return t.Failed() +} + +// Bench runs the given benchmark function. This pre-1.7 implementation renders +// the measurement useless, but allows the code to be compiled at least. +func Bench(b *testing.B, name string, fn func(b *testing.B)) bool { + b.Logf("Running %s...", name) + fn(b) + return b.Failed() +} diff --git a/vendor/golang.org/x/text/internal/testtext/go1_7.go b/vendor/golang.org/x/text/internal/testtext/go1_7.go new file mode 100644 index 0000000..66f9cf7 --- /dev/null +++ b/vendor/golang.org/x/text/internal/testtext/go1_7.go @@ -0,0 +1,17 @@ +// 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 go1.7 + +package testtext + +import "testing" + +func Run(t *testing.T, name string, fn func(t *testing.T)) bool { + return t.Run(name, fn) +} + +func Bench(b *testing.B, name string, fn func(b *testing.B)) bool { + return b.Run(name, fn) +} diff --git a/vendor/golang.org/x/text/internal/testtext/text.go b/vendor/golang.org/x/text/internal/testtext/text.go new file mode 100644 index 0000000..ce40d7e --- /dev/null +++ b/vendor/golang.org/x/text/internal/testtext/text.go @@ -0,0 +1,105 @@ +// 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. + +// Package testtext contains test data that is of common use to the text +// repository. +package testtext // import "golang.org/x/text/internal/testtext" + +const ( + + // ASCII is an ASCII string containing all letters in the English alphabet. + ASCII = "The quick brown fox jumps over the lazy dog. " + + "The quick brown fox jumps over the lazy dog. " + + "The quick brown fox jumps over the lazy dog. " + + "The quick brown fox jumps over the lazy dog. " + + "The quick brown fox jumps over the lazy dog. " + + "The quick brown fox jumps over the lazy dog. " + + "The quick brown fox jumps over the lazy dog. " + + "The quick brown fox jumps over the lazy dog. " + + "The quick brown fox jumps over the lazy dog. " + + "The quick brown fox jumps over the lazy dog. " + + // Vietnamese is a snippet from http://creativecommons.org/licenses/by-sa/3.0/vn/ + Vietnamese = `Với các điều kiện sau: Ghi nhận công của tác giả. +Nếu bạn sử dụng, chuyển đổi, hoặc xây dựng dự án từ +nội dung được chia sẻ này, bạn phải áp dụng giấy phép này hoặc +một giấy phép khác có các điều khoản tương tự như giấy phép này +cho dự án của bạn. Hiểu rằng: Miễn — Bất kỳ các điều kiện nào +trên đây cũng có thể được miễn bỏ nếu bạn được sự cho phép của +người sở hữu bản quyền. Phạm vi công chúng — Khi tác phẩm hoặc +bất kỳ chương nào của tác phẩm đã trong vùng dành cho công +chúng theo quy định của pháp luật thì tình trạng của nó không +bị ảnh hưởng bởi giấy phép trong bất kỳ trường hợp nào.` + + // Russian is a snippet from http://creativecommons.org/licenses/by-sa/1.0/deed.ru + Russian = `При обязательном соблюдении следующих условий: +Attribution — Вы должны атрибутировать произведение (указывать +автора и источник) в порядке, предусмотренном автором или +лицензиаром (но только так, чтобы никоим образом не подразумевалось, +что они поддерживают вас или использование вами данного произведения). +Υπό τις ακόλουθες προϋποθέσεις:` + + // Greek is a snippet from http://creativecommons.org/licenses/by-sa/3.0/gr/ + Greek = `Αναφορά Δημιουργού — Θα πρέπει να κάνετε την αναφορά στο έργο με τον +τρόπο που έχει οριστεί από το δημιουργό ή το χορηγούντο την άδεια +(χωρίς όμως να εννοείται με οποιονδήποτε τρόπο ότι εγκρίνουν εσάς ή +τη χρήση του έργου από εσάς). Παρόμοια Διανομή — Εάν αλλοιώσετε, +τροποποιήσετε ή δημιουργήσετε περαιτέρω βασισμένοι στο έργο θα +μπορείτε να διανέμετε το έργο που θα προκύψει μόνο με την ίδια ή +παρόμοια άδεια.` + + // Arabic is a snippet from http://creativecommons.org/licenses/by-sa/3.0/deed.ar + Arabic = `بموجب الشروط التالية نسب المصنف — يجب عليك أن +تنسب العمل بالطريقة التي تحددها المؤلف أو المرخص (ولكن ليس بأي حال من +الأحوال أن توحي وتقترح بتحول أو استخدامك للعمل). +المشاركة على قدم المساواة — إذا كنت يعدل ، والتغيير ، أو الاستفادة +من هذا العمل ، قد ينتج عن توزيع العمل إلا في ظل تشابه او تطابق فى واحد +لهذا الترخيص.` + + // Hebrew is a snippet from http://creativecommons.org/licenses/by-sa/1.0/il/ + Hebrew = `בכפוף לתנאים הבאים: ייחוס — עליך לייחס את היצירה (לתת קרדיט) באופן +המצויין על-ידי היוצר או מעניק הרישיון (אך לא בשום אופן המרמז על כך +שהם תומכים בך או בשימוש שלך ביצירה). שיתוף זהה — אם תחליט/י לשנות, +לעבד או ליצור יצירה נגזרת בהסתמך על יצירה זו, תוכל/י להפיץ את יצירתך +החדשה רק תחת אותו הרישיון או רישיון דומה לרישיון זה.` + + TwoByteUTF8 = Russian + Greek + Arabic + Hebrew + + // Thai is a snippet from http://creativecommons.org/licenses/by-sa/3.0/th/ + Thai = `ภายใต้เงื่อนไข ดังต่อไปนี้ : แสดงที่มา — คุณต้องแสดงที่ +มาของงานดังกล่าว ตามรูปแบบที่ผู้สร้างสรรค์หรือผู้อนุญาตกำหนด (แต่ +ไม่ใช่ในลักษณะที่ว่า พวกเขาสนับสนุนคุณหรือสนับสนุนการที่ +คุณนำงานไปใช้) อนุญาตแบบเดียวกัน — หากคุณดัดแปลง เปลี่ยนรูป หรื +อต่อเติมงานนี้ คุณต้องใช้สัญญาอนุญาตแบบเดียวกันหรือแบบที่เหมื +อนกับสัญญาอนุญาตที่ใช้กับงานนี้เท่านั้น` + + ThreeByteUTF8 = Thai + + // Japanese is a snippet from http://creativecommons.org/licenses/by-sa/2.0/jp/ + Japanese = `あなたの従うべき条件は以下の通りです。 +表示 — あなたは原著作者のクレジットを表示しなければなりません。 +継承 — もしあなたがこの作品を改変、変形または加工した場合、 +あなたはその結果生じた作品をこの作品と同一の許諾条件の下でのみ +頒布することができます。` + + // Chinese is a snippet from http://creativecommons.org/licenses/by-sa/2.5/cn/ + Chinese = `您可以自由: 复制、发行、展览、表演、放映、 +广播或通过信息网络传播本作品 创作演绎作品 +对本作品进行商业性使用 惟须遵守下列条件: +署名 — 您必须按照作者或者许可人指定的方式对作品进行署名。 +相同方式共享 — 如果您改变、转换本作品或者以本作品为基础进行创作, +您只能采用与本协议相同的许可协议发布基于本作品的演绎作品。` + + // Korean is a snippet from http://creativecommons.org/licenses/by-sa/2.0/kr/ + Korean = `다음과 같은 조건을 따라야 합니다: 저작자표시 +— 저작자나 이용허락자가 정한 방법으로 저작물의 +원저작자를 표시하여야 합니다(그러나 원저작자가 이용자나 이용자의 +이용을 보증하거나 추천한다는 의미로 표시해서는 안됩니다). +동일조건변경허락 — 이 저작물을 이용하여 만든 이차적 저작물에는 본 +라이선스와 동일한 라이선스를 적용해야 합니다.` + + CJK = Chinese + Japanese + Korean + + All = ASCII + Vietnamese + TwoByteUTF8 + ThreeByteUTF8 + CJK +) diff --git a/vendor/golang.org/x/text/transform/examples_test.go b/vendor/golang.org/x/text/transform/examples_test.go new file mode 100644 index 0000000..f2e284d --- /dev/null +++ b/vendor/golang.org/x/text/transform/examples_test.go @@ -0,0 +1,37 @@ +// 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. + +package transform_test + +import ( + "fmt" + "unicode" + + "golang.org/x/text/transform" + "golang.org/x/text/unicode/norm" +) + +func ExampleRemoveFunc() { + input := []byte(`tschüß; до свидания`) + + b := make([]byte, len(input)) + + t := transform.RemoveFunc(unicode.IsSpace) + n, _, _ := t.Transform(b, input, true) + fmt.Println(string(b[:n])) + + t = transform.RemoveFunc(func(r rune) bool { + return !unicode.Is(unicode.Latin, r) + }) + n, _, _ = t.Transform(b, input, true) + fmt.Println(string(b[:n])) + + n, _, _ = t.Transform(b, norm.NFD.Bytes(input), true) + fmt.Println(string(b[:n])) + + // Output: + // tschüß;досвидания + // tschüß + // tschuß +} diff --git a/vendor/golang.org/x/text/transform/transform.go b/vendor/golang.org/x/text/transform/transform.go new file mode 100644 index 0000000..fe47b9b --- /dev/null +++ b/vendor/golang.org/x/text/transform/transform.go @@ -0,0 +1,705 @@ +// 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. + +// Package transform provides reader and writer wrappers that transform the +// bytes passing through as well as various transformations. Example +// transformations provided by other packages include normalization and +// conversion between character sets. +package transform // import "golang.org/x/text/transform" + +import ( + "bytes" + "errors" + "io" + "unicode/utf8" +) + +var ( + // ErrShortDst means that the destination buffer was too short to + // receive all of the transformed bytes. + ErrShortDst = errors.New("transform: short destination buffer") + + // ErrShortSrc means that the source buffer has insufficient data to + // complete the transformation. + ErrShortSrc = errors.New("transform: short source buffer") + + // ErrEndOfSpan means that the input and output (the transformed input) + // are not identical. + ErrEndOfSpan = errors.New("transform: input and output are not identical") + + // errInconsistentByteCount means that Transform returned success (nil + // error) but also returned nSrc inconsistent with the src argument. + errInconsistentByteCount = errors.New("transform: inconsistent byte count returned") + + // errShortInternal means that an internal buffer is not large enough + // to make progress and the Transform operation must be aborted. + errShortInternal = errors.New("transform: short internal buffer") +) + +// Transformer transforms bytes. +type Transformer interface { + // Transform writes to dst the transformed bytes read from src, and + // returns the number of dst bytes written and src bytes read. The + // atEOF argument tells whether src represents the last bytes of the + // input. + // + // Callers should always process the nDst bytes produced and account + // for the nSrc bytes consumed before considering the error err. + // + // A nil error means that all of the transformed bytes (whether freshly + // transformed from src or left over from previous Transform calls) + // were written to dst. A nil error can be returned regardless of + // whether atEOF is true. If err is nil then nSrc must equal len(src); + // the converse is not necessarily true. + // + // ErrShortDst means that dst was too short to receive all of the + // transformed bytes. ErrShortSrc means that src had insufficient data + // to complete the transformation. If both conditions apply, then + // either error may be returned. Other than the error conditions listed + // here, implementations are free to report other errors that arise. + Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) + + // Reset resets the state and allows a Transformer to be reused. + Reset() +} + +// SpanningTransformer extends the Transformer interface with a Span method +// that determines how much of the input already conforms to the Transformer. +type SpanningTransformer interface { + Transformer + + // Span returns a position in src such that transforming src[:n] results in + // identical output src[:n] for these bytes. It does not necessarily return + // the largest such n. The atEOF argument tells whether src represents the + // last bytes of the input. + // + // Callers should always account for the n bytes consumed before + // considering the error err. + // + // A nil error means that all input bytes are known to be identical to the + // output produced by the Transformer. A nil error can be be returned + // regardless of whether atEOF is true. If err is nil, then then n must + // equal len(src); the converse is not necessarily true. + // + // ErrEndOfSpan means that the Transformer output may differ from the + // input after n bytes. Note that n may be len(src), meaning that the output + // would contain additional bytes after otherwise identical output. + // ErrShortSrc means that src had insufficient data to determine whether the + // remaining bytes would change. Other than the error conditions listed + // here, implementations are free to report other errors that arise. + // + // Calling Span can modify the Transformer state as a side effect. In + // effect, it does the transformation just as calling Transform would, only + // without copying to a destination buffer and only up to a point it can + // determine the input and output bytes are the same. This is obviously more + // limited than calling Transform, but can be more efficient in terms of + // copying and allocating buffers. Calls to Span and Transform may be + // interleaved. + Span(src []byte, atEOF bool) (n int, err error) +} + +// NopResetter can be embedded by implementations of Transformer to add a nop +// Reset method. +type NopResetter struct{} + +// Reset implements the Reset method of the Transformer interface. +func (NopResetter) Reset() {} + +// Reader wraps another io.Reader by transforming the bytes read. +type Reader struct { + r io.Reader + t Transformer + err error + + // dst[dst0:dst1] contains bytes that have been transformed by t but + // not yet copied out via Read. + dst []byte + dst0, dst1 int + + // src[src0:src1] contains bytes that have been read from r but not + // yet transformed through t. + src []byte + src0, src1 int + + // transformComplete is whether the transformation is complete, + // regardless of whether or not it was successful. + transformComplete bool +} + +const defaultBufSize = 4096 + +// NewReader returns a new Reader that wraps r by transforming the bytes read +// via t. It calls Reset on t. +func NewReader(r io.Reader, t Transformer) *Reader { + t.Reset() + return &Reader{ + r: r, + t: t, + dst: make([]byte, defaultBufSize), + src: make([]byte, defaultBufSize), + } +} + +// Read implements the io.Reader interface. +func (r *Reader) Read(p []byte) (int, error) { + n, err := 0, error(nil) + for { + // Copy out any transformed bytes and return the final error if we are done. + if r.dst0 != r.dst1 { + n = copy(p, r.dst[r.dst0:r.dst1]) + r.dst0 += n + if r.dst0 == r.dst1 && r.transformComplete { + return n, r.err + } + return n, nil + } else if r.transformComplete { + return 0, r.err + } + + // Try to transform some source bytes, or to flush the transformer if we + // are out of source bytes. We do this even if r.r.Read returned an error. + // As the io.Reader documentation says, "process the n > 0 bytes returned + // before considering the error". + if r.src0 != r.src1 || r.err != nil { + r.dst0 = 0 + r.dst1, n, err = r.t.Transform(r.dst, r.src[r.src0:r.src1], r.err == io.EOF) + r.src0 += n + + switch { + case err == nil: + if r.src0 != r.src1 { + r.err = errInconsistentByteCount + } + // The Transform call was successful; we are complete if we + // cannot read more bytes into src. + r.transformComplete = r.err != nil + continue + case err == ErrShortDst && (r.dst1 != 0 || n != 0): + // Make room in dst by copying out, and try again. + continue + case err == ErrShortSrc && r.src1-r.src0 != len(r.src) && r.err == nil: + // Read more bytes into src via the code below, and try again. + default: + r.transformComplete = true + // The reader error (r.err) takes precedence over the + // transformer error (err) unless r.err is nil or io.EOF. + if r.err == nil || r.err == io.EOF { + r.err = err + } + continue + } + } + + // Move any untransformed source bytes to the start of the buffer + // and read more bytes. + if r.src0 != 0 { + r.src0, r.src1 = 0, copy(r.src, r.src[r.src0:r.src1]) + } + n, r.err = r.r.Read(r.src[r.src1:]) + r.src1 += n + } +} + +// TODO: implement ReadByte (and ReadRune??). + +// Writer wraps another io.Writer by transforming the bytes read. +// The user needs to call Close to flush unwritten bytes that may +// be buffered. +type Writer struct { + w io.Writer + t Transformer + dst []byte + + // src[:n] contains bytes that have not yet passed through t. + src []byte + n int +} + +// NewWriter returns a new Writer that wraps w by transforming the bytes written +// via t. It calls Reset on t. +func NewWriter(w io.Writer, t Transformer) *Writer { + t.Reset() + return &Writer{ + w: w, + t: t, + dst: make([]byte, defaultBufSize), + src: make([]byte, defaultBufSize), + } +} + +// Write implements the io.Writer interface. If there are not enough +// bytes available to complete a Transform, the bytes will be buffered +// for the next write. Call Close to convert the remaining bytes. +func (w *Writer) Write(data []byte) (n int, err error) { + src := data + if w.n > 0 { + // Append bytes from data to the last remainder. + // TODO: limit the amount copied on first try. + n = copy(w.src[w.n:], data) + w.n += n + src = w.src[:w.n] + } + for { + nDst, nSrc, err := w.t.Transform(w.dst, src, false) + if _, werr := w.w.Write(w.dst[:nDst]); werr != nil { + return n, werr + } + src = src[nSrc:] + if w.n == 0 { + n += nSrc + } else if len(src) <= n { + // Enough bytes from w.src have been consumed. We make src point + // to data instead to reduce the copying. + w.n = 0 + n -= len(src) + src = data[n:] + if n < len(data) && (err == nil || err == ErrShortSrc) { + continue + } + } + switch err { + case ErrShortDst: + // This error is okay as long as we are making progress. + if nDst > 0 || nSrc > 0 { + continue + } + case ErrShortSrc: + if len(src) < len(w.src) { + m := copy(w.src, src) + // If w.n > 0, bytes from data were already copied to w.src and n + // was already set to the number of bytes consumed. + if w.n == 0 { + n += m + } + w.n = m + err = nil + } else if nDst > 0 || nSrc > 0 { + // Not enough buffer to store the remainder. Keep processing as + // long as there is progress. Without this case, transforms that + // require a lookahead larger than the buffer may result in an + // error. This is not something one may expect to be common in + // practice, but it may occur when buffers are set to small + // sizes during testing. + continue + } + case nil: + if w.n > 0 { + err = errInconsistentByteCount + } + } + return n, err + } +} + +// Close implements the io.Closer interface. +func (w *Writer) Close() error { + src := w.src[:w.n] + for { + nDst, nSrc, err := w.t.Transform(w.dst, src, true) + if _, werr := w.w.Write(w.dst[:nDst]); werr != nil { + return werr + } + if err != ErrShortDst { + return err + } + src = src[nSrc:] + } +} + +type nop struct{ NopResetter } + +func (nop) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + n := copy(dst, src) + if n < len(src) { + err = ErrShortDst + } + return n, n, err +} + +func (nop) Span(src []byte, atEOF bool) (n int, err error) { + return len(src), nil +} + +type discard struct{ NopResetter } + +func (discard) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + return 0, len(src), nil +} + +var ( + // Discard is a Transformer for which all Transform calls succeed + // by consuming all bytes and writing nothing. + Discard Transformer = discard{} + + // Nop is a SpanningTransformer that copies src to dst. + Nop SpanningTransformer = nop{} +) + +// chain is a sequence of links. A chain with N Transformers has N+1 links and +// N+1 buffers. Of those N+1 buffers, the first and last are the src and dst +// buffers given to chain.Transform and the middle N-1 buffers are intermediate +// buffers owned by the chain. The i'th link transforms bytes from the i'th +// buffer chain.link[i].b at read offset chain.link[i].p to the i+1'th buffer +// chain.link[i+1].b at write offset chain.link[i+1].n, for i in [0, N). +type chain struct { + link []link + err error + // errStart is the index at which the error occurred plus 1. Processing + // errStart at this level at the next call to Transform. As long as + // errStart > 0, chain will not consume any more source bytes. + errStart int +} + +func (c *chain) fatalError(errIndex int, err error) { + if i := errIndex + 1; i > c.errStart { + c.errStart = i + c.err = err + } +} + +type link struct { + t Transformer + // b[p:n] holds the bytes to be transformed by t. + b []byte + p int + n int +} + +func (l *link) src() []byte { + return l.b[l.p:l.n] +} + +func (l *link) dst() []byte { + return l.b[l.n:] +} + +// Chain returns a Transformer that applies t in sequence. +func Chain(t ...Transformer) Transformer { + if len(t) == 0 { + return nop{} + } + c := &chain{link: make([]link, len(t)+1)} + for i, tt := range t { + c.link[i].t = tt + } + // Allocate intermediate buffers. + b := make([][defaultBufSize]byte, len(t)-1) + for i := range b { + c.link[i+1].b = b[i][:] + } + return c +} + +// Reset resets the state of Chain. It calls Reset on all the Transformers. +func (c *chain) Reset() { + for i, l := range c.link { + if l.t != nil { + l.t.Reset() + } + c.link[i].p, c.link[i].n = 0, 0 + } +} + +// TODO: make chain use Span (is going to be fun to implement!) + +// Transform applies the transformers of c in sequence. +func (c *chain) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + // Set up src and dst in the chain. + srcL := &c.link[0] + dstL := &c.link[len(c.link)-1] + srcL.b, srcL.p, srcL.n = src, 0, len(src) + dstL.b, dstL.n = dst, 0 + var lastFull, needProgress bool // for detecting progress + + // i is the index of the next Transformer to apply, for i in [low, high]. + // low is the lowest index for which c.link[low] may still produce bytes. + // high is the highest index for which c.link[high] has a Transformer. + // The error returned by Transform determines whether to increase or + // decrease i. We try to completely fill a buffer before converting it. + for low, i, high := c.errStart, c.errStart, len(c.link)-2; low <= i && i <= high; { + in, out := &c.link[i], &c.link[i+1] + nDst, nSrc, err0 := in.t.Transform(out.dst(), in.src(), atEOF && low == i) + out.n += nDst + in.p += nSrc + if i > 0 && in.p == in.n { + in.p, in.n = 0, 0 + } + needProgress, lastFull = lastFull, false + switch err0 { + case ErrShortDst: + // Process the destination buffer next. Return if we are already + // at the high index. + if i == high { + return dstL.n, srcL.p, ErrShortDst + } + if out.n != 0 { + i++ + // If the Transformer at the next index is not able to process any + // source bytes there is nothing that can be done to make progress + // and the bytes will remain unprocessed. lastFull is used to + // detect this and break out of the loop with a fatal error. + lastFull = true + continue + } + // The destination buffer was too small, but is completely empty. + // Return a fatal error as this transformation can never complete. + c.fatalError(i, errShortInternal) + case ErrShortSrc: + if i == 0 { + // Save ErrShortSrc in err. All other errors take precedence. + err = ErrShortSrc + break + } + // Source bytes were depleted before filling up the destination buffer. + // Verify we made some progress, move the remaining bytes to the errStart + // and try to get more source bytes. + if needProgress && nSrc == 0 || in.n-in.p == len(in.b) { + // There were not enough source bytes to proceed while the source + // buffer cannot hold any more bytes. Return a fatal error as this + // transformation can never complete. + c.fatalError(i, errShortInternal) + break + } + // in.b is an internal buffer and we can make progress. + in.p, in.n = 0, copy(in.b, in.src()) + fallthrough + case nil: + // if i == low, we have depleted the bytes at index i or any lower levels. + // In that case we increase low and i. In all other cases we decrease i to + // fetch more bytes before proceeding to the next index. + if i > low { + i-- + continue + } + default: + c.fatalError(i, err0) + } + // Exhausted level low or fatal error: increase low and continue + // to process the bytes accepted so far. + i++ + low = i + } + + // If c.errStart > 0, this means we found a fatal error. We will clear + // all upstream buffers. At this point, no more progress can be made + // downstream, as Transform would have bailed while handling ErrShortDst. + if c.errStart > 0 { + for i := 1; i < c.errStart; i++ { + c.link[i].p, c.link[i].n = 0, 0 + } + err, c.errStart, c.err = c.err, 0, nil + } + return dstL.n, srcL.p, err +} + +// Deprecated: use runes.Remove instead. +func RemoveFunc(f func(r rune) bool) Transformer { + return removeF(f) +} + +type removeF func(r rune) bool + +func (removeF) Reset() {} + +// Transform implements the Transformer interface. +func (t removeF) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + for r, sz := rune(0), 0; len(src) > 0; src = src[sz:] { + + if r = rune(src[0]); r < utf8.RuneSelf { + sz = 1 + } else { + r, sz = utf8.DecodeRune(src) + + if sz == 1 { + // Invalid rune. + if !atEOF && !utf8.FullRune(src) { + err = ErrShortSrc + break + } + // We replace illegal bytes with RuneError. Not doing so might + // otherwise turn a sequence of invalid UTF-8 into valid UTF-8. + // The resulting byte sequence may subsequently contain runes + // for which t(r) is true that were passed unnoticed. + if !t(r) { + if nDst+3 > len(dst) { + err = ErrShortDst + break + } + nDst += copy(dst[nDst:], "\uFFFD") + } + nSrc++ + continue + } + } + + if !t(r) { + if nDst+sz > len(dst) { + err = ErrShortDst + break + } + nDst += copy(dst[nDst:], src[:sz]) + } + nSrc += sz + } + return +} + +// grow returns a new []byte that is longer than b, and copies the first n bytes +// of b to the start of the new slice. +func grow(b []byte, n int) []byte { + m := len(b) + if m <= 32 { + m = 64 + } else if m <= 256 { + m *= 2 + } else { + m += m >> 1 + } + buf := make([]byte, m) + copy(buf, b[:n]) + return buf +} + +const initialBufSize = 128 + +// String returns a string with the result of converting s[:n] using t, where +// n <= len(s). If err == nil, n will be len(s). It calls Reset on t. +func String(t Transformer, s string) (result string, n int, err error) { + t.Reset() + if s == "" { + // Fast path for the common case for empty input. Results in about a + // 86% reduction of running time for BenchmarkStringLowerEmpty. + if _, _, err := t.Transform(nil, nil, true); err == nil { + return "", 0, nil + } + } + + // Allocate only once. Note that both dst and src escape when passed to + // Transform. + buf := [2 * initialBufSize]byte{} + dst := buf[:initialBufSize:initialBufSize] + src := buf[initialBufSize : 2*initialBufSize] + + // The input string s is transformed in multiple chunks (starting with a + // chunk size of initialBufSize). nDst and nSrc are per-chunk (or + // per-Transform-call) indexes, pDst and pSrc are overall indexes. + nDst, nSrc := 0, 0 + pDst, pSrc := 0, 0 + + // pPrefix is the length of a common prefix: the first pPrefix bytes of the + // result will equal the first pPrefix bytes of s. It is not guaranteed to + // be the largest such value, but if pPrefix, len(result) and len(s) are + // all equal after the final transform (i.e. calling Transform with atEOF + // being true returned nil error) then we don't need to allocate a new + // result string. + pPrefix := 0 + for { + // Invariant: pDst == pPrefix && pSrc == pPrefix. + + n := copy(src, s[pSrc:]) + nDst, nSrc, err = t.Transform(dst, src[:n], pSrc+n == len(s)) + pDst += nDst + pSrc += nSrc + + // TODO: let transformers implement an optional Spanner interface, akin + // to norm's QuickSpan. This would even allow us to avoid any allocation. + if !bytes.Equal(dst[:nDst], src[:nSrc]) { + break + } + pPrefix = pSrc + if err == ErrShortDst { + // A buffer can only be short if a transformer modifies its input. + break + } else if err == ErrShortSrc { + if nSrc == 0 { + // No progress was made. + break + } + // Equal so far and !atEOF, so continue checking. + } else if err != nil || pPrefix == len(s) { + return string(s[:pPrefix]), pPrefix, err + } + } + // Post-condition: pDst == pPrefix + nDst && pSrc == pPrefix + nSrc. + + // We have transformed the first pSrc bytes of the input s to become pDst + // transformed bytes. Those transformed bytes are discontiguous: the first + // pPrefix of them equal s[:pPrefix] and the last nDst of them equal + // dst[:nDst]. We copy them around, into a new dst buffer if necessary, so + // that they become one contiguous slice: dst[:pDst]. + if pPrefix != 0 { + newDst := dst + if pDst > len(newDst) { + newDst = make([]byte, len(s)+nDst-nSrc) + } + copy(newDst[pPrefix:pDst], dst[:nDst]) + copy(newDst[:pPrefix], s[:pPrefix]) + dst = newDst + } + + // Prevent duplicate Transform calls with atEOF being true at the end of + // the input. Also return if we have an unrecoverable error. + if (err == nil && pSrc == len(s)) || + (err != nil && err != ErrShortDst && err != ErrShortSrc) { + return string(dst[:pDst]), pSrc, err + } + + // Transform the remaining input, growing dst and src buffers as necessary. + for { + n := copy(src, s[pSrc:]) + nDst, nSrc, err := t.Transform(dst[pDst:], src[:n], pSrc+n == len(s)) + pDst += nDst + pSrc += nSrc + + // If we got ErrShortDst or ErrShortSrc, do not grow as long as we can + // make progress. This may avoid excessive allocations. + if err == ErrShortDst { + if nDst == 0 { + dst = grow(dst, pDst) + } + } else if err == ErrShortSrc { + if nSrc == 0 { + src = grow(src, 0) + } + } else if err != nil || pSrc == len(s) { + return string(dst[:pDst]), pSrc, err + } + } +} + +// Bytes returns a new byte slice with the result of converting b[:n] using t, +// where n <= len(b). If err == nil, n will be len(b). It calls Reset on t. +func Bytes(t Transformer, b []byte) (result []byte, n int, err error) { + return doAppend(t, 0, make([]byte, len(b)), b) +} + +// Append appends the result of converting src[:n] using t to dst, where +// n <= len(src), If err == nil, n will be len(src). It calls Reset on t. +func Append(t Transformer, dst, src []byte) (result []byte, n int, err error) { + if len(dst) == cap(dst) { + n := len(src) + len(dst) // It is okay for this to be 0. + b := make([]byte, n) + dst = b[:copy(b, dst)] + } + return doAppend(t, len(dst), dst[:cap(dst)], src) +} + +func doAppend(t Transformer, pDst int, dst, src []byte) (result []byte, n int, err error) { + t.Reset() + pSrc := 0 + for { + nDst, nSrc, err := t.Transform(dst[pDst:], src[pSrc:], true) + pDst += nDst + pSrc += nSrc + if err != ErrShortDst { + return dst[:pDst], pSrc, err + } + + // Grow the destination buffer, but do not grow as long as we can make + // progress. This may avoid excessive allocations. + if nDst == 0 { + dst = grow(dst, pDst) + } + } +} diff --git a/vendor/golang.org/x/text/transform/transform_test.go b/vendor/golang.org/x/text/transform/transform_test.go new file mode 100644 index 0000000..771633d --- /dev/null +++ b/vendor/golang.org/x/text/transform/transform_test.go @@ -0,0 +1,1317 @@ +// 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. + +package transform + +import ( + "bytes" + "errors" + "fmt" + "io/ioutil" + "strconv" + "strings" + "testing" + "time" + "unicode/utf8" + + "golang.org/x/text/internal/testtext" +) + +type lowerCaseASCII struct{ NopResetter } + +func (lowerCaseASCII) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + n := len(src) + if n > len(dst) { + n, err = len(dst), ErrShortDst + } + for i, c := range src[:n] { + if 'A' <= c && c <= 'Z' { + c += 'a' - 'A' + } + dst[i] = c + } + return n, n, err +} + +// lowerCaseASCIILookahead lowercases the string and reports ErrShortSrc as long +// as the input is not atEOF. +type lowerCaseASCIILookahead struct{ NopResetter } + +func (lowerCaseASCIILookahead) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + n := len(src) + if n > len(dst) { + n, err = len(dst), ErrShortDst + } + for i, c := range src[:n] { + if 'A' <= c && c <= 'Z' { + c += 'a' - 'A' + } + dst[i] = c + } + if !atEOF { + err = ErrShortSrc + } + return n, n, err +} + +var errYouMentionedX = errors.New("you mentioned X") + +type dontMentionX struct{ NopResetter } + +func (dontMentionX) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + n := len(src) + if n > len(dst) { + n, err = len(dst), ErrShortDst + } + for i, c := range src[:n] { + if c == 'X' { + return i, i, errYouMentionedX + } + dst[i] = c + } + return n, n, err +} + +var errAtEnd = errors.New("error after all text") + +type errorAtEnd struct{ NopResetter } + +func (errorAtEnd) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + n := copy(dst, src) + if n < len(src) { + return n, n, ErrShortDst + } + if atEOF { + return n, n, errAtEnd + } + return n, n, nil +} + +type replaceWithConstant struct { + replacement string + written int +} + +func (t *replaceWithConstant) Reset() { + t.written = 0 +} + +func (t *replaceWithConstant) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + if atEOF { + nDst = copy(dst, t.replacement[t.written:]) + t.written += nDst + if t.written < len(t.replacement) { + err = ErrShortDst + } + } + return nDst, len(src), err +} + +type addAnXAtTheEnd struct{ NopResetter } + +func (addAnXAtTheEnd) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + n := copy(dst, src) + if n < len(src) { + return n, n, ErrShortDst + } + if !atEOF { + return n, n, nil + } + if len(dst) == n { + return n, n, ErrShortDst + } + dst[n] = 'X' + return n + 1, n, nil +} + +// doublerAtEOF is a strange Transformer that transforms "this" to "tthhiiss", +// but only if atEOF is true. +type doublerAtEOF struct{ NopResetter } + +func (doublerAtEOF) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + if !atEOF { + return 0, 0, ErrShortSrc + } + for i, c := range src { + if 2*i+2 >= len(dst) { + return 2 * i, i, ErrShortDst + } + dst[2*i+0] = c + dst[2*i+1] = c + } + return 2 * len(src), len(src), nil +} + +// rleDecode and rleEncode implement a toy run-length encoding: "aabbbbbbbbbb" +// is encoded as "2a10b". The decoding is assumed to not contain any numbers. + +type rleDecode struct{ NopResetter } + +func (rleDecode) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { +loop: + for len(src) > 0 { + n := 0 + for i, c := range src { + if '0' <= c && c <= '9' { + n = 10*n + int(c-'0') + continue + } + if i == 0 { + return nDst, nSrc, errors.New("rleDecode: bad input") + } + if n > len(dst) { + return nDst, nSrc, ErrShortDst + } + for j := 0; j < n; j++ { + dst[j] = c + } + dst, src = dst[n:], src[i+1:] + nDst, nSrc = nDst+n, nSrc+i+1 + continue loop + } + if atEOF { + return nDst, nSrc, errors.New("rleDecode: bad input") + } + return nDst, nSrc, ErrShortSrc + } + return nDst, nSrc, nil +} + +type rleEncode struct { + NopResetter + + // allowStutter means that "xxxxxxxx" can be encoded as "5x3x" + // instead of always as "8x". + allowStutter bool +} + +func (e rleEncode) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + for len(src) > 0 { + n, c0 := len(src), src[0] + for i, c := range src[1:] { + if c != c0 { + n = i + 1 + break + } + } + if n == len(src) && !atEOF && !e.allowStutter { + return nDst, nSrc, ErrShortSrc + } + s := strconv.Itoa(n) + if len(s) >= len(dst) { + return nDst, nSrc, ErrShortDst + } + copy(dst, s) + dst[len(s)] = c0 + dst, src = dst[len(s)+1:], src[n:] + nDst, nSrc = nDst+len(s)+1, nSrc+n + } + return nDst, nSrc, nil +} + +// trickler consumes all input bytes, but writes a single byte at a time to dst. +type trickler []byte + +func (t *trickler) Reset() { + *t = nil +} + +func (t *trickler) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + *t = append(*t, src...) + if len(*t) == 0 { + return 0, 0, nil + } + if len(dst) == 0 { + return 0, len(src), ErrShortDst + } + dst[0] = (*t)[0] + *t = (*t)[1:] + if len(*t) > 0 { + err = ErrShortDst + } + return 1, len(src), err +} + +// delayedTrickler is like trickler, but delays writing output to dst. This is +// highly unlikely to be relevant in practice, but it seems like a good idea +// to have some tolerance as long as progress can be detected. +type delayedTrickler []byte + +func (t *delayedTrickler) Reset() { + *t = nil +} + +func (t *delayedTrickler) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + if len(*t) > 0 && len(dst) > 0 { + dst[0] = (*t)[0] + *t = (*t)[1:] + nDst = 1 + } + *t = append(*t, src...) + if len(*t) > 0 { + err = ErrShortDst + } + return nDst, len(src), err +} + +type testCase struct { + desc string + t Transformer + src string + dstSize int + srcSize int + ioSize int + wantStr string + wantErr error + wantIter int // number of iterations taken; 0 means we don't care. +} + +func (t testCase) String() string { + return tstr(t.t) + "; " + t.desc +} + +func tstr(t Transformer) string { + if stringer, ok := t.(fmt.Stringer); ok { + return stringer.String() + } + s := fmt.Sprintf("%T", t) + return s[1+strings.Index(s, "."):] +} + +func (c chain) String() string { + buf := &bytes.Buffer{} + buf.WriteString("Chain(") + for i, l := range c.link[:len(c.link)-1] { + if i != 0 { + fmt.Fprint(buf, ", ") + } + buf.WriteString(tstr(l.t)) + } + buf.WriteString(")") + return buf.String() +} + +var testCases = []testCase{ + { + desc: "empty", + t: lowerCaseASCII{}, + src: "", + dstSize: 100, + srcSize: 100, + wantStr: "", + }, + + { + desc: "basic", + t: lowerCaseASCII{}, + src: "Hello WORLD.", + dstSize: 100, + srcSize: 100, + wantStr: "hello world.", + }, + + { + desc: "small dst", + t: lowerCaseASCII{}, + src: "Hello WORLD.", + dstSize: 3, + srcSize: 100, + wantStr: "hello world.", + }, + + { + desc: "small src", + t: lowerCaseASCII{}, + src: "Hello WORLD.", + dstSize: 100, + srcSize: 4, + wantStr: "hello world.", + }, + + { + desc: "small buffers", + t: lowerCaseASCII{}, + src: "Hello WORLD.", + dstSize: 3, + srcSize: 4, + wantStr: "hello world.", + }, + + { + desc: "very small buffers", + t: lowerCaseASCII{}, + src: "Hello WORLD.", + dstSize: 1, + srcSize: 1, + wantStr: "hello world.", + }, + + { + desc: "small dst with lookahead", + t: lowerCaseASCIILookahead{}, + src: "Hello WORLD.", + dstSize: 3, + srcSize: 100, + wantStr: "hello world.", + }, + + { + desc: "small src with lookahead", + t: lowerCaseASCIILookahead{}, + src: "Hello WORLD.", + dstSize: 100, + srcSize: 4, + wantStr: "hello world.", + }, + + { + desc: "small buffers with lookahead", + t: lowerCaseASCIILookahead{}, + src: "Hello WORLD.", + dstSize: 3, + srcSize: 4, + wantStr: "hello world.", + }, + + { + desc: "very small buffers with lookahead", + t: lowerCaseASCIILookahead{}, + src: "Hello WORLD.", + dstSize: 1, + srcSize: 2, + wantStr: "hello world.", + }, + + { + desc: "user error", + t: dontMentionX{}, + src: "The First Rule of Transform Club: don't mention Mister X, ever.", + dstSize: 100, + srcSize: 100, + wantStr: "The First Rule of Transform Club: don't mention Mister ", + wantErr: errYouMentionedX, + }, + + { + desc: "user error at end", + t: errorAtEnd{}, + src: "All goes well until it doesn't.", + dstSize: 100, + srcSize: 100, + wantStr: "All goes well until it doesn't.", + wantErr: errAtEnd, + }, + + { + desc: "user error at end, incremental", + t: errorAtEnd{}, + src: "All goes well until it doesn't.", + dstSize: 10, + srcSize: 10, + wantStr: "All goes well until it doesn't.", + wantErr: errAtEnd, + }, + + { + desc: "replace entire non-empty string with one byte", + t: &replaceWithConstant{replacement: "X"}, + src: "none of this will be copied", + dstSize: 1, + srcSize: 10, + wantStr: "X", + }, + + { + desc: "replace entire empty string with one byte", + t: &replaceWithConstant{replacement: "X"}, + src: "", + dstSize: 1, + srcSize: 10, + wantStr: "X", + }, + + { + desc: "replace entire empty string with seven bytes", + t: &replaceWithConstant{replacement: "ABCDEFG"}, + src: "", + dstSize: 3, + srcSize: 10, + wantStr: "ABCDEFG", + }, + + { + desc: "add an X (initialBufSize-1)", + t: addAnXAtTheEnd{}, + src: aaa[:initialBufSize-1], + dstSize: 10, + srcSize: 10, + wantStr: aaa[:initialBufSize-1] + "X", + }, + + { + desc: "add an X (initialBufSize+0)", + t: addAnXAtTheEnd{}, + src: aaa[:initialBufSize+0], + dstSize: 10, + srcSize: 10, + wantStr: aaa[:initialBufSize+0] + "X", + }, + + { + desc: "add an X (initialBufSize+1)", + t: addAnXAtTheEnd{}, + src: aaa[:initialBufSize+1], + dstSize: 10, + srcSize: 10, + wantStr: aaa[:initialBufSize+1] + "X", + }, + + { + desc: "small buffers", + t: dontMentionX{}, + src: "The First Rule of Transform Club: don't mention Mister X, ever.", + dstSize: 10, + srcSize: 10, + wantStr: "The First Rule of Transform Club: don't mention Mister ", + wantErr: errYouMentionedX, + }, + + { + desc: "very small buffers", + t: dontMentionX{}, + src: "The First Rule of Transform Club: don't mention Mister X, ever.", + dstSize: 1, + srcSize: 1, + wantStr: "The First Rule of Transform Club: don't mention Mister ", + wantErr: errYouMentionedX, + }, + + { + desc: "only transform at EOF", + t: doublerAtEOF{}, + src: "this", + dstSize: 100, + srcSize: 100, + wantStr: "tthhiiss", + }, + + { + desc: "basic", + t: rleDecode{}, + src: "1a2b3c10d11e0f1g", + dstSize: 100, + srcSize: 100, + wantStr: "abbcccddddddddddeeeeeeeeeeeg", + }, + + { + desc: "long", + t: rleDecode{}, + src: "12a23b34c45d56e99z", + dstSize: 100, + srcSize: 100, + wantStr: strings.Repeat("a", 12) + + strings.Repeat("b", 23) + + strings.Repeat("c", 34) + + strings.Repeat("d", 45) + + strings.Repeat("e", 56) + + strings.Repeat("z", 99), + }, + + { + desc: "tight buffers", + t: rleDecode{}, + src: "1a2b3c10d11e0f1g", + dstSize: 11, + srcSize: 3, + wantStr: "abbcccddddddddddeeeeeeeeeeeg", + }, + + { + desc: "short dst", + t: rleDecode{}, + src: "1a2b3c10d11e0f1g", + dstSize: 10, + srcSize: 3, + wantStr: "abbcccdddddddddd", + wantErr: ErrShortDst, + }, + + { + desc: "short src", + t: rleDecode{}, + src: "1a2b3c10d11e0f1g", + dstSize: 11, + srcSize: 2, + ioSize: 2, + wantStr: "abbccc", + wantErr: ErrShortSrc, + }, + + { + desc: "basic", + t: rleEncode{}, + src: "abbcccddddddddddeeeeeeeeeeeg", + dstSize: 100, + srcSize: 100, + wantStr: "1a2b3c10d11e1g", + }, + + { + desc: "long", + t: rleEncode{}, + src: strings.Repeat("a", 12) + + strings.Repeat("b", 23) + + strings.Repeat("c", 34) + + strings.Repeat("d", 45) + + strings.Repeat("e", 56) + + strings.Repeat("z", 99), + dstSize: 100, + srcSize: 100, + wantStr: "12a23b34c45d56e99z", + }, + + { + desc: "tight buffers", + t: rleEncode{}, + src: "abbcccddddddddddeeeeeeeeeeeg", + dstSize: 3, + srcSize: 12, + wantStr: "1a2b3c10d11e1g", + }, + + { + desc: "short dst", + t: rleEncode{}, + src: "abbcccddddddddddeeeeeeeeeeeg", + dstSize: 2, + srcSize: 12, + wantStr: "1a2b3c", + wantErr: ErrShortDst, + }, + + { + desc: "short src", + t: rleEncode{}, + src: "abbcccddddddddddeeeeeeeeeeeg", + dstSize: 3, + srcSize: 11, + ioSize: 11, + wantStr: "1a2b3c10d", + wantErr: ErrShortSrc, + }, + + { + desc: "allowStutter = false", + t: rleEncode{allowStutter: false}, + src: "aaaabbbbbbbbccccddddd", + dstSize: 10, + srcSize: 10, + wantStr: "4a8b4c5d", + }, + + { + desc: "allowStutter = true", + t: rleEncode{allowStutter: true}, + src: "aaaabbbbbbbbccccddddd", + dstSize: 10, + srcSize: 10, + ioSize: 10, + wantStr: "4a6b2b4c4d1d", + }, + + { + desc: "trickler", + t: &trickler{}, + src: "abcdefghijklm", + dstSize: 3, + srcSize: 15, + wantStr: "abcdefghijklm", + }, + + { + desc: "delayedTrickler", + t: &delayedTrickler{}, + src: "abcdefghijklm", + dstSize: 3, + srcSize: 15, + wantStr: "abcdefghijklm", + }, +} + +func TestReader(t *testing.T) { + for _, tc := range testCases { + testtext.Run(t, tc.desc, func(t *testing.T) { + r := NewReader(strings.NewReader(tc.src), tc.t) + // Differently sized dst and src buffers are not part of the + // exported API. We override them manually. + r.dst = make([]byte, tc.dstSize) + r.src = make([]byte, tc.srcSize) + got, err := ioutil.ReadAll(r) + str := string(got) + if str != tc.wantStr || err != tc.wantErr { + t.Errorf("\ngot %q, %v\nwant %q, %v", str, err, tc.wantStr, tc.wantErr) + } + }) + } +} + +func TestWriter(t *testing.T) { + tests := append(testCases, chainTests()...) + for _, tc := range tests { + sizes := []int{1, 2, 3, 4, 5, 10, 100, 1000} + if tc.ioSize > 0 { + sizes = []int{tc.ioSize} + } + for _, sz := range sizes { + testtext.Run(t, fmt.Sprintf("%s/%d", tc.desc, sz), func(t *testing.T) { + bb := &bytes.Buffer{} + w := NewWriter(bb, tc.t) + // Differently sized dst and src buffers are not part of the + // exported API. We override them manually. + w.dst = make([]byte, tc.dstSize) + w.src = make([]byte, tc.srcSize) + src := make([]byte, sz) + var err error + for b := tc.src; len(b) > 0 && err == nil; { + n := copy(src, b) + b = b[n:] + m := 0 + m, err = w.Write(src[:n]) + if m != n && err == nil { + t.Errorf("did not consume all bytes %d < %d", m, n) + } + } + if err == nil { + err = w.Close() + } + str := bb.String() + if str != tc.wantStr || err != tc.wantErr { + t.Errorf("\ngot %q, %v\nwant %q, %v", str, err, tc.wantStr, tc.wantErr) + } + }) + } + } +} + +func TestNop(t *testing.T) { + testCases := []struct { + str string + dstSize int + err error + }{ + {"", 0, nil}, + {"", 10, nil}, + {"a", 0, ErrShortDst}, + {"a", 1, nil}, + {"a", 10, nil}, + } + for i, tc := range testCases { + dst := make([]byte, tc.dstSize) + nDst, nSrc, err := Nop.Transform(dst, []byte(tc.str), true) + want := tc.str + if tc.dstSize < len(want) { + want = want[:tc.dstSize] + } + if got := string(dst[:nDst]); got != want || err != tc.err || nSrc != nDst { + t.Errorf("%d:\ngot %q, %d, %v\nwant %q, %d, %v", i, got, nSrc, err, want, nDst, tc.err) + } + } +} + +func TestDiscard(t *testing.T) { + testCases := []struct { + str string + dstSize int + }{ + {"", 0}, + {"", 10}, + {"a", 0}, + {"ab", 10}, + } + for i, tc := range testCases { + nDst, nSrc, err := Discard.Transform(make([]byte, tc.dstSize), []byte(tc.str), true) + if nDst != 0 || nSrc != len(tc.str) || err != nil { + t.Errorf("%d:\ngot %q, %d, %v\nwant 0, %d, nil", i, nDst, nSrc, err, len(tc.str)) + } + } +} + +// mkChain creates a Chain transformer. x must be alternating between transformer +// and bufSize, like T, (sz, T)* +func mkChain(x ...interface{}) *chain { + t := []Transformer{} + for i := 0; i < len(x); i += 2 { + t = append(t, x[i].(Transformer)) + } + c := Chain(t...).(*chain) + for i, j := 1, 1; i < len(x); i, j = i+2, j+1 { + c.link[j].b = make([]byte, x[i].(int)) + } + return c +} + +func chainTests() []testCase { + return []testCase{ + { + desc: "nil error", + t: mkChain(rleEncode{}, 100, lowerCaseASCII{}), + src: "ABB", + dstSize: 100, + srcSize: 100, + wantStr: "1a2b", + wantErr: nil, + wantIter: 1, + }, + + { + desc: "short dst buffer", + t: mkChain(lowerCaseASCII{}, 3, rleDecode{}), + src: "1a2b3c10d11e0f1g", + dstSize: 10, + srcSize: 3, + wantStr: "abbcccdddddddddd", + wantErr: ErrShortDst, + }, + + { + desc: "short internal dst buffer", + t: mkChain(lowerCaseASCII{}, 3, rleDecode{}, 10, Nop), + src: "1a2b3c10d11e0f1g", + dstSize: 100, + srcSize: 3, + wantStr: "abbcccdddddddddd", + wantErr: errShortInternal, + }, + + { + desc: "short internal dst buffer from input", + t: mkChain(rleDecode{}, 10, Nop), + src: "1a2b3c10d11e0f1g", + dstSize: 100, + srcSize: 3, + wantStr: "abbcccdddddddddd", + wantErr: errShortInternal, + }, + + { + desc: "empty short internal dst buffer", + t: mkChain(lowerCaseASCII{}, 3, rleDecode{}, 10, Nop), + src: "4a7b11e0f1g", + dstSize: 100, + srcSize: 3, + wantStr: "aaaabbbbbbb", + wantErr: errShortInternal, + }, + + { + desc: "empty short internal dst buffer from input", + t: mkChain(rleDecode{}, 10, Nop), + src: "4a7b11e0f1g", + dstSize: 100, + srcSize: 3, + wantStr: "aaaabbbbbbb", + wantErr: errShortInternal, + }, + + { + desc: "short internal src buffer after full dst buffer", + t: mkChain(Nop, 5, rleEncode{}, 10, Nop), + src: "cccccddddd", + dstSize: 100, + srcSize: 100, + wantStr: "", + wantErr: errShortInternal, + wantIter: 1, + }, + + { + desc: "short internal src buffer after short dst buffer; test lastFull", + t: mkChain(rleDecode{}, 5, rleEncode{}, 4, Nop), + src: "2a1b4c6d", + dstSize: 100, + srcSize: 100, + wantStr: "2a1b", + wantErr: errShortInternal, + }, + + { + desc: "short internal src buffer after successful complete fill", + t: mkChain(Nop, 3, rleDecode{}), + src: "123a4b", + dstSize: 4, + srcSize: 3, + wantStr: "", + wantErr: errShortInternal, + wantIter: 1, + }, + + { + desc: "short internal src buffer after short dst buffer; test lastFull", + t: mkChain(rleDecode{}, 5, rleEncode{}), + src: "2a1b4c6d", + dstSize: 4, + srcSize: 100, + wantStr: "2a1b", + wantErr: errShortInternal, + }, + + { + desc: "short src buffer", + t: mkChain(rleEncode{}, 5, Nop), + src: "abbcccddddeeeee", + dstSize: 4, + srcSize: 4, + ioSize: 4, + wantStr: "1a2b3c", + wantErr: ErrShortSrc, + }, + + { + desc: "process all in one go", + t: mkChain(rleEncode{}, 5, Nop), + src: "abbcccddddeeeeeffffff", + dstSize: 100, + srcSize: 100, + wantStr: "1a2b3c4d5e6f", + wantErr: nil, + wantIter: 1, + }, + + { + desc: "complete processing downstream after error", + t: mkChain(dontMentionX{}, 2, rleDecode{}, 5, Nop), + src: "3a4b5eX", + dstSize: 100, + srcSize: 100, + ioSize: 100, + wantStr: "aaabbbbeeeee", + wantErr: errYouMentionedX, + }, + + { + desc: "return downstream fatal errors first (followed by short dst)", + t: mkChain(dontMentionX{}, 8, rleDecode{}, 4, Nop), + src: "3a4b5eX", + dstSize: 100, + srcSize: 100, + ioSize: 100, + wantStr: "aaabbbb", + wantErr: errShortInternal, + }, + + { + desc: "return downstream fatal errors first (followed by short src)", + t: mkChain(dontMentionX{}, 5, Nop, 1, rleDecode{}), + src: "1a5bX", + dstSize: 100, + srcSize: 100, + ioSize: 100, + wantStr: "", + wantErr: errShortInternal, + }, + + { + desc: "short internal", + t: mkChain(Nop, 11, rleEncode{}, 3, Nop), + src: "abbcccddddddddddeeeeeeeeeeeg", + dstSize: 3, + srcSize: 100, + wantStr: "1a2b3c10d", + wantErr: errShortInternal, + }, + } +} + +func doTransform(tc testCase) (res string, iter int, err error) { + tc.t.Reset() + dst := make([]byte, tc.dstSize) + out, in := make([]byte, 0, 2*len(tc.src)), []byte(tc.src) + for { + iter++ + src, atEOF := in, true + if len(src) > tc.srcSize { + src, atEOF = src[:tc.srcSize], false + } + nDst, nSrc, err := tc.t.Transform(dst, src, atEOF) + out = append(out, dst[:nDst]...) + in = in[nSrc:] + switch { + case err == nil && len(in) != 0: + case err == ErrShortSrc && nSrc > 0: + case err == ErrShortDst && (nDst > 0 || nSrc > 0): + default: + return string(out), iter, err + } + } +} + +func TestChain(t *testing.T) { + if c, ok := Chain().(nop); !ok { + t.Errorf("empty chain: %v; want Nop", c) + } + + // Test Chain for a single Transformer. + for _, tc := range testCases { + tc.t = Chain(tc.t) + str, _, err := doTransform(tc) + if str != tc.wantStr || err != tc.wantErr { + t.Errorf("%s:\ngot %q, %v\nwant %q, %v", tc, str, err, tc.wantStr, tc.wantErr) + } + } + + tests := chainTests() + sizes := []int{1, 2, 3, 4, 5, 7, 10, 100, 1000} + addTest := func(tc testCase, t *chain) { + if t.link[0].t != tc.t && tc.wantErr == ErrShortSrc { + tc.wantErr = errShortInternal + } + if t.link[len(t.link)-2].t != tc.t && tc.wantErr == ErrShortDst { + tc.wantErr = errShortInternal + } + tc.t = t + tests = append(tests, tc) + } + for _, tc := range testCases { + for _, sz := range sizes { + tt := tc + tt.dstSize = sz + addTest(tt, mkChain(tc.t, tc.dstSize, Nop)) + addTest(tt, mkChain(tc.t, tc.dstSize, Nop, 2, Nop)) + addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop)) + if sz >= tc.dstSize && (tc.wantErr != ErrShortDst || sz == tc.dstSize) { + addTest(tt, mkChain(Nop, tc.srcSize, tc.t)) + addTest(tt, mkChain(Nop, 100, Nop, tc.srcSize, tc.t)) + } + } + } + for _, tc := range testCases { + tt := tc + tt.dstSize = 1 + tt.wantStr = "" + addTest(tt, mkChain(tc.t, tc.dstSize, Discard)) + addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Discard)) + addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, tc.dstSize, Discard)) + } + for _, tc := range testCases { + tt := tc + tt.dstSize = 100 + tt.wantStr = strings.Replace(tc.src, "0f", "", -1) + // Chain encoders and decoders. + if _, ok := tc.t.(rleEncode); ok && tc.wantErr == nil { + addTest(tt, mkChain(tc.t, tc.dstSize, Nop, 1000, rleDecode{})) + addTest(tt, mkChain(tc.t, tc.dstSize, Nop, tc.dstSize, rleDecode{})) + addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 100, rleDecode{})) + // decoding needs larger destinations + addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, rleDecode{}, 100, Nop)) + addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 100, rleDecode{}, 100, Nop)) + } else if _, ok := tc.t.(rleDecode); ok && tc.wantErr == nil { + // The internal buffer size may need to be the sum of the maximum segment + // size of the two encoders! + addTest(tt, mkChain(tc.t, 2*tc.dstSize, rleEncode{})) + addTest(tt, mkChain(tc.t, tc.dstSize, Nop, 101, rleEncode{})) + addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 100, rleEncode{})) + addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 200, rleEncode{}, 100, Nop)) + } + } + for _, tc := range tests { + str, iter, err := doTransform(tc) + mi := tc.wantIter != 0 && tc.wantIter != iter + if str != tc.wantStr || err != tc.wantErr || mi { + t.Errorf("%s:\ngot iter:%d, %q, %v\nwant iter:%d, %q, %v", tc, iter, str, err, tc.wantIter, tc.wantStr, tc.wantErr) + } + break + } +} + +func TestRemoveFunc(t *testing.T) { + filter := RemoveFunc(func(r rune) bool { + return strings.IndexRune("ab\u0300\u1234,", r) != -1 + }) + tests := []testCase{ + { + src: ",", + wantStr: "", + }, + + { + src: "c", + wantStr: "c", + }, + + { + src: "\u2345", + wantStr: "\u2345", + }, + + { + src: "tschüß", + wantStr: "tschüß", + }, + + { + src: ",до,свидания,", + wantStr: "досвидания", + }, + + { + src: "a\xbd\xb2=\xbc ⌘", + wantStr: "\uFFFD\uFFFD=\uFFFD ⌘", + }, + + { + // If we didn't replace illegal bytes with RuneError, the result + // would be \u0300 or the code would need to be more complex. + src: "\xcc\u0300\x80", + wantStr: "\uFFFD\uFFFD", + }, + + { + src: "\xcc\u0300\x80", + dstSize: 3, + wantStr: "\uFFFD\uFFFD", + wantIter: 2, + }, + + { + // Test a long buffer greater than the internal buffer size + src: "hello\xcc\xcc\xccworld", + srcSize: 13, + wantStr: "hello\uFFFD\uFFFD\uFFFDworld", + wantIter: 1, + }, + + { + src: "\u2345", + dstSize: 2, + wantStr: "", + wantErr: ErrShortDst, + }, + + { + src: "\xcc", + dstSize: 2, + wantStr: "", + wantErr: ErrShortDst, + }, + + { + src: "\u0300", + dstSize: 2, + srcSize: 1, + wantStr: "", + wantErr: ErrShortSrc, + }, + + { + t: RemoveFunc(func(r rune) bool { + return r == utf8.RuneError + }), + src: "\xcc\u0300\x80", + wantStr: "\u0300", + }, + } + + for _, tc := range tests { + tc.desc = tc.src + if tc.t == nil { + tc.t = filter + } + if tc.dstSize == 0 { + tc.dstSize = 100 + } + if tc.srcSize == 0 { + tc.srcSize = 100 + } + str, iter, err := doTransform(tc) + mi := tc.wantIter != 0 && tc.wantIter != iter + if str != tc.wantStr || err != tc.wantErr || mi { + t.Errorf("%+q:\ngot iter:%d, %+q, %v\nwant iter:%d, %+q, %v", tc.src, iter, str, err, tc.wantIter, tc.wantStr, tc.wantErr) + } + + tc.src = str + idem, _, _ := doTransform(tc) + if str != idem { + t.Errorf("%+q: found %+q; want %+q", tc.src, idem, str) + } + } +} + +func testString(t *testing.T, f func(Transformer, string) (string, int, error)) { + for _, tt := range append(testCases, chainTests()...) { + if tt.desc == "allowStutter = true" { + // We don't have control over the buffer size, so we eliminate tests + // that depend on a specific buffer size being set. + continue + } + if tt.wantErr == ErrShortDst || tt.wantErr == ErrShortSrc { + // The result string will be different. + continue + } + testtext.Run(t, tt.desc, func(t *testing.T) { + got, n, err := f(tt.t, tt.src) + if tt.wantErr != err { + t.Errorf("error: got %v; want %v", err, tt.wantErr) + } + // Check that err == nil implies that n == len(tt.src). Note that vice + // versa isn't necessarily true. + if err == nil && n != len(tt.src) { + t.Errorf("err == nil: got %d bytes, want %d", n, err) + } + if got != tt.wantStr { + t.Errorf("string: got %q; want %q", got, tt.wantStr) + } + }) + } +} + +func TestBytes(t *testing.T) { + testString(t, func(z Transformer, s string) (string, int, error) { + b, n, err := Bytes(z, []byte(s)) + return string(b), n, err + }) +} + +func TestAppend(t *testing.T) { + // Create a bunch of subtests for different buffer sizes. + testCases := [][]byte{ + nil, + make([]byte, 0, 0), + make([]byte, 0, 1), + make([]byte, 1, 1), + make([]byte, 1, 5), + make([]byte, 100, 100), + make([]byte, 100, 200), + } + for _, tc := range testCases { + testString(t, func(z Transformer, s string) (string, int, error) { + b, n, err := Append(z, tc, []byte(s)) + return string(b[len(tc):]), n, err + }) + } +} + +func TestString(t *testing.T) { + testtext.Run(t, "transform", func(t *testing.T) { testString(t, String) }) + + // Overrun the internal destination buffer. + for i, s := range []string{ + aaa[:1*initialBufSize-1], + aaa[:1*initialBufSize+0], + aaa[:1*initialBufSize+1], + AAA[:1*initialBufSize-1], + AAA[:1*initialBufSize+0], + AAA[:1*initialBufSize+1], + AAA[:2*initialBufSize-1], + AAA[:2*initialBufSize+0], + AAA[:2*initialBufSize+1], + aaa[:1*initialBufSize-2] + "A", + aaa[:1*initialBufSize-1] + "A", + aaa[:1*initialBufSize+0] + "A", + aaa[:1*initialBufSize+1] + "A", + } { + testtext.Run(t, fmt.Sprint("dst buffer test using lower/", i), func(t *testing.T) { + got, _, _ := String(lowerCaseASCII{}, s) + if want := strings.ToLower(s); got != want { + t.Errorf("got %s (%d); want %s (%d)", got, len(got), want, len(want)) + } + }) + } + + // Overrun the internal source buffer. + for i, s := range []string{ + aaa[:1*initialBufSize-1], + aaa[:1*initialBufSize+0], + aaa[:1*initialBufSize+1], + aaa[:2*initialBufSize+1], + aaa[:2*initialBufSize+0], + aaa[:2*initialBufSize+1], + } { + testtext.Run(t, fmt.Sprint("src buffer test using rleEncode/", i), func(t *testing.T) { + got, _, _ := String(rleEncode{}, s) + if want := fmt.Sprintf("%da", len(s)); got != want { + t.Errorf("got %s (%d); want %s (%d)", got, len(got), want, len(want)) + } + }) + } + + // Test allocations for non-changing strings. + // Note we still need to allocate a single buffer. + for i, s := range []string{ + "", + "123456789", + aaa[:initialBufSize-1], + aaa[:initialBufSize+0], + aaa[:initialBufSize+1], + aaa[:10*initialBufSize], + } { + testtext.Run(t, fmt.Sprint("alloc/", i), func(t *testing.T) { + if n := testtext.AllocsPerRun(5, func() { String(&lowerCaseASCIILookahead{}, s) }); n > 1 { + t.Errorf("#allocs was %f; want 1", n) + } + }) + } +} + +// TestBytesAllocation tests that buffer growth stays limited with the trickler +// transformer, which behaves oddly but within spec. In case buffer growth is +// not correctly handled, the test will either panic with a failed allocation or +// thrash. To ensure the tests terminate under the last condition, we time out +// after some sufficiently long period of time. +func TestBytesAllocation(t *testing.T) { + done := make(chan bool) + go func() { + in := bytes.Repeat([]byte{'a'}, 1000) + tr := trickler(make([]byte, 1)) + Bytes(&tr, in) + done <- true + }() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("time out, likely due to excessive allocation") + } +} + +// TestStringAllocation tests that buffer growth stays limited with the trickler +// transformer, which behaves oddly but within spec. In case buffer growth is +// not correctly handled, the test will either panic with a failed allocation or +// thrash. To ensure the tests terminate under the last condition, we time out +// after some sufficiently long period of time. +func TestStringAllocation(t *testing.T) { + done := make(chan bool) + go func() { + tr := trickler(make([]byte, 1)) + String(&tr, aaa[:1000]) + done <- true + }() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("time out, likely due to excessive allocation") + } +} + +func BenchmarkStringLowerEmpty(b *testing.B) { + for i := 0; i < b.N; i++ { + String(&lowerCaseASCIILookahead{}, "") + } +} + +func BenchmarkStringLowerIdentical(b *testing.B) { + for i := 0; i < b.N; i++ { + String(&lowerCaseASCIILookahead{}, aaa[:4096]) + } +} + +func BenchmarkStringLowerChanged(b *testing.B) { + for i := 0; i < b.N; i++ { + String(&lowerCaseASCIILookahead{}, AAA[:4096]) + } +} + +var ( + aaa = strings.Repeat("a", 4096) + AAA = strings.Repeat("A", 4096) +) diff --git a/vendor/golang.org/x/text/unicode/cldr/base.go b/vendor/golang.org/x/text/unicode/cldr/base.go new file mode 100644 index 0000000..63cdc16 --- /dev/null +++ b/vendor/golang.org/x/text/unicode/cldr/base.go @@ -0,0 +1,105 @@ +// 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. + +package cldr + +import ( + "encoding/xml" + "regexp" + "strconv" +) + +// Elem is implemented by every XML element. +type Elem interface { + setEnclosing(Elem) + setName(string) + enclosing() Elem + + GetCommon() *Common +} + +type hidden struct { + CharData string `xml:",chardata"` + Alias *struct { + Common + Source string `xml:"source,attr"` + Path string `xml:"path,attr"` + } `xml:"alias"` + Def *struct { + Common + Choice string `xml:"choice,attr,omitempty"` + Type string `xml:"type,attr,omitempty"` + } `xml:"default"` +} + +// Common holds several of the most common attributes and sub elements +// of an XML element. +type Common struct { + XMLName xml.Name + name string + enclElem Elem + Type string `xml:"type,attr,omitempty"` + Reference string `xml:"reference,attr,omitempty"` + Alt string `xml:"alt,attr,omitempty"` + ValidSubLocales string `xml:"validSubLocales,attr,omitempty"` + Draft string `xml:"draft,attr,omitempty"` + hidden +} + +// Default returns the default type to select from the enclosed list +// or "" if no default value is specified. +func (e *Common) Default() string { + if e.Def == nil { + return "" + } + if e.Def.Choice != "" { + return e.Def.Choice + } else if e.Def.Type != "" { + // Type is still used by the default element in collation. + return e.Def.Type + } + return "" +} + +// Element returns the XML element name. +func (e *Common) Element() string { + return e.name +} + +// GetCommon returns e. It is provided such that Common implements Elem. +func (e *Common) GetCommon() *Common { + return e +} + +// Data returns the character data accumulated for this element. +func (e *Common) Data() string { + e.CharData = charRe.ReplaceAllStringFunc(e.CharData, replaceUnicode) + return e.CharData +} + +func (e *Common) setName(s string) { + e.name = s +} + +func (e *Common) enclosing() Elem { + return e.enclElem +} + +func (e *Common) setEnclosing(en Elem) { + e.enclElem = en +} + +// Escape characters that can be escaped without further escaping the string. +var charRe = regexp.MustCompile(`&#x[0-9a-fA-F]*;|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|\\x[0-9a-fA-F]{2}|\\[0-7]{3}|\\[abtnvfr]`) + +// replaceUnicode converts hexadecimal Unicode codepoint notations to a one-rune string. +// It assumes the input string is correctly formatted. +func replaceUnicode(s string) string { + if s[1] == '#' { + r, _ := strconv.ParseInt(s[3:len(s)-1], 16, 32) + return string(r) + } + r, _, _, _ := strconv.UnquoteChar(s, 0) + return string(r) +} diff --git a/vendor/golang.org/x/text/unicode/cldr/cldr.go b/vendor/golang.org/x/text/unicode/cldr/cldr.go new file mode 100644 index 0000000..2197f8a --- /dev/null +++ b/vendor/golang.org/x/text/unicode/cldr/cldr.go @@ -0,0 +1,130 @@ +// 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. + +//go:generate go run makexml.go -output xml.go + +// Package cldr provides a parser for LDML and related XML formats. +// This package is intended to be used by the table generation tools +// for the various internationalization-related packages. +// As the XML types are generated from the CLDR DTD, and as the CLDR standard +// is periodically amended, this package may change considerably over time. +// This mostly means that data may appear and disappear between versions. +// That is, old code should keep compiling for newer versions, but data +// may have moved or changed. +// CLDR version 22 is the first version supported by this package. +// Older versions may not work. +package cldr // import "golang.org/x/text/unicode/cldr" + +import ( + "fmt" + "sort" +) + +// CLDR provides access to parsed data of the Unicode Common Locale Data Repository. +type CLDR struct { + parent map[string][]string + locale map[string]*LDML + resolved map[string]*LDML + bcp47 *LDMLBCP47 + supp *SupplementalData +} + +func makeCLDR() *CLDR { + return &CLDR{ + parent: make(map[string][]string), + locale: make(map[string]*LDML), + resolved: make(map[string]*LDML), + bcp47: &LDMLBCP47{}, + supp: &SupplementalData{}, + } +} + +// BCP47 returns the parsed BCP47 LDML data. If no such data was parsed, nil is returned. +func (cldr *CLDR) BCP47() *LDMLBCP47 { + return nil +} + +// Draft indicates the draft level of an element. +type Draft int + +const ( + Approved Draft = iota + Contributed + Provisional + Unconfirmed +) + +var drafts = []string{"unconfirmed", "provisional", "contributed", "approved", ""} + +// ParseDraft returns the Draft value corresponding to the given string. The +// empty string corresponds to Approved. +func ParseDraft(level string) (Draft, error) { + if level == "" { + return Approved, nil + } + for i, s := range drafts { + if level == s { + return Unconfirmed - Draft(i), nil + } + } + return Approved, fmt.Errorf("cldr: unknown draft level %q", level) +} + +func (d Draft) String() string { + return drafts[len(drafts)-1-int(d)] +} + +// SetDraftLevel sets which draft levels to include in the evaluated LDML. +// Any draft element for which the draft level is higher than lev will be excluded. +// If multiple draft levels are available for a single element, the one with the +// lowest draft level will be selected, unless preferDraft is true, in which case +// the highest draft will be chosen. +// It is assumed that the underlying LDML is canonicalized. +func (cldr *CLDR) SetDraftLevel(lev Draft, preferDraft bool) { + // TODO: implement + cldr.resolved = make(map[string]*LDML) +} + +// RawLDML returns the LDML XML for id in unresolved form. +// id must be one of the strings returned by Locales. +func (cldr *CLDR) RawLDML(loc string) *LDML { + return cldr.locale[loc] +} + +// LDML returns the fully resolved LDML XML for loc, which must be one of +// the strings returned by Locales. +func (cldr *CLDR) LDML(loc string) (*LDML, error) { + return cldr.resolve(loc) +} + +// Supplemental returns the parsed supplemental data. If no such data was parsed, +// nil is returned. +func (cldr *CLDR) Supplemental() *SupplementalData { + return cldr.supp +} + +// Locales returns the locales for which there exist files. +// Valid sublocales for which there is no file are not included. +// The root locale is always sorted first. +func (cldr *CLDR) Locales() []string { + loc := []string{"root"} + hasRoot := false + for l, _ := range cldr.locale { + if l == "root" { + hasRoot = true + continue + } + loc = append(loc, l) + } + sort.Strings(loc[1:]) + if !hasRoot { + return loc[1:] + } + return loc +} + +// Get fills in the fields of x based on the XPath path. +func Get(e Elem, path string) (res Elem, err error) { + return walkXPath(e, path) +} diff --git a/vendor/golang.org/x/text/unicode/cldr/cldr_test.go b/vendor/golang.org/x/text/unicode/cldr/cldr_test.go new file mode 100644 index 0000000..951028d --- /dev/null +++ b/vendor/golang.org/x/text/unicode/cldr/cldr_test.go @@ -0,0 +1,27 @@ +// Copyright 2014 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 cldr + +import "testing" + +func TestParseDraft(t *testing.T) { + tests := []struct { + in string + draft Draft + err bool + }{ + {"unconfirmed", Unconfirmed, false}, + {"provisional", Provisional, false}, + {"contributed", Contributed, false}, + {"approved", Approved, false}, + {"", Approved, false}, + {"foo", Approved, true}, + } + for _, tt := range tests { + if d, err := ParseDraft(tt.in); d != tt.draft || (err != nil) != tt.err { + t.Errorf("%q: was %v, %v; want %v, %v", tt.in, d, err != nil, tt.draft, tt.err) + } + } +} diff --git a/vendor/golang.org/x/text/unicode/cldr/collate.go b/vendor/golang.org/x/text/unicode/cldr/collate.go new file mode 100644 index 0000000..80ee28d --- /dev/null +++ b/vendor/golang.org/x/text/unicode/cldr/collate.go @@ -0,0 +1,359 @@ +// 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. + +package cldr + +import ( + "bufio" + "encoding/xml" + "errors" + "fmt" + "strconv" + "strings" + "unicode" + "unicode/utf8" +) + +// RuleProcessor can be passed to Collator's Process method, which +// parses the rules and calls the respective method for each rule found. +type RuleProcessor interface { + Reset(anchor string, before int) error + Insert(level int, str, context, extend string) error + Index(id string) +} + +const ( + // cldrIndex is a Unicode-reserved sentinel value used to mark the start + // of a grouping within an index. + // We ignore any rule that starts with this rune. + // See http://unicode.org/reports/tr35/#Collation_Elements for details. + cldrIndex = "\uFDD0" + + // specialAnchor is the format in which to represent logical reset positions, + // such as "first tertiary ignorable". + specialAnchor = "<%s/>" +) + +// Process parses the rules for the tailorings of this collation +// and calls the respective methods of p for each rule found. +func (c Collation) Process(p RuleProcessor) (err error) { + if len(c.Cr) > 0 { + if len(c.Cr) > 1 { + return fmt.Errorf("multiple cr elements, want 0 or 1") + } + return processRules(p, c.Cr[0].Data()) + } + if c.Rules.Any != nil { + return c.processXML(p) + } + return errors.New("no tailoring data") +} + +// processRules parses rules in the Collation Rule Syntax defined in +// http://www.unicode.org/reports/tr35/tr35-collation.html#Collation_Tailorings. +func processRules(p RuleProcessor, s string) (err error) { + chk := func(s string, e error) string { + if err == nil { + err = e + } + return s + } + i := 0 // Save the line number for use after the loop. + scanner := bufio.NewScanner(strings.NewReader(s)) + for ; scanner.Scan() && err == nil; i++ { + for s := skipSpace(scanner.Text()); s != "" && s[0] != '#'; s = skipSpace(s) { + level := 5 + var ch byte + switch ch, s = s[0], s[1:]; ch { + case '&': // followed by or '[' ']' + if s = skipSpace(s); consume(&s, '[') { + s = chk(parseSpecialAnchor(p, s)) + } else { + s = chk(parseAnchor(p, 0, s)) + } + case '<': // sort relation '<'{1,4}, optionally followed by '*'. + for level = 1; consume(&s, '<'); level++ { + } + if level > 4 { + err = fmt.Errorf("level %d > 4", level) + } + fallthrough + case '=': // identity relation, optionally followed by *. + if consume(&s, '*') { + s = chk(parseSequence(p, level, s)) + } else { + s = chk(parseOrder(p, level, s)) + } + default: + chk("", fmt.Errorf("illegal operator %q", ch)) + break + } + } + } + if chk("", scanner.Err()); err != nil { + return fmt.Errorf("%d: %v", i, err) + } + return nil +} + +// parseSpecialAnchor parses the anchor syntax which is either of the form +// ['before' ] +// or +// [