pax_global_header00006660000000000000000000000064126342065530014520gustar00rootroot0000000000000052 comment=b66e377f52e316206efe71abba20e276d8790d86 atlas-go-b66e377f52e316206efe71abba20e276d8790d86/000077500000000000000000000000001263420655300201625ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/.gitignore000066400000000000000000000004441263420655300221540ustar00rootroot00000000000000### Go ### # Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *.test *.prof /bin/ /build/ atlas-go-b66e377f52e316206efe71abba20e276d8790d86/.travis.yml000066400000000000000000000001371263420655300222740ustar00rootroot00000000000000sudo: false language: go go: - 1.4 branches: only: - master script: make deps test atlas-go-b66e377f52e316206efe71abba20e276d8790d86/LICENSE000066400000000000000000000371501263420655300211750ustar00rootroot00000000000000Mozilla Public License, version 2.0 1. Definitions 1.1. “Contributor” means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. “Contributor Version” means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution. 1.3. “Contribution” means Covered Software of a particular Contributor. 1.4. “Covered Software” means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. “Incompatible With Secondary Licenses” means a. that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or b. that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. “Executable Form” means any form of the work other than Source Code Form. 1.7. “Larger Work” means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. “License” means this document. 1.9. “Licensable” means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. “Modifications” means any of the following: a. any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or b. any new file in Source Code Form that contains any Covered Software. 1.11. “Patent Claims” of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. “Secondary License” means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. “Source Code Form” means the form of the work preferred for making modifications. 1.14. “You” (or “Your”) means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: a. under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and b. under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: a. for any code that a Contributor has removed from Covered Software; or b. for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or c. under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: a. such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and b. You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. 6. Disclaimer of Warranty Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. 7. Limitation of Liability Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. 8. Litigation Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims. 9. Miscellaneous This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - “Incompatible With Secondary Licenses” Notice This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0. atlas-go-b66e377f52e316206efe71abba20e276d8790d86/Makefile000066400000000000000000000005321263420655300216220ustar00rootroot00000000000000TEST?=./... DEPS = $(shell go list -f '{{range .TestImports}}{{.}} {{end}}' ./...) all: deps build deps: go get -d -v ./... echo $(DEPS) | xargs -n1 go get -d build: @mkdir -p bin/ go build -o bin/atlas-go ./v1 test: go test $(TEST) $(TESTARGS) -timeout=3s -parallel=4 go vet $(TEST) go test $(TEST) -race .PHONY: all deps build test atlas-go-b66e377f52e316206efe71abba20e276d8790d86/README.md000066400000000000000000000073241263420655300214470ustar00rootroot00000000000000Atlas Go ======== [![Latest Version](http://img.shields.io/github/release/hashicorp/atlas-go.svg?style=flat-square)][release] [![Build Status](http://img.shields.io/travis/hashicorp/atlas-go.svg?style=flat-square)][travis] [![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] [release]: https://github.com/hashicorp/atlas-go/releases [travis]: http://travis-ci.org/hashicorp/atlas-go [godocs]: http://godoc.org/github.com/hashicorp/atlas-go Atlas Go is the official Go client for [HashiCorp's Atlas][Atlas] service. Usage ----- ### Authenticating with username and password Atlas Go can automatically generate an API authentication token given a username and password. For example: ```go client := atlas.DefaultClient() token, err := client.Login("username", "password") if err != nil { panic(err) } ``` The `Login` function returns an API token that can be used to sign requests. This function also sets the `Token` parameter on the Atlas Client, so future requests are signed with this access token. **If you have two-factor authentication enabled, you must manually generate an access token on the Atlas website.** ### Usage with on-premise Atlas Atlas Go supports on-premise Atlas installs, but you must specify the URL of the Atlas server in the client: ```go client, err := atlas.NewClient("https://url.to.your.atlas.server") if err != nil { panic(err) } ``` Example ------- The following example generates a new access token for a user named "sethvargo", generates a new Application named "frontend", and uploads the contents of a path to said application with some user-supplied metadata: ```go client := atlas.DefaultClient() token, err := client.Login("sethvargo", "b@c0n") if err != nil { log.Fatalf("err logging in: %s", err) } app, err := client.CreateApp("sethvargo", "frontend") if err != nil { log.Fatalf("err creating app: %s", err) } metadata := map[string]interface{ "developed-on": runtime.GOOS, } data, size := functionThatReturnsAnIOReaderAndSize() version, err := client.UploadApp(app, metadata, data, size) if err != nil { log.Fatalf("err uploading app: %s", err) } // version is the unique version of the application that was just uploaded version ``` FAQ --- **Q: Can I specify my token via an environment variable?**
A: All of HashiCorp's products support the `ATLAS_TOKEN` environment variable. You can set this value in your shell profile or securely in your environment and it will be used. **Q: How can I authenticate if I have two-factor authentication enabled?**
A: If you have two-factor authentication enabled, you must generate an access token via the Atlas website and pass it to the client initialization. The Atlas Go client does not support generating access tokens from two-factor authentication enabled accounts via the command line. **Q: Why do I need to specify the "user" for an Application, Build Configuration, and Runtime?**
A: Since you can be a collaborator on different projects, we wanted to have absolute clarity around which artifact you are currently interacting with. Contributing ------------ To hack on Atlas Go, you will need a modern [Go][] environment. To compile the `atlas-go` binary and run the test suite, simply execute: ```shell $ make ``` This will compile the `atlas-go` binary into `bin/atlas-go` and run the test suite. If you just want to run the tests: ```shell $ make test ``` Or to run a specific test in the suite: ```shell go test ./... -run SomeTestFunction_name ``` Submit Pull Requests and Issues to the [Atlas Go project on GitHub][Atlas Go]. [Atlas]: https://atlas.hashicorp.com "HashiCorp's Atlas" [Atlas Go]: https://github.com/hashicorp/atlas-go "Atlas Go on GitHub" [Go]: http://golang.org "Go the language" atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/000077500000000000000000000000001263420655300216035ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/archive.go000066400000000000000000000266131263420655300235630ustar00rootroot00000000000000// archive is package that helps create archives in a format that // Atlas expects with its various upload endpoints. package archive import ( "archive/tar" "bufio" "compress/gzip" "fmt" "io" "io/ioutil" "log" "os" "path/filepath" "strings" ) // Archive is the resulting archive. The archive data is generally streamed // so the io.ReadCloser can be used to backpressure the archive progress // and avoid memory pressure. type Archive struct { io.ReadCloser Size int64 Metadata map[string]string } // ArchiveOpts are the options for defining how the archive will be built. type ArchiveOpts struct { // Exclude and Include are filters of files to include/exclude in // the archive when creating it from a directory. These filters should // be relative to the packaging directory and should be basic glob // patterns. Exclude []string Include []string // Extra is a mapping of extra files to include within the archive. The // key should be the path within the archive and the value should be // an absolute path to the file to put into the archive. These extra // files will override any other files in the archive. Extra map[string]string // VCS, if true, will detect and use a VCS system to determine what // files to include the archive. VCS bool } // IsSet says whether any options were set. func (o *ArchiveOpts) IsSet() bool { return len(o.Exclude) > 0 || len(o.Include) > 0 || o.VCS } // CreateArchive takes the given path and ArchiveOpts and archives it. // // The archive will be fully completed and put into a temporary file. // This must be done to retrieve the content length of the archive which // is needed for almost all operations involving archives with Atlas. Because // of this, sufficient disk space will be required to buffer the archive. func CreateArchive(path string, opts *ArchiveOpts) (*Archive, error) { log.Printf("[INFO] creating archive from %s", path) // Dereference any symlinks and determine the real path and info fi, err := os.Lstat(path) if err != nil { return nil, err } if fi.Mode()&os.ModeSymlink != 0 { path, fi, err = readLinkFull(path, fi) if err != nil { return nil, err } } // Windows path = filepath.ToSlash(path) // Direct file paths cannot have archive options if !fi.IsDir() && opts.IsSet() { return nil, fmt.Errorf( "options such as exclude, include, and VCS can't be set when " + "the path is a file.") } if fi.IsDir() { return archiveDir(path, opts) } else { return archiveFile(path) } } func archiveFile(path string) (*Archive, error) { f, err := os.Open(path) if err != nil { return nil, err } if _, err := gzip.NewReader(f); err == nil { // Reset the read offset for future reading if _, err := f.Seek(0, 0); err != nil { f.Close() return nil, err } // Get the file info for the size fi, err := f.Stat() if err != nil { f.Close() return nil, err } // This is a gzip file, let it through. return &Archive{ReadCloser: f, Size: fi.Size()}, nil } // Close the file, no use for it anymore f.Close() // We have a single file that is not gzipped. Compress it. path, err = filepath.Abs(path) if err != nil { return nil, err } // Act like we're compressing a directory, but only include this one // file. return archiveDir(filepath.Dir(path), &ArchiveOpts{ Include: []string{filepath.Base(path)}, }) } func archiveDir(root string, opts *ArchiveOpts) (*Archive, error) { var vcsInclude []string var metadata map[string]string if opts.VCS { var err error if err = vcsPreflight(root); err != nil { return nil, err } vcsInclude, err = vcsFiles(root) if err != nil { return nil, err } metadata, err = vcsMetadata(root) if err != nil { return nil, err } } // Make sure the root path is absolute root, err := filepath.Abs(root) if err != nil { return nil, err } // Create the temporary file that we'll send the archive data to. archiveF, err := ioutil.TempFile("", "atlas-archive") if err != nil { return nil, err } // Create the wrapper for the result which will automatically // remove the temporary file on close. archiveWrapper := &readCloseRemover{F: archiveF} // Buffer the writer so that we can push as much data to disk at // a time as possible. 4M should be good. bufW := bufio.NewWriterSize(archiveF, 4096*1024) // Gzip compress all the output data gzipW := gzip.NewWriter(bufW) // Tar the file contents tarW := tar.NewWriter(gzipW) // First, walk the path and do the normal files werr := filepath.Walk(root, copyDirWalkFn( tarW, root, "", opts, vcsInclude)) if werr == nil { // If that succeeded, handle the extra files werr = copyExtras(tarW, opts.Extra) } // Attempt to close all the things. If we get an error on the way // and we haven't had an error yet, then record that as the critical // error. But we still try to close everything. // Close the tar writer if err := tarW.Close(); err != nil && werr == nil { werr = err } // Close the gzip writer if err := gzipW.Close(); err != nil && werr == nil { werr = err } // Flush the buffer if err := bufW.Flush(); err != nil && werr == nil { werr = err } // If we had an error, then close the file (removing it) and // return the error. if werr != nil { archiveWrapper.Close() return nil, werr } // Seek to the beginning if _, err := archiveWrapper.F.Seek(0, 0); err != nil { archiveWrapper.Close() return nil, err } // Get the file information so we can get the size fi, err := archiveWrapper.F.Stat() if err != nil { archiveWrapper.Close() return nil, err } return &Archive{ ReadCloser: archiveWrapper, Size: fi.Size(), Metadata: metadata, }, nil } func copyDirWalkFn( tarW *tar.Writer, root string, prefix string, opts *ArchiveOpts, vcsInclude []string) filepath.WalkFunc { errFunc := func(err error) filepath.WalkFunc { return func(string, os.FileInfo, error) error { return err } } // Windows root = filepath.ToSlash(root) var includeMap map[string]struct{} // If we have an include/exclude pattern set, then setup the lookup // table to determine what we want to include. if opts != nil && len(opts.Include) > 0 { includeMap = make(map[string]struct{}) for _, pattern := range opts.Include { matches, err := filepath.Glob(filepath.Join(root, pattern)) if err != nil { return errFunc(fmt.Errorf( "error checking include glob '%s': %s", pattern, err)) } for _, path := range matches { // Windows path = filepath.ToSlash(path) subpath, err := filepath.Rel(root, path) subpath = filepath.ToSlash(subpath) if err != nil { return errFunc(err) } for { includeMap[subpath] = struct{}{} subpath = filepath.Dir(subpath) if subpath == "." { break } } } } } return func(path string, info os.FileInfo, err error) error { path = filepath.ToSlash(path) if err != nil { return err } // Get the relative path from the path since it contains the root // plus the path. subpath, err := filepath.Rel(root, path) if err != nil { return err } if subpath == "." { return nil } if prefix != "" { subpath = filepath.Join(prefix, subpath) } // Windows subpath = filepath.ToSlash(subpath) // If we have a list of VCS files, check that first skip := false if len(vcsInclude) > 0 { skip = true for _, f := range vcsInclude { if f == subpath { skip = false break } if info.IsDir() && strings.HasPrefix(f, subpath+"/") { skip = false break } } } // If include is present, we only include what is listed if len(includeMap) > 0 { if _, ok := includeMap[subpath]; !ok { skip = true } } // If exclude, it is one last gate to excluding files if opts != nil { for _, exclude := range opts.Exclude { match, err := filepath.Match(exclude, subpath) if err != nil { return err } if match { skip = true break } } } // If we have to skip this file, then skip it, properly skipping // children if we're a directory. if skip { if info.IsDir() { return filepath.SkipDir } return nil } // If this is a symlink, then we need to get the symlink target // rather than the symlink itself. if info.Mode()&os.ModeSymlink != 0 { target, info, err := readLinkFull(path, info) if err != nil { return err } // Copy the concrete entry for this path. This will either // be the file itself or just a directory entry. if err := copyConcreteEntry(tarW, subpath, target, info); err != nil { return err } if info.IsDir() { return filepath.Walk(target, copyDirWalkFn( tarW, target, subpath, opts, vcsInclude)) } } return copyConcreteEntry(tarW, subpath, path, info) } } func copyConcreteEntry( tarW *tar.Writer, entry string, path string, info os.FileInfo) error { // Windows path = filepath.ToSlash(path) // Build the file header for the tar entry header, err := tar.FileInfoHeader(info, path) if err != nil { return fmt.Errorf( "failed creating archive header: %s", path) } // Modify the header to properly be the full entry name header.Name = entry if info.IsDir() { header.Name += "/" } // Write the header first to the archive. if err := tarW.WriteHeader(header); err != nil { return fmt.Errorf( "failed writing archive header: %s", path) } // If it is a directory, then we're done (no body to write) if info.IsDir() { return nil } // Open the real file to write the data f, err := os.Open(path) if err != nil { return fmt.Errorf( "failed opening file '%s' to write compressed archive.", path) } defer f.Close() if _, err = io.Copy(tarW, f); err != nil { return fmt.Errorf( "failed copying file to archive: %s", path) } return nil } func copyExtras(w *tar.Writer, extra map[string]string) error { for entry, path := range extra { info, err := os.Stat(path) if err != nil { return err } // No matter what, write the entry. If this is a directory, // it'll just write the directory header. if err := copyConcreteEntry(w, entry, path, info); err != nil { return err } // If this is a directory, then we walk the internal contents // and copy those as well. if info.IsDir() { err := filepath.Walk(path, copyDirWalkFn( w, path, entry, nil, nil)) if err != nil { return err } } } return nil } func readLinkFull(path string, info os.FileInfo) (string, os.FileInfo, error) { // Read the symlink continously until we reach a concrete file. target := path tries := 0 for info.Mode()&os.ModeSymlink != 0 { var err error target, err = os.Readlink(target) if err != nil { return "", nil, err } if !filepath.IsAbs(target) { target, err = filepath.Abs(target) if err != nil { return "", nil, err } } info, err = os.Lstat(target) if err != nil { return "", nil, err } tries++ if tries > 100 { return "", nil, fmt.Errorf( "Symlink for %s is too deep, over 100 levels deep", path) } } return target, info, nil } // readCloseRemover is an io.ReadCloser implementation that will remove // the file on Close(). We use this to clean up our temporary file for // the archive. type readCloseRemover struct { F *os.File } func (r *readCloseRemover) Read(p []byte) (int, error) { return r.F.Read(p) } func (r *readCloseRemover) Close() error { // First close the file err := r.F.Close() // Next make sure to remove it, or at least try, regardless of error // above. os.Remove(r.F.Name()) return err } atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/archive_test.go000066400000000000000000000257651263420655300246310ustar00rootroot00000000000000package archive import ( "archive/tar" "bytes" "compress/gzip" "io" "io/ioutil" "os" "os/exec" "path/filepath" "reflect" "runtime" "sort" "testing" ) const fixturesDir = "./test-fixtures" var testHasGit bool var testHasHg bool func init() { if _, err := exec.LookPath("git"); err == nil { testHasGit = true } if _, err := exec.LookPath("hg"); err == nil { testHasHg = true } } func TestArchiveOptsIsSet(t *testing.T) { cases := []struct { Opts *ArchiveOpts Set bool }{ { &ArchiveOpts{}, false, }, { &ArchiveOpts{VCS: true}, true, }, { &ArchiveOpts{Exclude: make([]string, 0, 0)}, false, }, { &ArchiveOpts{Exclude: []string{"foo"}}, true, }, { &ArchiveOpts{Include: make([]string, 0, 0)}, false, }, { &ArchiveOpts{Include: []string{"foo"}}, true, }, } for i, tc := range cases { if tc.Opts.IsSet() != tc.Set { t.Fatalf("%d: expected %#v", i, tc.Set) } } } func TestArchive_file(t *testing.T) { path := filepath.Join(testFixture("archive-file"), "foo.txt") r, err := CreateArchive(path, new(ArchiveOpts)) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "foo.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_fileCompressed(t *testing.T) { path := filepath.Join(testFixture("archive-file-compressed"), "file.tar.gz") r, err := CreateArchive(path, new(ArchiveOpts)) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "./foo.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_fileNoExist(t *testing.T) { tf := tempFile(t) if err := os.Remove(tf); err != nil { t.Fatalf("err: %s", err) } r, err := CreateArchive(tf, nil) if err == nil { t.Fatal("err should not be nil") } if r != nil { t.Fatal("should be nil") } } func TestArchive_fileWithOpts(t *testing.T) { r, err := CreateArchive(tempFile(t), &ArchiveOpts{VCS: true}) if err == nil { t.Fatal("err should not be nil") } if r != nil { t.Fatal("should be nil") } } func TestArchive_dirExtra(t *testing.T) { opts := &ArchiveOpts{ Extra: map[string]string{ "hello.txt": filepath.Join( testFixture("archive-subdir"), "subdir", "hello.txt"), }, } r, err := CreateArchive(testFixture("archive-flat"), opts) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "baz.txt", "foo.txt", "hello.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_dirExtraDir(t *testing.T) { opts := &ArchiveOpts{ Extra: map[string]string{ "foo": filepath.Join(testFixture("archive-subdir"), "subdir"), }, } r, err := CreateArchive(testFixture("archive-flat"), opts) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "baz.txt", "foo.txt", "foo/", "foo/hello.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_dirMode(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("modes don't work on Windows") } opts := &ArchiveOpts{} r, err := CreateArchive(testFixture("archive-dir-mode"), opts) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "file.txt-exec", } entries := testArchive(t, r, true) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_dirSymlink(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("git symlinks don't work on Windows") } path := filepath.Join(testFixture("archive-symlink"), "link", "link") r, err := CreateArchive(path, new(ArchiveOpts)) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "foo.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_dirWithSymlink(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("git symlinks don't work on Windows") } path := filepath.Join(testFixture("archive-symlink"), "link") r, err := CreateArchive(path, new(ArchiveOpts)) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "link/", "link/foo.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_dirNoVCS(t *testing.T) { r, err := CreateArchive(testFixture("archive-flat"), new(ArchiveOpts)) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "baz.txt", "foo.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_dirSubdirsNoVCS(t *testing.T) { r, err := CreateArchive(testFixture("archive-subdir"), new(ArchiveOpts)) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "bar.txt", "foo.txt", "subdir/", "subdir/hello.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_dirExclude(t *testing.T) { opts := &ArchiveOpts{ Exclude: []string{"subdir", "subdir/*"}, } r, err := CreateArchive(testFixture("archive-subdir"), opts) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "bar.txt", "foo.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_dirInclude(t *testing.T) { opts := &ArchiveOpts{ Include: []string{"bar.txt"}, } r, err := CreateArchive(testFixture("archive-subdir"), opts) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "bar.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_dirIncludeStar(t *testing.T) { opts := &ArchiveOpts{ Include: []string{"build/**/*"}, } r, err := CreateArchive(testFixture("archive-subdir-splat"), opts) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "build/", "build/darwin-amd64/", "build/darwin-amd64/build.txt", "build/linux-amd64/", "build/linux-amd64/build.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_git(t *testing.T) { if !testHasGit { t.Log("git not found, skipping") t.Skip() } // Git doesn't allow nested ".git" directories so we do some hackiness // here to get around that... testDir := testFixture("archive-git") oldName := filepath.ToSlash(filepath.Join(testDir, "DOTgit")) newName := filepath.ToSlash(filepath.Join(testDir, ".git")) os.Remove(newName) if err := os.Rename(oldName, newName); err != nil { t.Fatalf("err: %s", err) } defer os.Rename(newName, oldName) // testDir with VCS set to true r, err := CreateArchive(testDir, &ArchiveOpts{VCS: true}) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "bar.txt", "foo.txt", "subdir/", "subdir/hello.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } // Test that metadata was added if r.Metadata == nil { t.Fatal("expected archive metadata to be set") } expectedMetadata := map[string]string{ "branch": "master", "commit": "7525d17cbbb56f3253a20903ffddc07c6c935c76", "remote.origin": "https://github.com/hashicorp/origin.git", "remote.upstream": "https://github.com/hashicorp/upstream.git", } if !reflect.DeepEqual(r.Metadata, expectedMetadata) { t.Fatalf("expected %+v to be %+v", r.Metadata, expectedMetadata) } } func TestArchive_gitSubdir(t *testing.T) { if !testHasGit { t.Log("git not found, skipping") t.Skip() } // Git doesn't allow nested ".git" directories so we do some hackiness // here to get around that... testDir := testFixture("archive-git") oldName := filepath.ToSlash(filepath.Join(testDir, "DOTgit")) newName := filepath.ToSlash(filepath.Join(testDir, ".git")) os.Remove(newName) if err := os.Rename(oldName, newName); err != nil { t.Fatalf("err: %s", err) } defer os.Rename(newName, oldName) // testDir with VCS set to true r, err := CreateArchive(filepath.Join(testDir, "subdir"), &ArchiveOpts{VCS: true}) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "hello.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("bad: %#v", entries) } } func TestArchive_hg(t *testing.T) { if !testHasHg { t.Log("hg not found, skipping") t.Skip() } // testDir with VCS set to true testDir := testFixture("archive-hg") r, err := CreateArchive(testDir, &ArchiveOpts{VCS: true}) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "bar.txt", "foo.txt", "subdir/", "subdir/hello.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("\n-- Expected --\n%#v\n-- Found --\n%#v", expected, entries) } } func TestArchive_hgSubdir(t *testing.T) { if !testHasHg { t.Log("hg not found, skipping") t.Skip() } // testDir with VCS set to true testDir := filepath.Join(testFixture("archive-hg"), "subdir") r, err := CreateArchive(testDir, &ArchiveOpts{VCS: true}) if err != nil { t.Fatalf("err: %s", err) } expected := []string{ "hello.txt", } entries := testArchive(t, r, false) if !reflect.DeepEqual(entries, expected) { t.Fatalf("\n-- Expected --\n%#v\n-- Found --\n%#v", expected, entries) } } func TestReadCloseRemover(t *testing.T) { f, err := ioutil.TempFile("", "atlas-go") if err != nil { t.Fatalf("err: %s", err) } r := &readCloseRemover{F: f} if err := r.Close(); err != nil { t.Fatalf("err: %s", err) } if _, err := os.Stat(f.Name()); err == nil { t.Fatal("file should not exist anymore") } } func testArchive(t *testing.T, r *Archive, detailed bool) []string { // Finish the archiving process in-memory var buf bytes.Buffer n, err := io.Copy(&buf, r) if err != nil { t.Fatalf("err: %s", err) } if n != r.Size { t.Fatalf("bad size: %d (expected: %d)", n, r.Size) } gzipR, err := gzip.NewReader(&buf) if err != nil { t.Fatalf("err: %s", err) } tarR := tar.NewReader(gzipR) // Read all the entries result := make([]string, 0, 5) for { hdr, err := tarR.Next() if err == io.EOF { break } if err != nil { t.Fatalf("err: %s", err) } text := hdr.Name if detailed { // Check if the file is executable. We use these stub names // to compensate for umask differences in test environments // and limitations in using "git clone". if hdr.FileInfo().Mode()&0111 != 0 { text = hdr.Name + "-exec" } else { text = hdr.Name + "-reg" } } result = append(result, text) } sort.Strings(result) return result } func tempFile(t *testing.T) string { tf, err := ioutil.TempFile("", "test") if err != nil { t.Fatalf("err: %s", err) } defer tf.Close() return tf.Name() } func testFixture(n string) string { return filepath.Join(fixturesDir, n) } atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/000077500000000000000000000000001263420655300244315ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-dir-mode/000077500000000000000000000000001263420655300275505ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-dir-mode/file.txt000077500000000000000000000000261263420655300312310ustar00rootroot00000000000000I should be mode 0777 atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-file-compressed/000077500000000000000000000000001263420655300311315ustar00rootroot00000000000000file.tar.gz000066400000000000000000000002201263420655300331120ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-file-compressedZPTA 0aמbNc:)E\).*$/Signed-off-by: \1/p') # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" # This example catches duplicate Signed-off-by lines. test "" = "$(grep '^Signed-off-by: ' "$1" | sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { echo >&2 Duplicate Signed-off-by lines. exit 1 } post-update.sample000077500000000000000000000002751263420655300345100ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/hooks#!/bin/sh # # An example hook script to prepare a packed repository for use over # dumb transports. # # To enable this hook, rename this file to "post-update". exec git update-server-info pre-applypatch.sample000077500000000000000000000006161263420655300351730ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/hooks#!/bin/sh # # An example hook script to verify what is about to be committed # by applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. # # To enable this hook, rename this file to "pre-applypatch". . git-sh-setup test -x "$GIT_DIR/hooks/pre-commit" && exec "$GIT_DIR/hooks/pre-commit" ${1+"$@"} : pre-commit.sample000077500000000000000000000031521263420655300343140ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/hooks#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against -- pre-push.sample000077500000000000000000000025101263420655300340000ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/hooks#!/bin/sh # An example hook script to verify what is about to be pushed. Called by "git # push" after it has checked the remote status, but before anything has been # pushed. If this script exits with a non-zero status nothing will be pushed. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If pushing without using a named remote those arguments will be equal. # # Information about the commits which are being pushed is supplied as lines to # the standard input in the form: # # # # This sample shows how to prevent push of commits where the log message starts # with "WIP" (work in progress). remote="$1" url="$2" z40=0000000000000000000000000000000000000000 IFS=' ' while read local_ref local_sha remote_ref remote_sha do if [ "$local_sha" = $z40 ] then # Handle delete : else if [ "$remote_sha" = $z40 ] then # New branch, examine all commits range="$local_sha" else # Update to existing branch, examine new commits range="$remote_sha..$local_sha" fi # Check for WIP commit commit=`git rev-list -n 1 --grep '^WIP' "$range"` if [ -n "$commit" ] then echo "Found WIP commit in $local_ref, not pushing" exit 1 fi fi done exit 0 pre-rebase.sample000077500000000000000000000115271263420655300342720ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/hooks#!/bin/sh # # Copyright (c) 2006, 2008 Junio C Hamano # # The "pre-rebase" hook is run just before "git rebase" starts doing # its job, and can prevent the command from running by exiting with # non-zero status. # # The hook is called with the following parameters: # # $1 -- the upstream the series was forked from. # $2 -- the branch being rebased (or empty when rebasing the current branch). # # This sample shows how to prevent topic branches that are already # merged to 'next' branch from getting rebased, because allowing it # would result in rebasing already published history. publish=next basebranch="$1" if test "$#" = 2 then topic="refs/heads/$2" else topic=`git symbolic-ref HEAD` || exit 0 ;# we do not interrupt rebasing detached HEAD fi case "$topic" in refs/heads/??/*) ;; *) exit 0 ;# we do not interrupt others. ;; esac # Now we are dealing with a topic branch being rebased # on top of master. Is it OK to rebase it? # Does the topic really exist? git show-ref -q "$topic" || { echo >&2 "No such branch $topic" exit 1 } # Is topic fully merged to master? not_in_master=`git rev-list --pretty=oneline ^master "$topic"` if test -z "$not_in_master" then echo >&2 "$topic is fully merged to master; better remove it." exit 1 ;# we could allow it, but there is no point. fi # Is topic ever merged to next? If so you should not be rebasing it. only_next_1=`git rev-list ^master "^$topic" ${publish} | sort` only_next_2=`git rev-list ^master ${publish} | sort` if test "$only_next_1" = "$only_next_2" then not_in_topic=`git rev-list "^$topic" master` if test -z "$not_in_topic" then echo >&2 "$topic is already up-to-date with master" exit 1 ;# we could allow it, but there is no point. else exit 0 fi else not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"` /usr/bin/perl -e ' my $topic = $ARGV[0]; my $msg = "* $topic has commits already merged to public branch:\n"; my (%not_in_next) = map { /^([0-9a-f]+) /; ($1 => 1); } split(/\n/, $ARGV[1]); for my $elem (map { /^([0-9a-f]+) (.*)$/; [$1 => $2]; } split(/\n/, $ARGV[2])) { if (!exists $not_in_next{$elem->[0]}) { if ($msg) { print STDERR $msg; undef $msg; } print STDERR " $elem->[1]\n"; } } ' "$topic" "$not_in_next" "$not_in_master" exit 1 fi exit 0 ################################################################ This sample hook safeguards topic branches that have been published from being rewound. The workflow assumed here is: * Once a topic branch forks from "master", "master" is never merged into it again (either directly or indirectly). * Once a topic branch is fully cooked and merged into "master", it is deleted. If you need to build on top of it to correct earlier mistakes, a new topic branch is created by forking at the tip of the "master". This is not strictly necessary, but it makes it easier to keep your history simple. * Whenever you need to test or publish your changes to topic branches, merge them into "next" branch. The script, being an example, hardcodes the publish branch name to be "next", but it is trivial to make it configurable via $GIT_DIR/config mechanism. With this workflow, you would want to know: (1) ... if a topic branch has ever been merged to "next". Young topic branches can have stupid mistakes you would rather clean up before publishing, and things that have not been merged into other branches can be easily rebased without affecting other people. But once it is published, you would not want to rewind it. (2) ... if a topic branch has been fully merged to "master". Then you can delete it. More importantly, you should not build on top of it -- other people may already want to change things related to the topic as patches against your "master", so if you need further changes, it is better to fork the topic (perhaps with the same name) afresh from the tip of "master". Let's look at this example: o---o---o---o---o---o---o---o---o---o "next" / / / / / a---a---b A / / / / / / / / c---c---c---c B / / / / \ / / / / b---b C \ / / / / / \ / ---o---o---o---o---o---o---o---o---o---o---o "master" A, B and C are topic branches. * A has one fix since it was merged up to "next". * B has finished. It has been fully merged up to "master" and "next", and is ready to be deleted. * C has not merged to "next" at all. We would want to allow C to be rebased, refuse A, and encourage B to be deleted. To compute (1): git rev-list ^master ^topic next git rev-list ^master next if these match, topic has not merged in next at all. To compute (2): git rev-list master..topic if this is empty, it is fully merged to "master". prepare-commit-msg.sample000077500000000000000000000023271263420655300357530ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/hooks#!/bin/sh # # An example hook script to prepare the commit log message. # Called by "git commit" with the name of the file that has the # commit message, followed by the description of the commit # message's source. The hook's purpose is to edit the commit # message file. If the hook fails with a non-zero status, # the commit is aborted. # # To enable this hook, rename this file to "prepare-commit-msg". # This hook includes three examples. The first comments out the # "Conflicts:" part of a merge commit. # # The second includes the output of "git diff --name-status -r" # into the message, just before the "git status" output. It is # commented because it doesn't cope with --amend or with squashed # commits. # # The third example adds a Signed-off-by line to the message, that can # still be edited. This is rarely a good idea. case "$2,$3" in merge,) /usr/bin/perl -i.bak -ne 's/^/# /, s/^# #/#/ if /^Conflicts/ .. /#/; print' "$1" ;; # ,|template,) # /usr/bin/perl -i.bak -pe ' # print "\n" . `git diff --cached --name-status -r` # if /^#/ && $first++ == 0' "$1" ;; *) ;; esac # SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" update.sample000077500000000000000000000070331263420655300335240ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/hooks#!/bin/sh # # An example hook script to blocks unannotated tags from entering. # Called by "git receive-pack" with arguments: refname sha1-old sha1-new # # To enable this hook, rename this file to "update". # # Config # ------ # hooks.allowunannotated # This boolean sets whether unannotated tags will be allowed into the # repository. By default they won't be. # hooks.allowdeletetag # This boolean sets whether deleting tags will be allowed in the # repository. By default they won't be. # hooks.allowmodifytag # This boolean sets whether a tag may be modified after creation. By default # it won't be. # hooks.allowdeletebranch # This boolean sets whether deleting branches will be allowed in the # repository. By default they won't be. # hooks.denycreatebranch # This boolean sets whether remotely creating branches will be denied # in the repository. By default this is allowed. # # --- Command line refname="$1" oldrev="$2" newrev="$3" # --- Safety check if [ -z "$GIT_DIR" ]; then echo "Don't run this script from the command line." >&2 echo " (if you want, you could supply GIT_DIR then run" >&2 echo " $0 )" >&2 exit 1 fi if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then echo "usage: $0 " >&2 exit 1 fi # --- Config allowunannotated=$(git config --bool hooks.allowunannotated) allowdeletebranch=$(git config --bool hooks.allowdeletebranch) denycreatebranch=$(git config --bool hooks.denycreatebranch) allowdeletetag=$(git config --bool hooks.allowdeletetag) allowmodifytag=$(git config --bool hooks.allowmodifytag) # check for no description projectdesc=$(sed -e '1q' "$GIT_DIR/description") case "$projectdesc" in "Unnamed repository"* | "") echo "*** Project description file hasn't been set" >&2 exit 1 ;; esac # --- Check types # if $newrev is 0000...0000, it's a commit to delete a ref. zero="0000000000000000000000000000000000000000" if [ "$newrev" = "$zero" ]; then newrev_type=delete else newrev_type=$(git cat-file -t $newrev) fi case "$refname","$newrev_type" in refs/tags/*,commit) # un-annotated tag short_refname=${refname##refs/tags/} if [ "$allowunannotated" != "true" ]; then echo "*** The un-annotated tag, $short_refname, is not allowed in this repository" >&2 echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2 exit 1 fi ;; refs/tags/*,delete) # delete tag if [ "$allowdeletetag" != "true" ]; then echo "*** Deleting a tag is not allowed in this repository" >&2 exit 1 fi ;; refs/tags/*,tag) # annotated tag if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1 then echo "*** Tag '$refname' already exists." >&2 echo "*** Modifying a tag is not allowed in this repository." >&2 exit 1 fi ;; refs/heads/*,commit) # branch if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then echo "*** Creating a branch is not allowed in this repository" >&2 exit 1 fi ;; refs/heads/*,delete) # delete branch if [ "$allowdeletebranch" != "true" ]; then echo "*** Deleting a branch is not allowed in this repository" >&2 exit 1 fi ;; refs/remotes/*,commit) # tracking branch ;; refs/remotes/*,delete) # delete tracking branch if [ "$allowdeletebranch" != "true" ]; then echo "*** Deleting a tracking branch is not allowed in this repository" >&2 exit 1 fi ;; *) # Anything else (is there anything else?) echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2 exit 1 ;; esac # --- Finished exit 0 atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/index000066400000000000000000000004001263420655300310110ustar00rootroot00000000000000DIRCTsTsGYWY}kI $-bar.txtTsTsG%|d,T?->V>foo.txtTsTsG%|d,T?->V>subdir/hello.txt%qo_'M#N\#>^`qatlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/info/000077500000000000000000000000001263420655300307205ustar00rootroot00000000000000exclude000066400000000000000000000003601263420655300322140ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/info# git ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): # *.[oa] # *~ atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/logs/000077500000000000000000000000001263420655300307315ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/logs/HEAD000066400000000000000000000002671263420655300313620ustar00rootroot000000000000000000000000000000000000000000000000000000 7525d17cbbb56f3253a20903ffddc07c6c935c76 Mitchell Hashimoto 1414446684 -0700 commit (initial): Those files tho 000077500000000000000000000000001263420655300316115ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/logs/refs000077500000000000000000000000001263420655300326755ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/logs/refs/headsmaster000066400000000000000000000002671263420655300341200ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/logs/refs/heads0000000000000000000000000000000000000000 7525d17cbbb56f3253a20903ffddc07c6c935c76 Mitchell Hashimoto 1414446684 -0700 commit (initial): Those files tho atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/objects/000077500000000000000000000000001263420655300314165ustar00rootroot00000000000000000077500000000000000000000000001263420655300315655ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/objects/257cc5642cb1a054f08cc83f2d943e56fd3ebe99000066400000000000000000000000231263420655300370660ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/objects/25xKOR0aHUB000077500000000000000000000000001263420655300315725ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/objects/5716ca5987cbf97d6bb54920bea6adde242d87e6000066400000000000000000000000231263420655300371560ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/objects/57xKOR0aHJ,!3000077500000000000000000000000001263420655300315725ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/objects/7525d17cbbb56f3253a20903ffddc07c6c935c76000066400000000000000000000002151263420655300367760ustar00rootroot00000000000000atlas-go-b66e377f52e316206efe71abba20e276d8790d86/archive/test-fixtures/archive-git/DOTgit/objects/75xM 0a9\IL ".ݸ@B7ZA:]xc&p4 cpsueFVETS{HR ݑrme6^2VDdBp֬:]S-9` 0 { request.ContentLength = ro.BodyLength } log.Printf("[DEBUG] raw request: %#v", request) return request, nil } // checkResp wraps http.Client.Do() and verifies that the request was // successful. A non-200 request returns an error formatted to included any // validation problems or otherwise. func checkResp(resp *http.Response, err error) (*http.Response, error) { // If the err is already there, there was an error higher up the chain, so // just return that if err != nil { return resp, err } log.Printf("[INFO] response: %d (%s)", resp.StatusCode, resp.Status) var buf bytes.Buffer if _, err := io.Copy(&buf, resp.Body); err != nil { log.Printf("[ERR] response: error copying response body") } else { log.Printf("[DEBUG] response: %s", buf.String()) // We are going to reset the response body, so we need to close the old // one or else it will leak. resp.Body.Close() resp.Body = &bytesReadCloser{&buf} } switch resp.StatusCode { case 200: return resp, nil case 201: return resp, nil case 202: return resp, nil case 204: return resp, nil case 400: return nil, parseErr(resp) case 401: return nil, ErrAuth case 404: return nil, ErrNotFound case 422: return nil, parseErr(resp) default: return nil, fmt.Errorf("client: %s", resp.Status) } } // parseErr is used to take an error JSON response and return a single string // for use in error messages. func parseErr(r *http.Response) error { re := &RailsError{} if err := decodeJSON(r, &re); err != nil { return fmt.Errorf("error decoding JSON body: %s", err) } return re } // decodeJSON is used to JSON decode a body into an interface. func decodeJSON(resp *http.Response, out interface{}) error { defer resp.Body.Close() dec := json.NewDecoder(resp.Body) return dec.Decode(out) } // bytesReadCloser is a simple wrapper around a bytes buffer that implements // Close as a noop. type bytesReadCloser struct { *bytes.Buffer } func (nrc *bytesReadCloser) Close() error { // we don't actually have to do anything here, since the buffer is just some // data in memory and the error is initialized to no-error return nil } atlas-go-b66e377f52e316206efe71abba20e276d8790d86/v1/client_test.go000066400000000000000000000116471263420655300233650ustar00rootroot00000000000000package atlas import ( "net/url" "reflect" "strings" "testing" ) func TestDefaultClient_url(t *testing.T) { client := DefaultClient() if client.URL.String() != atlasEndpoint { t.Fatalf("expected %q to be %q", client.URL.String(), atlasEndpoint) } } func TestNewClient_badURL(t *testing.T) { _, err := NewClient("") if err == nil { t.Fatal("expected error, but nothing was returned") } expected := "client: missing url" if !strings.Contains(err.Error(), expected) { t.Fatalf("expected %q to contain %q", err.Error(), expected) } } func TestNewClient_parsesURL(t *testing.T) { client, err := NewClient("https://example.com/foo/bar") if err != nil { t.Fatal(err) } expected := &url.URL{ Scheme: "https", Host: "example.com", Path: "/foo/bar", } if !reflect.DeepEqual(client.URL, expected) { t.Fatalf("expected %q to equal %q", client.URL, expected) } } func TestNewClient_setsDefaultHTTPClient(t *testing.T) { _, err := NewClient("https://example.com/foo/bar") if err != nil { t.Fatal(err) } } func TestLogin_missingUsername(t *testing.T) { client, err := NewClient("https://example.com/foo/bar") if err != nil { t.Fatal(err) } _, err = client.Login("", "") if err == nil { t.Fatal("expected error, but nothing was returned") } expected := "client: missing username" if !strings.Contains(err.Error(), expected) { t.Fatalf("expected %q to contain %q", err.Error(), expected) } } func TestLogin_missingPassword(t *testing.T) { client, err := NewClient("https://example.com/foo/bar") if err != nil { t.Fatal(err) } _, err = client.Login("username", "") if err == nil { t.Fatal("expected error, but nothing was returned") } expected := "client: missing password" if !strings.Contains(err.Error(), expected) { t.Fatalf("expected %q to contain %q", err.Error(), expected) } } func TestLogin_serverErrorMessage(t *testing.T) { server := newTestAtlasServer(t) defer server.Stop() client, err := NewClient(server.URL.String()) if err != nil { t.Fatal(err) } _, err = client.Login("username", "password") if err == nil { t.Fatal("expected error, but nothing was returned") } if err != ErrAuth { t.Fatalf("bad: %s", err) } } func TestLogin_success(t *testing.T) { server := newTestAtlasServer(t) defer server.Stop() client, err := NewClient(server.URL.String()) if err != nil { t.Fatal(err) } token, err := client.Login("sethloves", "bacon") if err != nil { t.Fatal(err) } if client.Token == "" { t.Fatal("expected client token to be set") } if token == "" { t.Fatal("expected token to be returned") } } func TestRequest_tokenAuth(t *testing.T) { server := newTestAtlasServer(t) defer server.Stop() client, err := NewClient(server.URL.String()) if err != nil { t.Fatal(err) } client.Token = "a.atlasv1.b" request, err := client.Request("GET", "/api/v1/token", nil) if err != nil { t.Fatal(err) } _, err = checkResp(client.HTTPClient.Do(request)) if err != nil { t.Fatal(err) } } func TestRequest_getsData(t *testing.T) { server := newTestAtlasServer(t) defer server.Stop() client, err := NewClient(server.URL.String()) if err != nil { t.Fatal(err) } request, err := client.Request("GET", "/_status/200", nil) if err != nil { t.Fatal(err) } if _, err := checkResp(client.HTTPClient.Do(request)); err != nil { t.Fatal(err) } } func TestRequest_railsError(t *testing.T) { server := newTestAtlasServer(t) defer server.Stop() client, err := NewClient(server.URL.String()) if err != nil { t.Fatal(err) } request, err := client.Request("GET", "/_rails-error", nil) if err != nil { t.Fatal(err) } _, err = checkResp(client.HTTPClient.Do(request)) if err == nil { t.Fatal("expected error, but nothing was returned") } expected := &RailsError{ Errors: []string{ "this is an error", "this is another error", }, } if !reflect.DeepEqual(err, expected) { t.Fatalf("expected %+v to be %+v", err, expected) } } func TestRequest_notFoundError(t *testing.T) { server := newTestAtlasServer(t) defer server.Stop() client, err := NewClient(server.URL.String()) if err != nil { t.Fatal(err) } request, err := client.Request("GET", "/_status/404", nil) if err != nil { t.Fatal(err) } _, err = checkResp(client.HTTPClient.Do(request)) if err == nil { t.Fatal("expected error, but nothing was returned") } if err != ErrNotFound { t.Fatalf("bad error: %#v", err) } } func TestRequestJSON_decodesData(t *testing.T) { server := newTestAtlasServer(t) defer server.Stop() client, err := NewClient(server.URL.String()) if err != nil { t.Fatal(err) } request, err := client.Request("GET", "/_json", nil) if err != nil { t.Fatal(err) } response, err := checkResp(client.HTTPClient.Do(request)) if err != nil { t.Fatal(err) } var decoded struct{ Ok bool } if err := decodeJSON(response, &decoded); err != nil { t.Fatal(err) } if !decoded.Ok { t.Fatal("expected decoded response to be Ok, but was not") } } atlas-go-b66e377f52e316206efe71abba20e276d8790d86/v1/terraform.go000066400000000000000000000044251263420655300230450ustar00rootroot00000000000000package atlas import ( "bytes" "encoding/json" "fmt" "io" "log" ) // TerraformConfigVersion represents a single uploaded version of a // Terraform configuration. type TerraformConfigVersion struct { Version int Remotes []string `json:"remotes"` Metadata map[string]string `json:"metadata"` Variables map[string]string `json:"variables"` } // TerraformConfigLatest returns the latest Terraform configuration version. func (c *Client) TerraformConfigLatest(user, name string) (*TerraformConfigVersion, error) { log.Printf("[INFO] getting terraform configuration %s/%s", user, name) endpoint := fmt.Sprintf("/api/v1/terraform/configurations/%s/%s/versions/latest", user, name) request, err := c.Request("GET", endpoint, nil) if err != nil { return nil, err } response, err := checkResp(c.HTTPClient.Do(request)) if err == ErrNotFound { return nil, nil } if err != nil { return nil, err } var wrapper tfConfigVersionWrapper if err := decodeJSON(response, &wrapper); err != nil { return nil, err } return wrapper.Version, nil } // CreateTerraformConfigVersion creatse a new Terraform configuration // versions and uploads a slug with it. func (c *Client) CreateTerraformConfigVersion( user string, name string, version *TerraformConfigVersion, data io.Reader, size int64) (int, error) { log.Printf("[INFO] creating terraform configuration %s/%s", user, name) endpoint := fmt.Sprintf( "/api/v1/terraform/configurations/%s/%s/versions", user, name) body, err := json.Marshal(&tfConfigVersionWrapper{ Version: version, }) if err != nil { return 0, err } request, err := c.Request("POST", endpoint, &RequestOptions{ Body: bytes.NewReader(body), Headers: map[string]string{ "Content-Type": "application/json", }, }) if err != nil { return 0, err } response, err := checkResp(c.HTTPClient.Do(request)) if err != nil { return 0, err } var result tfConfigVersionCreate if err := decodeJSON(response, &result); err != nil { return 0, err } if err := c.putFile(result.UploadPath, data, size); err != nil { return 0, err } return result.Version, nil } type tfConfigVersionCreate struct { UploadPath string `json:"upload_path"` Version int } type tfConfigVersionWrapper struct { Version *TerraformConfigVersion `json:"version"` } atlas-go-b66e377f52e316206efe71abba20e276d8790d86/v1/terraform_test.go000066400000000000000000000020631263420655300241000ustar00rootroot00000000000000package atlas import ( "bytes" "reflect" "testing" ) func TestTerraformConfigLatest(t *testing.T) { server := newTestAtlasServer(t) defer server.Stop() client, err := NewClient(server.URL.String()) if err != nil { t.Fatal(err) } actual, err := client.TerraformConfigLatest("hashicorp", "existing") if err != nil { t.Fatal(err) } expected := &TerraformConfigVersion{ Version: 5, Metadata: map[string]string{"foo": "bar"}, Variables: map[string]string{"foo": "bar"}, } if !reflect.DeepEqual(actual, expected) { t.Fatalf("%#v", actual) } } func TestCreateTerraformConfigVersion(t *testing.T) { server := newTestAtlasServer(t) defer server.Stop() client, err := NewClient(server.URL.String()) if err != nil { t.Fatal(err) } v := &TerraformConfigVersion{ Version: 5, Metadata: map[string]string{"foo": "bar"}, } data := new(bytes.Buffer) vsn, err := client.CreateTerraformConfigVersion( "hashicorp", "existing", v, data, int64(data.Len())) if err != nil { t.Fatal(err) } if vsn != 5 { t.Fatalf("bad: %v", vsn) } } atlas-go-b66e377f52e316206efe71abba20e276d8790d86/v1/util.go000066400000000000000000000011121263420655300220070ustar00rootroot00000000000000package atlas import ( "fmt" "strings" ) // ParseSlug parses a slug of the format (x/y) into the x and y components. It // accepts a string of the format "x/y" ("user/name" for example). If an empty // string is given, an error is returned. If the given string is not a valid // slug format, an error is returned. func ParseSlug(slug string) (string, string, error) { if slug == "" { return "", "", fmt.Errorf("missing slug") } parts := strings.Split(slug, "/") if len(parts) != 2 { return "", "", fmt.Errorf("malformed slug %q", slug) } return parts[0], parts[1], nil } atlas-go-b66e377f52e316206efe71abba20e276d8790d86/v1/util_test.go000066400000000000000000000024001263420655300230470ustar00rootroot00000000000000package atlas import ( "strings" "testing" ) func TestParseSlug_emptyString(t *testing.T) { _, _, err := ParseSlug("") if err == nil { t.Fatal("expected error, but nothing was returned") } expected := "missing slug" if !strings.Contains(err.Error(), expected) { t.Fatalf("expected %q to contain %q", err.Error(), expected) } } func TestParseSlug_noSlashes(t *testing.T) { _, _, err := ParseSlug("bacon") if err == nil { t.Fatal("expected error, but nothing was returned") } expected := "malformed slug" if !strings.Contains(err.Error(), expected) { t.Fatalf("expected %q to contain %q", err.Error(), expected) } } func TestParseSlug_multipleSlashes(t *testing.T) { _, _, err := ParseSlug("bacon/is/delicious/but/this/is/not/valid") if err == nil { t.Fatal("expected error, but nothing was returned") } expected := "malformed slug" if !strings.Contains(err.Error(), expected) { t.Fatalf("expected %q to contain %q", err.Error(), expected) } } func TestParseSlug_goodString(t *testing.T) { user, name, err := ParseSlug("hashicorp/project") if err != nil { t.Fatal(err) } if user != "hashicorp" { t.Fatalf("expected %q to be %q", user, "hashicorp") } if name != "project" { t.Fatalf("expected %q to be %q", name, "project") } }